Search in sources :

Example 31 with Broker

use of org.wso2.carbon.apimgt.core.api.Broker in project carbon-apimgt by wso2.

the class SolaceStoreUtils method getSolaceDeployedEnvsInfo.

/**
 * Get SolaceDeployedEnvironmentDTO using admin APIs and map into DTOs to parse Devportal
 *
 * @param solaceEnvironment Solace environment Object
 * @param solaceOrganization Solace broker organization name
 * @param applicationUuid      Subscribed Application UUID
 * @return List of SolaceDeployedEnvironmentDTO to use in Devportal
 * @throws APIManagementException if error occurred when creating SolaceDeployedEnvironmentDTO
 */
public static List<SolaceDeployedEnvironmentDTO> getSolaceDeployedEnvsInfo(Environment solaceEnvironment, String solaceOrganization, String applicationUuid) throws APIManagementException {
    Map<String, Environment> gatewayEnvironmentMap = APIUtil.getReadOnlyGatewayEnvironments();
    // Create solace admin APIs instance
    SolaceAdminApis solaceAdminApis = new SolaceAdminApis(solaceEnvironment.getServerURL(), solaceEnvironment.getUserName(), solaceEnvironment.getPassword(), solaceEnvironment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_DEV_NAME));
    HttpResponse response = solaceAdminApis.applicationGet(solaceOrganization, applicationUuid, "default");
    List<SolaceDeployedEnvironmentDTO> solaceEnvironments = new ArrayList<>();
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        try {
            String responseString = EntityUtils.toString(response.getEntity());
            org.json.JSONObject jsonObject = new org.json.JSONObject(responseString);
            // Get solace environments attached with the Solace application
            if (jsonObject.getJSONArray("environments") != null) {
                JSONArray environmentsArray = jsonObject.getJSONArray("environments");
                for (int i = 0; i < environmentsArray.length(); i++) {
                    SolaceDeployedEnvironmentDTO solaceDeployedEnvironmentsDTO = new SolaceDeployedEnvironmentDTO();
                    org.json.JSONObject environmentObject = environmentsArray.getJSONObject(i);
                    // Get details of Solace environment attached to the solace application
                    if (environmentObject.getString("name") != null) {
                        String environmentName = environmentObject.getString("name");
                        Environment gatewayEnvironment = gatewayEnvironmentMap.get(environmentName);
                        if (gatewayEnvironment != null) {
                            // Set Solace environment details
                            solaceDeployedEnvironmentsDTO.setEnvironmentName(gatewayEnvironment.getName());
                            solaceDeployedEnvironmentsDTO.setEnvironmentDisplayName(gatewayEnvironment.getDisplayName());
                            solaceDeployedEnvironmentsDTO.setOrganizationName(gatewayEnvironment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION));
                            boolean containsMQTTProtocol = false;
                            // Get messaging protocols from the response body
                            if (environmentObject.getJSONArray("messagingProtocols") != null) {
                                List<SolaceURLsDTO> endpointUrls = new ArrayList<>();
                                JSONArray protocolsArray = environmentObject.getJSONArray("messagingProtocols");
                                for (int j = 0; j < protocolsArray.length(); j++) {
                                    SolaceURLsDTO solaceURLsDTO = new SolaceURLsDTO();
                                    String protocol = protocolsArray.getJSONObject(j).getJSONObject("protocol").getString("name");
                                    if (SolaceConstants.MQTT_TRANSPORT_PROTOCOL_NAME.equalsIgnoreCase(protocol)) {
                                        containsMQTTProtocol = true;
                                    }
                                    String uri = protocolsArray.getJSONObject(j).getString("uri");
                                    solaceURLsDTO.setProtocol(protocol);
                                    solaceURLsDTO.setEndpointURL(uri);
                                    endpointUrls.add(solaceURLsDTO);
                                }
                                solaceDeployedEnvironmentsDTO.setSolaceURLs(endpointUrls);
                            }
                            // Get topic permissions from the solace application response body
                            if (environmentObject.getJSONObject("permissions") != null) {
                                org.json.JSONObject permissionsObject = environmentObject.getJSONObject("permissions");
                                SolaceTopicsObjectDTO solaceTopicsObjectDTO = new SolaceTopicsObjectDTO();
                                populateSolaceTopics(solaceTopicsObjectDTO, permissionsObject, "default");
                                // Handle the special case of MQTT protocol
                                if (containsMQTTProtocol) {
                                    HttpResponse responseForMqtt = solaceAdminApis.applicationGet(solaceOrganization, applicationUuid, SolaceConstants.MQTT_TRANSPORT_PROTOCOL_NAME.toUpperCase());
                                    org.json.JSONObject permissionsObjectForMqtt = extractPermissionsFromSolaceApplicationGetResponse(responseForMqtt, i, gatewayEnvironmentMap);
                                    if (permissionsObjectForMqtt != null) {
                                        populateSolaceTopics(solaceTopicsObjectDTO, permissionsObjectForMqtt, SolaceConstants.MQTT_TRANSPORT_PROTOCOL_NAME.toUpperCase());
                                    }
                                }
                                solaceDeployedEnvironmentsDTO.setSolaceTopicsObject(solaceTopicsObjectDTO);
                            }
                        }
                    }
                    solaceEnvironments.add(solaceDeployedEnvironmentsDTO);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return solaceEnvironments;
    } else {
        throw new APIManagementException("Solace Environment configurations are not provided properly");
    }
}
Also used : ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) HttpResponse(org.apache.http.HttpResponse) SolaceURLsDTO(org.wso2.carbon.apimgt.solace.dtos.SolaceURLsDTO) IOException(java.io.IOException) SolaceTopicsObjectDTO(org.wso2.carbon.apimgt.solace.dtos.SolaceTopicsObjectDTO) SolaceAdminApis(org.wso2.carbon.apimgt.solace.SolaceAdminApis) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Environment(org.wso2.carbon.apimgt.api.model.Environment) SolaceDeployedEnvironmentDTO(org.wso2.carbon.apimgt.solace.dtos.SolaceDeployedEnvironmentDTO)

Example 32 with Broker

use of org.wso2.carbon.apimgt.core.api.Broker in project carbon-apimgt by wso2.

the class SolaceAdminApis method renameApplication.

/**
 * Rename application in Solace Broker
 *
 * @param organization name of the Organization
 * @param application  Application object to be renamed
 * @return CloseableHttpResponse of the DELETE call
 */
public CloseableHttpResponse renameApplication(String organization, Application application) {
    URL serviceEndpointURL = new URL(baseUrl);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    HttpPatch httpPatch = new HttpPatch(baseUrl + "/" + organization + "/developers/" + developerUserName + "/apps/" + application.getUUID());
    httpPatch.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedCredentials());
    httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    org.json.JSONObject requestBody = buildRequestBodyForRenamingApp(application);
    StringEntity params = null;
    try {
        params = new StringEntity(requestBody.toString());
        httpPatch.setEntity(params);
        return APIUtil.executeHTTPRequest(httpPatch, httpClient);
    } catch (IOException | APIManagementException e) {
        log.error(e.getMessage());
    }
    return null;
}
Also used : StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) IOException(java.io.IOException) URL(org.apache.axis2.util.URL) HttpPatch(org.apache.http.client.methods.HttpPatch)

Example 33 with Broker

use of org.wso2.carbon.apimgt.core.api.Broker in project carbon-apimgt by wso2.

the class SolaceAdminApis method deleteApiProduct.

/**
 * Delete API Product from Solace Broker
 *
 * @param organization   name of the Organization
 * @param apiProductName name of the API product
 * @return CloseableHttpResponse of the DELETE call
 */
public CloseableHttpResponse deleteApiProduct(String organization, String apiProductName) {
    URL serviceEndpointURL = new URL(baseUrl);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    HttpDelete httpDelete = new HttpDelete(baseUrl + "/" + organization + "/apiProducts/" + apiProductName);
    httpDelete.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedCredentials());
    try {
        return APIUtil.executeHTTPRequest(httpDelete, httpClient);
    } catch (IOException | APIManagementException e) {
        log.error(e.getMessage());
    }
    return null;
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) IOException(java.io.IOException) URL(org.apache.axis2.util.URL)

Example 34 with Broker

use of org.wso2.carbon.apimgt.core.api.Broker in project carbon-apimgt by wso2.

the class SolaceKeyGenNotifier method syncSolaceApplicationClientId.

/**
 * Syncing consumer key of the dev portal applications with applications on the Solace broker
 *
 * @param event ApplicationEvent to sync Solace applications with dev portal applications
 * @throws NotifierException if error occurs when patching applications on the Solace broker
 */
private void syncSolaceApplicationClientId(ApplicationRegistrationEvent event) throws NotifierException {
    // get list of subscribed APIs in the application
    try {
        Application application = apiMgtDAO.getApplicationByUUID(event.getApplicationUUID());
        Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
        Set<SubscribedAPI> subscriptions = apiMgtDAO.getSubscribedAPIs(application.getSubscriber(), application.getName(), application.getGroupId());
        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;
                    }
                }
            }
        }
        // Patching consumerKey to Solace application using Admin Apis
        if (isContainsSolaceApis) {
            if (application.getKeys() != null) {
                String consumerSecret = null;
                APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(CarbonContext.getThreadLocalCarbonContext().getUsername());
                Set<APIKey> consumerKeys = apiConsumer.getApplicationKeysOfApplication(application.getId());
                for (APIKey key : consumerKeys) {
                    if (key.getConsumerKey().equals(event.getConsumerKey())) {
                        consumerSecret = key.getConsumerSecret();
                    }
                }
                SolaceNotifierUtils.patchSolaceApplicationClientId(organizationNameOfSolaceDeployment, application, event.getConsumerKey(), consumerSecret);
            } else {
                throw new NotifierException("Application keys are not found in the application : " + application.getName());
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) 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) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) List(java.util.List) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 35 with Broker

use of org.wso2.carbon.apimgt.core.api.Broker in project carbon-apimgt by wso2.

the class SolaceNotifierUtils method deployApplicationToSolaceBroker.

/**
 * Deploy an application to Solace broker
 *
 * @param application  Application to be deployed
 * @param apiProducts  Api products to be subscribed to Application
 * @param organization Name of the organization
 * @throws IOException            If an error occurs when deploying the application
 * @throws APIManagementException if an error occurs when getting Solace config
 */
public static void deployApplicationToSolaceBroker(Application application, ArrayList<String> apiProducts, String organization) throws IOException, APIManagementException {
    SolaceAdminApis solaceAdminApis = SolaceNotifierUtils.getSolaceAdminApis();
    // check existence of the developer
    CloseableHttpResponse response1 = solaceAdminApis.developerGet(organization);
    if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        if (log.isDebugEnabled()) {
            log.info("Developer found in Solace Broker");
        }
        // check application status
        CloseableHttpResponse response2 = solaceAdminApis.applicationGet(organization, application.getUUID(), "default");
        if (response2.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // app already exists
            if (log.isDebugEnabled()) {
                log.info("Solace application '" + application.getName() + "' already exists in Solace." + " Updating Application......");
            }
            CloseableHttpResponse response3 = solaceAdminApis.applicationPatchAddSubscription(organization, application, apiProducts);
            if (response3.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                log.info("Solace application '" + application.getName() + "' updated successfully");
            } else {
                if (log.isDebugEnabled()) {
                    log.error("Error while updating Solace application '" + application.getName() + ". : " + response3.getStatusLine().toString());
                }
                throw new HttpResponseException(response3.getStatusLine().getStatusCode(), response3.getStatusLine().getReasonPhrase());
            }
        } else if (response2.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            // If application keys are not generated we are not doing anything in Solace.
            if (application.getKeys().isEmpty()) {
                return;
            }
            String responseString = EntityUtils.toString(response2.getEntity());
            if (responseString.contains(String.valueOf(HttpStatus.SC_NOT_FOUND))) {
                // create new app
                if (log.isDebugEnabled()) {
                    log.info("Solace application '" + application.getName() + "' not found in Solace Broker." + "Creating new application......");
                }
                CloseableHttpResponse response4 = solaceAdminApis.createApplication(organization, application, apiProducts);
                if (response4.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                    log.info("Solace application '" + application.getName() + "' created successfully");
                } else {
                    if (log.isDebugEnabled()) {
                        log.error("Error while creating Solace application '" + application.getName() + ". : " + response4.getStatusLine().toString());
                    }
                    throw new HttpResponseException(response4.getStatusLine().getStatusCode(), response4.getStatusLine().getReasonPhrase());
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.error("Error while searching for application '" + application.getName() + ". : " + response2.getStatusLine().toString());
                }
                throw new HttpResponseException(response2.getStatusLine().getStatusCode(), response2.getStatusLine().getReasonPhrase());
            }
        } else {
            if (log.isDebugEnabled()) {
                log.error("Error while searching for application '" + application.getName() + ". : " + response2.getStatusLine().toString());
            }
            throw new HttpResponseException(response2.getStatusLine().getStatusCode(), response2.getStatusLine().getReasonPhrase());
        }
    } else if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        if (log.isDebugEnabled()) {
            log.error("Developer not found in Solace Broker");
        }
        throw new HttpResponseException(response1.getStatusLine().getStatusCode(), response1.getStatusLine().getReasonPhrase());
    } else {
        if (log.isDebugEnabled()) {
            log.error("Developer not found in Solace Broker");
        }
        throw new HttpResponseException(response1.getStatusLine().getStatusCode(), response1.getStatusLine().getReasonPhrase());
    }
}
Also used : SolaceAdminApis(org.wso2.carbon.apimgt.solace.SolaceAdminApis) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException)

Aggregations

Test (org.testng.annotations.Test)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)19 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)16 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)16 InMemoryBroker (org.wso2.siddhi.core.util.transport.InMemoryBroker)16 Environment (org.wso2.carbon.apimgt.api.model.Environment)15 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)13 ArrayList (java.util.ArrayList)11 SolaceAdminApis (org.wso2.carbon.apimgt.solace.SolaceAdminApis)9 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)8 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)7 DeployerException (org.wso2.carbon.apimgt.impl.deployer.exceptions.DeployerException)7 NotifierException (org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)7 IOException (java.io.IOException)6 Broker (org.wso2.carbon.apimgt.core.api.Broker)6 Test (org.junit.Test)5 API (org.wso2.carbon.apimgt.core.models.API)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4 ExternalGatewayDeployer (org.wso2.carbon.apimgt.impl.deployer.ExternalGatewayDeployer)4 JsonParser (com.google.gson.JsonParser)3