Search in sources :

Example 96 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class AsyncApiParser method generateAsyncAPIDefinition.

public String generateAsyncAPIDefinition(API api) throws APIManagementException {
    Aai20Document aaiDocument = new Aai20Document();
    aaiDocument.info = aaiDocument.createInfo();
    aaiDocument.info.title = api.getId().getName();
    aaiDocument.info.version = api.getId().getVersion();
    if (!APIConstants.API_TYPE_WEBSUB.equals(api.getType())) {
        Aai20Server server = (Aai20Server) aaiDocument.createServer("production");
        JSONObject endpointConfig = new JSONObject(api.getEndpointConfig());
        server.url = endpointConfig.getJSONObject("production_endpoints").getString("url");
        server.protocol = api.getType().toLowerCase();
        aaiDocument.addServer("production", server);
    }
    Map<String, AaiChannelItem> channels = new HashMap<>();
    for (URITemplate uriTemplate : api.getUriTemplates()) {
        Aai20ChannelItem channelItem = aaiDocument.createChannelItem(uriTemplate.getUriTemplate());
        Aai20Operation subscribeOp = new Aai20Operation(channelItem, "subscribe");
        channelItem.subscribe = subscribeOp;
        if (APIConstants.API_TYPE_WS.equals(api.getType())) {
            Aai20Operation publishOp = new Aai20Operation(channelItem, "publish");
            channelItem.publish = publishOp;
        }
        channels.put(uriTemplate.getUriTemplate(), channelItem);
    }
    aaiDocument.channels = channels;
    return Library.writeDocumentToJSONString(aaiDocument);
}
Also used : AaiChannelItem(io.apicurio.datamodels.asyncapi.models.AaiChannelItem) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Aai20Document(io.apicurio.datamodels.asyncapi.v2.models.Aai20Document) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Aai20Server(io.apicurio.datamodels.asyncapi.v2.models.Aai20Server) Aai20ChannelItem(io.apicurio.datamodels.asyncapi.v2.models.Aai20ChannelItem) Aai20Operation(io.apicurio.datamodels.asyncapi.v2.models.Aai20Operation)

Example 97 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method execute.

@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing API State change Workflow.");
        log.debug("Execute workflowDTO " + workflowDTO.toString());
    }
    if (stateList != null) {
        Map<String, List<String>> stateActionMap = getSelectedStatesToApprove();
        APIStateWorkflowDTO apiStateWorkFlowDTO = (APIStateWorkflowDTO) workflowDTO;
        if (stateActionMap.containsKey(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase()) && stateActionMap.get(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase()).contains(apiStateWorkFlowDTO.getApiLCAction())) {
            // set the auth application related info. This will be used to call the callback service
            setOAuthApplicationInfo(apiStateWorkFlowDTO);
            // build request payload
            String jsonPayload = buildPayloadForBPMNProcess(apiStateWorkFlowDTO);
            if (log.isDebugEnabled()) {
                log.debug("APIStateChange payload: " + jsonPayload);
            }
            if (serviceEndpoint == null) {
                // set the bps endpoint from the global configurations
                WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
                serviceEndpoint = workflowProperties.getServerUrl();
            }
            URL serviceEndpointURL = new URL(serviceEndpoint);
            HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
            HttpPost httpPost = new HttpPost(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH);
            // Generate the basic auth header using provided user credentials
            String authHeader = getBasicAuthHeader();
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
            StringEntity requestEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);
            try {
                HttpResponse response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                    String error = "Error while starting the process:  " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
                    log.error(error);
                    throw new WorkflowException(error);
                }
            } catch (ClientProtocolException e) {
                String errorMsg = "Error while creating the http client";
                log.error(errorMsg, e);
                throw new WorkflowException(errorMsg, e);
            } catch (IOException e) {
                String errorMsg = "Error while connecting to the BPMN process server from the WorkflowExecutor.";
                log.error(errorMsg, e);
                throw new WorkflowException(errorMsg, e);
            } finally {
                httpPost.reset();
            }
            super.execute(workflowDTO);
        } else {
            // For any other states, act as simpleworkflow executor.
            workflowDTO.setStatus(WorkflowStatus.APPROVED);
            // calling super.complete() instead of complete() to act as the simpleworkflow executor
            super.complete(workflowDTO);
        }
    } else {
        String msg = "State change list is not provided. Please check <stateList> element in ";
        log.error(msg);
        throw new WorkflowException(msg);
    }
    return new GeneralWorkflowResponse();
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) HttpClient(org.apache.http.client.HttpClient) ArrayList(java.util.ArrayList) List(java.util.List)

Example 98 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class AbstractApplicationRegistrationWorkflowExecutor method dogenerateKeysForApplication.

public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO) throws APIManagementException {
    log.debug("Registering Application and creating an Access Token... ");
    Application application = workflowDTO.getApplication();
    Subscriber subscriber = application.getSubscriber();
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
        dao.populateAppRegistrationWorkflowDTO(workflowDTO);
    }
    try {
        // get new key manager
        // Here the default flow is set expecting an ID as the keymanager as this flow only involves new applications
        String keyManagerId = workflowDTO.getKeyManager();
        KeyManagerConfigurationDTO km = dao.getKeyManagerConfigurationByUUID(keyManagerId);
        String tenantDomain = km.getOrganization();
        String keyManagerName = km.getName();
        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        if (keyManager == null) {
            throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
        }
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().setClientName(application.getName());
        // set applications attributes to the oAuthApplicationInfo
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
        // createApplication on oAuthorization server.
        OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());
        // update associateApplication
        ApplicationUtils.updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerId);
        // change create application status in to completed.
        dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED, workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerId);
        workflowDTO.setApplicationInfo(oAuthApplication);
        AccessTokenInfo tokenInfo;
        Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
        if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
            AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
            tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
        } else {
            tokenInfo = new AccessTokenInfo();
            tokenInfo.setAccessToken("");
            tokenInfo.setValidityPeriod(0L);
            String[] noScopes = new String[] { "N/A" };
            tokenInfo.setScope(noScopes);
            oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
        }
        workflowDTO.setAccessTokenInfo(tokenInfo);
    } catch (Exception e) {
        APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) Application(org.wso2.carbon.apimgt.api.model.Application) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 99 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class OrganizationPurgeDAO method deleteApplicationList.

/**
 * Deletes Applications along with subscriptions, keys and registration data
 *
 * @param organization Organization
 * @throws APIManagementException if failed to delete applications for organization
 */
public void deleteApplicationList(String organization) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        connection.setAutoCommit(false);
        if (multiGroupAppSharingEnabled) {
            updateGroupIDMappingsBulk(connection, organization);
        }
        try (PreparedStatement prepStmtGetConsumerKey = connection.prepareStatement(OrganizationPurgeConstants.GET_CONSUMER_KEYS_OF_APPLICATION_LIST_SQL);
            PreparedStatement deleteDomainApp = connection.prepareStatement(SQLConstants.REMOVE_APPLICATION_FROM_DOMAIN_MAPPINGS_SQL)) {
            prepStmtGetConsumerKey.setString(1, organization);
            try (ResultSet rs = prepStmtGetConsumerKey.executeQuery()) {
                while (rs.next()) {
                    String consumerKey = rs.getString(APIConstants.FIELD_CONSUMER_KEY);
                    String keyManagerName = rs.getString("NAME");
                    String keyManagerOrganization = rs.getString("ORGANIZATION");
                    // This is true when OAuth App has been created by pasting consumer key/secret in the screen.
                    String mode = rs.getString("CREATE_MODE");
                    if (consumerKey != null) {
                        deleteDomainApp.setString(1, consumerKey);
                        deleteDomainApp.addBatch();
                        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerOrganization, keyManagerName);
                        if (keyManager != null) {
                            try {
                                keyManager.deleteMappedApplication(consumerKey);
                                log.info("Mapped application deleted for consumer key: " + consumerKey + " and organization: " + organization);
                            } catch (APIManagementException e) {
                                handleException("Error while Deleting Client Application for consumer key: " + consumerKey + " and organization: " + organization, e);
                            }
                        }
                        // call delete.
                        if (!APIConstants.OAuthAppMode.MAPPED.name().equals(mode)) {
                            // delete on oAuthorization server.
                            if (log.isDebugEnabled()) {
                                log.debug("Deleting Oauth application with consumer key " + consumerKey + " from the " + "Oauth server for organization: " + organization);
                            }
                            if (keyManager != null) {
                                try {
                                    keyManager.deleteApplication(consumerKey);
                                    log.info("Client application deleted for consumer key: " + consumerKey + " and organization: " + organization);
                                } catch (APIManagementException e) {
                                    handleException("Error while Deleting Client Application for organization: " + organization, e);
                                }
                            }
                        }
                    }
                }
            }
            deleteDomainApp.executeBatch();
        } catch (SQLException domainAppsException) {
            connection.rollback();
            log.error("Failed to rollback removing domain applications for organization: " + organization, domainAppsException);
        }
        if (log.isDebugEnabled()) {
            log.debug("Subscription Key mapping details are deleted successfully for Applications for " + "organization: " + organization);
        }
        try (PreparedStatement deleteApp = connection.prepareStatement(OrganizationPurgeConstants.REMOVE_APPLICATION_LIST_FROM_APPLICATIONS_SQL)) {
            deleteApp.setString(1, organization);
            deleteApp.execute();
        } catch (SQLException appDeletionException) {
            connection.rollback();
            log.error("Failed to rollback removing applications for organization: " + organization, appDeletionException);
        }
        if (log.isDebugEnabled()) {
            log.debug("Applications are deleted successfully for organization: " + organization);
        }
        connection.commit();
    } catch (SQLException e) {
        handleException("Error while removing application details from the database for organization: " + organization, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 100 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class ThrottleDataPublisher method publishNonThrottledEvent.

/**
 * This method used to pass message context and let it run within separate thread.
 *
 * @param messageContext is message context object that holds
 */
public void publishNonThrottledEvent(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) {
    try {
        if (dataPublisherPool != null) {
            DataProcessAndPublishingAgent agent = dataPublisherPool.get();
            agent.setDataReference(applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId, messageContext, authenticationContext);
            if (log.isDebugEnabled()) {
                log.debug("Publishing throttle data from gateway to traffic-manager for: " + apiContext + " with ID: " + messageContext.getMessageID() + " started" + " at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
            }
            executor.execute(agent);
            if (log.isDebugEnabled()) {
                log.debug("Publishing throttle data from gateway to traffic-manager for: " + apiContext + " with ID: " + messageContext.getMessageID() + " ended" + " at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
            }
        } else {
            log.debug("Throttle data publisher pool is not initialized.");
        }
    } catch (Exception e) {
        log.error("Error while publishing throttling events to global policy server", e);
    }
}
Also used : SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) DataEndpointAuthenticationException(org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException) TransportException(org.wso2.carbon.databridge.commons.exception.TransportException) DataEndpointConfigurationException(org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException) DataEndpointException(org.wso2.carbon.databridge.agent.exception.DataEndpointException) DataEndpointAgentConfigurationException(org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 IOException (java.io.IOException)19 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)14 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 File (java.io.File)8 JSONObject (org.json.simple.JSONObject)7 MalformedURLException (java.net.MalformedURLException)6 URL (java.net.URL)6 OMElement (org.apache.axiom.om.OMElement)6 JSONObject (org.json.JSONObject)6 URI (java.net.URI)5 URISyntaxException (java.net.URISyntaxException)5 Test (org.testng.annotations.Test)5 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)5 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)5 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)5 Connection (java.sql.Connection)4 SQLException (java.sql.SQLException)4 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4