List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:com.treasuredata.jdbc.TDResultSet.java
private void initColumnNamesAndTypes(String resultSchema) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("resultSchema: " + resultSchema); }/*from w w w . j a va2 s .co m*/ if (resultSchema == null) { LOG.warning("Illegal resultSchema: null"); return; } @SuppressWarnings("unchecked") List<List<String>> cols = (List<List<String>>) JSONValue.parse(resultSchema); if (cols == null) { LOG.warning("Illegal resultSchema: " + resultSchema); return; } columnNames = new ArrayList<String>(cols.size()); columnTypes = new ArrayList<String>(cols.size()); for (List<String> col : cols) { columnNames.add(col.get(0)); columnTypes.add(col.get(1)); } }
From source file:co.edu.unal.arqdsoft.presentacion.servlet.ServletSoporte.java
private Respuesta crearReporteDano(JSONObject obj) { JSONObject datos = (JSONObject) JSONValue.parse(obj.get("datos").toString()); long idCliente = Long.parseLong(datos.get("cliente").toString()); int idOperador = Integer.parseInt(datos.get("operador").toString()); ;/* w w w. j a v a 2s. c o m*/ boolean enviaTecnico = Boolean.valueOf(datos.get("enviaTecnico").toString()); Date fechatecnico = null; boolean solucion = Boolean.valueOf(datos.get("solucion").toString()); try { if (!solucion) fechatecnico = new SimpleDateFormat("dd/mm/yy").parse(datos.get("fechaTecnico").toString()); } catch (ParseException ex) { Logger.getLogger(ServletSoporte.class.getName()).log(Level.SEVERE, null, ex); } String info = datos.get("info").toString(); String direccion = datos.get("direccion").toString(); int respuestaControl = ControlSoporte.crearReporteDano(idCliente, info, idOperador, solucion, enviaTecnico, direccion, fechatecnico); if (respuestaControl <= 0) return new Respuesta("Error de servidor: " + respuestaControl, new Contenido(null, "")); // return new Respuesta("not implemented", new Contenido(t, "")); return new Respuesta("Reporte creado con exito", new Contenido(null, "")); }
From source file:com.mobicage.rogerthat.registration.AbstractRegistrationWizard.java
protected void sendInstallationId(final MainService mainService) { if (mInstallationId == null) { throw new IllegalStateException("Installation id should be set!"); }//from w w w . ja v a 2 s . com new SafeAsyncTask<Object, Object, Boolean>() { @SuppressWarnings("unchecked") @Override protected Boolean safeDoInBackground(Object... params) { try { HttpClient httpClient = HTTPUtil.getHttpClient(10000, 3); final HttpPost httpPost = HTTPUtil.getHttpPost(mainService, CloudConstants.REGISTRATION_REGISTER_INSTALL_URL); List<NameValuePair> formParams = HTTPUtil.getRegistrationFormParams(mainService); formParams.add(new BasicNameValuePair("version", MainService.getVersion(mainService))); formParams.add(new BasicNameValuePair("install_id", getInstallationId())); UrlEncodedFormEntity entity; try { entity = new UrlEncodedFormEntity(formParams, HTTP.UTF_8); } catch (UnsupportedEncodingException e) { L.bug(e); return true; } httpPost.setEntity(entity); L.d("Sending installation id: " + getInstallationId()); try { HttpResponse response = httpClient.execute(httpPost); L.d("Installation id sent"); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { L.e("HTTP request resulted in status code " + statusCode); return false; } HttpEntity httpEntity = response.getEntity(); if (httpEntity == null) { L.e("Response of '" + CloudConstants.REGISTRATION_REGISTER_INSTALL_URL + "' was null"); return false; } final Map<String, Object> responseMap = (Map<String, Object>) JSONValue .parse(new InputStreamReader(httpEntity.getContent())); if (responseMap == null) { L.e("HTTP request responseMap was null"); return false; } if (!"success".equals(responseMap.get("result"))) { L.e("HTTP request result was not 'success' but: " + responseMap.get("result")); return false; } return true; } catch (ClientProtocolException e) { L.bug(e); return false; } catch (IOException e) { L.bug(e); return false; } } catch (Exception e) { L.bug(e); return false; } } }.execute(); }
From source file:ch.njol.skript.Updater.java
/** * @param sender Sender to receive messages * @param download Whether to directly download the newest version if one is found * @param isAutomatic//from www .ja v a 2s.c o m */ static void check(final CommandSender sender, final boolean download, final boolean isAutomatic) { stateLock.writeLock().lock(); try { if (state == UpdateState.CHECK_IN_PROGRESS || state == UpdateState.DOWNLOAD_IN_PROGRESS) return; state = UpdateState.CHECK_IN_PROGRESS; } finally { stateLock.writeLock().unlock(); } if (!isAutomatic || Skript.logNormal()) Skript.info(sender, "" + m_checking); Skript.newThread(new Runnable() { @Override public void run() { infos.clear(); InputStream in = null; try { final URLConnection conn = new URL(filesURL).openConnection(); conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)"); in = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(in, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding())); try { final String line = reader.readLine(); if (line != null) { final JSONArray a = (JSONArray) JSONValue.parse(line); for (final Object o : a) { final Object name = ((JSONObject) o).get("name"); if (!(name instanceof String) || !((String) name).matches("\\d+\\.\\d+(\\.\\d+)?( \\(jar( only)?\\))?"))// not the default version pattern to not match beta/etc. versions continue; final Object url = ((JSONObject) o).get("downloadUrl"); if (!(url instanceof String)) continue; final Version version = new Version(((String) name).contains(" ") ? "" + ((String) name).substring(0, ((String) name).indexOf(' ')) : ((String) name)); if (version.compareTo(Skript.getVersion()) > 0) { infos.add(new VersionInfo((String) name, version, (String) url)); } } } } finally { reader.close(); } if (!infos.isEmpty()) { Collections.sort(infos); latest.set(infos.get(0)); } else { latest.set(null); } getChangelogs(sender); final String message = infos.isEmpty() ? (Skript.getVersion().isStable() ? "" + m_running_latest_version : "" + m_running_latest_version_beta) : "" + m_update_available; if (isAutomatic && !infos.isEmpty()) { Skript.adminBroadcast(message); } else { Skript.info(sender, message); } if (download && !infos.isEmpty()) { stateLock.writeLock().lock(); try { state = UpdateState.DOWNLOAD_IN_PROGRESS; } finally { stateLock.writeLock().unlock(); } download_i(sender, isAutomatic); } else { stateLock.writeLock().lock(); try { state = UpdateState.CHECKED_FOR_UPDATE; } finally { stateLock.writeLock().unlock(); } } } catch (final IOException e) { stateLock.writeLock().lock(); try { state = UpdateState.CHECK_ERROR; error.set(ExceptionUtils.toString(e)); if (sender != null) Skript.error(sender, m_check_error.toString()); } finally { stateLock.writeLock().unlock(); } } catch (final Exception e) { if (sender != null) Skript.error(sender, m_internal_error.toString()); Skript.exception(e, "Unexpected error while checking for a new version of Skript"); stateLock.writeLock().lock(); try { state = UpdateState.CHECK_ERROR; error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage()); } finally { stateLock.writeLock().unlock(); } } finally { if (in != null) { try { in.close(); } catch (final IOException e) { } } } } }, "Skript update thread").start(); }
From source file:com.walmartlabs.mupd8.application.Config.java
@SuppressWarnings("unchecked") private void loadAppConfig(String filename) throws Exception { JSONObject appJson = (JSONObject) JSONValue.parse(readWithPreprocessing(new FileReader(filename))); JSONObject applicationNameObject = new JSONObject(); String applicationName = (String) appJson.get("application"); applicationNameObject.put(applicationName, appJson); JSONObject mupd8 = (JSONObject) configuration.get("mupd8"); mupd8.put("application", applicationNameObject); if (appJson.containsKey("performers")) { JSONArray performers = (JSONArray) appJson.get("performers"); for (int i = 0; i < performers.size(); i++) { JSONObject json = (JSONObject) performers.get(i); String performer = (String) json.get("performer"); workerJSONs.put(performer, json); }/*from w w w .j av a 2 s.c om*/ } }
From source file:cpd3314.project.ProductTest.java
/** * Test of toJSON method, of class Product. *//*from w ww. jav a 2 s . c o m*/ @Test public void testToJSON() throws Exception { System.out.println("toJSON"); Product instance = sample; JSONObject expected = new JSONObject(); expected.put("name", sampleName); expected.put("id", sampleId); expected.put("description", sampleDesc); expected.put("quantity", sampleQuantity); expected.put("dateAdded", sampleDate); String result = instance.toJSON(); JSONObject resultJSON = (JSONObject) JSONValue.parse(result); assertEquals(expected.toJSONString(), resultJSON.toJSONString()); }
From source file:com.hortonworks.amstore.view.TaskManagerService.java
/** * Handles: POST /taskmanager/postupdatetasks Add a task to the list of * tasks This is done because of BUG: a call to viewContext.putInstanceData * inside the servlet returns ERROR 500 after a while. * /*from ww w . j av a 2 s. co m*/ * @param headers * http headers * @param ui * uri info * * @return the response */ @POST @Path("/postupdatetasks") @Produces({ "text/html" }) public Response addPostUpdateTasks(String body, @Context HttpHeaders headers, @Context UriInfo ui) throws IOException { String current = viewContext.getInstanceData("post-update-tasks"); if (current == null) current = "[]"; JSONArray array = (JSONArray) JSONValue.parse(current); array.add(body); viewContext.putInstanceData("post-update-tasks", array.toString()); String output = "Added task:" + body; return Response.ok(output).type("text/html").build(); }
From source file:com.stratio.deep.core.extractor.ExtractorTest.java
/** * Transform RDD./* www .j ava 2 s . c om*/ * * @param <T> the type parameter * @param stringJavaRDD the string java rDD * @param entityClass the entity class * @return the java rDD */ protected <T> JavaRDD<T> transformRDD(JavaRDD<String> stringJavaRDD, final Class<T> entityClass) { JavaRDD<JSONObject> jsonObjectJavaRDD = stringJavaRDD.map(new Function<String, JSONObject>() { @Override public JSONObject call(String v1) throws Exception { return (JSONObject) JSONValue.parse(v1); } }); JavaRDD<T> javaRDD = jsonObjectJavaRDD.map(new Function<JSONObject, T>() { @Override public T call(JSONObject v1) throws Exception { return transform(v1, BOOK_INPUT, entityClass); } }); return javaRDD; }
From source file:iphonestalker.util.FindMyIPhoneReader.java
public boolean pollLocation(int device) { if (device < numDevices) { try {/*from w ww . j av a 2 s . c o m*/ // Poll for data HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); // Read the data JSONObject object = (JSONObject) JSONValue.parse(reader); JSONArray array = ((JSONArray) object.get("content")); //int devices = array.size(); //System.out.println("Found " + devices + " devices"); // Get the device data object = (JSONObject) array.get(device); // Update the route information IPhoneLocation iPhoneLocation = getLocation(object); if (iPhoneLocation != null) { iPhoneRouteList.get(device).addLocation(iPhoneLocation); } } catch (ClientProtocolException ex) { logger.log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return false; } } else { logger.log(Level.WARNING, "Device {0} is out of range ({1} max)", new Object[] { (device + 1), numDevices }); return false; } return true; }
From source file:formatter.handler.get.FormatterGetHandler.java
/** * Try to retrieve the CorTex/CorCode version specified by the path * @param db the database to fetch from/*from w w w .jav a 2s. co m*/ * @param docID the document ID * @param vPath the groups/version path to get * @return the CorTex/CorCode version contents or null if not found * @throws AeseException if the resource couldn't be found for some reason */ protected EcdosisVersion doGetResourceVersion(String db, String docID, String vPath) throws FormatterException { EcdosisVersion version = new EcdosisVersion(); JSONObject doc = null; char[] data = null; String res = null; //System.out.println("fetching version "+vPath ); try { res = Connector.getConnection().getFromDb(db, docID); } catch (Exception e) { throw new FormatterException(e); } if (res != null) doc = (JSONObject) JSONValue.parse(res); if (doc != null) { String format = (String) doc.get(JSONKeys.FORMAT); if (format == null) throw new FormatterException("doc missing format"); version.setFormat(format); if (version.getFormat().equals(Formats.MVD)) { MVD mvd = MVDFile.internalise((String) doc.get(JSONKeys.BODY)); if (vPath == null) vPath = (String) doc.get(JSONKeys.VERSION1); version.setStyle((String) doc.get(JSONKeys.STYLE)); String sName = Utils.getShortName(vPath); String gName = Utils.getGroupName(vPath); int vId = mvd.getVersionByNameAndGroup(sName, gName); //System.out.println("vId="+vId+" sName="+sName); version.setMVD(mvd); if (vId != 0) { data = mvd.getVersion(vId); String desc = mvd.getDescription(); //System.out.println("description="+desc); //int nversions = mvd.numVersions(); //System.out.println("nversions="+nversions); //System.out.println("length of version "+vId+"="+data.length); if (data != null) version.setVersion(data); else throw new FormatterException("Version " + vPath + " not found"); } else throw new FormatterException("Version " + vPath + " not found"); } else { String body = (String) doc.get(JSONKeys.BODY); version.setStyle((String) doc.get(JSONKeys.STYLE)); if (body == null) throw new FormatterException("empty body"); try { data = body.toCharArray(); } catch (Exception e) { throw new FormatterException(e); } version.setVersion(data); } } return version; }