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.topicquests.solrsherlock.interceptor.tests.FirstTest.java

/**
{"locator":{"boost":1,"firstValue":"123ABC","name":"locator","value":"123ABC","valueCount":1,"values":["123ABC"]},
"list":{"boost":1,"firstValue":"Hello","name":"list","value":["Hello","GoodBye"],"valueCount":2,"values":["Hello","GoodBye"]}}
 * @throws Exception/*from  ww  w .  j a  va  2  s.  c o m*/
 */
void runTest() throws Exception {
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("locator", "123ABC");
    List<String> x = new ArrayList<String>();
    x.add("Hello");
    x.add("GoodBye");
    doc.addField("list", x);
    JSONObject j = new JSONObject(doc);
    System.out.println(j.toString());
}

From source file:org.topicquests.tcp.TupleSpaceConnector.java

String getJSONString(String command, String tag, String cargo, String agentName) {
    Map<String, Object> m = new HashMap<String, Object>();
    m.put(ITupleFields.COMMAND, command);
    m.put(ITupleFields.TAG, tag);//  w  w w  .j a  va2  s  .co m
    m.put(ITupleFields.CARGO, cargo);
    if (agentName != null)
        m.put(ITupleFields.AGENT_NAME, agentName);
    JSONObject j = new JSONObject(m);
    return j.toString();
}

From source file:org.topicquests.tcp.TupleSpaceConnector.java

/**
 * Returns field "cargo" //  w  w  w  .  ja va 2  s  .  c o  m
 * @param json
 * @param listener
 */
void sendMessage(String json, ITupleSpaceConnectorListener listener) {
    IResult result = new ResultPojo();
    try {
        //         System.out.println("Server "+port);
        Socket skt = srvr.accept();
        //           System.out.println("Server has connected! ");
        PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
        //           System.out.println("Sending string: " + json);
        out.print(json);
        out.flush();
        //           System.out.println("SS-1");
        //   InputStream is = skt.getInputStream();
        //           System.out.println("SS-2");
        StringBuilder buf = new StringBuilder();
        String line;
        InputStream is = skt.getInputStream();
        //           System.out.println("SS-2a "+skt.isInputShutdown()); //false
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        //           System.out.println("SS-3 "+in.ready()); //false
        while (!in.ready()) { // stuck here
            //              System.out.print(".");
            synchronized (synchObject) {
                try {
                    synchObject.wait(50);
                } catch (Exception e) {
                }
            }
        }
        int x;
        while ((x = in.read()) > -1)
            buf.append((char) x);
        in.close();
        out.close();
        //           System.out.println("SS-4 "+buf);

        //         skt.close();
        line = buf.toString();
        environment.logDebug("TupleSpaceConnector got back " + line);
        JSONObject jobj = (JSONObject) parser.parse(line);
        //what we get back IS the cargo from the original tuple
        result.setResultObject(jobj.toString());
    } catch (Exception e) {
        environment.logError(e.getMessage(), e);
        result.addErrorString(e.getMessage());
    }
    listener.acceptResult(result);
}

From source file:org.trec.liveqa.GetYAnswersPropertiesFromQid.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: GetYAnswersPropertiesFromQid <plaintext-list-of-qids> <out-file>");
        return;// w  w  w.j ava  2s .  c  om
    }

    BufferedWriter writer = getWriter(args[1]);
    String[] qids = getQids(args[0]);

    for (String qid : qids) {
        System.out.println("Getting data for QID " + qid);
        Map<String, String> data = extractData(qid);
        JSONObject jo = new JSONObject();
        for (Map.Entry<String, String> e : data.entrySet()) {
            jo.put(e.getKey(), JSONValue.escape(e.getValue()));
        }

        writer.append(jo.toString());
        writer.newLine();
        writer.flush();
    }
    writer.close();
}

From source file:org.tsugi.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];/*  w ww .  j a v  a2  s .c o  m*/
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = TEST_KEY;
    String profile = PERSIST.get("profile");
    ToolProxy toolProxy = new ToolProxy(profile);
    JSONObject security_contract = toolProxy.getSecurityContract();
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    Object retval = BasicLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:org.wso2.carbon.apimgt.core.impl.ServiceDiscovererKubernetes.java

/**
 * Populates the necessary parameters required by the Endpoint object,
 * and call buildEndpoint method in the super class.
 *
 * @param serviceName  service name as defined in the cluster
 * @param namespace    service's namespace as defined in the cluster
 * @param portType     whether http or https
 * @param urlType      type of the service URL (eg. NodePort)
 * @param url          endpoint URL//ww w. jav  a 2s  .  c  o m
 * @param labels       service's labels as defined in the cluster
 * @return {@link org.wso2.carbon.apimgt.core.models.Endpoint} object
 */
private Endpoint constructEndpoint(String serviceName, String namespace, String portType, String urlType,
        URL url, String labels) {
    JSONObject endpointConfig = new JSONObject();
    endpointConfig.put("serviceUrl", url.toString());
    endpointConfig.put("urlType", urlType);
    endpointConfig.put(ServiceDiscoveryConstants.NAMESPACE, namespace);
    endpointConfig.put(ServiceDiscoveryConstants.CRITERIA, labels);

    String endpointIndex = String.format("kubernetes-%d", this.serviceEndpointIndex);

    return buildEndpoint(endpointIndex, serviceName, endpointConfig.toString(), 1000L, portType,
            "{\"enabled\": false}", APIMgtConstants.GLOBAL_ENDPOINT);
}

From source file:org.wso2.carbon.apimgt.gateway.handlers.WebsocketInboundHandler.java

/**
 * Checks if the request is throttled// w  w  w.j  a v  a 2  s  . com
 *
 * @param ctx ChannelHandlerContext
 * @return false if throttled
 * @throws APIManagementException
 */
public boolean doThrottle(ChannelHandlerContext ctx, WebSocketFrame msg) throws APIManagementException {

    String applicationLevelTier = infoDTO.getApplicationTier();
    String apiLevelTier = infoDTO.getApiTier();
    String subscriptionLevelTier = infoDTO.getTier();
    String resourceLevelTier = apiLevelTier;
    String authorizedUser;
    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(infoDTO.getSubscriberTenantDomain())) {
        authorizedUser = infoDTO.getSubscriber() + "@" + infoDTO.getSubscriberTenantDomain();
    } else {
        authorizedUser = infoDTO.getSubscriber();
    }
    String apiName = infoDTO.getApiName();
    String apiContext = apiContextUri;
    String apiVersion = version;
    String appTenant = infoDTO.getSubscriberTenantDomain();
    String apiTenant = tenantDomain;
    String appId = infoDTO.getApplicationId();
    String applicationLevelThrottleKey = appId + ":" + authorizedUser;
    String apiLevelThrottleKey = apiContext + ":" + apiVersion;
    String resourceLevelThrottleKey = apiLevelThrottleKey;
    String subscriptionLevelThrottleKey = appId + ":" + apiContext + ":" + apiVersion;
    String messageId = UIDGenerator.generateURNString();
    String remoteIP = getRemoteIP(ctx);
    if (remoteIP.indexOf(":") > 0) {
        remoteIP = remoteIP.substring(1, remoteIP.indexOf(":"));
    }
    JSONObject jsonObMap = new JSONObject();
    if (remoteIP != null && remoteIP.length() > 0) {
        jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP));
    }
    jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, msg.content().capacity());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        boolean isThrottled = WebsocketUtil.isThrottled(resourceLevelThrottleKey, subscriptionLevelThrottleKey,
                applicationLevelThrottleKey);
        if (isThrottled) {
            return false;
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    Object[] objects = new Object[] { messageId, applicationLevelThrottleKey, applicationLevelTier,
            apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier,
            resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant,
            apiTenant, appId, apiName, jsonObMap.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(
            "org.wso2.throttle.request.stream:1.0.0", System.currentTimeMillis(), null, null, objects);
    throttleDataPublisher.getDataPublisher().tryPublish(event);
    return true;
}

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

@Override
public SubscriptionResponse addSubscription(APIIdentifier identifier, String userId, int applicationId)
        throws APIManagementException {
    API api = getAPI(identifier);//w w w  .  ja  v a2  s.co  m
    WorkflowResponse workflowResponse = null;
    int subscriptionId;
    if (api.getStatus().equals(APIStatus.PUBLISHED)) {
        subscriptionId = apiMgtDAO.addSubscription(identifier, api.getContext(), applicationId,
                APIConstants.SubscriptionStatus.ON_HOLD, userId);

        boolean isTenantFlowStarted = false;
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }

        String applicationName = apiMgtDAO.getApplicationNameFromId(applicationId);

        try {
            WorkflowExecutor addSubscriptionWFExecutor = WorkflowExecutorFactory.getInstance()
                    .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);

            SubscriptionWorkflowDTO workflowDTO = new SubscriptionWorkflowDTO();
            workflowDTO.setStatus(WorkflowStatus.CREATED);
            workflowDTO.setCreatedTime(System.currentTimeMillis());
            workflowDTO.setTenantDomain(tenantDomain);
            workflowDTO.setTenantId(tenantId);
            workflowDTO.setExternalWorkflowReference(addSubscriptionWFExecutor.generateUUID());
            workflowDTO.setWorkflowReference(String.valueOf(subscriptionId));
            workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
            workflowDTO.setCallbackUrl(addSubscriptionWFExecutor.getCallbackURL());
            workflowDTO.setApiName(identifier.getApiName());
            workflowDTO.setApiContext(api.getContext());
            workflowDTO.setApiVersion(identifier.getVersion());
            workflowDTO.setApiProvider(identifier.getProviderName());
            workflowDTO.setTierName(identifier.getTier());
            workflowDTO.setApplicationName(apiMgtDAO.getApplicationNameFromId(applicationId));
            workflowDTO.setSubscriber(userId);
            workflowResponse = addSubscriptionWFExecutor.execute(workflowDTO);
        } catch (WorkflowException e) {
            //If the workflow execution fails, roll back transaction by removing the subscription entry.
            apiMgtDAO.removeSubscriptionById(subscriptionId);
            log.error("Could not execute Workflow", e);
            throw new APIManagementException("Could not execute Workflow", e);
        } finally {
            if (isTenantFlowStarted) {
                PrivilegedCarbonContext.endTenantFlow();
            }
        }

        if (APIUtil.isAPIGatewayKeyCacheEnabled()) {
            invalidateCachedKeys(applicationId);
        }

        SubscribedAPI addedSubscription = getSubscriptionById(subscriptionId);

        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + identifier.getApiName() + ", API Version "
                    + identifier.getVersion() + ", Subscription Status: " + addedSubscription.getSubStatus()
                    + " subscribe by " + userId + " for app " + applicationName;
            log.debug(logMessage);
        }

        JSONObject subsLogObject = new JSONObject();
        subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getApiName());
        subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
        subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, applicationId);
        subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
        subsLogObject.put(APIConstants.AuditLogConstants.TIER, identifier.getTier());

        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(),
                APIConstants.AuditLogConstants.CREATED, this.username);

        return new SubscriptionResponse(addedSubscription.getSubStatus(), addedSubscription.getUUID(),
                workflowResponse);
    } else {
        throw new APIManagementException(
                "Subscriptions not allowed on APIs in the state: " + api.getStatus().getStatus());
    }
}

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

@Override
public void removeSubscription(APIIdentifier identifier, String userId, int applicationId)
        throws APIManagementException {
    boolean isTenantFlowStarted = false;

    String providerTenantDomain = MultitenantUtils
            .getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));

    String applicationName = apiMgtDAO.getApplicationNameFromId(applicationId);

    try {//from  ww  w. j a v a  2  s . co m
        if (providerTenantDomain != null
                && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(providerTenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(providerTenantDomain, true);
            isTenantFlowStarted = true;
        }

        API api = getAPI(identifier);
        SubscriptionWorkflowDTO workflowDTO;
        WorkflowExecutor createSubscriptionWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
        WorkflowExecutor removeSubscriptionWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
        String workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(identifier,
                applicationId);

        // in a normal flow workflowExtRef is null when workflows are not enabled
        if (workflowExtRef == null) {
            workflowDTO = new SubscriptionWorkflowDTO();
        } else {
            workflowDTO = (SubscriptionWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);

            // set tiername to the workflowDTO only when workflows are enabled
            SubscribedAPI subscription = apiMgtDAO
                    .getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference()));
            workflowDTO.setTierName(subscription.getTier().getName());
        }
        workflowDTO.setApiProvider(identifier.getProviderName());
        workflowDTO.setApiContext(api.getContext());
        workflowDTO.setApiName(identifier.getApiName());
        workflowDTO.setApiVersion(identifier.getVersion());
        workflowDTO.setApplicationName(applicationName);
        workflowDTO.setTenantDomain(tenantDomain);
        workflowDTO.setTenantId(tenantId);
        workflowDTO.setExternalWorkflowReference(workflowExtRef);
        workflowDTO.setSubscriber(userId);
        workflowDTO.setCallbackUrl(removeSubscriptionWFExecutor.getCallbackURL());

        String status = apiMgtDAO.getSubscriptionStatus(identifier, applicationId);
        if (APIConstants.SubscriptionStatus.ON_HOLD.equals(status)) {
            try {
                createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
            } catch (WorkflowException ex) {

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

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

        JSONObject subsLogObject = new JSONObject();
        subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getApiName());
        subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
        subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, applicationId);
        subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);

        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(),
                APIConstants.AuditLogConstants.DELETED, this.username);

    } catch (WorkflowException e) {
        String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION
                + " for apiID " + identifier.getApiName();
        handleException(errorMsg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    if (APIUtil.isAPIGatewayKeyCacheEnabled()) {
        invalidateCachedKeys(applicationId);
    }
    if (log.isDebugEnabled()) {
        String logMessage = "API Name: " + identifier.getApiName() + ", API Version " + identifier.getVersion()
                + " subscription removed from app " + applicationName + " by " + userId;
        log.debug(logMessage);
    }
}

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

/**
 * Add a new Application from the store.
 * @param application - {@link org.wso2.carbon.apimgt.api.model.Application}
 * @param userId - {@link String}//from   w ww. j  a va2  s . co  m
 * @return {@link String}
 */
@Override
public int addApplication(Application application, String userId) throws APIManagementException {

    if (APIUtil.isApplicationExist(userId, application.getName(), application.getGroupId())) {
        handleResourceAlreadyExistsException(
                "A duplicate application already exists by the name - " + application.getName());
    }
    //check whether callback url is empty and set null
    if (StringUtils.isBlank(application.getCallbackUrl())) {
        application.setCallbackUrl(null);
    }
    int applicationId = apiMgtDAO.addApplication(application, userId);

    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.CREATED, this.username);

    boolean isTenantFlowStarted = false;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        isTenantFlowStarted = true;
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    }

    try {

        WorkflowExecutor appCreationWFExecutor = WorkflowExecutorFactory.getInstance()
                .getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        ApplicationWorkflowDTO appWFDto = new ApplicationWorkflowDTO();
        appWFDto.setApplication(application);

        appWFDto.setExternalWorkflowReference(appCreationWFExecutor.generateUUID());
        appWFDto.setWorkflowReference(String.valueOf(applicationId));
        appWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
        appWFDto.setCallbackUrl(appCreationWFExecutor.getCallbackURL());
        appWFDto.setStatus(WorkflowStatus.CREATED);
        appWFDto.setTenantDomain(tenantDomain);
        appWFDto.setTenantId(tenantId);
        appWFDto.setUserName(userId);
        appWFDto.setCreatedTime(System.currentTimeMillis());

        appCreationWFExecutor.execute(appWFDto);
    } catch (WorkflowException e) {
        //If the workflow execution fails, roll back transaction by removing the application entry.
        application.setId(applicationId);
        apiMgtDAO.deleteApplication(application);
        log.error("Unable to execute Application Creation Workflow", e);
        handleException("Unable to execute Application Creation Workflow", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Application Name: " + application.getName() + " added successfully.");
    }

    return applicationId;
}