List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:net.dv8tion.jda.core.handle.MessageUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { if (content.has("author")) { if (content.has("type")) { MessageType type = MessageType.fromId(content.getInt("type")); switch (type) { case DEFAULT: return handleDefaultMessage(content); default: WebSocketClient.LOG//from www .ja v a 2 s. co m .debug("JDA received a message of unknown type. Type: " + type + " JSON: " + content); return null; } } else { //TODO: handle partial message update info. Example: //From webhook/rich-embed. //{"author":{"bot":true,"id":"233501884294365184","avatar":"27ae7496b3b30cddab2feaaed06d862a","username":"GitHub","discriminator":"0000"},"id":"234838126969880596","embeds":[{"color":15109472,"author":{"icon_url":"https://avatars.githubusercontent.com/u/2415829?v=3","name":"abalabahaha","proxy_icon_url":"https://images-ext-2.discordapp.net/eyJ1cmwiOiJodHRwczovL2F2YXRhcnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3UvMjQxNTgyOT92PTMifQ.mMTBuOMUKYowcUU1H8Gzc7g4fFQ","url":"https://github.com/abalabahaha"},"description":"It was removed from the unofficial docs and other places because devs didn't want automated registration.","type":"rich","title":"[hammerandchisel/discord-api-docs] New comment on issue #148: Register API call","url":"https://github.com/hammerandchisel/discord-api-docs/issues/148#issuecomment-252524279"}],"channel_id":"168311874624946176"} return null; } } else if (content.has("call")) { handleCallMessage(content); return null; } else return handleMessageEmbed(content); }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testJsonSerializer() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); SerializableBean bean = new SerializableBean(); bean.setBooleanValue(true);/*from ww w. j a va 2s .c o m*/ bean.setDoubleValue(0.451); bean.setFloatValue(1.34f); bean.setIntValue(3400100); bean.setLongValue(3400100200L); bean.setShortValue((short) 32767); bean.setStringValue("String"); bean.setDateValue(format.parse("2011-08-24T08:50:23+0200")); Date calDate = format.parse("2011-08-24T08:52:23+0200"); Calendar cal = Calendar.getInstance(); cal.setTime(calDate); bean.setCalendarValue(cal); bean.setObjectValue(TimeZone.getDefault()); InBean inBean = new InBean(); inBean.setFirst(true); inBean.setSecond(0.567d); inBean.setThird(0.342f); inBean.setFourth(100); inBean.setFifth(3400200100L); inBean.setSixth((short) 32767); inBean.setSeventh("String"); inBean.setEight(format.parse("2011-08-25T08:50:23+0200")); cal = Calendar.getInstance(); calDate = format.parse("2011-08-25T08:52:23+0200"); cal.setTime(calDate); inBean.setNinth(cal); bean.setBeanValue(inBean); List<InBean> beanList = new ArrayList<InBean>(); beanList.add(inBean); beanList.add(inBean); bean.setBeanListValue(beanList); List<String> stringList = new ArrayList<String>(); stringList.add("One"); stringList.add("Two"); stringList.add("Three"); bean.setStringListValue(stringList); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean); writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("serializableBean")); json = json.getJSONObject("serializableBean"); assertEquals(true, json.getBoolean("booleanValue")); assertEquals(0.451, json.getDouble("doubleValue")); assertEquals(1.34f, (float) json.getDouble("floatValue")); assertEquals(3400100, json.getInt("intValue")); assertEquals(3400100200L, json.getLong("longValue")); assertEquals(32767, (short) json.getInt("shortValue")); assertEquals("String", json.getString("stringValue")); assertEquals("2011-08-24T08:50:23+02:00", json.getString("dateValue")); assertEquals("2011-08-24T08:52:23+02:00", json.getString("calendarValue")); assertEquals(TimeZone.getDefault().toString(), json.getString("objectValue")); assertTrue(json.has("beanValue")); JSONObject inBeanJson = json.getJSONObject("beanValue"); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); assertTrue(json.has("stringListValue")); JSONArray stringListJson = json.getJSONArray("stringListValue"); assertEquals("One", stringListJson.get(0)); assertEquals("Two", stringListJson.get(1)); assertEquals("Three", stringListJson.get(2)); assertTrue(json.has("beanListValue")); JSONArray beanListJson = json.getJSONArray("beanListValue"); inBeanJson = beanListJson.getJSONObject(0); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); inBeanJson = beanListJson.getJSONObject(1); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testNamedJsonSerializer() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); NamedBean bean = new NamedBean(); bean.setBooleanValue(true);// w ww . j a v a 2s . c o m bean.setDoubleValue(0.451); bean.setFloatValue(1.34f); bean.setIntValue(3400100); bean.setLongValue(3400100200L); bean.setShortValue((short) 32767); bean.setStringValue("String"); bean.setDateValue(format.parse("2011-08-24T08:50:23+0200")); Date calDate = format.parse("2011-08-24T08:52:23+0200"); Calendar cal = Calendar.getInstance(); cal.setTime(calDate); bean.setCalendarValue(cal); bean.setObjectValue(TimeZone.getDefault()); InBean inBean = new InBean(); inBean.setFirst(true); inBean.setSecond(0.567d); inBean.setThird(0.342f); inBean.setFourth(100); inBean.setFifth(3400200100L); inBean.setSixth((short) 32767); inBean.setSeventh("String"); inBean.setEight(format.parse("2011-08-25T08:50:23+0200")); cal = Calendar.getInstance(); calDate = format.parse("2011-08-25T08:52:23+0200"); cal.setTime(calDate); inBean.setNinth(cal); bean.setBeanValue(inBean); List<InBean> beanList = new ArrayList<InBean>(); beanList.add(inBean); beanList.add(inBean); bean.setBeanListValue(beanList); List<String> stringList = new ArrayList<String>(); stringList.add("One"); stringList.add("Two"); stringList.add("Three"); bean.setStringListValue(stringList); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean); writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("testNamedBean")); json = json.getJSONObject("testNamedBean"); assertEquals(true, json.getBoolean("testBooleanValue")); assertEquals(0.451, json.getDouble("testDoubleValue")); assertEquals(1.34f, (float) json.getDouble("testFloatValue")); assertEquals(3400100, json.getInt("testIntValue")); assertEquals(3400100200L, json.getLong("testLongValue")); assertEquals(32767, (short) json.getInt("testShortValue")); assertEquals("String", json.getString("testStringValue")); assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue")); assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue")); assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue")); assertTrue(json.has("testBeanValue")); JSONObject inBeanJson = json.getJSONObject("testBeanValue"); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); assertTrue(json.has("testStringListValue")); JSONArray stringListJson = json.getJSONArray("testStringListValue"); assertEquals("One", stringListJson.get(0)); assertEquals("Two", stringListJson.get(1)); assertEquals("Three", stringListJson.get(2)); assertTrue(json.has("testBeanListValue")); JSONArray beanListJson = json.getJSONArray("testBeanListValue"); inBeanJson = beanListJson.getJSONObject(0); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); inBeanJson = beanListJson.getJSONObject(1); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testEmptyJsonSerializer() throws Exception { SerializableBean bean = new SerializableBean(); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean);/*from w w w. j a v a 2 s.c om*/ writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("serializableBean")); json = json.getJSONObject("serializableBean"); assertEquals(false, json.getBoolean("booleanValue")); assertEquals(0.0d, json.getDouble("doubleValue")); assertEquals(0.0f, (float) json.getDouble("floatValue")); assertEquals(0, json.getInt("intValue")); assertEquals(0L, json.getLong("longValue")); assertEquals(0, (short) json.getInt("shortValue")); assertFalse(json.has("stringValue")); assertFalse(json.has("dateValue")); assertFalse(json.has("calendarValue")); assertFalse(json.has("objectValue")); }
From source file:org.brickred.socialauth.provider.SalesForceImpl.java
/** * @return/*ww w . j a v a 2 s . c om*/ * @throws Exception */ private Profile getProfile() throws Exception { if (accessGrant.getAttribute("id") != null) { profileURL = (String) accessGrant.getAttribute("id"); } LOG.debug("Profile URL : " + profileURL); Profile p = new Profile(); Map<String, String> headerParam = new HashMap<String, String>(); headerParam.put("Authorization", "OAuth " + accessGrant.getKey()); headerParam.put("Content-Type", "application/json"); headerParam.put("Accept", "application/json"); Response serviceResponse; try { serviceResponse = authenticationStrategy.executeFeed(profileURL, MethodType.GET.toString(), null, headerParam, null); // HttpUtil.doHttpRequest(profileURL, "GET", null, headerParam); } catch (Exception e) { throw new SocialAuthException("Failed to retrieve the user profile from " + profileURL, e); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); LOG.debug("User Profile :" + result); } catch (Exception e) { throw new SocialAuthException("Failed to read response from " + profileURL, e); } try { JSONObject resp = new JSONObject(result); if (resp.has("user_id")) { p.setValidatedId(resp.getString("user_id")); } if (resp.has("first_name")) { p.setFirstName(resp.getString("first_name")); } if (resp.has("last_name")) { p.setLastName(resp.getString("last_name")); } p.setDisplayName(resp.getString("display_name")); p.setEmail(resp.getString("email")); String locale = resp.getString("locale"); if (locale != null) { String a[] = locale.split("_"); p.setLanguage(a[0]); p.setCountry(a[1]); } if (resp.has("photos")) { JSONObject photosResp = resp.getJSONObject("photos"); if (p.getProfileImageURL() == null || p.getProfileImageURL().length() <= 0) { p.setProfileImageURL(photosResp.getString("thumbnail")); } } serviceResponse.close(); p.setProviderId(getProviderId()); userProfile = p; return p; } catch (Exception e) { throw new SocialAuthException("Failed to parse the user profile json : " + result, e); } }
From source file:org.catnut.metadata.User.java
@Override public ContentValues convert(JSONObject json) { ContentValues user = new ContentValues(); user.put(BaseColumns._ID, json.optLong(Constants.ID)); user.put(screen_name, json.optString(screen_name)); user.put(name, json.optString(name)); user.put(province, json.optInt(province)); user.put(city, json.optInt(city));/* www . j a v a2 s.co m*/ user.put(location, json.optString(location)); user.put(description, json.optString(description)); user.put(url, json.optString(url)); user.put(profile_image_url, json.optString(profile_image_url)); user.put(cover_image, json.optString(cover_image)); user.put(cover_image_phone, json.optString(cover_image_phone)); user.put(profile_url, json.optString(profile_url)); user.put(domain, json.optString(domain)); user.put(weihao, json.optString(weihao)); user.put(gender, json.optString(gender)); user.put(followers_count, json.optInt(followers_count)); user.put(friends_count, json.optInt(friends_count)); user.put(statuses_count, json.optInt(statuses_count)); user.put(favourites_count, json.optInt(favourites_count)); user.put(created_at, json.optString(created_at)); user.put(following, json.optBoolean(following)); user.put(allow_all_act_msg, json.optBoolean(allow_all_act_msg)); user.put(geo_enabled, json.optBoolean(geo_enabled)); user.put(verified, json.optBoolean(verified)); user.put(verified_type, json.optInt(verified_type)); user.put(remark, json.optString(remark)); // user.put(ptype, json.optInt(ptype)); user.put(allow_all_comment, json.optBoolean(allow_all_comment)); user.put(avatar_large, json.optString(avatar_large)); user.put(avatar_hd, json.optString(avatar_hd)); user.put(verified_reason, json.optString(verified_reason)); user.put(follow_me, json.optBoolean(follow_me)); user.put(online_status, json.optInt(online_status)); user.put(bi_followers_count, json.optInt(bi_followers_count)); user.put(lang, json.optString(lang)); // user.put(star, json.optString(star)); // user.put(mbtype, json.optInt(mbtype)); // user.put(mbrank, json.optInt(mbrank)); // user.put(block_word, json.optInt(block_word)); // ?id if (json.has(SINGLE)) { user.put(status_id, json.optJSONObject(Status.SINGLE).optLong(Constants.ID)); } return user; }
From source file:com.basetechnology.s0.agentserver.field.MoneyField.java
public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) { String type = fieldJson.optString("type"); if (type == null || !type.equals("money")) return null; String name = fieldJson.has("name") ? fieldJson.optString("name") : null; String label = fieldJson.has("label") ? fieldJson.optString("label") : null; String description = fieldJson.has("description") ? fieldJson.optString("description") : null; double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0; double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE; double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE; int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0; String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null; return new MoneyField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth, compute);/*from www . j a va2s .c om*/ }
From source file:com.trk.aboutme.facebook.FacebookRequestError.java
static FacebookRequestError checkResponseAndCreateError(JSONObject singleResult, Object batchResult, HttpURLConnection connection) { try {//from w w w.j a v a 2 s .c o m if (singleResult.has(CODE_KEY)) { int responseCode = singleResult.getInt(CODE_KEY); Object body = Utility.getStringPropertyAsJSON(singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY); if (body != null && body instanceof JSONObject) { JSONObject jsonBody = (JSONObject) body; // Does this response represent an error from the service? We might get either an "error" // with several sub-properties, or else one or more top-level fields containing error info. String errorType = null; String errorMessage = null; int errorCode = INVALID_ERROR_CODE; int errorSubCode = INVALID_ERROR_CODE; boolean hasError = false; if (jsonBody.has(ERROR_KEY)) { // We assume the error object is correctly formatted. JSONObject error = (JSONObject) Utility.getStringPropertyAsJSON(jsonBody, ERROR_KEY, null); errorType = error.optString(ERROR_TYPE_FIELD_KEY, null); errorMessage = error.optString(ERROR_MESSAGE_FIELD_KEY, null); errorCode = error.optInt(ERROR_CODE_FIELD_KEY, INVALID_ERROR_CODE); errorSubCode = error.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } else if (jsonBody.has(ERROR_CODE_KEY) || jsonBody.has(ERROR_MSG_KEY) || jsonBody.has(ERROR_REASON_KEY)) { errorType = jsonBody.optString(ERROR_REASON_KEY, null); errorMessage = jsonBody.optString(ERROR_MSG_KEY, null); errorCode = jsonBody.optInt(ERROR_CODE_KEY, INVALID_ERROR_CODE); errorSubCode = jsonBody.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } if (hasError) { return new FacebookRequestError(responseCode, errorCode, errorSubCode, errorType, errorMessage, jsonBody, singleResult, batchResult, connection); } } // If we didn't get error details, but we did get a failure response code, report it. if (!HTTP_RANGE_SUCCESS.contains(responseCode)) { return new FacebookRequestError(responseCode, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null, null, singleResult.has(BODY_KEY) ? (JSONObject) Utility.getStringPropertyAsJSON(singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY) : null, singleResult, batchResult, connection); } } } catch (JSONException e) { // defer the throwing of a JSONException to the graph object proxy } return null; }
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 /*from ww w . ja va 2 s. co m*/ * @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
/** * 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 /*from w ww . j av a2 s . co 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; }