List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:com.treasure_data.client.DefaultClientAdaptorImpl.java
private ListDatabasesResult doListDatabases(ListDatabasesRequest request) throws ClientException { request.setCredentials(getConfig().getCredentials()); validator.validateCredentials(this, request); String jsonData = null;/* ww w .j a v a2s .c o m*/ String message = null; int code = 0; try { conn = createConnection(); // send request String path = HttpURL.V3_DATABASE_LIST; Map<String, String> header = new HashMap<String, String>(); setUserAgentHeader(header); Map<String, String> params = null; conn.doGetRequest(request, path, header, params); // receive response code and body code = conn.getResponseCode(); message = conn.getResponseMessage(); if (code != HttpURLConnection.HTTP_OK) { String errMessage = conn.getErrorMessage(); LOG.severe(HttpClientException.toMessage("List databases failed", message, code)); LOG.severe(errMessage); throw new HttpClientException("List databases failed", message + ", detail = " + errMessage, code); } // receive response body jsonData = conn.getResponseBody(); validator.validateJSONData(jsonData); } catch (IOException e) { LOG.throwing(getClass().getName(), "listDatabases", e); LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code)); throw new HttpClientException("List databases failed", message, code, e); } finally { if (conn != null) { conn.disconnect(); } } // parse JSON data @SuppressWarnings("rawtypes") Map map = (Map) JSONValue.parse(jsonData); validator.validateJavaObject(jsonData, map); @SuppressWarnings("unchecked") Iterator<Map<String, Object>> dbMaps = ((List<Map<String, Object>>) map.get("databases")).iterator(); List<DatabaseSummary> databases = new ArrayList<DatabaseSummary>(); while (dbMaps.hasNext()) { Map<String, Object> dbMap = dbMaps.next(); String name = (String) dbMap.get("name"); long count = (Long) dbMap.get("count"); String createdAt = (String) dbMap.get("created_at"); String updatedAt = (String) dbMap.get("updated_at"); databases.add(new DatabaseSummary(name, count, createdAt, updatedAt)); } return new ListDatabasesResult(new ListDatabases<DatabaseSummary>(databases)); }
From source file:ch.simas.jtoggl.JToggl.java
/** * Create a new project./*from ww w . ja v a 2 s . com*/ * @param project * @return created {@link Project} */ public Project createProject(Project project) { Client client = prepareClient(); WebResource webResource = client.resource(PROJECTS); JSONObject object = createProjectRequestParameter(project); String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE) .post(String.class); object = (JSONObject) JSONValue.parse(response); JSONObject data = (JSONObject) object.get(DATA); return new Project(data.toJSONString()); }
From source file:biomine.bmvis2.crawling.CrawlSuggestionList.java
private ArrayList<NodeType> fetchList(String q, int type, int organism) throws IOException { ArrayList<NodeType> ret = new ArrayList<NodeType>(); if (q.length() == 0) return ret; String typePar = type <= 0 ? "" : ("type=" + type + "__"); String orgPar = organism <= 0 ? "" : ("organism=" + organism + "__"); String dbPar = db == null ? "" : ("db=" + URLEncoder.encode(db, "UTF-8") + "__"); URL u = new URL(WebConstants.DEFAULT_BASEURL + "suggest.cgi?" + orgPar + typePar + dbPar + "term=" + URLEncoder.encode(q, "UTF-8")); System.out.println("querying " + u + " organism=" + organism + " type=" + type); String jsonStr = URLUtils.getURLContents(u); if (type != 0) { NodeType back = new NodeType(); back.name = "back to unfiltered results"; back.tcode = 0;// w ww . j av a 2 s .c o m back.ocode = 0; ret.add(back); } try { JSONArray ja = (JSONArray) JSONValue.parse(jsonStr); for (Object orgz : ja) { JSONObject orgtype = (JSONObject) orgz; Long tcodeL = (Long) orgtype.get("type"); int tcode = tcodeL.intValue(); Long ocodeL = (Long) orgtype.get("organism"); int ocode = ocodeL.intValue(); NodeType curType = null; curType = new NodeType(); curType.tcode = tcode; curType.ocode = ocode; curType.name = orgtype.get("text").toString(); curType.more = orgtype.get("unshown").toString(); ret.add(curType); JSONArray match = (JSONArray) orgtype.get("matches"); for (Object o : match) { JSONObject node = (JSONObject) o; String code = node.get("term").toString(); String name = node.get("title").toString(); NodeItem it = new NodeItem(code, name); curType.items.add(it); } } } catch (ClassCastException e) { throw new IOException("Invalid JSON from server", e); } return ret; }
From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java
/** * Returns a list of the most popular tags. * //from www. ja v a2 s . c o m * @param numberOfTags * the number of popular tags to return. * @return the most popular tags or null if an error occurred. */ @SuppressWarnings("unchecked") public static JSONArray getMostPopularTags(int numberOfTags) { // check the parameters if (numberOfTags <= 0) { return null; } // the JSON array to return JSONArray toReturn = new JSONArray(); // prepare the REST API call String RESTcall = "api/tag_counts"; try { String tagListString = connectorInstance.restCall(RESTcall); if (tagListString == null) { log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!"); return null; } // parse the JSON string and obtain an array of JSON objects Object obj = JSONValue.parse(tagListString); JSONArray array = (JSONArray) obj; HashMap<String, Long> map = new HashMap<String, Long>(); // fill unsorted HashMap with all keys and values for (Object tag : array) { JSONArray tagArray = (JSONArray) tag; map.put((String) tagArray.get(0), (Long) tagArray.get(1)); } // call sortHashMapByValues HashMap<String, Long> sortedHashMap = sortHashMapByValues(map); // calculate number of return array size if (sortedHashMap.size() < numberOfTags) { numberOfTags = sortedHashMap.size(); } // iterate over n fields and fill toReturn if (sortedHashMap.size() >= numberOfTags) { List<String> mapKeys = new ArrayList<String>(sortedHashMap.keySet()); Iterator<String> keyIt = mapKeys.iterator(); int i = 0; while (keyIt.hasNext() && i < numberOfTags) { String key = keyIt.next(); // (key, (Long) sortedHashMap.get(key)); JSONObject tag = new JSONObject(); tag.put("count", sortedHashMap.get(key)); tag.put("tag_name", key); toReturn.add(tag); i++; } } } // catch potential exceptions catch (MalformedURLException e) { log.log(Level.SEVERE, "Malformed URL \"" + url + RESTcall + "\" !!!"); return null; } catch (IOException e) { return null; } return toReturn; }
From source file:bbdn.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 (!"42".equals(profile_id)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/*from ww w .j a va 2 s . com*/ } String key = "42"; String secret = "zaphod"; 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.debug(jsonText); PrintWriter out = response.getWriter(); out.println(jsonText); }
From source file:com.searchbox.collection.oppfin.TopicCollection.java
public ItemReader<JSONObject> callReader() { return new ItemReader<JSONObject>() { String callListJSON = loadFromUrl(env.getProperty(CALL_LIST_URL, CALL_LIST_URL_DEFAULT)); // Topic list is a json list and we are interested in topicData => // Topics => all Object obj = JSONValue.parse(callListJSON); JSONObject jsonObject = (JSONObject) obj; JSONObject callData = (JSONObject) jsonObject.get("callData"); JSONArray calls = (JSONArray) callData.get("Calls"); // loop array Iterator<JSONObject> iterator = calls.iterator(); public JSONObject read() { if (iterator.hasNext()) { return iterator.next(); }//from w w w . jav a2s .co m return null; } }; }
From source file:com.bchalk.GVCallback.callback.GVCommunicator.java
public boolean messageMarkRead(String id, boolean read) { HttpPost post = new HttpPost(BASE + "/voice/inbox/mark/"); List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>(); data.add(new BasicNameValuePair("messages", id)); data.add(new BasicNameValuePair("read", read ? "1" : "0")); data.add(new BasicNameValuePair("_rnr_se", myToken)); try {/* ww w . j a v a 2 s.c om*/ post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8)); HttpResponse response = myClient.execute(post); String rsp = getContent(response.getEntity()); JSONObject val = (JSONObject) JSONValue.parse(rsp); if (val == null) { return true; } return (Boolean) val.get("ok"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
From source file:mml.handler.get.MMLGetMMLHandler.java
/** * Create the MMLtext using the invert index and the cortex and corcode * @param cortex the plain text version//from w w w. ja v a 2 s . co m * @param ccDflt the default STIL markup for that plain text * @param ccPages the page-breaks or null * @param layer the number of the layer to build */ void createMML(ScratchVersion cortex, ScratchVersion ccDflt, ScratchVersion ccPages, int layer) { String text = cortex.getLayerString(layer); mml = new StringBuilder(); String stilDflt = ccDflt.getLayerString(layer); String stilPages = (ccPages == null) ? null : ccPages.getLayerString(layer); JSONObject mDflt = (JSONObject) JSONValue.parse(stilDflt); if (stilPages != null) { JSONObject mPages = (JSONObject) JSONValue.parse(stilPages); mDflt = mergeCorcodes(mDflt, mPages); } JSONArray ranges = (JSONArray) mDflt.get("ranges"); Stack<EndTag> stack = new Stack<EndTag>(); int offset = 0; for (int i = 0; i < ranges.size(); i++) { JSONObject r = (JSONObject) ranges.get(i); Number len = (Number) r.get("len"); Number relOff = (Number) r.get("reloff"); String name = (String) r.get("name"); if (invertIndex.containsKey(name)) { JSONObject def = invertIndex.get(name); String startTag = mmlStartTag(def, offset); String endTag = mmlEndTag(def, len.intValue()); int start = offset + relOff.intValue(); // 1. insert pending end-tags and text before current range int pos = offset; while (!stack.isEmpty() && stack.peek().offset <= start) { // check for NLs here if obj is of type lineformat int tagEnd = stack.peek().offset; boolean isLF = isLineFormat(stack); for (int j = pos; j < tagEnd; j++) { char c = text.charAt(j); if (c != '\n') { if (globals.containsKey(c)) mml.append(globals.get(c)); else mml.append(c); } else if (isLF && j < tagEnd - 1) startPreLine(stack); else mml.append(c); } pos = tagEnd; // newlines are not permitted before tag end while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n') mml.setLength(mml.length() - 1); mml.append(stack.pop().text); } // 2. insert intervening text boolean inPre = isLineFormat(stack); int nNLs = countTerminalNLs(mml); for (int j = pos; j < start; j++) { char c = text.charAt(j); if (c == '\n') { if (mml.length() == 0 || nNLs == 0) mml.append(c); if (nNLs > 0) nNLs--; if (inPre) startPreLine(stack); } else { mml.append(c); nNLs = 0; } } // 3. insert new start tag normaliseNewlines(startTag); mml.append(startTag); stack.push(new EndTag(start + len.intValue(), endTag, def)); } else System.out.println("Ignoring tag " + name); offset += relOff.intValue(); } //empty stack int pos = offset; while (!stack.isEmpty()) { int tagEnd = stack.peek().offset; boolean inPre = isLineFormat(stack); for (int j = pos; j < tagEnd; j++) { char c = text.charAt(j); mml.append(c); if (c == '\n' && inPre && j < tagEnd - 1) startPreLine(stack); } pos = tagEnd; // newlines are not permitted before tag end while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n') mml.setLength(mml.length() - 1); mml.append(stack.pop().text); } }
From source file:ch.simas.jtoggl.JToggl.java
/** * Update a project.//from w w w. j a v a 2 s.c o m * * @param project * @return updated {@link Project} */ public Project updateProject(Project project) { Client client = prepareClient(); String url = PROJECT.replace(PLACEHOLDER, project.getId().toString()); WebResource webResource = client.resource(url); JSONObject object = createProjectRequestParameter(project); String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE) .put(String.class); object = (JSONObject) JSONValue.parse(response); JSONObject data = (JSONObject) object.get(DATA); return new Project(data.toJSONString()); }
From source file:importer.handler.post.stages.StageThreeXML.java
/** * Process the files//from w w w . j a v a 2 s .c om * @param cortex the cortext MVD to accumulate files into * @param corcode the corcode MVD to accumulate files into * @return the log output */ @Override public String process(Archive cortex, Archive corcode) throws ImporterException { try { if (files.size() > 0) { JSONObject jDoc = (JSONObject) JSONValue.parse(splitConfig); Splitter splitter = new Splitter(jDoc); for (int i = 0; i < files.size(); i++) { File file = files.get(i); String fileText = file.toString(); long startTime = System.currentTimeMillis(); Map<String, String> map = splitter.split(fileText); long diff = System.currentTimeMillis() - startTime; log.append("Split "); log.append(file.name); log.append(" in "); log.append(diff); log.append(" milliseconds into "); log.append(map.size()); log.append(" versions\n"); Set<String> keys = map.keySet(); Iterator<String> iter = keys.iterator(); while (iter.hasNext()) { String key = iter.next(); JSONResponse markup = new JSONResponse(JSONResponse.STIL); JSONResponse text = new JSONResponse(JSONResponse.TEXT); AeseStripper stripper = new AeseStripper(); String xml = map.get(key); // extract the notes from the xml String vid = extractVersionName(files.get(i).name); NoteStripper ns = new NoteStripper(); // strip out the bona fide notes xml = ns.strip(xml, docid, vid + "/" + key); ArrayList notes = ns.getNotes(); int res = stripper.strip(xml, stripConfig, style, dict, hhExcepts, Utils.isHtml(xml), text, markup); if (res == 1) { // save notes in database if any if (notes.size() > 0) { Connection conn = Connector.getConnection(); if (!vid.startsWith("/")) vid = "/" + vid; conn.removeFromDbByExpr(Database.ANNOTATIONS, JSONKeys.DOCID, docid + vid + "/.*"); RandomID rid = new RandomID(); String config = getHtmlConfig(conn); JSONObject jObj = (JSONObject) JSONValue.parse(config); if (jObj != null) { for (int j = 0; j < notes.size(); j++) { Annotation ann = (Annotation) notes.get(j); String json = ann.toJSONString(jObj); String annid = docid; if (vid.startsWith("/")) annid += vid; else annid += "/" + vid; annid += "/" + rid.newKey(); conn.putToDb(Database.ANNOTATIONS, annid, json); } } else System.out.println("Failed to load xml->html config"); } if (map.size() > 1) vid += "/" + key; //char[] chars = text.getBody().toCharArray(); //convertQuotes( chars ); //cortex.put( group+key, new String(chars).getBytes("UTF-8") ); StandoffPair pair = new StandoffPair(markup.getBody(), text.getBody(), vid); //System.out.println("text len="+text.getBody().length()+" xml length ="+xml.length()); convertCorcode(pair); cortex.put(vid, pair.text.toCharArray()); corcode.put(vid, pair.stil.toCharArray()); if (!verifyCorCode(pair.stil, pair.text)) System.out.println("corcode of " + pair.vid + " was invalid"); log.append("Stripped "); log.append(file.name); log.append("("); log.append(key); log.append(")"); log.append(" successfully\n"); } else { throw new ImporterException("Stripping of " + files.get(i).name + " XML failed"); } } } } } catch (Exception e) { if (e instanceof ImporterException) throw (ImporterException) e; else throw new ImporterException(e); } return log.toString(); }