List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:formatter.handler.post.FormatterPostHandler.java
/** * Handle a POST request//from w ww .j a va 2s . c om * @param request the raw request * @param response the response we will write to * @param urn the rest of the URL after stripping off the context * @throws ProjectException */ public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws FormatterException { try { //System.out.println("About to parse params"); parseImportParams(request); Connection conn = Connector.getConnection(); String jStr = conn.getFromDb(Database.METADATA, docid); JSONObject jDoc = (JSONObject) JSONValue.parse(jStr); if (version1 != null && isEditor) { //System.out.println("adding "+version1+"to metadata"); jDoc.put(JSONKeys.VERSION1, version1); jStr = jDoc.toJSONString(); jStr = jStr.replaceAll("\\\\/", "/"); String resp = conn.putToDb(Database.METADATA, docid, jStr); //System.out.println("Server response:"+resp); } else System.out.println("version1=" + version1 + " isEditor:" + Boolean.toString(isEditor)); } catch (Exception e) { try { response.getWriter().println("Status: 500; Exception " + e.getMessage()); } catch (Exception ex) { } System.out.println(e.getMessage()); throw new FormatterException(e); } }
From source file:de.mpg.imeji.presentation.servlet.autocompleter.java
/** * Parse a CoNE Vocabulary (read the title value) * //from w ww. ja va 2s . co m * @param cone * @return * @throws IOException */ @SuppressWarnings("unchecked") private String parseConeVocabulary(String cone) throws IOException { Object obj = JSONValue.parse(cone); JSONArray array = (JSONArray) obj; JSONArray result = new JSONArray(); for (int i = 0; i < array.size(); ++i) { JSONObject parseObject = (JSONObject) array.get(i); JSONObject sendObject = new JSONObject(); sendObject.put("label", parseObject.get("http_purl_org_dc_elements_1_1_title")); sendObject.put("value", parseObject.get("http_purl_org_dc_elements_1_1_title")); result.add(sendObject); } StringWriter out = new StringWriter(); result.writeJSONString(out); return out.toString(); }
From source file:com.rylinaux.plugman.util.BukGetUtil.java
/** * Get the plugin data for a certain version. * * @param slug the plugin slug.//from ww w . jav a 2 s. co m * @return the JSON encoded data. */ public static JSONObject getPluginData(String slug, String version) { HttpClient client = HttpClients.createMinimal(); HttpGet get = new HttpGet(API_BASE_URL + "plugins/bukkit/" + slug + "/" + version); try { HttpResponse response = client.execute(get); String body = IOUtils.toString(response.getEntity().getContent()); return (JSONObject) JSONValue.parse(body); } catch (IOException e) { } return null; }
From source file:de.bitzeche.logging.gelfamqp4j.GelfAMQP4jAppender.java
@SuppressWarnings("unchecked") public void setAdditionalFields(String additionalFields) { fields = (Map<String, String>) JSONValue.parse(additionalFields.replaceAll("'", "\"")); }
From source file:com.precioustech.fxtrading.oanda.restapi.account.transaction.OandaTransactionDataProviderService.java
@Override public Transaction<Long, Long, String> getTransaction(Long transactionId, Long accountId) { Preconditions.checkNotNull(transactionId); Preconditions.checkNotNull(accountId); CloseableHttpClient httpClient = getHttpClient(); try {/*from w w w . j a v a 2s . com*/ HttpUriRequest httpGet = new HttpGet(getSingleAccountTransactionUrl(transactionId, accountId)); httpGet.setHeader(authHeader); httpGet.setHeader(OandaConstants.UNIX_DATETIME_HEADER); LOG.info(TradingUtils.executingRequestMsg(httpGet)); HttpResponse httpResponse = httpClient.execute(httpGet); String strResp = TradingUtils.responseToString(httpResponse); if (strResp != StringUtils.EMPTY) { JSONObject transactionJson = (JSONObject) JSONValue.parse(strResp); final String instrument = transactionJson.get(OandaJsonKeys.instrument) .toString();/* do not use derive instrument here */ final String type = transactionJson.get(OandaJsonKeys.type).toString(); final Long tradeUnits = getUnits(transactionJson); final DateTime timestamp = getTransactionTime(transactionJson); final Double pnl = getPnl(transactionJson); final Double interest = getInterest(transactionJson); final Double price = getPrice(transactionJson); final String side = getSide(transactionJson); return new Transaction<Long, Long, String>(transactionId, OandaUtils.toOandaTransactionType(type), accountId, instrument, tradeUnits, OandaUtils.toTradingSignal(side), timestamp, price, interest, pnl); } else { TradingUtils.printErrorMsg(httpResponse); } } catch (Exception e) { LOG.error(e); } return null; }
From source file:iphonestalker.util.FindMyIPhoneReader.java
public String connect(String username, String password) { numDevices = 0;/*from ww w. ja v a2 s .c o m*/ // Setup HTTP parameters HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Find iPhone/1.1 MeKit (iPhone: iPhone OS/4.2.1)"); client = new DefaultHttpClient(params); // Construct the post post = new HttpPost("https://fmipmobile.me.com/fmipservice/device/" + username); post.addHeader("X-Client-Uuid", "0000000000000000000000000000000000000000"); post.addHeader("X-Client-Name", "My iPhone"); Header[] headers = { new BasicHeader("X-Apple-Find-Api-Ver", "2.0"), new BasicHeader("X-Apple-Authscheme", "UserIdGuest"), new BasicHeader("X-Apple-Realm-Support", "1.0"), new BasicHeader("Content-Type", "application/json; charset=utf-8"), new BasicHeader("Accept-Language", "en-us"), new BasicHeader("Pragma", "no-cache"), new BasicHeader("Connection", "keep-alive"), new BasicHeader("Authorization", "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes()))) }; post.setHeaders(headers); HttpResponse response = null; try { // Execute response = client.execute(post); // We should get a redirect if (response.getStatusLine().getStatusCode() == 330) { String newHost = (((Header[]) response.getHeaders("X-Apple-MME-Host"))[0]).getValue(); try { post.setURI(new URI("https://" + newHost + "/fmipservice/device/" + username + "/initClient")); } catch (URISyntaxException ex) { logger.log(Level.SEVERE, null, ex); return "Couldn't post URI: " + ex; } // Dump the data so we can execute a new post BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); JSONObject object = (JSONObject) JSONValue.parse(reader); // This post should get us our data response = client.execute(post); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); // Read the data object = (JSONObject) JSONValue.parse(reader); JSONArray array = ((JSONArray) object.get("content")); numDevices = array.size(); // Setup the route data iPhoneRouteList = new ArrayList<IPhoneRoute>(); for (int i = 0; i < numDevices; i++) { // Get the device data object = (JSONObject) array.get(i); IPhoneLocation iPhoneLocation = getLocation(object); // Add route data IPhoneRoute iPhoneRoute = new IPhoneRoute(); String modelDisplayName = (String) object.get("modelDisplayName"); String deviceModelName = (String) object.get("deviceModel"); String name = (String) object.get("name"); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); iPhoneRoute.name = "[FMI #" + (i + 1) + "]" + name + ":" + modelDisplayName + " " + deviceModelName; iPhoneRoute.lastBackupDate = cal.getTime(); iPhoneRoute.setFMI(true); if (iPhoneLocation != null) { iPhoneRoute.addLocation(iPhoneLocation); } iPhoneRouteList.add(iPhoneRoute); } } else { logger.log(Level.WARNING, "Couldn\'t retrieve iPhone data: " + response.getStatusLine().toString()); return "Couldn't retrieve iPhone data: " + response.getStatusLine().toString(); } } catch (ClientProtocolException ex) { logger.log(Level.SEVERE, null, ex); return "Couldn't retrieve iPhone data: " + ex; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return "Couldn't retrieve iPhone data: " + ex; } return null; }
From source file:com.github.maoo.indexer.webscripts.NodeChangesWebScript.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { final String serviceContextPath = req.getServerPath() + req.getServiceContextPath(); //start time//w w w. j av a 2 s . c om long startTime = System.currentTimeMillis(); //Fetching request params Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars(); String storeId = templateArgs.get("storeId"); String storeProtocol = templateArgs.get("storeProtocol"); String lastTxnIdString = req.getParameter("lastTxnId"); String lastAclChangesetIdString = req.getParameter("lastAclChangesetId"); String maxTxnsString = req.getParameter("maxTxns"); String maxAclChangesetsString = req.getParameter("maxAclChangesets"); //Parsing parameters passed from the WebScript invocation Long lastTxnId = (lastTxnIdString == null ? null : Long.valueOf(lastTxnIdString)); Long lastAclChangesetId = (lastAclChangesetIdString == null ? null : Long.valueOf(lastAclChangesetIdString)); Integer maxTxns = (maxTxnsString == null ? maxNodesPerTxns : Integer.valueOf(maxTxnsString)); Integer maxAclChangesets = (maxAclChangesetsString == null ? maxNodesPerAcl : Integer.valueOf(maxAclChangesetsString)); JSONObject indexingFilters = null; try { indexingFilters = req.getParameter("indexingFilters") != null ? (JSONObject) JSONValue.parse(URLDecoder.decode(req.getParameter("indexingFilters"), "UTF-8")) : null; } catch (UnsupportedEncodingException e) { throw new WebScriptException(e.getMessage(), e); } logger.debug(String.format("Invoking Changes Webscript, using the following params\n" + "lastTxnId: %s\n" + "lastAclChangesetId: %s\n" + "storeId: %s\n" + "storeProtocol: %s\n" + "indexingFilters: %s\n", lastTxnId, lastAclChangesetId, storeId, storeProtocol, indexingFilters)); //Indexing filters Filters filters = null; if (indexingFilters != null) filters = this.getIndexingFilters(indexingFilters); //Getting the Store ID on which the changes are requested Pair<Long, StoreRef> store = nodeDao.getStore(new StoreRef(storeProtocol, storeId)); if (store == null) { throw new IllegalArgumentException("Invalid store reference: " + storeProtocol + "://" + storeId); } Set<NodeEntity> nodes = new HashSet<NodeEntity>(); //Updating the last IDs being processed //Depending on params passed to the request, results will be rendered out if (lastTxnId == null) { lastTxnId = new Long(0); } List<NodeEntity> nodesFromTxns = indexingService.getNodesByTransactionId(store, lastTxnId, maxTxns, filters); if (nodesFromTxns != null && nodesFromTxns.size() > 0) { nodes.addAll(nodesFromTxns); } //Set the last database transaction ID or increment it by maxTxns Long lastTxnIdDB = indexingService.getLastTransactionID(); if ((lastTxnId + maxTxns) > lastTxnIdDB) { lastTxnId = lastTxnIdDB; } else { lastTxnId += maxTxns; } if (lastAclChangesetId == null) { lastAclChangesetId = new Long(0); } List<NodeEntity> nodesFromAcls = indexingService.getNodesByAclChangesetId(store, lastAclChangesetId, maxAclChangesets, filters); if (nodesFromAcls != null && nodesFromAcls.size() > 0) { nodes.addAll(nodesFromAcls); } //Set the last database aclChangeSet ID or increment it by maxAclChangesets Long lastAclChangesetIdDB = indexingService.getLastAclChangeSetID(); if ((lastAclChangesetId + maxAclChangesets) > lastAclChangesetIdDB) { lastAclChangesetId = lastAclChangesetIdDB; } else { lastAclChangesetId += maxAclChangesets; } //elapsed time long elapsedTime = System.currentTimeMillis() - startTime; //Render them out Map<String, Object> model = new HashMap<String, Object>(1, 1.0f); model.put("qnameDao", qnameDao); model.put("nsResolver", namespaceService); model.put("nodes", nodes); model.put("lastTxnId", lastTxnId); model.put("lastAclChangesetId", lastAclChangesetId); model.put("storeId", storeId); model.put("storeProtocol", storeProtocol); model.put("serviceContextPath", serviceContextPath); model.put("propertiesUrlPrefix", propertiesUrlPrefix); model.put("elapsedTime", elapsedTime); //This allows to call the static method QName.createQName from the FTL template try { BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel qnameStatics = (TemplateHashModel) staticModels .get("org.alfresco.service.namespace.QName"); model.put("QName", qnameStatics); } catch (Exception e) { throw new AlfrescoRuntimeException( "Cannot add BeansWrapper for static QName.createQName method to be used from a Freemarker template", e); } logger.debug(String.format("Attaching %s nodes to the WebScript template", nodes.size())); return model; }
From source file:com.arduino2fa.xbee.ReceivePacket.java
private ReceivePacket() throws Exception { XBee xbee = new XBee(); int count = 0; int errors = 0; // Transmit stuff final int timeout = 5000; int ackErrors = 0; int ccaErrors = 0; int purgeErrors = 0; long now;//from w w w. ja v a2 s.c o m // HTTP stuff CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpHost httpHost = new HttpHost("ec2-54-186-213-97.us-west-2.compute.amazonaws.com", 3000, "http"); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials("admin", "admin") // TODO get from command line ); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); BasicScheme basicScheme = new BasicScheme(); authCache.put(httpHost, basicScheme); // Add AuthCache to the execution context HttpClientContext httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); httpClientContext.setAuthCache(authCache); HttpGet httpGet = new HttpGet("/token-requests/1"); CloseableHttpResponse httpResponse; BufferedReader br; StringBuffer result; String line; try { // Connect to the XBee xbee.open(XbeeConfig.PORT, XbeeConfig.BAUD_RATE); now = System.currentTimeMillis(); // Loop indefinitely; sleeps for a few seconds at the end of every iteration while (true) { // Check if there are queued tx requests on the server httpResponse = httpClient.execute(httpHost, httpGet, httpClientContext); br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); result = new StringBuffer(); while ((line = br.readLine()) != null) { result.append(line); } // Check if the result is a JSON object if (result.charAt(0) != '{') { log.error("Result " + result.toString() + " is not a JSON object"); continue; } JSONObject object = (JSONObject) JSONValue.parse(result.toString()); if (object != null) { Long time = (Long) object.get("time"); // Check if the request is a new one (created after last check) if (time > last) { String token = (String) object.get("token"); byte[] tokenHex = SimpleCrypto.toByte(token); int[] payload = new int[] { tokenHex[0], tokenHex[1], tokenHex[2] }; XBeeAddress16 destination = new XBeeAddress16(0xFF, 0xFF); TxRequest16 tx = new TxRequest16(destination, payload); try { log.info("sending tx request with payload: " + token); XBeeResponse response = xbee.sendSynchronous(tx, timeout); if (response.getApiId() != ApiId.TX_STATUS_RESPONSE) { log.debug("expected tx status but received " + response); } else { log.debug("got tx status"); if (((TxStatusResponse) response).getFrameId() != tx.getFrameId()) { throw new RuntimeException("frame id does not match"); } if (((TxStatusResponse) response).getStatus() != TxStatusResponse.Status.SUCCESS) { errors++; if (((TxStatusResponse) response).isAckError()) { ackErrors++; } else if (((TxStatusResponse) response).isCcaError()) { ccaErrors++; } else if (((TxStatusResponse) response).isPurged()) { purgeErrors++; } log.debug("Tx status failure with status: " + ((TxStatusResponse) response).getStatus()); } else { // success log.debug("Success. count is " + count + ", errors is " + errors + ", in " + (System.currentTimeMillis() - now) + ", ack errors " + ackErrors + ", ccaErrors " + ccaErrors + ", purge errors " + purgeErrors); } count++; } } catch (XBeeTimeoutException e) { e.printStackTrace(); } } } last = System.currentTimeMillis(); httpGet.releaseConnection(); // Delay Thread.sleep(2000); } } finally { xbee.close(); } }
From source file:eu.hansolo.accs.RestClient.java
public void deleteLocation(final Location LOCATION) { JSONObject jsonObject = getLocation(LOCATION.name); final String OID = ((JSONObject) JSONValue.parse(jsonObject.get("_id").toString())).get("$oid").toString(); URIBuilder builder = new URIBuilder(); builder.setScheme("https").setHost("api.mlab.com").setPort(443) .setPath(String.join("/", DbCollection.LOCATIONS.REST_URL, OID)) .setParameter("apiKey", MLAB_API_KEY); deleteSpecific(builder);//from www . jav a2 s. c o m }
From source file:gov.nih.nci.eagle.web.ajax.DynamicListHelper.java
public String getDetailsFromList(String listName) { WebContext ctx = WebContextFactory.get(); String cacheId = ctx.getSession(false).getId(); UserListBeanHelper ulbh = new UserListBeanHelper(cacheId); String jdetails = ulbh.getDetailsFromList(listName); Object o = JSONValue.parse(jdetails); //object [string -> listName], [string -> listType], [jsonArray->validItems] //validItems array of JSONObjects [name], [notes], [rank] JSONObject listDetails = (JSONObject) o; Object oo = listDetails.get("validItems"); JSONArray validItems = (JSONArray) oo; for (Object ooo : validItems) { JSONObject itemDesc = (JSONObject) ooo; //see which specimens this item has ArrayList specimens = new ArrayList(); for (SpecimenType sp : SpecimenType.values()) { List justone = new ArrayList(); justone.add(itemDesc.get("name")); List shouldbeone = listValidationService.validateList(justone, sp); if (shouldbeone.size() == 1) { //hit specimens.add(sp.toString()); } else { specimens.add(""); }//from ww w.j a v a 2 s . co m } itemDesc.put("specimens", StringUtils.join(specimens.toArray(), ",")); } return listDetails.toString(); }