List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java
@Override public List<PlayerRecord> doBulkLookup(UUID... uuids) { String list = combine(uuids); String response = doUrlRequest(getConnectionUrl() + "/name/list/" + list); if (response != null) { JSONObject json = (JSONObject) JSONValue.parse(response); if (json.containsKey("results")) { JSONObject object = (JSONObject) json.get("results"); List<PlayerRecord> records = new ArrayList<>(); for (Object key : object.keySet()) { UUID uuid = convertUuid(key.toString()); String name = (String) ((JSONObject) object.get(key)).get("name"); if (uuid == null || name.equals("unknown")) continue; PlayerRecord record = new Turt2LivePlayerRecord(uuid, name); records.add(record);//w w w. j a v a 2s. c om } return records; } } return null; }
From source file:co.edu.unal.arqdsoft.presentacion.servlet.ServletVentas.java
private Respuesta setVenta(JSONObject ventaJson) { String error = "Problemas con la comunicacin"; try {//w w w. j a v a2 s . c o m ventaJson = (JSONObject) JSONValue.parse(ventaJson.get("datos").toString()); int idEmpleado = Integer.parseInt(ventaJson.get("empleado").toString()); int idPlan = Integer.parseInt(ventaJson.get("plan").toString()); String direccionVenta = ventaJson.get("dirInstal").toString(); int idCliente = 0; String nombreCliente = ""; String informacionCliente = ""; try { JSONObject clienteJson = (JSONObject) JSONValue.parse(ventaJson.get("cliente").toString()); idCliente = Integer.parseInt(clienteJson.get("id").toString()); nombreCliente = clienteJson.get("nombre").toString(); informacionCliente = clienteJson.get("informacion").toString(); } catch (Exception e) { error = "Problemas con el cliente"; } boolean respuesta = ControlVentas.setVenta(idEmpleado, idCliente, nombreCliente, informacionCliente, idPlan, direccionVenta); /*TEST*/ // respuesta = true; // respuesta = false; /*TEST FIN*/ if (respuesta) { // t.put("nombre", p.getCliente().getNombre()); // t.put("id", p.getId()); // t.put("informacion", p.getCliente().getInformacion()); // t.put("empleado", p.getVendedor().getId()); // t.put("plan", p.getPlan()); // t.put("dirInstal", p.getDireccionInstalacion()); return new Respuesta("", new Contenido(null, "Venta realizada exitosamente")); } else { error = "No se realiz la venta"; throw new Exception(); } } catch (Exception ex) { Logger.getLogger(ServletProductos.class.getName()).log(Level.SEVERE, null, ex); return new Respuesta(error, new Contenido()); } }
From source file:com.precioustech.fxtrading.oanda.restapi.streaming.events.OandaEventsStreamingService.java
@Override public void startEventsStreaming() { stopEventsStreaming();//from w w w . j a v a2s.co m streamThread = new Thread(new Runnable() { @Override public void run() { CloseableHttpClient httpClient = getHttpClient(); try { BufferedReader br = setUpStreamIfPossible(httpClient); if (br != null) { String line; while ((line = br.readLine()) != null && serviceUp) { Object obj = JSONValue.parse(line); JSONObject jsonPayLoad = (JSONObject) obj; if (jsonPayLoad.containsKey(heartbeat)) { handleHeartBeat(jsonPayLoad); } else if (jsonPayLoad.containsKey(transaction)) { JSONObject transactionObject = (JSONObject) jsonPayLoad.get(transaction); String transactionType = transactionObject.get(type).toString(); /*convert here so that event bus can post to an appropriate handler, * event though this does not belong here*/ EventPayLoad<JSONObject> payLoad = OandaUtils.toOandaEventPayLoad(transactionType, transactionObject); if (payLoad != null) { eventCallback.onEvent(payLoad); } } else if (jsonPayLoad.containsKey(OandaJsonKeys.disconnect)) { handleDisconnect(line); } } br.close(); } } catch (Exception e) { LOG.error("error encountered inside event streaming thread", e); } finally { serviceUp = false; TradingUtils.closeSilently(httpClient); } } }, "OandEventStreamingThread"); streamThread.start(); }
From source file:com.precioustech.fxtrading.oanda.restapi.streaming.marketdata.OandaMarketDataStreamingService.java
@Override public void startMarketDataStreaming() { stopMarketDataStreaming();/*from w w w .ja va 2 s. c o m*/ this.streamThread = new Thread(new Runnable() { @Override public void run() { CloseableHttpClient httpClient = getHttpClient(); try { BufferedReader br = setUpStreamIfPossible(httpClient); if (br != null) { String line; while ((line = br.readLine()) != null && serviceUp) { Object obj = JSONValue.parse(line); JSONObject instrumentTick = (JSONObject) obj; // unwrap if necessary if (instrumentTick.containsKey(tick)) { instrumentTick = (JSONObject) instrumentTick.get(tick); } if (instrumentTick.containsKey(OandaJsonKeys.instrument)) { final String instrument = instrumentTick.get(OandaJsonKeys.instrument).toString(); final String timeAsString = instrumentTick.get(time).toString(); final long eventTime = Long.parseLong(timeAsString); final double bidPrice = ((Number) instrumentTick.get(bid)).doubleValue(); final double askPrice = ((Number) instrumentTick.get(ask)).doubleValue(); marketEventCallback.onMarketEvent(new TradeableInstrument<String>(instrument), bidPrice, askPrice, new DateTime(TradingUtils.toMillisFromNanos(eventTime))); } else if (instrumentTick.containsKey(heartbeat)) { handleHeartBeat(instrumentTick); } else if (instrumentTick.containsKey(disconnect)) { handleDisconnect(line); } } br.close(); // stream.close(); } } catch (Exception e) { LOG.error("error encountered inside market data streaming thread", e); } finally { serviceUp = false; TradingUtils.closeSilently(httpClient); } } }, "OandMarketDataStreamingThread"); this.streamThread.start(); }
From source file:com.storageroomapp.client.Collection.java
/** * Parses a String of json text and returns an Collection object. * It will correctly parse the Collection object if it is toplevel, * or also if nested in an 'collection' key-value pair. * //from w ww . jav a 2 s. c om * @param json the String with the json text * @return an Collection object, or null if the parsing failed */ static public Collection parseJson(Application parent, String json) { JSONObject collectionObj = (JSONObject) JSONValue.parse(json); if (collectionObj == null) { return null; } // unwrap the Collection object if it is a value with key 'collection; JSONObject collectionInnerObj = (JSONObject) collectionObj.get("collection"); if (collectionInnerObj != null) { collectionObj = collectionInnerObj; } return parseJsonObject(parent, collectionObj); }
From source file:com.punyal.medusaserver.californiumServer.core.MedusaAuthenticationThread.java
@Override public void run() { running = true;/*from w w w . j a v a 2 s . co m*/ Logger.getLogger("org.eclipse.californium.core.network.CoAPEndpoint").setLevel(Level.OFF); Logger.getLogger("org.eclipse.californium.core.network.EndpointManager").setLevel(Level.OFF); Logger.getLogger("org.eclipse.californium.core.network.stack.ReliabilityLayer").setLevel(Level.OFF); CoapResponse response; while (running) { if (ticket.isValid()) { //System.out.println("Valid Ticket"); } else { //System.out.println("Not Valid Ticket"); try { coapClient.setURI(medusaServerAddress + "/" + MEDUSA_SERVER_AUTHENTICATION_SERVICE_NAME); response = coapClient.get(); if (response != null) { try { JSONObject json = (JSONObject) JSONValue.parse(response.getResponseText()); ticket.setAuthenticator(json.get(JSON_AUTHENTICATOR).toString()); //System.out.println(ticket.getAuthenticator()); json.clear(); json.put(JSON_USER_NAME, medusaUserName); json.put(JSON_USER_PASSWORD, Cryptonizer.encryptCoAP(medusaSecretKey, ticket.getAuthenticator(), medusaUserPass)); json.put(JSON_INFO, medusaUserInfo); //System.out.println(json.toString()); response = coapClient.put(json.toString(), 0); if (response != null) { json.clear(); try { json = (JSONObject) JSONValue.parse(response.getResponseText()); ticket.setTicket( UnitConversion.hexStringToByteArray(json.get(JSON_TICKET).toString())); ticket.setExpireTime( (Long) json.get(JSON_TIME_TO_EXPIRE) + (new Date()).getTime()); //System.out.println((Long)json.get(JSON_TIME_TO_EXPIRE)); noAuthenticationResponseCounter = 0; noTicketResponseCounter = 0; if (authenticated == false) { //LOGGER.log(Level.INFO, SMS_AUTHENTICATED); System.err.println(SMS_AUTHENTICATED); authenticated = true; } } catch (Exception e) { noTicketResponseCounter++; //System.out.println("JSON Error "+e); } } else { //System.out.println("No Ticket received."); noTicketResponseCounter++; } } catch (Exception e) { noAuthenticationResponseCounter++; //System.out.println("JSON Error "+e); } } else { //System.out.println("No Authentication received."); noAuthenticationResponseCounter++; } } catch (IllegalArgumentException ex) { noAuthenticationResponseCounter++; } if ((authenticated == true) && ((noAuthenticationResponseCounter != 0) || (noTicketResponseCounter != 0))) { //LOGGER.log(Level.INFO, SMS_NO_AUTHENTICATED); System.err.println(SMS_NO_AUTHENTICATED); authenticated = false; } if (noAuthenticationResponseCounter > MAX_NO_AUTHENTICATION_RESPONSES) { try { //LOGGER.log(Level.WARNING, SMS_NO_AUTHENTICATION_RESPONSE); System.err.println(SMS_NO_AUTHENTICATION_RESPONSE); sleep(NO_AUTHENTICATION_RESPONSES_DELAY); } catch (InterruptedException ex) { Logger.getLogger(MedusaAuthenticationThread.class.getName()).log(Level.SEVERE, null, ex); } noAuthenticationResponseCounter = 0; noTicketResponseCounter = 0; } if (noTicketResponseCounter > MAX_NO_TICKET_RESPONSES) { try { //LOGGER.log(Level.WARNING, SMS_NO_TICKET_RESPONSE); System.err.println(SMS_NO_TICKET_RESPONSE); sleep(NO_TICKET_RESPONSES_DELAY); } catch (InterruptedException ex) { Logger.getLogger(MedusaAuthenticationThread.class.getName()).log(Level.SEVERE, null, ex); } noAuthenticationResponseCounter = 0; noTicketResponseCounter = 0; } } } LOGGER.log(Level.WARNING, "Thread [{0}] dying", MedusaAuthenticationThread.class.getSimpleName()); }
From source file:mml.handler.post.MMLPostHandler.java
/** * Parse the import params from the request * @param request the http request//from w w w.ja va 2 s .c o m */ void parseImportParams(HttpServletRequest request) throws MMLException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(this.encoding); if (fieldName.equals(Params.DOCID)) { int index = contents.lastIndexOf("."); if (index != -1) contents = contents.substring(0, index); docid = contents; } else if (fieldName.equals(Params.AUTHOR)) this.author = contents; else if (fieldName.equals(Params.TITLE)) this.title = contents; else if (fieldName.equals(Params.STYLE)) this.style = contents; else if (fieldName.equals(Params.FORMAT)) this.format = contents; else if (fieldName.equals(Params.SECTION)) this.section = contents; else if (fieldName.equals(Params.VERSION1)) this.version1 = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.ANNOTATIONS)) annotations = (JSONArray) JSONValue.parse(contents); } } else if (item.getName().length() > 0) { try { // item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if (type != null) { if (type.startsWith("image/")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData()); if (images == null) images = new ArrayList<ImageFile>(); images.add(iFile); } else if (type.equals("text/plain")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } String style = new String(bh.getData(), encoding); if (files == null) files = new ArrayList<String>(); files.add(style); } } } catch (Exception e) { throw new MMLException(e); } } } } catch (Exception e) { throw new MMLException(e); } }
From source file:com.linemetrics.monk.api.RestClient.java
private JSONObject request(HttpRequestBase req, Boolean attachAuthHeader) throws RestException, IOException { req.addHeader("Accept", "application/json"); if (creds != null && attachAuthHeader) { creds.authenticate(req);//from w w w .ja v a2 s . c o m } StringBuilder result = new StringBuilder(); try { HttpResponse resp = httpClient.execute(req); HttpEntity ent = resp.getEntity(); if (ent != null) { String encoding = null; if (ent.getContentEncoding() != null) { encoding = ent.getContentEncoding().getValue(); } if (encoding == null) { Header contentTypeHeader = resp.getFirstHeader("content-type"); HeaderElement[] contentTypeElements = contentTypeHeader.getElements(); for (HeaderElement he : contentTypeElements) { NameValuePair nvp = he.getParameterByName("charset"); if (nvp != null) { encoding = nvp.getValue(); } } } InputStreamReader isr = encoding != null ? new InputStreamReader(ent.getContent(), encoding) : new InputStreamReader(ent.getContent()); BufferedReader br = new BufferedReader(isr); String line = ""; while ((line = br.readLine()) != null) result.append(line); } StatusLine sl = resp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString()); } } catch (Exception e) { e.printStackTrace(); throw new RestException(e.getMessage(), -1, ""); } finally { req.releaseConnection(); } return (JSONObject) JSONValue.parse(!result.toString().isEmpty() ? result.toString() : "{\"data\":[]}"); }
From source file:eu.ebbitsproject.peoplemanager.utils.HttpUtils.java
public static String findPerson(String errorType, String location) { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = PropertiesUtils.getProperty("uiapp.address"); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("action", "find-persons")); String properties = "demo-e1:competence=" + errorType + ",demo-e1:area-responsibility=" + location; String pmProperties = "available=true"; nvps.add(new BasicNameValuePair("properties", properties)); nvps.add(new BasicNameValuePair("pmProperties", pmProperties)); try {//from ww w.j a v a2 s . c om httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException ex) { Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex); } CloseableHttpResponse response = null; String personJSON = null; try { response = httpClient.execute(httpPost); personJSON = EntityUtils.toString(response.getEntity()); System.out.println("######## PersonJSON: " + personJSON); } catch (IOException e) { Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e); } finally { try { response.close(); } catch (IOException e) { Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e); } } if (personJSON != null) { JSONArray persons = (JSONArray) JSONValue.parse(personJSON); Iterator<JSONObject> i = persons.iterator(); if (i.hasNext()) { JSONObject o = i.next(); return o.get("id").toString(); } } return personJSON; }
From source file:importer.Archive.java
/** * Using the project version info set long names for each short name * @param docid the project docid/*from w w w .ja va 2s .c o m*/ * @throws ImporterException */ public void setVersionInfo(String docid) throws ImporterException { try { String project = Connector.getConnection().getFromDb(Database.PROJECTS, docid); if (project == null) { String[] parts = docid.split("/"); if (parts.length == 3) docid = parts[0] + "/" + parts[1]; else throw new Exception("Couldn't find project " + docid); project = Connector.getConnection().getFromDb(Database.PROJECTS, docid); if (project == null) throw new Exception("Couldn't find project " + docid); } JSONObject jObj = (JSONObject) JSONValue.parse(project); if (jObj.containsKey(JSONKeys.VERSIONS)) { JSONArray versions = (JSONArray) jObj.get(JSONKeys.VERSIONS); for (int i = 0; i < versions.size(); i++) { JSONObject version = (JSONObject) versions.get(i); Set<String> keys = version.keySet(); Iterator<String> iter = keys.iterator(); while (iter.hasNext()) { String key = iter.next(); nameMap.put(key, (String) version.get(key)); } } } } catch (Exception e) { throw new ImporterException(e); } }