Java Code Examples for org.json.simple.JSONObject#toString()

The following examples show how to use org.json.simple.JSONObject#toString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static String getKeySetJSON(Map<String, RSAPublicKey> keys)
		throws java.security.NoSuchAlgorithmException {
	JSONArray jar = new JSONArray();

	for (Map.Entry<String, RSAPublicKey> entry : keys.entrySet()) {
		RSAPublicKey key = (RSAPublicKey) entry.getValue();
		com.nimbusds.jose.jwk.RSAKey rsaKey = new com.nimbusds.jose.jwk.RSAKey.Builder(key).algorithm(JWSAlgorithm.RS256).build();
		String keyStr = rsaKey.toJSONString();

		JSONObject kobj = (JSONObject) JSONValue.parse(keyStr);
		kobj.put("kid", (String) entry.getKey());
		kobj.put("use", "sig");
		jar.add(kobj);
	}

	JSONObject keyset = new JSONObject();
	keyset.put("keys", jar);

	String keySetJSON = keyset.toString();
	return keySetJSON;
}
 
Example 2
/**
 * Adds a key to a given Application
 *
 * @param username    User for import application
 * @param application Application used to add key
 * @param apiKey      API key for adding to application
 * @throws APIManagementException
 */
public void addApplicationKey(String username, Application application, APIKey apiKey) throws APIManagementException {
    String[] accessAllowDomainsArray = {"ALL"};
    JSONObject jsonParamObj = new JSONObject();
    jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
    String grantTypes = apiKey.getGrantTypes();
    if (!StringUtils.isEmpty(grantTypes)) {
        jsonParamObj.put(APIConstants.JSON_GRANT_TYPES, grantTypes);
    }
    /* Read clientId & clientSecret from ApplicationKeyGenerateRequestDTO object.
       User can provide clientId only or both clientId and clientSecret
       User cannot provide clientSecret only
     */
    if (!StringUtils.isEmpty(apiKey.getConsumerKey())) {
        jsonParamObj.put(APIConstants.JSON_CLIENT_ID, apiKey.getConsumerKey());
        if (!StringUtils.isEmpty(apiKey.getConsumerSecret())) {
            jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, apiKey.getConsumerSecret());
        }
    }
    String jsonParams = jsonParamObj.toString();
    String tokenScopes = apiKey.getTokenScope();
    apiConsumer.requestApprovalForApplicationRegistration(
            username, application.getName(), apiKey.getType(), apiKey.getCallbackUrl(),
            accessAllowDomainsArray, Long.toString(apiKey.getValidityPeriod()), tokenScopes, application.getGroupId(),
            jsonParams,apiKey.getKeyManager());
}
 
Example 3
public static String getKeySetJSON(Map<String, RSAPublicKey> keys)
		throws java.security.NoSuchAlgorithmException {
	JSONArray jar = new JSONArray();

	for (Map.Entry<String, RSAPublicKey> entry : keys.entrySet()) {
		RSAPublicKey key = (RSAPublicKey) entry.getValue();
		com.nimbusds.jose.jwk.RSAKey rsaKey = new com.nimbusds.jose.jwk.RSAKey.Builder(key).algorithm(JWSAlgorithm.RS256).build();
		String keyStr = rsaKey.toJSONString();

		JSONObject kobj = (JSONObject) JSONValue.parse(keyStr);
		kobj.put("kid", (String) entry.getKey());
		kobj.put("use", "sig");
		jar.add(kobj);
	}

	JSONObject keyset = new JSONObject();
	keyset.put("keys", jar);

	String keySetJSON = keyset.toString();
	return keySetJSON;
}
 
Example 4
/**
 * Adds a key to a given Application
 *
 * @param username    User for import application
 * @param application Application used to add key
 * @param apiKey      API key for adding to application
 * @throws APIManagementException
 */
public void addApplicationKey(String username, Application application, APIKey apiKey) throws APIManagementException {
    String[] accessAllowDomainsArray = {"ALL"};
    JSONObject jsonParamObj = new JSONObject();
    jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
    String grantTypes = apiKey.getGrantTypes();
    if (!StringUtils.isEmpty(grantTypes)) {
        jsonParamObj.put(APIConstants.JSON_GRANT_TYPES, grantTypes);
    }
    /* Read clientId & clientSecret from ApplicationKeyGenerateRequestDTO object.
       User can provide clientId only or both clientId and clientSecret
       User cannot provide clientSecret only
     */
    if (!StringUtils.isEmpty(apiKey.getConsumerKey())) {
        jsonParamObj.put(APIConstants.JSON_CLIENT_ID, apiKey.getConsumerKey());
        if (!StringUtils.isEmpty(apiKey.getConsumerSecret())) {
            jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, apiKey.getConsumerSecret());
        }
    }
    String jsonParams = jsonParamObj.toString();
    String tokenScopes = apiKey.getTokenScope();
    String keyManager = apiKey.getKeyManager();
    apiConsumer.requestApprovalForApplicationRegistration(
            username, application.getName(), apiKey.getType(), apiKey.getCallbackUrl(),
            accessAllowDomainsArray, Long.toString(apiKey.getValidityPeriod()), tokenScopes, application.getGroupId(),
            jsonParams, keyManager);
}
 
Example 5
private String post(String urlString, JSONObject content) {
    try {
        HttpPost httpost = new HttpPost(urlString);
        httpost.setHeader("Authorization","Bearer " + accessToken);
      
        StringEntity params = new StringEntity(content.toString());
        httpost.addHeader("content-type", "application/json");
        httpost.setEntity(params);
        LOGGER.log(Level.INFO, "Params: {0}", params);
        
        HttpResponse response = httpClient.execute(httpost, httpContext);

        LOGGER.log(Level.INFO, "Response code {0}", response.getStatusLine().getStatusCode());
        for (Header header : response.getAllHeaders()) {
            LOGGER.log(Level.INFO, "Response header ({0}:{1})", new Object[]{header.getName(), header.getValue()});
        }

        HttpEntity entity = response.getEntity();
        String text = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return text;
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error", e);
    }

    return null;
}
 
Example 6
Source Project: BiglyBT   File: EngineImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String
exportToJSONString()

	throws IOException
{
	JSONObject	obj = new JSONObject();

	exportToJSONObject( obj );

	return( obj.toString());
}
 
Example 7
@SuppressWarnings("unchecked")
@Override
public String createInputJSON(String question) {
	JSONObject json = new JSONObject();
	
	json.put("queryRequestString", question);
	JSONArray components = new JSONArray();
	json.put("components", components);
	json.put("requiresQueryBuilding", true);
	JSONArray tasks = new JSONArray();
	json.put("conf", tasks);

	return json.toString();
}
 
Example 8
@SuppressWarnings("unchecked")
@Override
public String createInputJSON(String question) {
	JSONObject json = new JSONObject();	
	json.put("question", question);
	json.put("simplified_npparser", 1);
	return json.toString();
}
 
Example 9
Source Project: carbon-apimgt   File: SelfSignUpUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to get the consent purposes
 *
 * @param tenantDomain tenant domain
 * @return A json string containing consent purposes
 * @throws APIManagementException APIManagement Exception
 * @throws IOException            IO Exception
 * @throws ParseException         Parse Exception
 */
public static String getConsentPurposes(String tenantDomain)
        throws APIManagementException, IOException, ParseException {
    String tenant = tenantDomain;
    String purposesEndpoint;
    String purposesJsonString = "";
    if (tenant == null) {
        tenant = APIConstants.SUPER_TENANT_DOMAIN;
    }
    purposesEndpoint = getPurposesEndpoint(tenant);
    String purposesResponse = executeGet(purposesEndpoint, tenantDomain);
    JSONParser parser = new JSONParser();
    JSONArray purposes = (JSONArray) parser.parse(purposesResponse);
    JSONArray purposesResponseArray = new JSONArray();
    for (int purposeIndex = 0; purposeIndex < purposes.size(); purposeIndex++) {
        JSONObject purpose = (JSONObject) purposes.get(purposeIndex);
        if (!isDefaultPurpose(purpose)) {
            purpose = retrievePurpose(((Long) purpose.get(PURPOSE_ID)).intValue(), tenant);
            if (hasPIICategories(purpose)) {
                purposesResponseArray.add(purpose);
            }
        }
    }
    if (!purposesResponseArray.isEmpty()) {
        JSONObject purposesJson = new JSONObject();
        purposesJson.put(PURPOSES, purposesResponseArray);
        purposesJsonString = purposesJson.toString();
    }
    return purposesJsonString;
}
 
Example 10
/**
 * Simulate transfer of MSubmission structure using SubmissionBean
 *
 * @param submission Submission to transfer
 * @return
 */
private MSubmission transfer(MSubmission submission) {
  SubmissionsBean bean = new SubmissionsBean(submission);
  JSONObject json = bean.extract(false);

  String string = json.toString();

  JSONObject retrievedJson = JSONUtils.parse(string);
  SubmissionsBean retrievedBean = new SubmissionsBean();
  retrievedBean.restore(retrievedJson);

  return retrievedBean.getSubmissions().get(0);
}
 
Example 11
/**
 * Simulate transfer of a list of MSubmission structures using SubmissionBean
 *
 * @param submissions Submissions to transfer
 * @return
 */
private List<MSubmission> transfer(List<MSubmission> submissions) {
  SubmissionsBean bean = new SubmissionsBean(submissions);
  JSONObject json = bean.extract(false);

  String string = json.toString();

  JSONObject retrievedJson = JSONUtils.parse(string);
  SubmissionsBean retrievedBean = new SubmissionsBean();
  retrievedBean.restore(retrievedJson);

  return retrievedBean.getSubmissions();
}
 
Example 12
@SuppressWarnings("unchecked")
private static String convertArrayToJsonString(String[] infoArray) {
	// Depending on prefered formating, use of temp is not necessary.
	final JSONObject temp = new JSONObject();
	final JSONObject jObj = new JSONObject();
	final int length = infoArray.length;
	for (int i = 1; i < length - 1; i += 2) {
		final int y = i + 1;
		temp.put(infoArray[i].trim(), infoArray[y].trim());
	}
	// Name of the cpu is always located first in the array.
	jObj.put(infoArray[0], temp);
	return jObj.toString();
}
 
Example 13
@Test
	public void testRSAFromString() throws
			NoSuchAlgorithmException, NoSuchProviderException, java.security.spec.InvalidKeySpecException {
		String serialized = "-----BEGIN PUBLIC KEY-----\n"
				+ "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApgviDRUN1Z6hIOBg5uj1k\n"
				+ "KSJjfJjayEJeJR7A06sm5K4QjYKYMve55LaD8CMqf98l/gnZ0vIaCuf4G9mkphc/y\n"
				+ "V0cgFY65wQmecPxv3IZ77wbJ+g5lL5vuCVTbh55nD++cj/hSBznXecQTXQNV9d51r\n"
				+ "Ca65+PQ+YL1oRnrpUuLNPbdnc8kT/ZUq5Ic0WJM+NprN1tbbn2LafBY+igqbRQVox\n"
				+ "It75B8cd+35iQAUm8B4sw8zGs1bFpBy3A8rhCYcBAOdK2iSSudK2WEfW1E7RWnnNv\n"
				+ "w3ykMoVh1pq7zwL4P0IHXevvPnja+PmAT9zTwgU8WhiiIKl7YtJzkR9pEWtTwIDAQ\n"
				+ "AB\n"
				+ "-----END PUBLIC KEY-----";

		Key publicKey = LTI13Util.string2PublicKey(serialized);
		// Cast
		RSAPublicKey rsaPublic = (RSAPublicKey) publicKey;

		com.nimbusds.jose.jwk.RSAKey rsaKey = new com.nimbusds.jose.jwk.RSAKey.Builder(rsaPublic).build();
		String keyStr = rsaKey.toJSONString();

		JSONArray jar = new JSONArray();
		JSONObject kobj = (JSONObject) JSONValue.parse(keyStr);
		jar.add(kobj);
		JSONObject keyset = new JSONObject();
		keyset.put("keys", jar);

		String keysetJSON = keyset.toString();
		/*
{"keys":[{"kty":"RSA","e":"AQAB","n":"pgviDRUN1Z6hIOBg5uj1kKSJjfJjayEJeJR7A06sm5K4QjYKYMve55LaD8CMqf98l_gnZ0vIaCuf4G9mkphc_yV0cgFY65wQmecPxv3IZ77wbJ-g5lL5vuCVTbh55nD--cj_hSBznXecQTXQNV9d51rCa65-PQ-YL1oRnrpUuLNPbdnc8kT_ZUq5Ic0WJM-NprN1tbbn2LafBY-igqbRQVoxIt75B8cd-35iQAUm8B4sw8zGs1bFpBy3A8rhCYcBAOdK2iSSudK2WEfW1E7RWnnNvw3ykMoVh1pq7zwL4P0IHXevvPnja-PmAT9zTwgU8WhiiIKl7YtJzkR9pEWtTw"}]}
		 */
		boolean good = keysetJSON.contains("{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",");
		if (!good) {
			System.out.println("keyset JSON is bad\n");
			System.out.println(keysetJSON);
		}
		assertTrue(good);
	}
 
Example 14
public String toJson() {

        JSONObject tokenResponse = new JSONObject();
        tokenResponse.put(CellerySTSConstants.CellerySTSResponse.STS_TOKEN, stsToken);
        return tokenResponse.toString();
    }
 
Example 15
private static String toMessage(Object data, String action) {
    JSONObject msg = new JSONObject();
    msg.put("DATA", data);
    msg.put("res", action);
    return msg.toString();
}
 
Example 16
public String toString() {
    JSONObject obj = new JSONObject();
    obj.put(ApiApplicationConstants.OAUTH_CLIENT_ID, this.getConsumerKey());
    obj.put(ApiApplicationConstants.OAUTH_CLIENT_SECRET, this.getConsumerSecret());
    return obj.toString();
}
 
Example 17
/**
 * Generate keys for a application
 *
 * @param applicationId     application identifier
 * @param body              request body
 * @return A response object containing application keys
 */
@Override
public Response applicationsApplicationIdGenerateKeysPost(String applicationId, ApplicationKeyGenerateRequestDTO
        body, MessageContext messageContext) throws APIManagementException {

    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
                String[] accessAllowDomainsArray = {"ALL"};
                JSONObject jsonParamObj = new JSONObject();
                jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
                String grantTypes = StringUtils.join(body.getGrantTypesToBeSupported(), ',');
                if (!StringUtils.isEmpty(grantTypes)) {
                    jsonParamObj.put(APIConstants.JSON_GRANT_TYPES, grantTypes);
                }
                /* Read clientId & clientSecret from ApplicationKeyGenerateRequestDTO object.
                   User can provide clientId only or both clientId and clientSecret
                   User cannot provide clientSecret only */
                if (!StringUtils.isEmpty(body.getClientId())) {
                    jsonParamObj.put(APIConstants.JSON_CLIENT_ID, body.getClientId());
                    if (!StringUtils.isEmpty(body.getClientSecret())) {
                        jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, body.getClientSecret());
                    }
                }

                if (body.getAdditionalProperties() != null) {
                    if (body.getAdditionalProperties() instanceof String &&
                            StringUtils.isNotEmpty((String) body.getAdditionalProperties())) {
                        jsonParamObj.put(APIConstants.JSON_ADDITIONAL_PROPERTIES, body.getAdditionalProperties());
                    } else if (body.getAdditionalProperties() instanceof Map) {
                        String jsonContent = new Gson().toJson(body.getAdditionalProperties());
                        jsonParamObj.put(APIConstants.JSON_ADDITIONAL_PROPERTIES, jsonContent);
                    }
                }
                String jsonParams = jsonParamObj.toString();
                String tokenScopes = StringUtils.join(body.getScopes(), " ");
                String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
                if (StringUtils.isNotEmpty(body.getKeyManager())) {
                    keyManagerName = body.getKeyManager();
                }
                Map<String, Object> keyDetails = apiConsumer.requestApprovalForApplicationRegistration(
                        username, application.getName(), body.getKeyType().toString(), body.getCallbackUrl(),
                        accessAllowDomainsArray, body.getValidityTime(), tokenScopes, application.getGroupId(),
                        jsonParams, keyManagerName);
                ApplicationKeyDTO applicationKeyDTO =
                        ApplicationKeyMappingUtil.fromApplicationKeyToDTO(keyDetails, body.getKeyType().toString());
                applicationKeyDTO.setKeyManager(keyManagerName);
                return Response.ok().entity(applicationKeyDTO).build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (EmptyCallbackURLForCodeGrantsException e) {
        RestApiUtil.handleBadRequest(e.getMessage(), log);
    }
    return null;
}
 
Example 18
public void run() {

        JSONObject jsonObMap = new JSONObject();

        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                .getAxis2MessageContext();
        //Set transport headers of the message
        TreeMap<String, String> transportHeaderMap = (TreeMap<String, String>) axis2MessageContext
                .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);


        String remoteIP = GatewayUtils.getIp(axis2MessageContext);
        if (log.isDebugEnabled()) {
            log.debug("Remote IP address : " + remoteIP);
        }

        if (remoteIP != null && remoteIP.length() > 0) {
            try {
                InetAddress address = APIUtil.getAddress(remoteIP);
                if (address instanceof Inet4Address) {
                    jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(remoteIP));
                    jsonObMap.put(APIThrottleConstants.IPv6, 0);
                } else if (address instanceof Inet6Address) {
                    jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(remoteIP));
                    jsonObMap.put(APIThrottleConstants.IP, 0);
                }
            } catch (UnknownHostException e) {
                //send empty value as ip
                log.error("Error while parsing host IP " + remoteIP, e);
                jsonObMap.put(APIThrottleConstants.IPv6, 0);
                jsonObMap.put(APIThrottleConstants.IP, 0);
            }
        }

        //HeaderMap will only be set if the Header Publishing has been enabled.
        if (this.headersMap != null) {
            jsonObMap.putAll(this.headersMap);
        }

        //Setting query parameters
        if (getThrottleProperties().isEnableQueryParamConditions()) {
            Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext);
            if (queryParams != null) {
                jsonObMap.putAll(queryParams);
            }

        }

        //Publish jwt claims
        if (getThrottleProperties().isEnableJwtConditions()) {
            if (authenticationContext.getCallerToken() != null) {
                Map assertions = GatewayUtils.getJWTClaims(authenticationContext);
                if (assertions != null) {
                    jsonObMap.putAll(assertions);
                }
            }
        }

        //this parameter will be used to capture message size and pass it to calculation logic
        
        ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
        boolean isVerbInfoContentAware = false;
        if (list != null && !list.isEmpty()) {
            VerbInfoDTO verbInfoDTO = list.get(0);
            isVerbInfoContentAware = verbInfoDTO.isContentAware();
        }

        if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
            if (log.isDebugEnabled()) {
                log.debug("Message size: " + messageSizeInBytes + "B");
            }
            jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes);
            if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) {
                jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName());
            }
            if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils
                    .isEmpty(authenticationContext.getProductProvider())) {
                jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE);
            } else {
                jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE);
            }

        }

        Object[] objects = new Object[]{messageContext.getMessageID(),
                                        this.applicationLevelThrottleKey, this.applicationLevelTier,
                                        this.apiLevelThrottleKey, this.apiLevelTier,
                                        this.subscriptionLevelThrottleKey, this.subscriptionLevelTier,
                                        this.resourceLevelThrottleKey, this.resourceLevelTier,
                                        this.authorizedUser, this.apiContext, this.apiVersion,
                                        this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString()};
        org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID,
                                                                                                      System.currentTimeMillis(), null, null, objects);
        dataPublisher.tryPublish(event);
    }
 
Example 19
Source Project: BiglyBT   File: JSONUtils.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * Encodes a map into a JSON formatted string.
 * <p>
 * Handles multiple layers of Maps and Lists.  Handls String, Number,
 * Boolean, and null values.
 *
 * @param map Map to change into a JSON formatted string
 * @return JSON formatted string
 *
 * @since 3.0.1.5
 */
public static String encodeToJSON(Map map) {
	JSONObject jobj = encodeToJSONObject(map);
	StringBuilder	sb = new StringBuilder(8192);
	jobj.toString( sb );
	return( sb.toString());
}
 
Example 20
Source Project: yes-cart   File: LiqPay.java    License: Apache License 2.0 3 votes vote down vote up
@SuppressWarnings("unchecked")
public HashMap<String, Object> api(String path, HashMap<String, String> list) throws Exception{

    JSONObject json = new JSONObject();

    json.put("public_key", pub_key);

    for (Map.Entry<String, String> entry: list.entrySet())
        json.put(entry.getKey(), entry.getValue());

    String dataJson = json.toString();
    String signature = LiqPayUtil.base64_encode( LiqPayUtil.sha1( priv_key + dataJson + priv_key) );

    HashMap<String, String> data = new HashMap<String, String>();
    data.put("data", dataJson);
    data.put("signature", signature);
    String resp = LiqPayRequest.post(host + path, data, this);

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(resp);
    JSONObject jsonObj = (JSONObject) obj;

    HashMap<String, Object> res_json = LiqPayUtil.parseJson(jsonObj);

    return res_json;

}