Search in sources :

Example 11 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
    for (APIProductResource resource : resources) {
        List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
        ListIterator it = resourceScopes.listIterator();
        while (it.hasNext()) {
            Scope resourceScope = (Scope) it.next();
            String scopeKey = resourceScope.getKey();
            if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                resourceScope = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 12 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class TenantWorkflowConfigHolder method load.

public void load() throws WorkflowException, RegistryException {
    workflowExecutorMap = new ConcurrentHashMap<>();
    InputStream in = null;
    try {
        String workFlowConfig = ServiceReferenceHolder.getInstance().getApimConfigService().getWorkFlowConfig(tenantDomain);
        if (StringUtils.isNotEmpty(workFlowConfig)) {
            in = new ByteArrayInputStream(workFlowConfig.getBytes());
            StAXOMBuilder builder = new StAXOMBuilder(in);
            secretResolver = SecretResolverFactory.create(builder.getDocumentElement(), true);
            OMElement workflowExtensionsElem = builder.getDocument().getFirstChildWithName(new QName(WorkflowConstants.WORKFLOW_EXTENSIONS));
            OMElement workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.APPLICATION_CREATION));
            String executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            Class clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            WorkflowExecutor workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.PRODUCTION_APPLICATION_REGISTRATION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SANDBOX_APPLICATION_REGISTRATION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.USER_SIGN_UP));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_CREATION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_UPDATE));
            if (workflowElem != null) {
                executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
                clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
                workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
                loadProperties(workflowElem, workFlowExecutor);
                workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE, workFlowExecutor);
            } else {
                executorClass = DEFAULT_SUBSCRIPTION_UPDATE_EXECUTOR_CLASS;
                clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
                workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
                workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE, workFlowExecutor);
            }
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_DELETION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.APPLICATION_DELETION));
            executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.API_STATE_CHANGE));
            if (workflowElem == null) {
                // TO handle migrated environment, create the default simple workflow executor
                workflowElem = OMAbstractFactory.getOMFactory().createOMElement(new QName(WorkflowConstants.API_STATE_CHANGE));
                executorClass = WorkflowConstants.DEFAULT_EXECUTOR_API_STATE_CHANGE;
                workflowElem.addAttribute(WorkflowConstants.EXECUTOR, executorClass, null);
            } else {
                executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            }
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_API_STATE, workFlowExecutor);
            workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.API_PRODUCT_STATE_CHANGE));
            if (workflowElem == null) {
                // To handle migration, create the default simple workflow executor
                workflowElem = OMAbstractFactory.getOMFactory().createOMElement(new QName(WorkflowConstants.API_PRODUCT_STATE_CHANGE));
                executorClass = WorkflowConstants.DEFAULT_EXECUTOR_API_PRODUCT_STATE_CHANGE;
                workflowElem.addAttribute(WorkflowConstants.EXECUTOR, executorClass, null);
            } else {
                executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
            }
            clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
            workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
            loadProperties(workflowElem, workFlowExecutor);
            workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE, workFlowExecutor);
        }
    } catch (XMLStreamException e) {
        log.error("Error building xml", e);
        handleException("Error building xml", e);
    } catch (ClassNotFoundException e) {
        log.error("Unable to find class", e);
        handleException("Unable to find class", e);
    } catch (InstantiationException e) {
        log.error("Unable to instantiate class", e);
        handleException("Unable to instantiate class", e);
    } catch (IllegalAccessException e) {
        log.error("Illegal attempt to invoke class methods", e);
        handleException("Illegal attempt to invoke class methods", e);
    } catch (WorkflowException e) {
        log.error("Unable to load workflow executor class", e);
        handleException("Unable to load workflow executor class", e);
    } catch (APIManagementException e) {
        log.error("Unable to retrieve workflow configurations", e);
        handleException("Unable to retrieve workflow configurations", e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) XMLStreamException(javax.xml.stream.XMLStreamException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) StAXOMBuilder(org.apache.axiom.om.impl.builder.StAXOMBuilder)

Example 13 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class VHostUtils method getVhostFromEnvironment.

/**
 * Get VHost object of given environment and given host name
 *
 * @param environment Gateway environment name
 * @param host Host name of the VHost
 * @return VHost object of the given host
 */
public static VHost getVhostFromEnvironment(Environment environment, String host) {
    // If there are any inconstancy (if VHost not found) use default VHost
    VHost defaultVhost = new VHost();
    defaultVhost.setHost(host);
    defaultVhost.setHttpContext("");
    defaultVhost.setHttpsPort(APIConstants.HTTPS_PROTOCOL_PORT);
    defaultVhost.setHttpPort(APIConstants.HTTP_PROTOCOL_PORT);
    defaultVhost.setWsPort(APIConstants.WS_PROTOCOL_PORT);
    defaultVhost.setWssPort(APIConstants.WSS_PROTOCOL_PORT);
    if (host == null && environment.getVhosts().size() > 0) {
        // VHost is NULL set first Vhost (set in deployment toml)
        return environment.getVhosts().get(0);
    }
    return environment.getVhosts().stream().filter(v -> StringUtils.equals(v.getHost(), host)).findAny().orElse(defaultVhost);
}
Also used : VHost(org.wso2.carbon.apimgt.api.model.VHost)

Example 14 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method getAPI.

/**
 * This Method is different from getAPI method, as this one returns
 * URLTemplates without aggregating duplicates. This is to be used for building synapse config.
 *
 * @param artifact
 * @param registry
 * @return API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion, artifact.getId());
        api = new API(apiIdentifier);
        // set uuid
        api.setUuid(artifact.getId());
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        // String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
        // + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName())
        // + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR
        // + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY;
        Resource apiResource = registry.get(artifactPath);
        api = setResourceProperties(api, apiResource, artifactPath);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
            api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        } else {
            // If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
            api.setEndpointUTPassword(apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY));
        }
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
        api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        api.setAsyncTransportProtocols(artifact.getAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
            if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
                cacheTimeout = Integer.parseInt(strCacheTimeout);
            }
        } catch (NumberFormatException e) {
            if (log.isWarnEnabled()) {
                log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
            }
        // ignore the exception and use default cache timeout value
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
        api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
        api.setAdvertiseOnlyAPIVendor(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY_API_VENDOR));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Set<Tier> availableTiers = new HashSet<Tier>();
        if (tiers != null) {
            String[] tiersArray = tiers.split("\\|\\|");
            for (String tierName : tiersArray) {
                availableTiers.add(new Tier(tierName));
            }
        }
        api.setAvailableTiers(availableTiers);
        // This contains the resolved context
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        // We set the context template here
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        api.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.setTags(tags);
        api.setLastUpdated(apiResource.getLastModified());
        api.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setWebsubSubscriptionConfiguration(getWebsubSubscriptionConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // set data and status related to monetization
        api.setMonetizationEnabled(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        api.setWsUriMapping(getWsUriMappingFromArtifact(artifact));
        api.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
        api.setVersionTimestamp(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP));
        // set selected clusters which API needs to be deployed
        String deployments = artifact.getAttribute(APIConstants.API_OVERVIEW_DEPLOYMENTS);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            api.setMonetizationProperties(jsonObj);
        }
        api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
        // get endpoint config string from artifact, parse it as a json and set the environment list configured with
        // non empty URLs to API object
        String keyManagers = artifact.getAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS);
        if (StringUtils.isNotEmpty(keyManagers)) {
            api.setKeyManagers(new Gson().fromJson(keyManagers, List.class));
        } else {
            api.setKeyManagers(Arrays.asList(APIConstants.API_LEVEL_ALL_KEY_MANAGERS));
        }
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ArrayList(java.util.ArrayList) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Example 15 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class EnvironmentMappingUtil method fromEnvDtoToEnv.

/**
 * Convert EnvironmentDTO to Environment
 *
 * @param envDTO EnvironmentDTO
 * @return Environment
 */
public static Environment fromEnvDtoToEnv(EnvironmentDTO envDTO) {
    Environment env = new Environment();
    env.setUuid(envDTO.getId());
    env.setName(envDTO.getName());
    env.setDisplayName(envDTO.getDisplayName());
    env.setDescription(envDTO.getDescription());
    env.setProvider(envDTO.getProvider());
    env.setReadOnly(false);
    env.setVhosts(envDTO.getVhosts().stream().map(EnvironmentMappingUtil::fromVHostDtoToVHost).collect(Collectors.toList()));
    env.setAdditionalProperties(fromAdditionalPropertiesDTOToAdditionalProperties(envDTO.getAdditionalProperties()));
    return env;
}
Also used : Environment(org.wso2.carbon.apimgt.api.model.Environment)

Aggregations

Environment (org.wso2.carbon.apimgt.api.model.Environment)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 ArrayList (java.util.ArrayList)35 HashMap (java.util.HashMap)25 API (org.wso2.carbon.apimgt.api.model.API)22 IOException (java.io.IOException)19 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)19 Map (java.util.Map)15 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)12 JsonObject (com.google.gson.JsonObject)10 PreparedStatement (java.sql.PreparedStatement)10 SQLException (java.sql.SQLException)10 HashSet (java.util.HashSet)10 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)10 SolaceAdminApis (org.wso2.carbon.apimgt.solace.SolaceAdminApis)10 Gson (com.google.gson.Gson)9 JSONObject (org.json.simple.JSONObject)9 Test (org.junit.Test)9 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)9