Search in sources :

Example 46 with Environment

use of org.wso2.carbon.apimgt.api.model.Environment in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method createAPIGatewayDTOtoPublishAPI.

private static GatewayAPIDTO createAPIGatewayDTOtoPublishAPI(Environment environment, APIProduct apiProduct, APITemplateBuilder builder, String tenantDomain, Map<String, APIDTO> associatedAPIsMap, List<ClientCertificateDTO> clientCertificatesDTOList) throws APITemplateException, XMLStreamException, APIManagementException {
    APIProductIdentifier id = apiProduct.getId();
    GatewayAPIDTO productAPIDto = new GatewayAPIDTO();
    productAPIDto.setProvider(id.getProviderName());
    productAPIDto.setApiId(apiProduct.getUuid());
    productAPIDto.setName(id.getName());
    productAPIDto.setVersion(id.getVersion());
    productAPIDto.setTenantDomain(tenantDomain);
    productAPIDto.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    String definition = apiProduct.getDefinition();
    productAPIDto.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(apiProduct.getUuid(), productAPIDto.getLocalEntriesToBeRemove()));
    GatewayContentDTO productLocalEntry = new GatewayContentDTO();
    productLocalEntry.setName(apiProduct.getUuid());
    productLocalEntry.setContent("<localEntry key=\"" + apiProduct.getUuid() + "\">" + definition.replaceAll("&(?!amp;)", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</localEntry>");
    productAPIDto.setLocalEntriesToBeAdd(addGatewayContentToList(productLocalEntry, productAPIDto.getLocalEntriesToBeAdd()));
    setClientCertificatesToBeAdded(tenantDomain, productAPIDto, clientCertificatesDTOList);
    for (Map.Entry<String, APIDTO> apidtoEntry : associatedAPIsMap.entrySet()) {
        String apiExtractedPath = apidtoEntry.getKey();
        APIDTO apidto = apidtoEntry.getValue();
        API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
        api.setUuid(apidto.getId());
        GatewayUtils.setCustomSequencesToBeRemoved(apiProduct.getId(), api.getUuid(), productAPIDto);
        APITemplateBuilder apiTemplateBuilder = new APITemplateBuilderImpl(api, apiProduct);
        addEndpoints(api, apiTemplateBuilder, productAPIDto);
        setCustomSequencesToBeAdded(apiProduct, api, productAPIDto, apiExtractedPath, apidto);
        setAPIFaultSequencesToBeAdded(api, productAPIDto, apiExtractedPath, apidto);
        String prefix = id.getName() + "--v" + id.getVersion();
        setSecureVaultPropertyToBeAdded(prefix, api, productAPIDto);
    }
    productAPIDto.setApiDefinition(builder.getConfigStringForTemplate(environment));
    return productAPIDto;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APITemplateBuilder(org.wso2.carbon.apimgt.impl.template.APITemplateBuilder) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl) GatewayContentDTO(org.wso2.carbon.apimgt.api.gateway.GatewayContentDTO)

Example 47 with Environment

use of org.wso2.carbon.apimgt.api.model.Environment in project carbon-apimgt by wso2.

the class APIControllerUtil method handleRestEndpoints.

/**
 * This method will handle the HTTP/REST endpoint configurations.
 *
 * @param envParams                 Json object of Env parameters
 * @param defaultProductionEndpoint Default production endpoint json object
 * @param defaultSandboxEndpoint    Default sandbox endpoint json object
 * @param routingPolicy             String of endpoint routing policy
 * @return JsonObject with HTTP/REST Endpoint configs
 * @throws APIManagementException If an error occurs when extracting endpoint configurations
 */
private static JsonObject handleRestEndpoints(String routingPolicy, JsonObject envParams, JsonObject defaultProductionEndpoint, JsonObject defaultSandboxEndpoint) throws APIManagementException {
    // if the endpoint routing policy is not specified, but the endpoints field is specified, this is the usual
    // scenario
    JsonObject updatedRESTEndpointParams = new JsonObject();
    JsonObject endpoints = null;
    if (envParams.get(ImportExportConstants.ENDPOINTS_FIELD) != null) {
        endpoints = envParams.get(ImportExportConstants.ENDPOINTS_FIELD).getAsJsonObject();
    }
    if (StringUtils.isEmpty(routingPolicy)) {
        updatedRESTEndpointParams.addProperty(ImportExportConstants.ENDPOINT_TYPE_PROPERTY, ImportExportConstants.HTTP_TYPE_ENDPOINT);
        handleEndpointValues(endpoints, updatedRESTEndpointParams, defaultProductionEndpoint, defaultSandboxEndpoint);
    } else if (ImportExportConstants.LOAD_BALANCE_ROUTING_POLICY.equals(routingPolicy)) {
        // if the routing policy is specified and it is load balanced
        // get load balanced configs from params
        JsonElement loadBalancedConfigElement = envParams.get(ImportExportConstants.LOAD_BALANCE_ENDPOINTS_FIELD);
        JsonObject loadBalancedConfigs;
        if (loadBalancedConfigElement == null) {
            throw new APIManagementException("Please specify loadBalanceEndpoints for the environment and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
        } else {
            loadBalancedConfigs = loadBalancedConfigElement.getAsJsonObject();
        }
        updatedRESTEndpointParams.addProperty(ImportExportConstants.ENDPOINT_TYPE_PROPERTY, ImportExportConstants.LOAD_BALANCE_TYPE_ENDPOINT);
        updatedRESTEndpointParams.addProperty(ImportExportConstants.LOAD_BALANCE_ALGORITHM_CLASS_PROPERTY, ImportExportConstants.DEFAULT_ALGORITHM_CLASS);
        JsonElement sessionManagement = loadBalancedConfigs.get(ImportExportConstants.LOAD_BALANCE_SESSION_MANAGEMENT_PROPERTY);
        if (sessionManagement != null) {
            // Otherwise APIM won't recognize this as "transport".
            if (!sessionManagement.isJsonNull()) {
                if (!StringUtils.equals(sessionManagement.getAsString(), ImportExportConstants.LOAD_BALANCE_SESSION_MANAGEMENT_TRANSPORT_TYPE)) {
                    updatedRESTEndpointParams.add(ImportExportConstants.LOAD_BALANCE_SESSION_MANAGEMENT_PROPERTY, loadBalancedConfigs.get(ImportExportConstants.LOAD_BALANCE_SESSION_MANAGEMENT_PROPERTY));
                }
            }
        }
        JsonElement sessionTimeOut = loadBalancedConfigs.get(ImportExportConstants.LOAD_BALANCE_SESSION_TIME_OUT_PROPERTY);
        if (sessionTimeOut != null) {
            updatedRESTEndpointParams.add(ImportExportConstants.LOAD_BALANCE_SESSION_TIME_OUT_PROPERTY, loadBalancedConfigs.get(ImportExportConstants.LOAD_BALANCE_SESSION_TIME_OUT_PROPERTY));
        }
        handleEndpointValues(loadBalancedConfigs, updatedRESTEndpointParams, defaultProductionEndpoint, defaultSandboxEndpoint);
    } else if (ImportExportConstants.FAILOVER_ROUTING_POLICY.equals(routingPolicy)) {
        // if the routing policy is specified and it is failover
        // get failover configs from params
        JsonElement failoverConfigElement = envParams.get(ImportExportConstants.FAILOVER_ENDPOINTS_FIELD);
        JsonObject failoverConfigs;
        if (failoverConfigElement == null) {
            throw new APIManagementException("Please specify failoverEndpoints field for the environment and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
        } else {
            failoverConfigs = failoverConfigElement.getAsJsonObject();
        }
        updatedRESTEndpointParams.addProperty(ImportExportConstants.ENDPOINT_TYPE_PROPERTY, ImportExportConstants.FAILOVER_ROUTING_POLICY);
        updatedRESTEndpointParams.addProperty(ImportExportConstants.FAILOVER_TYPE_ENDPOINT, Boolean.TRUE.toString());
        // check production failover endpoints
        JsonElement productionEndpoints = failoverConfigs.get(ImportExportConstants.PRODUCTION_ENDPOINTS_JSON_PROPERTY);
        JsonElement productionFailOvers = failoverConfigs.get(ImportExportConstants.PRODUCTION_FAILOVERS_ENDPOINTS_JSON_PROPERTY);
        if (productionFailOvers == null) {
            // if failover endpoints are not specified but general endpoints are specified
            if (productionEndpoints != null) {
                throw new APIManagementException("Please specify production failover field for the environment and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
            }
        } else if (!productionFailOvers.isJsonNull()) {
            updatedRESTEndpointParams.add(ImportExportConstants.PRODUCTION_FAILOVERS_ENDPOINTS_PROPERTY, productionFailOvers);
        }
        // check sandbox failover endpoints
        JsonElement sandboxFailOvers = failoverConfigs.get(ImportExportConstants.SANDBOX_FAILOVERS_ENDPOINTS_JSON_PROPERTY);
        JsonElement sandboxEndpoints = failoverConfigs.get(ImportExportConstants.SANDBOX_ENDPOINTS_JSON_PROPERTY);
        if (sandboxFailOvers == null) {
            // if failover endpoints are not specified but general endpoints are specified
            if (sandboxEndpoints != null) {
                throw new APIManagementException("Please specify sandbox failover field for for the environment and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
            }
        } else if (!sandboxFailOvers.isJsonNull()) {
            updatedRESTEndpointParams.add(ImportExportConstants.SANDBOX_FAILOVERS_ENDPOINTS_PROPERTY, sandboxFailOvers);
        }
        handleEndpointValues(failoverConfigs, updatedRESTEndpointParams, defaultProductionEndpoint, defaultSandboxEndpoint);
    }
    return updatedRESTEndpointParams;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject)

Example 48 with Environment

use of org.wso2.carbon.apimgt.api.model.Environment in project carbon-apimgt by wso2.

the class SolaceApplicationNotifier method renameSolaceApplication.

/**
 * Rename applications on the Solace broker
 *
 * @param event ApplicationEvent to rename Solace applications
 * @throws NotifierException if error occurs when renaming applications on the Solace broker
 */
private void renameSolaceApplication(ApplicationEvent event) throws NotifierException {
    // get list of subscribed APIs in the application
    Subscriber subscriber = new Subscriber(event.getSubscriber());
    try {
        Application application = apiMgtDAO.getApplicationByUUID(event.getUuid());
        Set<SubscribedAPI> subscriptions = apiMgtDAO.getSubscribedAPIs(subscriber, event.getApplicationName(), event.getGroupId());
        Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
        boolean isContainsSolaceApis = false;
        String organizationNameOfSolaceDeployment = null;
        labelOne: // Check whether the application needs to be updated has a Solace API subscription
        for (SubscribedAPI api : subscriptions) {
            List<APIRevisionDeployment> deployments = apiMgtDAO.getAPIRevisionDeploymentByApiUUID(api.getIdentifier().getUUID());
            for (APIRevisionDeployment deployment : deployments) {
                if (gatewayEnvironments.containsKey(deployment.getDeployment())) {
                    if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(gatewayEnvironments.get(deployment.getDeployment()).getProvider())) {
                        isContainsSolaceApis = true;
                        organizationNameOfSolaceDeployment = gatewayEnvironments.get(deployment.getDeployment()).getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION);
                        break labelOne;
                    }
                }
            }
        }
        // Renaming application using Solace Admin Apis
        if (isContainsSolaceApis) {
            SolaceNotifierUtils.renameSolaceApplication(organizationNameOfSolaceDeployment, application);
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Environment(org.wso2.carbon.apimgt.api.model.Environment) ArrayList(java.util.ArrayList) List(java.util.List) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) Application(org.wso2.carbon.apimgt.api.model.Application) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)

Example 49 with Environment

use of org.wso2.carbon.apimgt.api.model.Environment in project carbon-apimgt by wso2.

the class SolaceSubscriptionsNotifier method crateSubscription.

/**
 * Create subscriptions to Solace APIs
 *
 * @param event SubscriptionEvent to create Solace API subscriptions
 * @throws NotifierException if error occurs when creating subscription for Solace APIs
 */
private void crateSubscription(SubscriptionEvent event) throws NotifierException {
    String apiUUID = event.getApiUUID();
    String applicationUUID = event.getApplicationUUID();
    try {
        APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(CarbonContext.getThreadLocalCarbonContext().getUsername());
        API api = apiProvider.getAPIbyUUID(apiUUID, apiMgtDAO.getOrganizationByAPIUUID(apiUUID));
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(CarbonContext.getThreadLocalCarbonContext().getUsername());
        Application application = apiMgtDAO.getApplicationByUUID(applicationUUID);
        Set<APIKey> consumerKeys = apiConsumer.getApplicationKeysOfApplication(application.getId());
        for (APIKey apiKey : consumerKeys) {
            application.addKey(apiKey);
        }
        // Check whether the subscription is belongs to an API deployed in Solace
        if (SolaceConstants.SOLACE_ENVIRONMENT.equals(api.getGatewayVendor())) {
            ArrayList<String> solaceApiProducts = new ArrayList<>();
            List<Environment> deployedSolaceEnvironments = SolaceNotifierUtils.getDeployedSolaceEnvironmentsFromRevisionDeployments(api);
            String applicationOrganizationName = SolaceNotifierUtils.getSolaceOrganizationName(deployedSolaceEnvironments);
            if (applicationOrganizationName != null) {
                try {
                    boolean apiProductDeployedIntoSolace = SolaceNotifierUtils.checkApiProductAlreadyDeployedIntoSolaceEnvironments(api, deployedSolaceEnvironments);
                    if (apiProductDeployedIntoSolace) {
                        for (Environment environment : deployedSolaceEnvironments) {
                            solaceApiProducts.add(SolaceNotifierUtils.generateApiProductNameForSolaceBroker(api, environment.getName()));
                        }
                        SolaceNotifierUtils.deployApplicationToSolaceBroker(application, solaceApiProducts, applicationOrganizationName);
                    }
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.error("Cannot create solace application " + application.getName() + "with API product " + "deployed in different organizations...");
                }
                throw new APIManagementException("Cannot create solace application " + application.getName() + "with API product deployed in different organizations...");
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIKey(org.wso2.carbon.apimgt.api.model.APIKey) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Environment(org.wso2.carbon.apimgt.api.model.Environment) API(org.wso2.carbon.apimgt.api.model.API) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 50 with Environment

use of org.wso2.carbon.apimgt.api.model.Environment in project carbon-apimgt by wso2.

the class SolaceEnvironmentImpl method getExternalEndpointURLs.

/**
 * Get endpoint URLs of the Solace environment
 *
 * @return List of protocol endpoint URLs map of Solace
 */
@Override
public List<AsyncProtocolEndpoint> getExternalEndpointURLs(Environment environment) {
    SolaceAdminApis solaceAdminApis = new SolaceAdminApis(environment.getServerURL(), environment.getUserName(), environment.getPassword(), environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_DEV_NAME));
    HttpResponse response = solaceAdminApis.environmentGET(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION), environment.getName());
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String responseString = null;
        try {
            responseString = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        JSONObject jsonObject = new JSONObject(responseString);
        if (jsonObject.has("messagingProtocols")) {
            JSONArray protocols = jsonObject.getJSONArray("messagingProtocols");
            List<AsyncProtocolEndpoint> asyncProtocolEndpoints = new ArrayList<>();
            for (int i = 0; i < protocols.length(); i++) {
                JSONObject protocolDetails = protocols.getJSONObject(i);
                String protocolName = protocolDetails.getJSONObject("protocol").getString("name");
                String endpointURI = protocolDetails.getString("uri");
                AsyncProtocolEndpoint asyncProtocolEndpoint = new AsyncProtocolEndpoint();
                asyncProtocolEndpoint.setProtocol(protocolName);
                asyncProtocolEndpoint.setProtocolUrl(endpointURI);
                asyncProtocolEndpoints.add(asyncProtocolEndpoint);
            }
            return asyncProtocolEndpoints;
        }
    }
    return null;
}
Also used : SolaceAdminApis(org.wso2.carbon.apimgt.solace.SolaceAdminApis) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) AsyncProtocolEndpoint(org.wso2.carbon.apimgt.api.model.AsyncProtocolEndpoint) AsyncProtocolEndpoint(org.wso2.carbon.apimgt.api.model.AsyncProtocolEndpoint)

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