Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:fi.elfcloud.sci.container.Cluster.java

public Cluster(Client client, JSONObject object) throws JSONException {
    this.client = client;
    this.id = object.getInt("id");
    this.name = object.getString("name");
    this.childCount = object.getInt("descendants");
    this.dataItemCount = object.getInt("dataitems");
    this.parent_id = object.getInt("parent_id");
    this.last_accessed_date = (object.get("last_accessed_date") != JSONObject.NULL
            ? object.getString("last_accessed_date")
            : "");
    this.last_modified_date = (object.get("modified_date") != JSONObject.NULL
            ? object.getString("modified_date")
            : "");
    this.permissions = object.getJSONArray("permissions");
}

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleMapSerializer.java

@SuppressWarnings("unchecked")
@Override/*w  w w.  j av  a2s .co  m*/
public Object unmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException {
    Map map = null;
    try {
        try {
            try {
                if (clazz.isInterface()) {
                    map = new java.util.HashMap();
                } else
                    map = (Map) clazz.newInstance();
            } catch (ClassCastException cce) {
                throw new UnmarshallException("invalid unmarshalling Class " + cce.getMessage());
            }
        } catch (IllegalAccessException iae) {
            throw new UnmarshallException("no access unmarshalling object " + iae.getMessage());
        }
    } catch (InstantiationException ie) {
        throw new UnmarshallException("unable to instantiate unmarshalling object " + ie.getMessage());
    }
    JSONObject jso = (JSONObject) o;
    Iterator keys = jso.keys();
    state.setSerialized(o, map);
    try {
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, ser.unmarshall(state, null, jso.get(key)));
        }
    } catch (JSONException je) {
        throw new UnmarshallException("Could not read map: " + je.getMessage());
    }

    return map;
}

From source file:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * Connect method which is generating authentication of the connector for each request.
 *
 * @param messageContext ESB messageContext.
 * @throws java.io.UnsupportedEncodingException
 * @throws IllegalStateException /* w w  w .j av  a 2s  . c om*/
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.InvalidKeyException
 * @throws JSONException 
 */
public final Map<String, String> getRequestPayload(final JSONObject signatureRequestObject)
        throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException,
        UnsupportedEncodingException, JSONException {

    final StringBuilder canonicalRequest = new StringBuilder();
    final StringBuilder stringToSign = new StringBuilder();
    final StringBuilder payloadBuilder = new StringBuilder();
    final StringBuilder payloadStrBuilder = new StringBuilder();
    final StringBuilder authHeader = new StringBuilder();
    init(signatureRequestObject);

    // Generate time-stamp which will be sent to API and to be used in Signature
    final Date date = new Date();
    final TimeZone timeZone = TimeZone.getTimeZone(AmazonSQSConstants.GMT);
    final DateFormat dateFormat = new SimpleDateFormat(AmazonSQSConstants.ISO8601_BASIC_DATE_FORMAT);
    dateFormat.setTimeZone(timeZone);
    final String amzDate = dateFormat.format(date);

    final DateFormat shortDateFormat = new SimpleDateFormat(AmazonSQSConstants.SHORT_DATE_FORMAT);
    shortDateFormat.setTimeZone(timeZone);
    final String shortDate = shortDateFormat.format(date);

    signatureRequestObject.put(AmazonSQSConstants.AMZ_DATE, amzDate);
    final Map<String, String> parameterNamesMap = getParameterNamesMap();
    final Map<String, String> parametersMap = getSortedParametersMap(signatureRequestObject, parameterNamesMap);
    canonicalRequest.append(signatureRequestObject.get(AmazonSQSConstants.HTTP_METHOD));
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    final String charSet = Charset.defaultCharset().toString();
    if (signatureRequestObject.has(AmazonSQSConstants.URL_QUEUE_NAME)
            && !("").equals(signatureRequestObject.get(AmazonSQSConstants.URL_QUEUE_NAME))
            && signatureRequestObject.has(AmazonSQSConstants.QUEUE_ID)
            && !("").equals(signatureRequestObject.get(AmazonSQSConstants.QUEUE_ID))) {
        // queue ID and queue name should be encoded twise to match the Signature being generated by API,
        // Note that API it looks encodes the incoming URL once before creating the signature, SInce
        // we send url encoded URLs, API signatures are twise encoded
        final String encodedQueueID = URLEncoder
                .encode(signatureRequestObject.get(AmazonSQSConstants.QUEUE_ID).toString(), charSet);
        final String encodedQueueName = URLEncoder
                .encode(signatureRequestObject.get(AmazonSQSConstants.URL_QUEUE_NAME).toString(), charSet);
        canonicalRequest.append((AmazonSQSConstants.FORWARD_SLASH + URLEncoder.encode(encodedQueueID, charSet)
                + AmazonSQSConstants.FORWARD_SLASH + URLEncoder.encode(encodedQueueName, charSet)
                + AmazonSQSConstants.FORWARD_SLASH).replaceAll(AmazonSQSConstants.REGEX_ASTERISK,
                        AmazonSQSConstants.URL_ENCODED_ASTERISK));
        // Sets the http request Uri to message context 
        signatureRequestObject.put(AmazonSQSConstants.HTTP_REQUEST_URI,
                AmazonSQSConstants.FORWARD_SLASH + encodedQueueID + AmazonSQSConstants.FORWARD_SLASH
                        + encodedQueueName + AmazonSQSConstants.FORWARD_SLASH);
    } else {
        canonicalRequest.append(AmazonSQSConstants.FORWARD_SLASH);
    }

    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);

    final Set<String> keySet = parametersMap.keySet();
    for (String key : keySet) {
        payloadBuilder.append(URLEncoder.encode(key, charSet));
        payloadBuilder.append(AmazonSQSConstants.EQUAL);
        payloadBuilder.append(URLEncoder.encode(parametersMap.get(key), charSet));
        payloadBuilder.append(AmazonSQSConstants.AMPERSAND);
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(key);
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(AmazonSQSConstants.COLON);
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(parametersMap.get(key));
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(AmazonSQSConstants.COMMA);

    }
    // Adds authorization header to message context, removes additionally appended comma at the end
    if (payloadStrBuilder.length() > 0) {
        signatureRequestObject.put(AmazonSQSConstants.REQUEST_PAYLOAD,
                payloadStrBuilder.substring(0, payloadStrBuilder.length() - 1));
    }
    // Appends empty string since no URL parameters are used in POST API requests
    canonicalRequest.append("");
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    final Map<String, String> headersMap = getSortedHeadersMap(signatureRequestObject, parameterNamesMap);
    final StringBuilder canonicalHeaders = new StringBuilder();
    final StringBuilder signedHeader = new StringBuilder();
    final Set<String> keysSet = headersMap.keySet();
    for (String key : keysSet) {
        canonicalHeaders.append(key);
        canonicalHeaders.append(AmazonSQSConstants.COLON);
        canonicalHeaders.append(headersMap.get(key));
        canonicalHeaders.append(AmazonSQSConstants.NEW_LINE);
        signedHeader.append(key);
        signedHeader.append(AmazonSQSConstants.SEMI_COLON);
    }
    canonicalRequest.append(canonicalHeaders.toString());
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    // Remove unwanted semi-colon at the end of the signedHeader string
    String signedHeaders = "";
    if (signedHeader.length() > 0) {
        signedHeaders = signedHeader.substring(0, signedHeader.length() - 1);
    }
    canonicalRequest.append(signedHeaders);
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    // HashedPayload = HexEncode(Hash(requestPayload))
    String requestPayload = "";
    if (payloadBuilder.length() > 0) {
        /*
         * First removes the additional ampersand appended to the end of the payloadBuilder, then o
         * further modifications to preserve unreserved characters as per the API guide
         * (http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html)
         */
        requestPayload = payloadBuilder.substring(0, payloadBuilder.length() - 1).toString()
                .replace(AmazonSQSConstants.PLUS, AmazonSQSConstants.URL_ENCODED_PLUS)
                .replace(AmazonSQSConstants.URL_ENCODED_TILT, AmazonSQSConstants.TILT)
                .replace(AmazonSQSConstants.ASTERISK, AmazonSQSConstants.URL_ENCODED_ASTERISK);
    }
    canonicalRequest.append(bytesToHex(hash(requestPayload)).toLowerCase());
    stringToSign.append(AmazonSQSConstants.AWS4_HMAC_SHA_256);
    stringToSign.append(AmazonSQSConstants.NEW_LINE);
    stringToSign.append(amzDate);
    stringToSign.append(AmazonSQSConstants.NEW_LINE);
    stringToSign.append(shortDate);
    stringToSign.append(AmazonSQSConstants.FORWARD_SLASH);
    stringToSign.append(signatureRequestObject.get(AmazonSQSConstants.REGION));
    stringToSign.append(AmazonSQSConstants.FORWARD_SLASH);
    stringToSign.append(signatureRequestObject.get(AmazonSQSConstants.SERVICE));
    stringToSign.append(AmazonSQSConstants.FORWARD_SLASH);
    stringToSign.append(signatureRequestObject.get(AmazonSQSConstants.TERMINATION_STRING));
    stringToSign.append(AmazonSQSConstants.NEW_LINE);
    stringToSign.append(bytesToHex(hash(canonicalRequest.toString())).toLowerCase());
    final byte[] signingKey = getSignatureKey(signatureRequestObject,
            signatureRequestObject.get(AmazonSQSConstants.SECRET_ACCESS_KEY).toString(), shortDate,
            signatureRequestObject.get(AmazonSQSConstants.REGION).toString(),
            signatureRequestObject.get(AmazonSQSConstants.SERVICE).toString());

    // Construction of authorization header value to be in cluded in API request
    authHeader.append(AmazonSQSConstants.AWS4_HMAC_SHA_256);
    authHeader.append(AmazonSQSConstants.COMMA);
    authHeader.append(AmazonSQSConstants.CREDENTIAL);
    authHeader.append(AmazonSQSConstants.EQUAL);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.ACCESS_KEY_ID));
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(shortDate);
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.REGION));
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.SERVICE));
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.TERMINATION_STRING));
    authHeader.append(AmazonSQSConstants.COMMA);
    authHeader.append(AmazonSQSConstants.SIGNED_HEADERS);
    authHeader.append(AmazonSQSConstants.EQUAL);
    authHeader.append(signedHeaders);
    authHeader.append(AmazonSQSConstants.COMMA);
    authHeader.append(AmazonSQSConstants.API_SIGNATURE);
    authHeader.append(AmazonSQSConstants.EQUAL);
    authHeader.append(bytesToHex(hmacSHA256(signingKey, stringToSign.toString())).toLowerCase());
    // Adds authorization header to message context
    signatureRequestObject.put(AmazonSQSConstants.AUTHORIZATION_HEADER, authHeader.toString());

    Map<String, String> responseMap = new HashMap<String, String>();
    responseMap.put(AmazonSQSConstants.AUTHORIZATION_HEADER, authHeader.toString());
    responseMap.put(AmazonSQSConstants.AMZ_DATE, amzDate);
    responseMap.put(AmazonSQSConstants.REQUEST_PAYLOAD, requestPayload);
    return responseMap;
}

From source file:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * @param signatureRequestObject// w w  w  .  j av a2 s .com
 * @throws JSONException
 */
private void init(JSONObject signatureRequestObject) throws JSONException {
    signatureRequestObject.put(AmazonSQSConstants.SERVICE, "sqs");
    signatureRequestObject.put(AmazonSQSConstants.SIGNATURE_METHOD, "HmacSHA256");
    signatureRequestObject.put(AmazonSQSConstants.SIGNATURE_VERSION, "4");
    signatureRequestObject.put(AmazonSQSConstants.CONTENT_TYPE, "application/x-www-form-urlencoded");
    signatureRequestObject.put(AmazonSQSConstants.HTTP_METHOD, "POST");
    signatureRequestObject.put(AmazonSQSConstants.TERMINATION_STRING, "aws4_request");
    signatureRequestObject.put(AmazonSQSConstants.HOST,
            "sqs." + signatureRequestObject.get(AmazonSQSConstants.REGION) + ".amazonaws.com");
}

From source file:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * getParametersMap method used to return list of parameter values sorted by expected API parameter names.
 *
 * @param signatureRequestObject ESB messageContext.
 * @param namesMap contains a map of esb parameter names and matching API parameter names
 * @return assigned parameter values as a HashMap.
 * @throws JSONException //  w w w  .ja  v  a2s .  c o m
 */
private Map<String, String> getSortedParametersMap(final JSONObject signatureRequestObject,
        final Map<String, String> namesMap) throws JSONException {
    final String[] singleValuedKeys = getParameterKeys();
    final Map<String, String> parametersMap = new TreeMap<String, String>();
    // Stores sorted, single valued API parameters
    for (byte index = 0; index < singleValuedKeys.length; index++) {
        final String key = singleValuedKeys[index];
        // builds the parameter map only if provided by the user
        if (signatureRequestObject.has(key) && !("").equals((String) signatureRequestObject.get(key))) {
            parametersMap.put(namesMap.get(key), (String) signatureRequestObject.get(key));
        }
    }
    final String[] multiValuedKeys = getMultivaluedParameterKeys();
    // Stores sorted, multi-valued API parameters
    for (byte index = 0; index < multiValuedKeys.length; index++) {
        final String key = multiValuedKeys[index];
        // builds the parameter map only if provided by the user
        if (signatureRequestObject.has(key) && !("").equals((String) signatureRequestObject.get(key))) {
            final String collectionParam = (String) signatureRequestObject.get(key);
            // Splits the collection parameter to retrieve parameters separately
            final String[] keyValuepairs = collectionParam.split(AmazonSQSConstants.AMPERSAND);
            for (String keyValue : keyValuepairs) {
                if (keyValue.contains(AmazonSQSConstants.EQUAL)
                        && keyValue.split(AmazonSQSConstants.EQUAL).length == AmazonSQSConstants.TWO) {
                    // Split the key and value of parameters to be sent to API
                    parametersMap.put(keyValue.split(AmazonSQSConstants.EQUAL)[0],
                            keyValue.split(AmazonSQSConstants.EQUAL)[1]);
                } else {
                    throw new IllegalArgumentException();
                }
            }
        }
    }
    return parametersMap;
}

From source file:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * getSortedHeadersMap method used to return list of header values sorted by expected API parameter names.
 *
 * @param signatureRequestObject ESB messageContext.
 * @param namesMap contains a map of esb parameter names and matching API parameter names
 * @return assigned header values as a HashMap.
 * @throws JSONException /*from   w  w w .ja  va2s  .co  m*/
 */
private Map<String, String> getSortedHeadersMap(final JSONObject signatureRequestObject,
        final Map<String, String> namesMap) throws JSONException {

    final String[] headerKeys = getHeaderKeys();
    final Map<String, String> parametersMap = new TreeMap<String, String>();
    // Stores sorted, single valued API parameters
    for (byte index = 0; index < headerKeys.length; index++) {
        final String key = headerKeys[index];
        // builds the parameter map only if provided by the user
        if (signatureRequestObject.has(key) && !("").equals((String) signatureRequestObject.get(key))) {
            parametersMap.put(namesMap.get(key).toLowerCase(), signatureRequestObject.get(key).toString().trim()
                    .replaceAll(AmazonSQSConstants.TRIM_SPACE_REGEX, AmazonSQSConstants.SPACE));
        }
    }
    return parametersMap;
}

From source file:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * Returns the encoded signature key to be used for further encodings as per API doc.
 *
 * @param signatureRequestObject message context of the connector
 * @param key key to be used for signing
 * @param dateStamp current date stamp/*from  ww w  .j  a  v a2 s.c  om*/
 * @param regionName region name given to the connector
 * @param serviceName Name of the service being addressed
 *
 * @return Signature key
 * @throws java.io.UnsupportedEncodingException  Unsupported Encoding Exception
 * @throws IllegalStateException  Illegal Argument Exception
 * @throws java.security.NoSuchAlgorithmException  No Such Algorithm Exception
 * @throws java.security.InvalidKeyException  Invalid Key Exception
 * @throws JSONException 
 */
private byte[] getSignatureKey(final JSONObject signatureRequestObject, final String key,
        final String dateStamp, final String regionName, final String serviceName)
        throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException,
        IllegalStateException, JSONException {

    final byte[] kSecret = (AmazonSQSConstants.AWS4 + key).getBytes(AmazonSQSConstants.UTF8);
    final byte[] kDate = hmacSHA256(kSecret, dateStamp);
    final byte[] kRegion = hmacSHA256(kDate, regionName);
    final byte[] kService = hmacSHA256(kRegion, serviceName);
    return hmacSHA256(kService, signatureRequestObject.get(AmazonSQSConstants.TERMINATION_STRING).toString());
}

From source file:com.jennifer.ui.util.DomUtil.java

public DomUtil css(JSONObject o) {

    String[] names = JSONObject.getNames(o);

    for (String key : names) {
        css(key, o.get(key));
    }/* w  w w  . java  2 s .c om*/

    return this;
}

From source file:com.jennifer.ui.util.DomUtil.java

public DomUtil attr(JSONObject JSONObject) {
    JSONArray list = JSONObject.names();

    for (int i = 0, len = list.length(); i < len; i++) {
        String key = list.getString(i);
        put(key, JSONObject.get(key));
    }/* w ww .j  a  va2  s. c  o m*/

    return this;
}

From source file:ru.neverdark.phototools.utils.Geocoder.java

/**
 * Gets coordinate from location name//from   ww  w  .  j  a  va  2  s  .  c o m
 * 
 * @param searchString
 *            user specify location name
 * @return coordinates for founded location or null if not found
 */
public LatLng getFromLocation(String searchString) {
    LatLng coords = null;
    String locationInfo = getLocationInfo(searchString);

    if (locationInfo.length() > 0) {
        try {
            JSONObject jsonObject = new JSONObject(locationInfo);
            JSONArray jsonArray = (JSONArray) jsonObject.get("results");
            JSONObject jsonLocation = jsonArray.getJSONObject(0).getJSONObject("geometry")
                    .getJSONObject("location");
            Double longitude = jsonLocation.getDouble("lng");
            Double latitude = jsonLocation.getDouble("lat");

            coords = new LatLng(latitude, longitude);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return coords;
}