Example usage for org.json.simple JSONValue toJSONString

List of usage examples for org.json.simple JSONValue toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONValue toJSONString.

Prototype

public static String toJSONString(Object value) 

Source Link

Usage

From source file:org.sakaiproject.lti2.LTI2Service.java

public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    Map<String, Object> deploy = ltiService.getDeployForConsumerKeyDao(profile_id);
    if (deploy == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w w w  .j  av  a2  s.  c  o m*/
    }
    Long deployKey = foorm.getLong(deploy.get(LTIService.LTI_ID));

    // See if we can even register...
    Long reg_state = foorm.getLong(deploy.get(LTIService.LTI_REG_STATE));
    String key = null;
    String secret = null;
    if (reg_state == 0) {
        key = (String) deploy.get(LTIService.LTI_REG_KEY);
        secret = (String) deploy.get(LTIService.LTI_REG_PASSWORD);
    } else {
        key = (String) deploy.get(LTIService.LTI_CONSUMERKEY);
        secret = (String) deploy.get(LTIService.LTI_SECRET);
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }
    // System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Blank out the new shared secret
    security_contract.put(LTI2Constants.SHARED_SECRET, "*********");

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = getToolConsumerProfile(deploy, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Passed all the tests, lets commit this...
    Map<String, Object> deployUpdate = new TreeMap<String, Object>();
    shared_secret = SakaiBLTIUtil.encryptSecret(shared_secret);
    deployUpdate.put(LTIService.LTI_SECRET, shared_secret);

    // Indicate ready to validate and kill the interim info
    deployUpdate.put(LTIService.LTI_REG_STATE, LTIService.LTI_REG_STATE_REGISTERED);
    deployUpdate.put(LTIService.LTI_REG_KEY, "");
    deployUpdate.put(LTIService.LTI_REG_PASSWORD, "");
    if (default_custom != null)
        deployUpdate.put(LTIService.LTI_SETTINGS, default_custom.toString());
    deployUpdate.put(LTIService.LTI_REG_PROFILE, providerProfile.toString());

    M_log.debug("deployUpdate=" + deployUpdate);

    Object obj = ltiService.updateDeployDao(deployKey, deployUpdate);
    boolean success = (obj instanceof Boolean) && ((Boolean) obj == Boolean.TRUE);
    if (!success) {
        M_log.warn(
                "updateDeployDao fail deployKey=" + deployKey + "\nretval=" + obj + "\ndata=" + deployUpdate);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Failed update of deployment=" + deployKey, null);
        return;
    }

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    String serverUrl = ServerConfigurationService.getServerUrl();
    jsonResponse.put(LTI2Constants.JSONLD_ID, resourceUrl + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            resourceUrl + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.debug(jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

From source file:org.sakaiproject.lti2.LTI2Service.java

public void handleResultRequest(HttpServletRequest request, HttpServletResponse response, String sourcedid)
        throws java.io.IOException {
    String allowOutcomes = ServerConfigurationService.getString(SakaiBLTIUtil.BASICLTI_OUTCOMES_ENABLED,
            SakaiBLTIUtil.BASICLTI_OUTCOMES_ENABLED_DEFAULT);
    if (!"true".equals(allowOutcomes)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, null, "Result resources not available", null);
        return;/*  ww w  . j  a  v  a 2s.  com*/
    }

    Object retval = null;
    IMSJSONRequest jsonRequest = null;
    if ("GET".equals(request.getMethod())) {
        retval = SakaiBLTIUtil.getGrade(sourcedid, request, ltiService);
        if (!(retval instanceof Map)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) retval, null);
            return;
        }
        Map grade = (Map) retval;
        Map jsonResponse = new TreeMap();
        Map resultScore = new TreeMap();

        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.RESULT_CONTEXT);
        jsonResponse.put(LTI2Constants.TYPE, StandardServices.RESULT_TYPE);
        jsonResponse.put(LTI2Constants.COMMENT, grade.get(LTI2Constants.COMMENT));
        resultScore.put(LTI2Constants.TYPE, LTI2Constants.GRADE_TYPE_DECIMAL);
        resultScore.put(LTI2Constants.VALUE, grade.get(LTI2Constants.GRADE));
        jsonResponse.put(LTI2Constants.RESULTSCORE, resultScore);
        response.setContentType(StandardServices.RESULT_FORMAT);
        response.setStatus(HttpServletResponse.SC_OK);
        String jsonText = JSONValue.toJSONString(jsonResponse);
        M_log.debug(jsonText);
        PrintWriter out = response.getWriter();
        out.println(jsonText);
    } else if ("PUT".equals(request.getMethod())) {
        retval = "Error parsing input data";
        try {
            jsonRequest = new IMSJSONRequest(request);
            // System.out.println(jsonRequest.getPostBody());
            JSONObject requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
            String comment = (String) requestData.get(LTI2Constants.COMMENT);
            JSONObject resultScore = (JSONObject) requestData.get(LTI2Constants.RESULTSCORE);
            String sGrade = (String) resultScore.get(LTI2Constants.VALUE);
            Double dGrade = new Double(sGrade);
            retval = SakaiBLTIUtil.setGrade(sourcedid, request, ltiService, dGrade, comment);
        } catch (Exception e) {
            retval = "Error: " + e.getMessage();
        }
        if (retval instanceof Boolean && (Boolean) retval) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        retval = "Unsupported operation:" + request.getMethod();
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    if (retval instanceof String) {
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }
}

From source file:org.spigotmc.timings.TimingsExport.java

@Override
public void run() {
    sender.sendMessage(ChatColor.GREEN + "Preparing Timings Report...");

    out.put("data", toObjectMapper(history, new Function<TimingHistory, JSONPair>() {
        @Override//  w w w. ja v  a 2s .c  om
        public JSONPair apply(TimingHistory input) {
            return input.export();
        }
    }));

    String response = null;
    try {
        HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
        con.setDoOutput(true);
        con.setRequestProperty("User-Agent",
                "Spigot/" + Bukkit.getServerName() + "/" + InetAddress.getLocalHost().getHostName());
        con.setRequestMethod("POST");
        con.setInstanceFollowRedirects(false);

        OutputStream request = new GZIPOutputStream(con.getOutputStream()) {
            {
                this.def.setLevel(7);
            }
        };

        request.write(JSONValue.toJSONString(out).getBytes("UTF-8"));
        request.close();

        response = getResponse(con);

        if (con.getResponseCode() != 302) {
            sender.sendMessage(
                    ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage());
            sender.sendMessage(ChatColor.RED + "Check your logs for more information");
            if (response != null) {
                Bukkit.getLogger().log(Level.SEVERE, response);
            }
            return;
        }

        String location = con.getHeaderField("Location");
        sender.sendMessage(ChatColor.GREEN + "View Timings Report: " + location);
        if (!(sender instanceof ConsoleCommandSender)) {
            Bukkit.getLogger().log(Level.INFO, "View Timings Report: " + location);
        }

        if (response != null && !response.isEmpty()) {
            Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response);
        }
    } catch (IOException ex) {
        sender.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information");
        if (response != null) {
            Bukkit.getLogger().log(Level.SEVERE, response);
        }
        Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex);
    }
}

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

@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    // Normally we would look up the deployment descriptor
    if (!TEST_KEY.equals(profile_id)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//from  w  w w  .  j a v  a 2s.c  om
    }

    String key = TEST_KEY;
    String secret = TEST_SECRET;

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }

    System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    ToolProxy toolProxy = null;
    try {
        toolProxy = new ToolProxy(jsonRequest.getPostBody());
        // System.out.println("OBJ:"+toolProxy);
    } catch (Throwable t) {
        t.printStackTrace();
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = toolProxy.getCustom();

    JSONObject security_contract = toolProxy.getSecurityContract();
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    System.out.println("shared_secret=" + shared_secret);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = toolProxy.validateServices(consumer);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = toolProxy.validateCapabilities(consumer);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Pass the profile to the launch process
    PERSIST.put("profile", toolProxy.toString());

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.debug(jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
public void handleResultRequest(HttpServletRequest request, HttpServletResponse response, String sourcedid)
        throws java.io.IOException {
    IMSJSONRequest jsonRequest = null;/*from   ww  w . j a va  2  s  .  co m*/
    String retval = null;
    if ("GET".equals(request.getMethod())) {
        String grade = PERSIST.get("grade");
        String comment = PERSIST.get("comment");

        Map jsonResponse = new TreeMap();
        Map resultScore = new TreeMap();

        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.RESULT_CONTEXT);
        jsonResponse.put(LTI2Constants.TYPE, StandardServices.RESULT_TYPE);
        resultScore.put(LTI2Constants.TYPE, LTI2Constants.GRADE_TYPE_DECIMAL);
        jsonResponse.put(LTI2Constants.COMMENT, grade);
        resultScore.put(LTI2Constants.VALUE, comment);
        jsonResponse.put(LTI2Constants.RESULTSCORE, resultScore);
        response.setContentType(StandardServices.RESULT_FORMAT);
        response.setStatus(HttpServletResponse.SC_OK);
        String jsonText = JSONValue.toJSONString(jsonResponse);
        M_log.debug(jsonText);
        PrintWriter out = response.getWriter();
        out.println(jsonText);
        return;
    } else if ("PUT".equals(request.getMethod())) {
        retval = "Error parsing input data";
        try {
            jsonRequest = new IMSJSONRequest(request);
            // System.out.println(jsonRequest.getPostBody());
            JSONObject requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
            String comment = (String) requestData.get(LTI2Constants.COMMENT);
            JSONObject resultScore = (JSONObject) requestData.get(LTI2Constants.RESULTSCORE);
            String sGrade = (String) resultScore.get(LTI2Constants.VALUE);
            Double dGrade = new Double(sGrade);

            PERSIST.put("comment", comment);
            PERSIST.put("grade", dGrade + "");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            retval = "Error: " + e.getMessage();
        }
    } else {
        retval = "Unsupported operation:" + request.getMethod();
    }

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    doErrorJSON(request, response, jsonRequest, (String) retval, null);
}

From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java

/**
 * This method is to functionality of getting an existing API to API-Provider based
 *
 * @param cx      Rhino context//from   ww  w .j av  a2s .co  m
 * @param thisObj Scriptable object
 * @param args    Passing arguments
 * @param funObj  Function object
 * @return a native array
 * @throws APIManagementException Wrapped exception by org.wso2.carbon.apimgt.api.APIManagementException
 */

public static NativeArray jsFunction_getAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws APIManagementException {
    NativeArray myn = new NativeArray(0);

    if (args == null || !isStringValues(args)) {
        handleException("Invalid number of parameters or their types.");
    }
    String providerName = args[0].toString();
    String providerNameTenantFlow = args[0].toString();
    providerName = APIUtil.replaceEmailDomain(providerName);
    String apiName = args[1].toString();
    String version = args[2].toString();

    APIIdentifier apiId = new APIIdentifier(providerName, apiName, version);
    APIProvider apiProvider = getAPIProvider(thisObj);
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils
                .getTenantDomain(APIUtil.replaceEmailDomainBack(providerNameTenantFlow));
        String userTenantDomain = MultitenantUtils.getTenantDomain(
                APIUtil.replaceEmailDomainBack(((APIProviderHostObject) thisObj).getUsername()));
        if (!tenantDomain.equals(userTenantDomain)) {
            throw new APIManagementException(
                    "Invalid Operation: Cannot access API:" + apiId + "from current tenant.");
        }
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }

        API api = null;
        try {
            api = apiProvider.getAPI(apiId);
        } catch (APIManagementException e) {
            handleException("Cannot find the requested API- " + apiName + "-" + version, e);
        }

        if (api != null) {
            Set<URITemplate> uriTemplates = api.getUriTemplates();

            myn.put(0, myn, checkValue(api.getId().getApiName()));
            myn.put(1, myn, checkValue(api.getDescription()));
            myn.put(2, myn, checkValue(api.getUrl()));
            myn.put(3, myn, checkValue(api.getWsdlUrl()));
            myn.put(4, myn, checkValue(api.getId().getVersion()));
            StringBuilder tagsSet = new StringBuilder("");
            for (int k = 0; k < api.getTags().toArray().length; k++) {
                tagsSet.append(api.getTags().toArray()[k].toString());
                if (k != api.getTags().toArray().length - 1) {
                    tagsSet.append(",");
                }
            }
            myn.put(5, myn, checkValue(tagsSet.toString()));
            StringBuilder tiersSet = new StringBuilder("");
            StringBuilder tiersDisplayNamesSet = new StringBuilder("");
            StringBuilder tiersDescSet = new StringBuilder("");
            Set<Tier> tierSet = api.getAvailableTiers();
            Iterator it = tierSet.iterator();
            int j = 0;
            while (it.hasNext()) {
                Object tierObject = it.next();
                Tier tier = (Tier) tierObject;
                tiersSet.append(tier.getName());
                tiersDisplayNamesSet.append(tier.getDisplayName());
                tiersDescSet.append(tier.getDescription());
                if (j != tierSet.size() - 1) {
                    tiersSet.append(",");
                    tiersDisplayNamesSet.append(",");
                    tiersDescSet.append(",");
                }
                j++;
            }

            myn.put(6, myn, checkValue(tiersSet.toString()));
            myn.put(7, myn, checkValue(api.getStatus().toString()));
            myn.put(8, myn, getWebContextRoot(api.getThumbnailUrl()));
            myn.put(9, myn, api.getContext());
            myn.put(10, myn, checkValue(Long.valueOf(api.getLastUpdated().getTime()).toString()));
            myn.put(11, myn, getSubscriberCount(apiId, thisObj));

            if (uriTemplates.size() != 0) {
                NativeArray uriTempArr = new NativeArray(uriTemplates.size());
                Iterator i = uriTemplates.iterator();
                List<NativeArray> uriTemplatesArr = new ArrayList<NativeArray>();
                while (i.hasNext()) {
                    List<String> utArr = new ArrayList<String>();
                    URITemplate ut = (URITemplate) i.next();
                    utArr.add(ut.getUriTemplate());
                    utArr.add(ut.getMethodsAsString().replaceAll("\\s", ","));
                    utArr.add(ut.getAuthTypeAsString().replaceAll("\\s", ","));
                    utArr.add(ut.getThrottlingTiersAsString().replaceAll("\\s", ","));
                    NativeArray utNArr = new NativeArray(utArr.size());
                    for (int p = 0; p < utArr.size(); p++) {
                        utNArr.put(p, utNArr, utArr.get(p));
                    }
                    uriTemplatesArr.add(utNArr);
                }

                for (int c = 0; c < uriTemplatesArr.size(); c++) {
                    uriTempArr.put(c, uriTempArr, uriTemplatesArr.get(c));
                }

                myn.put(12, myn, uriTempArr);
            }

            myn.put(13, myn, checkValue(api.getSandboxUrl()));
            myn.put(14, myn, checkValue(tiersDescSet.toString()));
            myn.put(15, myn, checkValue(api.getBusinessOwner()));
            myn.put(16, myn, checkValue(api.getBusinessOwnerEmail()));
            myn.put(17, myn, checkValue(api.getTechnicalOwner()));
            myn.put(18, myn, checkValue(api.getTechnicalOwnerEmail()));
            myn.put(19, myn, checkValue(api.getWadlUrl()));
            myn.put(20, myn, checkValue(api.getVisibility()));
            myn.put(21, myn, checkValue(api.getVisibleRoles()));
            myn.put(22, myn, checkValue(api.getVisibleTenants()));
            myn.put(23, myn, checkValue(api.getEndpointUTUsername()));
            myn.put(24, myn, checkValue(api.getEndpointUTPassword()));
            myn.put(25, myn, checkValue(Boolean.toString(api.isEndpointSecured())));
            myn.put(26, myn, APIUtil.replaceEmailDomainBack(checkValue(api.getId().getProviderName())));
            myn.put(27, myn, checkTransport("http", api.getTransports()));
            myn.put(28, myn, checkTransport("https", api.getTransports()));
            Set<APIStore> storesSet = apiProvider.getExternalAPIStores(api.getId());
            if (storesSet != null && storesSet.size() != 0) {
                NativeArray apiStoresArray = new NativeArray(0);
                int i = 0;
                for (APIStore store : storesSet) {
                    NativeObject storeObject = new NativeObject();
                    storeObject.put("name", storeObject, store.getName());
                    storeObject.put("displayName", storeObject, store.getDisplayName());
                    storeObject.put("published", storeObject, store.isPublished());
                    apiStoresArray.put(i, apiStoresArray, storeObject);
                    i++;
                }
                myn.put(29, myn, apiStoresArray);
            }
            myn.put(30, myn, checkValue(api.getInSequence()));
            myn.put(31, myn, checkValue(api.getOutSequence()));

            myn.put(32, myn, checkValue(api.getSubscriptionAvailability()));
            myn.put(33, myn, checkValue(api.getSubscriptionAvailableTenants()));

            //@todo need to handle backword compatibility
            myn.put(34, myn, checkValue(api.getEndpointConfig()));

            myn.put(35, myn, checkValue(api.getResponseCache()));
            myn.put(36, myn, checkValue(Integer.toString(api.getCacheTimeout())));
            myn.put(37, myn, checkValue(tiersDisplayNamesSet.toString()));

            myn.put(38, myn, checkValue(api.getFaultSequence()));

            //todo implement resource load

            if (uriTemplates.size() != 0) {
                JSONArray resourceArray = new JSONArray();
                Iterator i = uriTemplates.iterator();
                List<NativeArray> uriTemplatesArr = new ArrayList<NativeArray>();
                while (i.hasNext()) {
                    JSONObject resourceObj = new JSONObject();
                    URITemplate ut = (URITemplate) i.next();

                    resourceObj.put("url_pattern", ut.getUriTemplate());
                    resourceObj.put("http_verbs", JSONValue.parse(ut.getResourceMap()));

                    resourceArray.add(resourceObj);
                }

                myn.put(40, myn, JSONValue.toJSONString(resourceArray));
            }

            Set<Scope> scopes = api.getScopes();
            JSONArray scopesNative = new JSONArray();
            for (Scope scope : scopes) {
                JSONObject scopeNative = new JSONObject();
                scopeNative.put("id", scope.getId());
                scopeNative.put("key", scope.getKey());
                scopeNative.put("name", scope.getName());
                scopeNative.put("roles", scope.getRoles());
                scopeNative.put("description", scope.getDescription());
                scopesNative.add(scopeNative);
            }
            myn.put(41, myn, scopesNative.toJSONString());
            myn.put(42, myn, checkValue(Boolean.toString(api.isDefaultVersion())));
            myn.put(43, myn, api.getImplementation());
            myn.put(44, myn, APIUtil.writeEnvironmentsToArtifact(api));
            //get new key manager
            KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance();
            Map registeredResource = keyManager.getResourceByApiId(api.getId().toString());
            myn.put(45, myn, JSONObject.toJSONString(registeredResource));
            myn.put(46, myn, checkValue(api.getProductionMaxTps()));
            myn.put(47, myn, checkValue(api.getSandboxMaxTps()));
            myn.put(48, myn, checkValue(Boolean.toString(api.isEndpointAuthDigest())));
            CORSConfiguration corsConfigurationDto = api.getCorsConfiguration();
            if (corsConfigurationDto == null) {
                corsConfigurationDto = new CORSConfiguration(false, Collections.EMPTY_LIST, false,
                        Collections.EMPTY_LIST, Collections.EMPTY_LIST);
            }
            String corsJson = APIUtil.getCorsConfigurationJsonFromDto(corsConfigurationDto);
            myn.put(49, myn, corsJson);

            StringBuilder policiesSet = new StringBuilder("");

            myn.put(50, myn, checkValue(policiesSet.toString()));
            myn.put(51, myn, checkValue(api.getApiLevelPolicy()));

        } else {
            handleException("Cannot find the requested API- " + apiName + "-" + version);
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return myn;
}

From source file:org.wso2.carbon.appmgt.hostobjects.APIStoreHostObject.java

/**
 * Returns the subscription for the given criteria based on the subscription type. e.g. Individual, Enterprise
 * @param cx/*from  w w w.  ja  v  a2 s  .  co m*/
 * @param thisObj
 * @param args
 * @param funObj
 * @return
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 */
public static NativeObject jsFunction_getSubscription(Context cx, Scriptable thisObj, Object[] args,
        Function funObj) throws AppManagementException {

    APIConsumer apiConsumer = getAPIConsumer(thisObj);

    String providerName = (String) args[0];
    providerName = AppManagerUtil.replaceEmailDomain(providerName);
    String apiName = (String) args[1];
    String version = (String) args[2];
    String applicationName = (String) args[3];
    String subscriptionType = (String) args[4];
    String userId = (String) args[5];

    int applicationId = AppManagerUtil.getApplicationId(applicationName, userId);

    APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);

    NativeObject subscriptionToReturn = null;

    try {
        Subscription subscription = apiConsumer.getSubscription(apiIdentifier, applicationId, subscriptionType);

        if (subscription != null) {
            subscriptionToReturn = new NativeObject();

            subscriptionToReturn.put("subscriptionId", subscriptionToReturn, subscription.getSubscriptionId());
            subscriptionToReturn.put("webAppId", subscriptionToReturn, subscription.getWebAppId());
            subscriptionToReturn.put("applicationId", subscriptionToReturn, subscription.getApplicationId());
            subscriptionToReturn.put("subscriptionType", subscriptionToReturn,
                    subscription.getSubscriptionType());
            subscriptionToReturn.put("subscriptionStatus", subscriptionToReturn,
                    subscription.getSubscriptionStatus());
            subscriptionToReturn.put("subscriptionTime", subscriptionToReturn,
                    subscription.getSubscriptionTime());
            subscriptionToReturn.put("subscribedUser", subscriptionToReturn, subscription.getUserId());

            Set<String> trustedIdps = subscription.getTrustedIdps();

            String trustedIdpsJsonString = "[]";
            if (trustedIdps != null) {
                JSONArray jsonArray = new JSONArray();

                for (String idp : trustedIdps) {
                    jsonArray.add(idp);
                }

                trustedIdpsJsonString = JSONValue.toJSONString(jsonArray);
            }

            subscriptionToReturn.put("trustedIdps", subscriptionToReturn, trustedIdpsJsonString);

        }

        return subscriptionToReturn;

    } catch (AppManagementException e) {
        handleException("Error while getting subscription", e);
        return null;
    }

}

From source file:org.wso2.carbon.appmgt.impl.dao.AppMDAO.java

/**
 * returns the application related data against the given application
 *
 * @param appContext/*from  w  w  w. j  a v  a 2s. c om*/
 * @param appVersion
 * @param consumer
 * @param authenticatedIDPs
 * @return application related data
 * @throws AppManagementException
 */
public APIKeyValidationInfoDTO getApplicationData(String appContext, String appVersion, String consumer,
        AuthenticatedIDP[] authenticatedIDPs) throws AppManagementException {
    Connection connection = null;
    APIKeyValidationInfoDTO info = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        boolean hasValidSubscription = false;
        boolean isSelfSubscriptionEnabled = ServiceReferenceHolder.getInstance()
                .getAPIManagerConfigurationService().getAPIManagerConfiguration().isSelfSubscriptionEnabled();
        boolean isEnterpriseSubscriptionEnabled = ServiceReferenceHolder.getInstance()
                .getAPIManagerConfigurationService().getAPIManagerConfiguration()
                .isEnterpriseSubscriptionEnabled();
        Subscription subscription = null;

        if (isSelfSubscriptionEnabled) {
            subscription = getIndividualSubscription(consumer, appContext, appVersion, connection);
            // If there is an individual subscription proceed with it.
            if (subscription != null) {
                hasValidSubscription = true;
            } else if (isEnterpriseSubscriptionEnabled) {
                if (authenticatedIDPs != null) {
                    subscription = getEnterpriseSubscription(appContext, appVersion, connection);
                    // If there is an enterprise subscription for this app and the authenticated IDP is a trusted
                    // IDP, proceed.
                    if (subscription != null && subscription.isTrustedIdp(authenticatedIDPs)) {
                        hasValidSubscription = true;
                    }
                }
            }
        } else if (!isSelfSubscriptionEnabled) {
            if (isEnterpriseSubscriptionEnabled) {
                if (authenticatedIDPs != null) {
                    subscription = getEnterpriseSubscription(appContext, appVersion, connection);
                    // If there is an enterprise subscription for this app and the authenticated IDP is a trusted
                    // IDP, proceed.
                    if (subscription != null && subscription.isTrustedIdp(authenticatedIDPs)) {
                        hasValidSubscription = true;
                    }
                }
            } else {
                hasValidSubscription = true;
            }
        }

        // If there is no either an individual subscription or an enterprise subscription, don't authorize;
        info = new APIKeyValidationInfoDTO();

        if (!hasValidSubscription) {
            info.setValidationStatus(AppMConstants.API_AUTH_FORBIDDEN);
            info.setAuthorized(false);
            return info;
        }

        // Get App info from the database.
        WebApp webApp = getWebApp(appContext, appVersion, connection);

        info.setApiName(webApp.getId().getApiName());
        info.setApiVersion(webApp.getId().getVersion());
        info.setApiPublisher(webApp.getId().getProviderName());
        info.setTier(AppMConstants.UNLIMITED_TIER);
        info.setContext(appContext);
        info.setLogoutURL(webApp.getLogoutURL());

        if (isEnterpriseSubscriptionEnabled) {
            // Set trusted IDPs.
            info.setTrustedIdp(JSONValue.toJSONString(subscription.getTrustedIdps()));
        }

        info.setAuthorized(true);
        if (isSelfSubscriptionEnabled || isEnterpriseSubscriptionEnabled) {
            // Validate the subscription status.
            String subscriptionStatus = subscription.getSubscriptionStatus();

            if (subscriptionStatus.equals(AppMConstants.SubscriptionStatus.BLOCKED)) {
                info.setValidationStatus(AppMConstants.KeyValidationStatus.API_BLOCKED);
                info.setAuthorized(false);
            } else if (AppMConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus)
                    || AppMConstants.SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
                info.setValidationStatus(AppMConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
                info.setAuthorized(false);
            }
        }

    } catch (SQLException e) {
        handleException("Error while getting WebApp data for : " + appContext + "-" + appVersion, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(null, connection, null);
    }
    return info;
}

From source file:org.wso2.carbon.event.processor.core.internal.storm.TopologyManager.java

public static void submitTopology(ExecutionPlanConfiguration configuration, List<String> importStreams,
        List<String> exportStreams, int tenantId, int resubmitRetryInterval)
        throws StormDeploymentException, ExecutionPlanConfigurationException {
    String executionPlanName = configuration.getName();
    TopologyBuilder builder;/*from ww w.j a  va 2s  . c om*/
    try {
        Document document = StormQueryPlanBuilder.constructStormQueryPlanXML(configuration, importStreams,
                exportStreams);
        String stormQueryPlan = getStringQueryPlan(document);
        if (log.isDebugEnabled()) {
            log.debug("Following is the generated Storm query plan for execution plan: "
                    + configuration.getName() + "\n" + stormQueryPlan);
        }
        builder = StormTopologyConstructor.constructTopologyBuilder(stormQueryPlan, executionPlanName, tenantId,
                EventProcessorValueHolder.getStormDeploymentConfig());
    } catch (XMLStreamException e) {
        throw new StormDeploymentException(
                "Invalid Config for Execution Plan " + executionPlanName + " for tenant " + tenantId, e);
    } catch (TransformerException e) {
        throw new StormDeploymentException("Error while converting to storm query plan string. "
                + "Execution plan: " + executionPlanName + " Tenant: " + tenantId, e);
    } catch (StormQueryConstructionException e) {
        throw new StormDeploymentException("Error while converting to XML storm query plan. "
                + "Execution plan: " + executionPlanName + " Tenant: " + tenantId + ". " + e.getMessage(), e);
    }

    String uploadedJarLocation = StormSubmitter.submitJar(stormConfig, jarLocation);

    try {
        String jsonConf = JSONValue.toJSONString(stormConfig);
        client.submitTopology(getTopologyName(executionPlanName, tenantId), uploadedJarLocation, jsonConf,
                builder.createTopology());
        log.info(
                "Successfully submitted storm topology '" + getTopologyName(executionPlanName, tenantId) + "'");

        waitForTopologyToBeActive(getTopologyName(executionPlanName, tenantId));
    } catch (AlreadyAliveException e) {
        log.warn("Topology '" + getTopologyName(executionPlanName, tenantId) + "' already existing", e);
        Thread retryThread = new Thread(new TopologySubmitter(executionPlanName, uploadedJarLocation,
                builder.createTopology(), tenantId, true, resubmitRetryInterval));
        retryThread.start();
    } catch (TException e) {
        log.warn("Error connecting to storm when trying to submit topology '"
                + getTopologyName(executionPlanName, tenantId) + "'", e);
        Thread retryThread = new Thread(new TopologySubmitter(executionPlanName, uploadedJarLocation,
                builder.createTopology(), tenantId, false, resubmitRetryInterval));
        retryThread.start();
    } catch (InvalidTopologyException e) {
        // No point in retrying to submit if the topology is invalid. Therefore, throwing an exception without retrying.
        throw new ExecutionPlanConfigurationException(
                "Invalid Execution Plan " + executionPlanName + " for tenant " + tenantId, e);
    }
}

From source file:pgentity.Gift.java

@Override
public void saveToDB() {
    Map<String, String> data = new HashMap(2);

    data.put(PGMacro.GIFT_PRIZE, JSONValue.toJSONString(prizeData));
    data.put(PGMacro.GIFT_EXPIRED_TIME, String.valueOf(this.expiredTime));

    DBContext.Redis().hset(redisKey, data);
}