List of usage examples for org.json JSONArray get
public Object get(int index) throws JSONException
From source file:at.alladin.rmbt.android.util.LogTask.java
@Override protected Void doInBackground(final String... params) { try {//from ww w .j a v a 2 s. c o m serverConn = new ControlServerConnection(activity); final List<File> logFiles = new ArrayList<File>(); if (params == null || params.length == 0) { File f = new File(Environment.getExternalStorageDirectory(), "qosdebug"); final File[] logs = f.listFiles(); if (logs != null) { for (File l : logs) { if (l.length() > 0) { logFiles.add(l); } else { //delete old empty log file l.delete(); } } } } else { for (String fileName : params) { File f = new File(fileName); if (f.exists() && f.length() > 0) { logFiles.add(f); } } } System.out.println("log files found: " + logFiles); if (logFiles.size() > 0) { for (File logFile : logFiles) { System.out.println("Sending file: " + logFile.getAbsolutePath()); Scanner s = null; try { BufferedReader br = new BufferedReader(new FileReader(logFile)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } final JSONObject requestData = new JSONObject(); requestData.put("content", sb.toString()); requestData.put("logfile", LOGFILE_PREFIX + "_" + ConfigHelper.getUUID(activity) + "_" + logFile.getName()); final JSONObject fileTimes = new JSONObject(); fileTimes.put("last_access", TimeUnit.SECONDS.convert(logFile.lastModified(), TimeUnit.MILLISECONDS)); fileTimes.put("last_modified", TimeUnit.SECONDS.convert(logFile.lastModified(), TimeUnit.MILLISECONDS)); fileTimes.put("created", TimeUnit.SECONDS.convert(logFile.lastModified(), TimeUnit.MILLISECONDS)); requestData.put("file_times", fileTimes); JSONArray result = serverConn.sendLogReport(requestData); if (result != null) { final String resultStatus = ((JSONObject) result.get(0)).getString("status"); if ("OK".equals(resultStatus.toUpperCase(Locale.US))) { System.out.println("Log file sent successfully. Deleting."); br.close(); logFile.delete(); } } } finally { br.close(); } } catch (Exception e) { e.printStackTrace(); } finally { if (s != null) { s.close(); } } } } } catch (Throwable t) { t.printStackTrace(); } return null; }
From source file:uk.ac.imperial.presage2.core.cli.run.ExecutorModule.java
/** * <p>/*from w w w . j a v a 2 s .c o m*/ * Load an {@link AbstractModule} which can inject an * {@link ExecutorManager} with the appropriate {@link SimulationExecutor}s * as per provided configuration. * </p> * * <p> * The executor config can be provided in two ways (in order of precedence): * </p> * <ul> * <li><code>executors.properties</code> file on the classpath. This file * should contain a <code>module</code> key who's value is the fully * qualified name of a class which extends {@link AbstractModule} and has a * public constructor which takes a single {@link Properties} object as an * argument or public no-args constructor. An instance of this class will be * returned.</li> * <li><code>executors.json</code> file on the classpath. This file contains * a specification of the executors to load in JSON format. If this file is * valid we will instantiate each executor defined in the spec and add it to * an {@link ExecutorModule} which will provide the bindings for them.</li> * </ul> * * <h3>executors.json format</h3> * * <p> * The <code>executors.json</code> file should contain a JSON object with * the following: * <ul> * <li><code>executors</code> key whose value is an array. Each element of * the array is a JSON object with the following keys: * <ul> * <li><code>class</code>: the fully qualified name of the executor class.</li> * <li><code>args</code>: an array of arguments to pass to a public * constructor of the class.</li> * <li><code>enableLogs</code> (optional): boolean value whether this * executor should save logs to file. Defaults to global value.</li> * <li><code>logDir</code> (optional): string path to save logs to. Defaults * to global value</li> * </ul> * </li> * <li><code>enableLogs</code> (optional): Global value for enableLogs for * each executor. Defaults to false.</li> * <li><code>logDir</code> (optional): Global value for logDir for each * executor. Default values depend on the executor.</li> * </ul> * </p> * <p> * e.g.: * </p> * * <pre class="prettyprint"> * { * "executors": [{ * "class": "my.fully.qualified.Executor", * "args": [1, "some string", true] * },{ * ... * }], * "enableLogs": true * } * </pre> * * @return */ public static AbstractModule load() { Logger logger = Logger.getLogger(ExecutorModule.class); // look for executors.properties // This defines an AbstractModule to use instead of this one. // We try and load the module class given and return it. try { Properties execProps = new Properties(); execProps.load(ExecutorModule.class.getClassLoader().getResourceAsStream("executors.properties")); String moduleName = execProps.getProperty("module", ""); Class<? extends AbstractModule> module = Class.forName(moduleName).asSubclass(AbstractModule.class); // look for suitable ctor, either Properties parameter or default Constructor<? extends AbstractModule> ctor; try { ctor = module.getConstructor(Properties.class); return ctor.newInstance(execProps); } catch (NoSuchMethodException e) { ctor = module.getConstructor(); return ctor.newInstance(); } } catch (Exception e) { logger.debug("Could not create module from executors.properties"); } // executors.properties fail, look for executors.json // This file defines a set of classes to load with parameters for the // constructor. // We try to create each defined executor and add it to this // ExecutorModule. try { // get executors.json file and parse to JSON. // throws NullPointerException if file doesn't exist, or // JSONException if we can't parse the JSON. InputStream is = ExecutorModule.class.getClassLoader().getResourceAsStream("executors.json"); logger.debug("Processing executors from executors.json"); JSONObject execConf = new JSONObject(new JSONTokener(new InputStreamReader(is))); // Create our module and look for executor specs under the executors // array in the JSON. ExecutorModule module = new ExecutorModule(); JSONArray executors = execConf.getJSONArray("executors"); // optional global settings boolean enableLogs = execConf.optBoolean("enableLogs", false); String logDir = execConf.optString("logDir"); logger.info("Building Executors from executors.json"); // Try and instantiate an instance of each executor in the spec. for (int i = 0; i < executors.length(); i++) { try { JSONObject executorSpec = executors.getJSONObject(i); String executorClass = executorSpec.getString("class"); JSONArray args = executorSpec.getJSONArray("args"); Class<? extends SimulationExecutor> clazz = Class.forName(executorClass) .asSubclass(SimulationExecutor.class); // build constructor args. // We assume all types are in primitive form where // applicable. // The only available types are boolean, int, double and // String. Class<?>[] argTypes = new Class<?>[args.length()]; Object[] argValues = new Object[args.length()]; for (int j = 0; j < args.length(); j++) { argValues[j] = args.get(j); Class<?> type = argValues[j].getClass(); if (type == Boolean.class) type = Boolean.TYPE; else if (type == Integer.class) type = Integer.TYPE; else if (type == Double.class) type = Double.TYPE; argTypes[j] = type; } SimulationExecutor exe = clazz.getConstructor(argTypes).newInstance(argValues); logger.debug("Adding executor to pool: " + exe.toString()); module.addExecutorInstance(exe); // logging config boolean exeEnableLog = executorSpec.optBoolean("enableLogs", enableLogs); String exeLogDir = executorSpec.optString("logDir", logDir); exe.enableLogs(exeEnableLog); if (exeLogDir.length() > 0) { exe.setLogsDirectory(exeLogDir); } } catch (JSONException e) { logger.warn("Error parsing executor config", e); } catch (ClassNotFoundException e) { logger.warn("Unknown executor class in config", e); } catch (IllegalArgumentException e) { logger.warn("Illegal arguments for executor ctor", e); } catch (NoSuchMethodException e) { logger.warn("No matching public ctor for args in executor config", e); } catch (Exception e) { logger.warn("Could not create executor from specification", e); } } return module; } catch (JSONException e) { logger.debug("Could not create module from executors.json"); } catch (NullPointerException e) { logger.debug("Could not open executors.json"); } // no executor config, use a default config: 1 local sub process // executor. logger.info("Using default ExecutorModule."); return new ExecutorModule(1); }
From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java
/** * Given either a {@link JSONArray} or a {@link JSONObject}, a key ending and a prefix to add, * it looks for keys at any object inside the provided JSON ending with the key ending and adds * the given prefix to that ending.//from ww w . j av a 2 s .c o m * This method calls itself recursively to traverse inner parts of {@link JSONObject}s. * @param jsonRoot The root {@link JSONObject} or {@link JSONArray}. If an object of any other type is provided, * the method just does nothing. * @param oldKeyEnding the ending to look for. * @param prefixToAdd the prefix to add to that ending. */ private void addPrefixToJSONKeysEndingsRecursive(Object jsonRoot, String oldKeyEnding, String prefixToAdd) { if (jsonRoot instanceof JSONObject) { JSONObject jsonObject = (JSONObject) jsonRoot; SortedSet<String> keys = ImmutableSortedSet.<String>naturalOrder().addAll(jsonObject.keySet()).build(); for (String key : keys) { Object value = jsonObject.get(key); addPrefixToJSONKeysEndingsRecursive(value, oldKeyEnding, prefixToAdd); if (key.endsWith(oldKeyEnding)) { String newKey = key.replaceAll(Pattern.quote(oldKeyEnding) + "$", prefixToAdd + oldKeyEnding); jsonObject.remove(key); jsonObject.put(newKey, value); } } } else if (jsonRoot instanceof JSONArray) { JSONArray jsonArray = (JSONArray) jsonRoot; for (int i = 0; i < jsonArray.length(); i++) { Object value = jsonArray.get(i); addPrefixToJSONKeysEndingsRecursive(value, oldKeyEnding, prefixToAdd); } } else { return; } }
From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java
/** * This method adds additional quotes to any String value inside a JSON. * This helps to distinguish whether values come from strings or other * primitive types when the JSON is converted to XML. * @param jsonRoot//from ww w. j a v a 2 s. com */ private void quoteStringsAtJSON(Object jsonRoot) { if (jsonRoot instanceof JSONObject) { JSONObject jsonObject = (JSONObject) jsonRoot; ImmutableSet<String> jsonObjectKeys = ImmutableSet.copyOf(jsonObject.keys()); for (String key : jsonObjectKeys) { Object value = jsonObject.get(key); if (value instanceof String) { String valueStr = (String) value; jsonObject.put(key, "\"" + valueStr + "\""); } else if (value instanceof JSONObject || value instanceof JSONArray) { quoteStringsAtJSON(value); } } } else if (jsonRoot instanceof JSONArray) { JSONArray jsonArray = (JSONArray) jsonRoot; for (int i = 0; i < jsonArray.length(); i++) { Object value = jsonArray.get(i); if (value instanceof String) { String valueStr = (String) value; jsonArray.put(i, "\"" + valueStr + "\""); } else if (value instanceof JSONObject || value instanceof JSONArray) { quoteStringsAtJSON(value); } } } else { return; } }
From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java
/** * This method looks recursively for arrays and encapsulates each of them into another array. * So, anything like this:<br/>//w w w.j a va 2 s. com * <code> * {"myKey":["stuff1","stuff2"]} * </code><br/> * would become this:<br/> * <code> * {"myKey":[["stuff1","stuff2"]]} * </code><br/> * We do this strange preprocessing because structures like the first example are * converted to XML producing this result:<br/> * <code> * <myKey>stuff1</myKey><myKey>stuff2</myKey> * </code><br/> * Which makes impossible to distinguish single-element arrays from an element * outside any array, because, both this: * <code> * {"singleElement":["stuff"]} * </code><br/> * and this:<br/> * <code> * {"singleElement":"stuff"} * </code><br/> * Would be converted to:<br/> * <code> * <singleElement>stuff</singleElement> * </code><br/> * By doing this, we allow distingushing a single-element array from an non-array element, because * the first one would be converted to:<br/> * <code> * <singleElement><array>stuff</array></singleElement> * * @param jsonRoot The {@link JSONObject} or {@link JSONArray} which is the root of our JSON document. */ private void encapsulateArraysAtJSONRecursive(Object jsonRoot) { if (jsonRoot instanceof JSONObject) { JSONObject jsonObject = (JSONObject) jsonRoot; Set<String> keys = ImmutableSet.copyOf(jsonObject.keySet()); for (String key : keys) { Object value = jsonObject.get(key); encapsulateArraysAtJSONRecursive(value); if (value instanceof JSONArray) { JSONArray encapsulatingJsonArray = new JSONArray(); encapsulatingJsonArray.put(0, value); jsonObject.put(key, encapsulatingJsonArray); } } } else if (jsonRoot instanceof JSONArray) { JSONArray jsonArray = (JSONArray) jsonRoot; for (int i = 0; i < jsonArray.length(); i++) { Object value = jsonArray.get(i); encapsulateArraysAtJSONRecursive(value); if (value instanceof JSONArray) { JSONObject encapsulatingJsonObject = new JSONObject(); encapsulatingJsonObject.put(XSDInferenceConfiguration.ARRAY_ELEMENT_NAME, value); jsonArray.put(i, encapsulatingJsonObject); } } } else { return; } }
From source file:fr.liglab.adele.cilia.workbench.restmonitoring.parser.platform.PlatformChain.java
public PlatformChain(JSONObject json, PlatformModel platform) throws CiliaException { super(getJSONname(json)); this.platform = platform; this.refArchitectureID = null; PlatformID platformId = platform.getPlatformID(); String chainId = getName();// ww w. j a v a 2s.c o m try { JSONArray mediatorsList = json.getJSONArray("Mediators"); for (int i = 0; i < mediatorsList.length(); i++) { String mediatorName = (String) mediatorsList.get(i); JSONObject jsonNode = CiliaRestHelper.getMediatorContent(platform.getPlatformID(), getName(), mediatorName); String state = jsonNode.getString("State"); String type = jsonNode.getString("Type"); String namespace = jsonNode.getString("Namespace"); NameNamespaceID mediatorTypeID = new NameNamespaceID(type, namespace); mediators.add(new MediatorInstanceRef(mediatorName, mediatorTypeID, state, platformId, chainId)); } } catch (JSONException e) { throw new CiliaException("error while parsing mediators list", e); } try { JSONObject adaptersRoot = json.getJSONObject("Adapters"); if (adaptersRoot.has("in-only")) { JSONArray inAdaptersList = adaptersRoot.getJSONArray("in-only"); for (int i = 0; i < inAdaptersList.length(); i++) { String adapterName = (String) inAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("out-only")) { JSONArray outAdaptersList = adaptersRoot.getJSONArray("out-only"); for (int i = 0; i < outAdaptersList.length(); i++) { String adapterName = (String) outAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("in-out")) { JSONArray inOutAdaptersList = adaptersRoot.getJSONArray("in-out"); for (int i = 0; i < inOutAdaptersList.length(); i++) { String adapterName = (String) inOutAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("unknown")) { JSONArray unknownAdaptersList = adaptersRoot.getJSONArray("unknown"); for (int i = 0; i < unknownAdaptersList.length(); i++) { String adapterName = (String) unknownAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } } catch (JSONException e) { throw new CiliaException("error while parsing adapters list", e); } try { JSONArray bindingsList = json.getJSONArray("Bindings"); for (int i = 0; i < bindingsList.length(); i++) { JSONObject binding = (JSONObject) bindingsList.get(i); bindings.add(new BindingInstance(binding, platformId, chainId)); } } catch (JSONException e) { throw new CiliaException("error while parsing adapters list", e); } }
From source file:com.zotoh.core.json.JUT.java
@Test public void testFromString() throws Exception { JSONObject top = JSONUte.read(jsonStr()); JSONArray a; JSONObject obj;/*from w ww .ja va 2 s. co m*/ assertTrue(top != null); assertTrue("hello".equals(top.getString("a"))); assertTrue("world".equals(top.getString("b"))); a = top.getJSONArray("c"); assertTrue(a != null); assertTrue(a.length() == 2); assertTrue(a.get(0).equals(true)); assertTrue(a.get(1).equals(false)); obj = top.getJSONObject("d"); assertTrue(obj != null); }
From source file:com.voidsearch.data.provider.facebook.SimpleGraphAPIClient.java
/** * load result list from json response for given feed * * @param results/*from ww w . ja va 2 s . com*/ * @param resultArray * @param feedName * @param <T> * @throws Exception */ private <T> void loadResults(LinkedList<T> results, JSONArray resultArray, String feedName) throws Exception { for (int i = 0; i < resultArray.length(); i++) { results.add((T) GraphObjectFactory.getObject(feedName, (JSONObject) resultArray.get(i))); } }
From source file:com.microsoft.sharepointservices.ListClient.java
/** * Gets columns from default view./*from w w w . j a va2 s. c o m*/ * * @param listName the list name * @return the columns from default view */ public ListenableFuture<List<String>> getColumnsFromDefaultView(final String listName) { final SettableFuture<List<String>> result = SettableFuture.create(); String getViewUrl = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/defaultView/viewfields", urlEncode(listName)); ListenableFuture<JSONObject> request = executeRequestJson(getViewUrl, "GET"); Futures.addCallback(request, new FutureCallback<JSONObject>() { @Override public void onFailure(Throwable t) { result.setException(t); } @Override public void onSuccess(JSONObject json) { try { JSONObject container = json.getJSONObject("d"); JSONArray results = container.getJSONObject("Items").getJSONArray("results"); ArrayList<String> columnNames = new ArrayList<String>(); for (int i = 0; i < results.length(); i++) { columnNames.add(results.get(i).toString()); } result.set(columnNames); } catch (JSONException e) { log(e); } } }); return result; }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static void addRepeatToXml(Element root, Repeat repeat, JSONObject in, String section, String permlevel) throws JSONException, UnderlyingStorageException { if (repeat.isServicesReadOnly()) { // Omit fields that are read-only in the services layer. log.debug("Omitting services-readonly repeat: " + repeat.getID()); return;/*from w w w . j a v a 2 s. c o m*/ } Element element = root; if (repeat.hasServicesParent()) { for (String path : repeat.getServicesParent()) { if (path != null) { element = element.addElement(path); } } } else if (!repeat.getXxxServicesNoRepeat()) { // Sometimes the UI is ahead of the services layer element = root.addElement(repeat.getServicesTag()); } Object value = null; if (repeat.getXxxUiNoRepeat()) { // and sometimes the Servcies ahead of teh UI FieldSet[] children = repeat.getChildren(permlevel); if (children.length == 0) return; addFieldSetToXml(element, children[0], in, section, permlevel); return; } else { value = in.opt(repeat.getID()); } if (value == null || ((value instanceof String) && StringUtils.isBlank((String) value))) return; if (value instanceof String) { // And sometimes the services ahead of the UI JSONArray next = new JSONArray(); next.put(value); value = next; } if (!(value instanceof JSONArray)) throw new UnderlyingStorageException( "Bad JSON in repeated field: must be string or array for repeatable field" + repeat.getID()); JSONArray array = (JSONArray) value; //reorder the list if it has a primary //XXX this will be changed when service layer accepts non-initial values as primary if (repeat.hasPrimary()) { Stack<Object> orderedarray = new Stack<Object>(); for (int i = 0; i < array.length(); i++) { Object one_value = array.get(i); if (one_value instanceof JSONObject) { if (((JSONObject) one_value).has("_primary")) { if (((JSONObject) one_value).getBoolean("_primary")) { orderedarray.add(0, one_value); continue; } } } orderedarray.add(one_value); } JSONArray newarray = new JSONArray(); int j = 0; for (Object obj : orderedarray) { newarray.put(j, obj); j++; } array = newarray; } Element repeatelement = element; for (int i = 0; i < array.length(); i++) { if (repeat.hasServicesParent()) { repeatelement = element.addElement(repeat.getServicesTag()); } Object one_value = array.get(i); if (one_value == null || ((one_value instanceof String) && StringUtils.isBlank((String) one_value))) continue; if (one_value instanceof String) { // Assume it's just the first entry (useful if there's only one) FieldSet[] fs = repeat.getChildren(permlevel); if (fs.length < 1) continue; JSONObject d1 = new JSONObject(); d1.put(fs[0].getID(), one_value); addFieldSetToXml(repeatelement, fs[0], d1, section, permlevel); } else if (one_value instanceof JSONObject) { List<FieldSet> children = getChildrenWithGroupFields(repeat, permlevel); for (FieldSet fs : children) addFieldSetToXml(repeatelement, fs, (JSONObject) one_value, section, permlevel); } } element = repeatelement; }