List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:org.imsglobal.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 av a 2 s .com } 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; } 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); 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 = 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; } // Pass the profile to the launch process PERSIST.put("profile", providerProfile.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.log(Level.FINE, jsonText); PrintWriter out = response.getWriter(); out.println(jsonText); }
From source file:org.imsglobal.lti2.LTI2Servlet.java
@SuppressWarnings("unused") public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts) throws java.io.IOException { String URL = request.getRequestURL().toString(); System.out.println("URL=" + URL); String scope = parts[4];//from www . ja va 2 s .c o m System.out.println("scope=" + scope); String acceptHdr = request.getHeader("Accept"); String contentHdr = request.getContentType(); boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0; System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex); // Check the JSON on PUT and check the oauth_body_hash IMSJSONRequest jsonRequest = null; JSONObject requestData = null; if ("PUT".equals(request.getMethod())) { try { jsonRequest = new IMSJSONRequest(request); requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody()); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e); return; } } String consumer_key = TEST_KEY; String profile = PERSIST.get("profile"); JSONObject providerProfile = (JSONObject) JSONValue.parse(profile); JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET); // Validate the incoming message LtiVerificationResult result = BasicLTIUtil.validateMessage(request, URL, oauth_secret); if (!result.getSuccess()) { response.setStatus(HttpStatus.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, result.getMessage(), null); return; } // The URLs for the various settings resources String settingsUrl = getServiceURL(request) + SVC_Settings; String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key; String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD"; String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD"; // Load and parse the old settings... JSONObject link_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_LtiLink)); JSONObject binding_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding)); JSONObject proxy_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxy)); // For a GET request we depend on LTI2Util to do the GET logic if ("GET".equals(request.getMethod())) { Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings, link_url, binding_url, proxy_url); if (obj instanceof String) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, (String) obj, null); return; } if (acceptComplex) { response.setContentType(StandardServices.TOOLSETTINGS_FORMAT); } else { response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT); } JSONObject jsonResponse = (JSONObject) obj; response.setStatus(HttpServletResponse.SC_OK); PrintWriter out = response.getWriter(); System.out.println("jsonResponse=" + jsonResponse); out.println(jsonResponse.toString()); return; } else if ("PUT".equals(request.getMethod())) { // This is assuming the rule that a PUT of the complex settings // format that there is only one entry in the graph and it is // the same as our current URL. We parse without much checking. String settings = null; try { JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH); if (graph.size() != 1) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null); return; } JSONObject firstChild = (JSONObject) graph.get(0); JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM); settings = custom.toString(); } catch (Exception e) { settings = jsonRequest.getPostBody(); } PERSIST.put(scope, settings); System.out.println("Stored settings scope=" + scope); System.out.println("settings=" + settings); response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null); } }
From source file:org.imsglobal.lti2.LTI2Util.java
public static String parseToolProfile(List<Properties> theTools, Properties info, JSONObject jsonObject) { try {/*from w w w.j av a 2 s . c o m*/ return parseToolProfileInternal(theTools, info, jsonObject); } catch (Exception e) { M_log.warning("Internal error parsing tool proxy\n" + jsonObject.toString()); e.printStackTrace(); return "Internal error parsing tool proxy:" + e.getLocalizedMessage(); } }
From source file:org.jboss.aerogear.unifiedpush.utils.variant.SimplePushVariantUtils.java
@SuppressWarnings("unchecked") public static Response registerSimplePushVariant(String pushAppId, SimplePushVariant variant, Session session) { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", variant.getName()); jsonObject.put("description", variant.getDescription()); Response response = session.givenAuthorized().contentType(ContentTypes.json()).header(Headers.acceptJson()) .body(jsonObject.toString()).post("/rest/applications/{pushAppId}/simplePush", pushAppId); return response; }
From source file:org.jboss.aerogear.unifiedpush.utils.variant.SimplePushVariantUtils.java
@SuppressWarnings("unchecked") public static Response updateSimplePushVariant(String pushAppId, SimplePushVariant variant, String variantId, Session session) {/*w w w.j a v a2 s.c om*/ JSONObject jsonObject = new JSONObject(); jsonObject.put("name", variant.getName()); jsonObject.put("description", variant.getDescription()); Response response = session.givenAuthorized().contentType(ContentTypes.json()).header(Headers.acceptJson()) .body(jsonObject.toString()) .put("/rest/applications/{pushAppId}/simplePush/{variantId}", pushAppId, variantId); return response; }
From source file:org.jolokia.converter.object.StringToObjectConverterTest.java
@Test public void jsonConversion() { JSONObject json = new JSONObject(); json.put("name", "roland"); json.put("kind", "jolokia"); Object object = converter.convertFromString(JSONObject.class.getName(), json.toString()); assertEquals(json, object);/*from ww w . j av a2 s. com*/ JSONArray array = new JSONArray(); array.add("roland"); array.add("jolokia"); object = converter.convertFromString(JSONArray.class.getName(), array.toString()); assertEquals(array, object); try { converter.convertFromString(JSONObject.class.getName(), "{bla:blub{"); fail(); } catch (IllegalArgumentException exp) { } }
From source file:org.kawanfw.sql.json.JsonColPosition.java
/** * Format from JSON string Map<String, Integer> of (column name, column * position) of a result set//from ww w. j ava 2 s. co m * * @param jsonString * formated JSON string containing the Map<String, Integer> of * (column name, column position) * @return Map<String, Integer> of (column name, column position) */ public static Map<String, Integer> fromJson(String jsonString) { if (jsonString == null) { throw new IllegalArgumentException("jsonString is null!"); } jsonString = HtmlConverter.fromHtml(jsonString); // Revert it Object obj = JSONValue.parse(jsonString); JSONObject mapBack = (JSONObject) obj; debug("jsonString : " + jsonString); debug("mapBack.toString(): " + mapBack.toString()); Map<String, Integer> columnPositions = new LinkedHashMap<String, Integer>(); Set<?> set = mapBack.keySet(); for (Iterator<?> iterator = set.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); long value = (Long) mapBack.get(key); columnPositions.put(key, (int) value); } // free objects obj = null; mapBack = null; return columnPositions; }
From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java
public List<Group> findSimpleGroup(String search) { List<Group> searchResults = new ArrayList<Group>(); Group entry = null;/* w w w . j a v a2 s . c o m*/ StringBuilder queryString = new StringBuilder(); if (search != null && !search.trim().isEmpty()) { queryString.append("searchCriteria="); queryString.append(search.trim()); } LOG.debug("Group serach QueryString will be : " + queryString.toString()); try { URLConnection connection = new URL(GROUP_SEARCH_URL).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET); OutputStream output = null; output = connection.getOutputStream(); output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET)); String jsonData = null; jsonData = IOUtils.toString(connection.getInputStream(), DEFAULT_CHARACTER_SET); LOG.debug("Attempting to parse JSON using JSON.simple."); LOG.debug(jsonData); JSONParser parser = new JSONParser(); Object rootObj = parser.parse(jsonData); JSONObject jsonObject = (JSONObject) rootObj; JSONArray groups = (JSONArray) jsonObject.get("group"); for (Object group : groups) { JSONObject g = (JSONObject) group; LOG.debug(g.toString()); entry = (Group) getApplicationContext().getBean("directoryGroup"); entry.setDN((String) g.get("distinguishedName")); if (null != g.get("errors") && (g.get("errors")) instanceof JSONObject) { JSONObject error = (JSONObject) g.get("errors"); if (null != error.get("global")) { JSONObject globalError = (JSONObject) error.get("global"); entry.setDisplayName("Error"); List<String> tDesc = new ArrayList<String>(); tDesc.add((String) globalError.get("description")); entry.setDescriptions(tDesc); } } else { if (null != g.get("description")) { if ((g.get("description")) instanceof String) { List<String> tDesc = new ArrayList<String>(); tDesc.add((String) g.get("description")); entry.setDescriptions(tDesc); } else { entry.setDescriptions((List) g.get("description")); } } entry.setDisplayName((String) g.get("displayName")); entry.setEmail((String) g.get("email")); } searchResults.add(entry); } } catch (IOException ioe) { LOG.error(ioe.getLocalizedMessage(), ioe); } catch (ParseException pe) { LOG.error(pe.getLocalizedMessage(), pe); } return searchResults; }
From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java
private Person parsePerson(final JSONObject jsonData) { Person person = null;//from ww w . ja v a 2 s. c o m person = (Person) getApplicationContext().getBean("directoryPerson"); if (jsonData.isEmpty() || "".equalsIgnoreCase(jsonData.toString())) { person.setDisplayName("Error"); List<String> tDesc = new ArrayList<String>(); tDesc.add("To many search results found. Please try again."); person.setAffiliations(tDesc); } else if (null != jsonData.get("errors") && (jsonData.get("errors")) instanceof JSONObject) { JSONObject error = (JSONObject) jsonData.get("errors"); if (null != error.get("global")) { JSONObject globalError = (JSONObject) error.get("global"); person.setDisplayName("Error"); List<String> tDesc = new ArrayList<String>(); tDesc.add((String) globalError.get("description")); person.setAffiliations(tDesc); } } else { person.setDisplayName((String) jsonData.get("displayName")); if (null != jsonData.get("name") && !"".equalsIgnoreCase((String) jsonData.get("name"))) { person.setDisplayName((String) jsonData.get("name")); } person.setEmail((String) jsonData.get("email")); person.setUserName((String) jsonData.get("uniqname")); if (null != jsonData.get("affiliation")) { if (jsonData.get("affiliation") instanceof String) { List<String> tList = new ArrayList<String>(); tList.add((String) jsonData.get("affiliation")); person.setAffiliations(tList); } else { person.setAffiliations((List) jsonData.get("affiliation")); } } if (null != jsonData.get("aff")) { if (jsonData.get("aff") instanceof String) { List<String> tList = new ArrayList<String>(); tList.add((String) jsonData.get("aff")); person.setAffiliations(tList); } else { person.setAffiliations((List) jsonData.get("aff")); } } if (null != jsonData.get("title")) { if (jsonData.get("title") instanceof String) { List<String> tList = new ArrayList<String>(); tList.add((String) jsonData.get("title")); person.setDepartments(tList); } else { person.setDepartments((List) jsonData.get("title")); } } if (null != jsonData.get("workAddress")) { if (jsonData.get("workAddress") instanceof String) { person.setAddress(((String) jsonData.get("workAddress")).replace(" $ ", "\n")); } else { JSONArray addresses = (JSONArray) jsonData.get("workAddress"); person.setAddress(((String) addresses.get(0)).replace(" $ ", "\n")); } } if (null != jsonData.get("workPhone")) { if (jsonData.get("workPhone") instanceof String) { person.setPhone(((String) jsonData.get("workPhone")).replace(" $ ", "\n")); } else { JSONArray phones = (JSONArray) jsonData.get("workPhone"); person.setPhone(((String) phones.get(0)).replace(" $ ", "\n")); } } } return person; }
From source file:org.mozilla.android.sync.SyncCryptographer.java
private CryptoStatusBundle decryptKeysWBO(JSONObject payload) { // Get the keys to decrypt the crypto keys bundle KeyBundle cryptoKeysBundleKeys;//from w w w.ja v a2s . com try { cryptoKeysBundleKeys = getCryptoKeysBundleKeys(); } catch (Exception e) { return new CryptoStatusBundle(CryptoStatus.MISSING_SYNCKEY_OR_USER, payload.toString()); } byte[] cryptoKeysBundle = decryptPayload(payload, cryptoKeysBundleKeys); // Extract decrypted keys InputStream stream = new ByteArrayInputStream(cryptoKeysBundle); Reader in = new InputStreamReader(stream); JSONObject json = null; try { json = (JSONObject) new JSONParser().parse(in); } catch (Exception e) { e.printStackTrace(); } // Verify that this is indeed the crypto/keys bundle and decryption worked String id = (String) json.get(KEY_ID); String collection = (String) json.get(KEY_COLLECTION); if (id.equalsIgnoreCase(ID_CRYPTO_KEYS) && collection.equalsIgnoreCase(CRYPTO_KEYS_COLLECTION) && json.containsKey(KEY_DEFAULT_COLLECTION)) { // Extract the keys and add them to this Object jsonKeysObj = json.get(KEY_DEFAULT_COLLECTION); if (jsonKeysObj.getClass() != JSONArray.class) { return new CryptoStatusBundle(CryptoStatus.INVALID_KEYS_BUNDLE, json.toString()); } JSONArray jsonKeys = (JSONArray) jsonKeysObj; this.setKeys((String) jsonKeys.get(0), (String) jsonKeys.get(1)); // Return the string containing the decrypted payload return new CryptoStatusBundle(CryptoStatus.OK, new String(cryptoKeysBundle)); } else { return new CryptoStatusBundle(CryptoStatus.INVALID_KEYS_BUNDLE, json.toString()); } }