Example usage for org.json.simple JSONObject toString

List of usage examples for org.json.simple JSONObject toString

Introduction

In this page you can find the example usage for org.json.simple JSONObject toString.

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/** Updates an Application identified by its id
 *
 * @param application Application object to be updated
 * @throws APIManagementException//from www .  j a va 2  s. c o m
 */
@Override
public void updateApplication(Application application) throws APIManagementException {

    Application existingApp;
    String uuid = application.getUUID();
    if (!StringUtils.isEmpty(uuid)) {
        existingApp = apiMgtDAO.getApplicationByUUID(uuid);
        application.setId(existingApp.getId());
    } else {
        existingApp = apiMgtDAO.getApplicationById(application.getId());
    }

    if (existingApp != null
            && APIConstants.ApplicationStatus.APPLICATION_CREATED.equals(existingApp.getStatus())) {
        throw new APIManagementException("Cannot update the application while it is INACTIVE");
    }
    //validate callback url
    if (!APIUtil.isValidURL(application.getCallbackUrl())) {
        log.warn("Invalid Call Back URL " + application.getCallbackUrl());
    }

    apiMgtDAO.updateApplication(application);
    if (log.isDebugEnabled()) {
        log.debug("Successfully updated the Application: " + application.getId() + " in the database.");
    }

    JSONObject appLogObject = new JSONObject();
    appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
    appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
    appLogObject.put(APIConstants.AuditLogConstants.STATUS, existingApp != null ? existingApp.getStatus() : "");
    appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());

    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(),
            APIConstants.AuditLogConstants.UPDATED, this.username);

    APIKey[] apiKeys = null;

    // Update on OAuthApps are performed by
    if ((application.getCallbackUrl() != null && existingApp != null
            && !application.getCallbackUrl().equals(existingApp.getCallbackUrl()))
            || (existingApp != null && !application.getName().equals(existingApp.getName()))) {

        // Only the OauthApps created from UI will be changed. Mapped Clients won't be touched.
        apiKeys = apiMgtDAO.getConsumerKeysWithMode(application.getId(),
                APIConstants.OAuthAppMode.CREATED.toString());
    }
    if (apiKeys != null && apiKeys.length > 0) {
        for (APIKey apiKey : apiKeys) {
            OAuthApplicationInfo applicationInfo = new OAuthApplicationInfo();
            applicationInfo.setClientId(apiKey.getConsumerKey());

            if (application.getCallbackUrl() != null
                    && application.getCallbackUrl().equals(existingApp.getCallbackUrl())) {
                applicationInfo.setCallBackURL(application.getCallbackUrl());
            }

            if (application.getName() != null && !application.getName().equals(existingApp.getName())) {
                applicationInfo.setClientName(application.getName() + '_' + apiKey.getType());
            }
            applicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME,
                    application.getSubscriber().getName());

            // This parameter is set as a way of indicating from which point updateApplication was called. When
            // integrating with different OAuthProviders, if the implementers do not wish to change CallBackUrl
            // when an update is performed on the AM_Application, then using this variable that update can be
            // ignored.
            applicationInfo.addParameter("executing_mode", "AM_APPLICATION_UPDATE");

            OAuthAppRequest oAuthAppRequest = new OAuthAppRequest();
            oAuthAppRequest.setOAuthApplicationInfo(applicationInfo);
            KeyManagerHolder.getKeyManagerInstance().updateApplication(oAuthAppRequest);

        }
    }
    try {
        invalidateCachedKeys(application.getId());
    } catch (APIManagementException ignore) {
        //Log and ignore since we do not want to throw exceptions to the front end due to cache invalidation failure.
        log.warn("Failed to invalidate Gateway Cache " + ignore.getMessage(), ignore);
    }
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * Function to remove an Application from the API Store
 *
 * @param application - The Application Object that represents the Application
 * @throws APIManagementException//from  www .j  ava 2  s . c om
 */
@Override
public void removeApplication(Application application) throws APIManagementException {
    String uuid = application.getUUID();
    if (application.getId() == 0 && !StringUtils.isEmpty(uuid)) {
        application = apiMgtDAO.getApplicationByUUID(uuid);
    }
    boolean isTenantFlowStarted = false;
    int applicationId = application.getId();

    try {
        String workflowExtRef;
        ApplicationWorkflowDTO workflowDTO;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }

        WorkflowExecutor createApplicationWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        WorkflowExecutor createSubscriptionWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        WorkflowExecutor createProductionRegistrationWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        WorkflowExecutor createSandboxRegistrationWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        WorkflowExecutor removeApplicationWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);

        workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceByApplicationID(application.getId());

        // in a normal flow workflowExtRef is null when workflows are not enabled
        if (workflowExtRef == null) {
            workflowDTO = new ApplicationWorkflowDTO();
        } else {
            workflowDTO = (ApplicationWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
        }
        workflowDTO.setApplication(application);
        workflowDTO.setCallbackUrl(removeApplicationWFExecutor.getCallbackURL());
        workflowDTO.setUserName(this.username);
        workflowDTO.setTenantDomain(tenantDomain);
        workflowDTO.setTenantId(tenantId);

        // Remove from cache first since we won't be able to find active access tokens
        // once the application is removed.
        invalidateCachedKeys(application.getId());

        // clean up pending subscription tasks
        Set<Integer> pendingSubscriptions = apiMgtDAO.getPendingSubscriptionsByApplicationId(applicationId);
        for (int subscription : pendingSubscriptions) {
            try {
                workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(subscription);
                createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (APIManagementException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to get external workflow reference for subscription " + subscription);
            } catch (WorkflowException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending subscription approval task: " + subscription);
            }
        }

        // cleanup pending application registration tasks
        String productionKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId,
                APIConstants.API_KEY_TYPE_PRODUCTION);
        String sandboxKeyStatus = apiMgtDAO.getRegistrationApprovalState(applicationId,
                APIConstants.API_KEY_TYPE_SANDBOX);
        if (WorkflowStatus.CREATED.toString().equals(productionKeyStatus)) {
            try {
                workflowExtRef = apiMgtDAO.getRegistrationWFReference(applicationId,
                        APIConstants.API_KEY_TYPE_PRODUCTION);
                createProductionRegistrationWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (APIManagementException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to get external workflow reference for production key of application "
                        + applicationId);
            } catch (WorkflowException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending production key approval task of " + applicationId);
            }
        }
        if (WorkflowStatus.CREATED.toString().equals(sandboxKeyStatus)) {
            try {
                workflowExtRef = apiMgtDAO.getRegistrationWFReference(applicationId,
                        APIConstants.API_KEY_TYPE_SANDBOX);
                createSandboxRegistrationWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (APIManagementException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to get external workflow reference for sandbox key of application "
                        + applicationId);
            } catch (WorkflowException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending sandbox key approval task of " + applicationId);
            }
        }
        if (workflowExtRef != null) {
            try {
                createApplicationWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (WorkflowException ex) {

                // failed cleanup processes are ignored to prevent failing the application removal process
                log.warn("Failed to clean pending application approval task of " + applicationId);
            }
        }

        // update attributes of the new remove workflow to be created
        workflowDTO.setStatus(WorkflowStatus.CREATED);
        workflowDTO.setCreatedTime(System.currentTimeMillis());
        workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION);
        workflowDTO.setExternalWorkflowReference(removeApplicationWFExecutor.generateUUID());

        removeApplicationWFExecutor.execute(workflowDTO);

        JSONObject appLogObject = new JSONObject();
        appLogObject.put(APIConstants.AuditLogConstants.NAME, application.getName());
        appLogObject.put(APIConstants.AuditLogConstants.TIER, application.getTier());
        appLogObject.put(APIConstants.AuditLogConstants.CALLBACK, application.getCallbackUrl());

        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(),
                APIConstants.AuditLogConstants.DELETED, this.username);

    } catch (WorkflowException e) {
        String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION
                + " " + "for applicationID " + application.getId();
        handleException(errorMsg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    if (log.isDebugEnabled()) {
        String logMessage = "Application Name: " + application.getName() + " successfully removed";
        log.debug(logMessage);
    }
}

From source file:org.wso2.carbon.apimgt.impl.APIProviderImpl.java

/**
 * Adds a new API to the Store//w  w w  .ja  v  a  2  s.  co m
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 *          if failed to add API
 */
@Override
public void addAPI(API api) throws APIManagementException {
    try {
        createAPI(api);

        if (log.isDebugEnabled()) {
            log.debug("API details successfully added to the registry. API Name: " + api.getId().getApiName()
                    + ", API Version : " + api.getId().getVersion() + ", API context : " + api.getContext());
        }

        int tenantId;
        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        try {
            tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new APIManagementException(
                    "Error in retrieving Tenant Information while adding api :" + api.getId().getApiName(), e);
        }
        apiMgtDAO.addAPI(api, tenantId);

        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());

        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(),
                APIConstants.AuditLogConstants.CREATED, this.username);

        if (log.isDebugEnabled()) {
            log.debug("API details successfully added to the API Manager Database. API Name: "
                    + api.getId().getApiName() + ", API Version : " + api.getId().getVersion()
                    + ", API context : " + api.getContext());
        }

        if (APIUtil.isAPIManagementEnabled()) {
            Cache contextCache = APIUtil.getAPIContextCache();
            Boolean apiContext = null;

            Object cachedObject = contextCache.get(api.getContext());
            if (cachedObject != null) {
                apiContext = Boolean.valueOf(cachedObject.toString());
            }
            if (apiContext == null) {
                contextCache.put(api.getContext(), Boolean.TRUE);
            }
        }
    } catch (APIManagementException e) {
        throw new APIManagementException("Error in adding API :" + api.getId().getApiName(), e);
    }
}

From source file:org.wso2.carbon.apimgt.impl.APIProviderImpl.java

/**
 * Updates an existing API/*  ww w  . ja va2 s .com*/
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 *          if failed to update API
 * @throws org.wso2.carbon.apimgt.api.FaultGatewaysException on Gateway Failure
 */
@Override
public void updateAPI(API api) throws APIManagementException, FaultGatewaysException {

    boolean isValid = isAPIUpdateValid(api);
    if (!isValid) {
        throw new APIManagementException(" User doesn't have permission for update");
    }

    Map<String, Map<String, String>> failedGateways = new ConcurrentHashMap<String, Map<String, String>>();
    API oldApi = getAPI(api.getId());
    if (oldApi.getStatus().equals(api.getStatus())) {

        String previousDefaultVersion = getDefaultVersion(api.getId());
        String publishedDefaultVersion = getPublishedDefaultVersion(api.getId());

        if (previousDefaultVersion != null) {

            APIIdentifier defaultAPIId = new APIIdentifier(api.getId().getProviderName(),
                    api.getId().getApiName(), previousDefaultVersion);
            if (api.isDefaultVersion() ^ api.getId().getVersion().equals(previousDefaultVersion)) { // A change has
                                                                                                    // happen
                                                                                                    // Remove the previous default API entry from the Registry
                updateDefaultAPIInRegistry(defaultAPIId, false);
                if (!api.isDefaultVersion()) {// default api tick is removed
                    // todo: if it is ok, these two variables can be put to the top of the function to remove
                    // duplication
                    APIManagerConfiguration config = ServiceReferenceHolder.getInstance()
                            .getAPIManagerConfigurationService().getAPIManagerConfiguration();
                    String gatewayType = config.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
                    if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
                        removeDefaultAPIFromGateway(api);
                    }
                }
            }
        }

        //Update WSDL in the registry
        if (api.getWsdlUrl() != null) {
            updateWsdl(api);
        }

        boolean updatePermissions = false;
        if (!oldApi.getVisibility().equals(api.getVisibility())
                || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility())
                        && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
            updatePermissions = true;
        }
        updateApiArtifact(api, true, updatePermissions);
        if (!oldApi.getContext().equals(api.getContext())) {
            api.setApiHeaderChanged(true);
        }

        int tenantId;
        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
        try {
            tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new APIManagementException(
                    "Error in retrieving Tenant Information while updating api :" + api.getId().getApiName(),
                    e);
        }
        apiMgtDAO.updateAPI(api, tenantId);
        if (log.isDebugEnabled()) {
            log.debug("Successfully updated the API: " + api.getId() + " in the database");
        }

        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());

        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(),
                APIConstants.AuditLogConstants.UPDATED, this.username);

        APIManagerConfiguration config = ServiceReferenceHolder.getInstance()
                .getAPIManagerConfigurationService().getAPIManagerConfiguration();
        boolean gatewayExists = config.getApiGatewayEnvironments().size() > 0;
        String gatewayType = config.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
        boolean isAPIPublished = false;
        // gatewayType check is required when API Management is deployed on other servers to avoid synapse
        if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
            isAPIPublished = isAPIPublished(api);
            if (gatewayExists) {
                if (isAPIPublished) {
                    API apiPublished = getAPI(api.getId());
                    apiPublished.setAsDefaultVersion(api.isDefaultVersion());
                    if (api.getId().getVersion().equals(previousDefaultVersion) && !api.isDefaultVersion()) {
                        // default version tick has been removed so a default api for current should not be
                        // added/updated
                        apiPublished.setAsPublishedDefaultVersion(false);
                    } else {
                        apiPublished.setAsPublishedDefaultVersion(
                                api.getId().getVersion().equals(publishedDefaultVersion));
                    }
                    apiPublished.setOldInSequence(oldApi.getInSequence());
                    apiPublished.setOldOutSequence(oldApi.getOutSequence());
                    //old api contain what environments want to remove
                    Set<String> environmentsToRemove = new HashSet<String>(oldApi.getEnvironments());
                    //updated api contain what environments want to add
                    Set<String> environmentsToPublish = new HashSet<String>(apiPublished.getEnvironments());
                    Set<String> environmentsRemoved = new HashSet<String>(oldApi.getEnvironments());
                    if (!environmentsToPublish.isEmpty() && !environmentsToRemove.isEmpty()) {
                        // this block will sort what gateways have to remove and published
                        environmentsRemoved.retainAll(environmentsToPublish);
                        environmentsToRemove.removeAll(environmentsRemoved);
                    }
                    // map contain failed to publish Environments
                    Map<String, String> failedToPublishEnvironments = publishToGateway(apiPublished);
                    apiPublished.setEnvironments(environmentsToRemove);
                    // map contain failed to remove Environments
                    Map<String, String> failedToRemoveEnvironments = removeFromGateway(apiPublished);
                    environmentsToPublish.removeAll(failedToPublishEnvironments.keySet());
                    environmentsToPublish.addAll(failedToRemoveEnvironments.keySet());
                    apiPublished.setEnvironments(environmentsToPublish);
                    updateApiArtifact(apiPublished, true, false);
                    failedGateways.clear();
                    failedGateways.put("UNPUBLISHED", failedToRemoveEnvironments);
                    failedGateways.put("PUBLISHED", failedToPublishEnvironments);
                } else if (api.getStatus() != APIStatus.CREATED && api.getStatus() != APIStatus.RETIRED) {
                    if ("INLINE".equals(api.getImplementation()) && api.getEnvironments().isEmpty()) {
                        api.setEnvironments(
                                ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                                        .getAPIManagerConfiguration().getApiGatewayEnvironments().keySet());
                    }
                    Map<String, String> failedToPublishEnvironments = publishToGateway(api);
                    if (!failedToPublishEnvironments.isEmpty()) {
                        Set<String> publishedEnvironments = new HashSet<String>(api.getEnvironments());
                        publishedEnvironments.removeAll(failedToPublishEnvironments.keySet());
                        api.setEnvironments(publishedEnvironments);
                        updateApiArtifact(api, true, false);
                        failedGateways.clear();
                        failedGateways.put("PUBLISHED", failedToPublishEnvironments);
                        failedGateways.put("UNPUBLISHED", Collections.<String, String>emptyMap());
                    }
                }
            } else {
                log.debug("Gateway is not existed for the current API Provider");
            }
        }

        //If gateway(s) exist, remove resource paths saved on the cache.

        if (gatewayExists && isAPIPublished && !oldApi.getUriTemplates().equals(api.getUriTemplates())) {
            Set<URITemplate> resourceVerbs = api.getUriTemplates();

            Map<String, Environment> gatewayEns = config.getApiGatewayEnvironments();
            for (Environment environment : gatewayEns.values()) {
                try {
                    APIAuthenticationAdminClient client = new APIAuthenticationAdminClient(environment);
                    if (resourceVerbs != null) {
                        for (URITemplate resourceVerb : resourceVerbs) {
                            String resourceURLContext = resourceVerb.getUriTemplate();
                            client.invalidateResourceCache(api.getContext(), api.getId().getVersion(),
                                    resourceURLContext, resourceVerb.getHTTPVerb());
                            if (log.isDebugEnabled()) {
                                log.debug("Calling invalidation cache");
                            }
                        }
                    }
                } catch (AxisFault ex) {
                    /*
                    didn't throw this exception to handle multiple gateway publishing feature therefore
                    this didn't break invalidating cache from the all the gateways if one gateway is
                    unreachable
                    */
                    log.error("Error while invalidating from environment " + environment.getName(), ex);
                }
            }

        }

        // update apiContext cache
        if (APIUtil.isAPIManagementEnabled()) {
            Cache contextCache = APIUtil.getAPIContextCache();
            contextCache.remove(oldApi.getContext());
            contextCache.put(api.getContext(), Boolean.TRUE);
        }

    } else {
        // We don't allow API status updates via this method.
        // Use changeAPIStatus for that kind of updates.
        throw new APIManagementException("Invalid API update operation involving API status changes");
    }
    if (!failedGateways.isEmpty()
            && (!failedGateways.get("UNPUBLISHED").isEmpty() || !failedGateways.get("PUBLISHED").isEmpty())) {
        throw new FaultGatewaysException(failedGateways);
    }
}

From source file:org.wso2.carbon.apimgt.impl.APIProviderImpl.java

public void deleteAPI(APIIdentifier identifier) throws APIManagementException {
    String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
            + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName()
            + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();

    String apiArtifactPath = APIUtil.getAPIPath(identifier);

    try {//from  w  w w. j a  v a2s  .  co  m

        long subsCount = apiMgtDAO.getAPISubscriptionCountByAPI(identifier);
        if (subsCount > 0) {
            handleException("Cannot remove the API as active subscriptions exist.", null);
        }

        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        Resource apiResource = registry.get(path);
        String artifactId = apiResource.getUUID();

        Resource apiArtifactResource = registry.get(apiArtifactPath);
        String apiArtifactResourceId = apiArtifactResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + path);
        }

        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiArtifactResourceId);
        String inSequence = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE);
        String outSequence = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE);
        String environments = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);

        //Delete the dependencies associated  with the api artifact
        GovernanceArtifact[] dependenciesArray = apiArtifact.getDependencies();

        if (dependenciesArray.length > 0) {
            for (GovernanceArtifact artifact : dependenciesArray) {
                registry.delete(artifact.getPath());
            }
        }
        String isDefaultVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION);
        artifactManager.removeGenericArtifact(apiArtifact);
        artifactManager.removeGenericArtifact(artifactId);

        String thumbPath = APIUtil.getIconPath(identifier);
        if (registry.resourceExists(thumbPath)) {
            registry.delete(thumbPath);
        }

        /*Remove API Definition Resource - swagger*/
        String apiDefinitionFilePath = APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR
                + identifier.getApiName() + '-' + identifier.getVersion() + '-' + identifier.getProviderName();
        if (registry.resourceExists(apiDefinitionFilePath)) {
            registry.delete(apiDefinitionFilePath);
        }

        APIManagerConfiguration config = ServiceReferenceHolder.getInstance()
                .getAPIManagerConfigurationService().getAPIManagerConfiguration();
        boolean gatewayExists = config.getApiGatewayEnvironments().size() > 0;
        String gatewayType = config.getFirstProperty(APIConstants.API_GATEWAY_TYPE);

        API api = new API(identifier);
        api.setAsDefaultVersion(Boolean.parseBoolean(isDefaultVersion));
        api.setAsPublishedDefaultVersion(
                api.getId().getVersion().equals(apiMgtDAO.getPublishedDefaultVersion(api.getId())));

        // gatewayType check is required when API Management is deployed on
        // other servers to avoid synapse
        if (gatewayExists && "Synapse".equals(gatewayType)) {

            api.setInSequence(inSequence); // need to remove the custom sequences
            api.setOutSequence(outSequence);
            api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environments));
            removeFromGateway(api);
            if (api.isDefaultVersion()) {
                removeDefaultAPIFromGateway(api);
            }

        } else {
            log.debug("Gateway is not existed for the current API Provider");
        }
        //Check if there are already published external APIStores.If yes,removing APIs from them.
        Set<APIStore> apiStoreSet = getPublishedExternalAPIStores(api.getId());
        WSO2APIPublisher wso2APIPublisher = new WSO2APIPublisher();
        if (apiStoreSet != null && !apiStoreSet.isEmpty()) {
            for (APIStore store : apiStoreSet) {
                wso2APIPublisher.deleteFromStore(api.getId(),
                        APIUtil.getExternalAPIStore(store.getName(), tenantId));
            }
        }

        //if manageAPIs == true
        if (APIUtil.isAPIManagementEnabled()) {
            Cache contextCache = APIUtil.getAPIContextCache();
            String context = apiMgtDAO.getAPIContext(identifier);
            contextCache.remove(context);
            contextCache.put(context, Boolean.FALSE);
        }

        apiMgtDAO.deleteAPI(identifier);

        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + api.getId().getApiName() + ", API Version "
                    + api.getId().getVersion() + " successfully removed from the database.";
            log.debug(logMessage);
        }

        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, identifier.getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, identifier.getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());

        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(),
                APIConstants.AuditLogConstants.DELETED, this.username);

        /*remove empty directories*/
        String apiCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
                + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName();
        if (registry.resourceExists(apiCollectionPath)) {
            Resource apiCollection = registry.get(apiCollectionPath);
            CollectionImpl collection = (CollectionImpl) apiCollection;
            //if there is no other versions of apis delete the directory of the api
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more versions of the API found, removing API collection from registry");
                }
                registry.delete(apiCollectionPath);
            }
        }

        String apiProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
                + identifier.getProviderName();

        if (registry.resourceExists(apiProviderPath)) {
            Resource providerCollection = registry.get(apiProviderPath);
            CollectionImpl collection = (CollectionImpl) providerCollection;
            //if there is no api for given provider delete the provider directory
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more APIs from the provider " + identifier.getProviderName() + " found. "
                            + "Removing provider collection from registry");
                }
                registry.delete(apiProviderPath);
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to remove the API from : " + path, e);
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java

/**
 * Logs an audit message on actions performed on entities (APIs, Applications, etc). The log is printed in the
 * following JSON format// ww w  .  ja v  a2 s  . co m
 *  {
 "typ": "API",
 "action": "update",
 "performedBy": "admin@carbon.super",
 "info": {
 "name": "Twitter",
 "context": "/twitter",
 "version": "1.0.0",
 "provider": "nuwan"
 }
 }
 * @param entityType - The entity type. Ex: API, Application
 * @param entityInfo - The details of the entity. Ex: API Name, Context
 * @param action - The type of action performed. Ex: Create, Update
 * @param performedBy - The user who performs the action.
 */
public static void logAuditMessage(String entityType, String entityInfo, String action, String performedBy) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("typ", entityType);
    jsonObject.put("action", action);
    jsonObject.put("performedBy", performedBy);
    jsonObject.put("info", entityInfo);
    audit.info(jsonObject.toString());
}

From source file:org.wso2.carbon.apimgt.rest.api.impl.ApplicationsApiServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public Response applicationsApplicationIdGenerateKeysPost(String applicationId,
        ApplicationKeyGenerateRequestDTO body, String contentType, String ifMatch, String ifUnmodifiedSince) {

    String username = RestApiUtil.getLoggedInUsername();
    try {// w  ww .j a v  a  2  s  .c  o m
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        String[] accessAllowDomainsArray = body.getAccessAllowDomains().toArray(new String[1]);
        JSONObject jsonParamObj = new JSONObject();
        jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
        String jsonParams = jsonParamObj.toString();
        String tokenScopes = StringUtils.join(body.getScopes(), " ");

        Map<String, Object> keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username,
                application.getName(), body.getKeyType().toString(), body.getCallbackUrl(),
                accessAllowDomainsArray, body.getValidityTime(), tokenScopes, application.getGroupId(),
                jsonParams);
        ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(keyDetails,
                body.getKeyType().toString());

        //get the updated application again
        application = apiConsumer.getApplicationByUUID(applicationId);
        ApplicationDTO applicationDTO = ApplicationMappingUtil.fromApplicationtoDTO(application);

        boolean alreadyContainsKey = false;
        for (APIKey apiKey : application.getKeys()) {
            String keyType = apiKey.getType();
            if (keyType != null && keyType.equals(applicationKeyDTO.getKeyType().toString())) {
                alreadyContainsKey = true;
                break;
            }
        }
        if (!alreadyContainsKey) {
            applicationDTO.getKeys().add(applicationKeyDTO);
        }
        return Response.ok().entity(applicationDTO).build();
    } catch (APIManagementException e) {
        throw new InternalServerErrorException(e);
    }
}

From source file:org.wso2.carbon.apimgt.rest.api.store.impl.ApplicationsApiServiceImpl.java

/**
 * Generate keys for a application//from w w w.java 2s . com
 *
 * @param applicationId     application identifier
 * @param body              request body
 * @param contentType       Content-Type header value
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @return A response object containing application keys
 */
@Override
@SuppressWarnings("unchecked")
public Response applicationsGenerateKeysPost(String applicationId, ApplicationKeyGenerateRequestDTO body,
        String contentType, String ifMatch, String ifUnmodifiedSince) {

    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                String[] accessAllowDomainsArray = body.getAccessAllowDomains().toArray(new String[1]);
                JSONObject jsonParamObj = new JSONObject();
                jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
                String jsonParams = jsonParamObj.toString();
                String tokenScopes = StringUtils.join(body.getScopes(), " ");

                Map<String, Object> keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username,
                        application.getName(), body.getKeyType().toString(), body.getCallbackUrl(),
                        accessAllowDomainsArray, body.getValidityTime(), tokenScopes, application.getGroupId(),
                        jsonParams);
                ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil
                        .fromApplicationKeyToDTO(keyDetails, body.getKeyType().toString());

                return Response.ok().entity(applicationKeyDTO).build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId,
                        log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.rootCauseMessageMatches(e, "primary key violation")) {
            RestApiUtil.handleResourceAlreadyExistsError(
                    "Keys already generated for the application " + applicationId, e, log);
        } else {
            RestApiUtil.handleInternalServerError(
                    "Error while generating keys for application " + applicationId, e, log);
        }
    }
    return null;
}

From source file:org.wso2.carbon.apimgt.sciquest.keymanager.APIManagerOAuthClient.java

/**
 * This method validates the access token with external OAuth Server
 *
 * @param accessToken - the token which need to be validated
 * @return an {@code AccessTokenInfo} having token validation meta data
 * @throws APIManagementException/*from   w w  w  .  j a v a 2  s  .c om*/
 */

public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken(accessToken);

    KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(ClientConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(ClientConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(ClientConstants.INTROSPECTION_CS);
    String encodedSecret = Base64
            .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
        URIBuilder uriBuilder = new URIBuilder(introspectionURL);
        uriBuilder.addParameter("access_token", accessToken);
        uriBuilder.build();

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpClient client = new DefaultHttpClient();

        httpGet.setHeader("Authorization", "Basic " + encodedSecret);
        HttpResponse response = client.execute(httpGet);
        int responseCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("HTTP Response code for Token Validation from external OAuth Server: " + responseCode);
        }

        // Response Format from OAuth 2 Server

        /*{
        "audience":"MappedClient",
            "scopes":[
                "test"
            ],
            "principal":{
                "name":"mappedclient",
                "roles":[
                
                ],
                "groups":[
                
                ],
                "adminPrincipal":false,
                "attributes":{
                
                }
            },
            "expires_in":1433059160531
        }*/

        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

        if (HttpStatus.SC_OK == responseCode) {
            //pass bufferReader object  and get read it and retrieve  the parsedJson object
            parsedObject = getParsedObjectByReader(reader);
            if (parsedObject != null) {
                Object principal = parsedObject.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("name");
                Long expiryTimeString = (Long) parsedObject.get("expires_in");

                // Returning false if mandatory attributes are missing.
                if (clientId == null || expiryTimeString == null) {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

                long currentTime = System.currentTimeMillis();
                long expiryTime = expiryTimeString;
                if (expiryTime > currentTime) {
                    tokenInfo.setTokenValid(true);
                    tokenInfo.setConsumerKey(clientId);
                    tokenInfo.setValidityPeriod(expiryTime - currentTime);
                    // Considering Current Time as the issued time.
                    tokenInfo.setIssuedTime(currentTime);
                    JSONArray scopesArray = (JSONArray) parsedObject.get("scopes");

                    if (log.isDebugEnabled()) {
                        StringBuilder tokens = new StringBuilder("[");
                        Iterator iterator = scopesArray.iterator();
                        while (iterator.hasNext()) {
                            tokens.append(iterator.next());
                            if (iterator.hasNext()) {
                                tokens.append(", ");
                            }
                        }
                        tokens.append("]");

                        log.debug("Tokens " + tokens);
                    }

                    if (scopesArray != null && !scopesArray.isEmpty()) {

                        String[] scopes = new String[scopesArray.size()];
                        for (int i = 0; i < scopes.length; i++) {
                            scopes[i] = (String) scopesArray.get(i);
                        }
                        tokenInfo.setScope(scopes);
                    }

                    JSONObject jso = new JSONObject();
                    jso.putAll(principalMap);
                    tokenInfo.setEndUserName(jso.toString());

                    if (log.isDebugEnabled()) {
                        log.debug("Token Response Principle : " + jso.toJSONString());
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

            } else {
                log.error("Invalid Token " + accessToken);
                tokenInfo.setTokenValid(false);
                tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                return tokenInfo;
            }
        } //for other HTTP error codes we just pass generic message.
        else {
            log.error("Invalid Token " + accessToken);
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
        }

    } catch (UnsupportedEncodingException e) {
        handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        handleException(
                "HTTP request error has occurred while sending request  to OAuth Provider. " + e.getMessage(),
                e);
    } catch (IOException e) {
        handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
        handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return tokenInfo;
}

From source file:org.wso2.carbon.appmgt.impl.publishers.WSO2ExternalAppStorePublisher.java

private String getTagsAsJsonString(WebApp webApp) {
    Set<String> tagsSet = webApp.getTags();
    if (tagsSet.size() > 0) {
        JSONArray tagList = new JSONArray();
        for (String tag : tagsSet) {
            tagList.add(tag);//from  ww w  . j  ava 2  s.  c  om
        }
        JSONObject tags = new JSONObject();
        tags.put("tags", tagList);
        return tags.toString();
    }
    return null;
}