List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:hoot.services.controllers.ingest.CustomScriptResource.java
/** * _getDefaultList reads the DefaultTranslations.json and passes default translations list. * The list is used by UI to distinguish between custom and default translations. * * @return JSONArray of translation objects * @throws Exception/*from www .j ava2 s . com*/ */ protected JSONArray _getDefaultList() throws Exception { JSONArray filesList = new JSONArray(); //defaultTranslationsConfig File f = new File(defaultTranslationsConfig); if (f.exists()) { FileReader reader = new FileReader(defaultTranslationsConfig); JSONParser jsonParser = new JSONParser(); JSONArray defTranslations = (JSONArray) jsonParser.parse(reader); for (int i = 0; i < defTranslations.size(); i++) { JSONObject oTrans = (JSONObject) defTranslations.get(i); oTrans.put("DEFAULT", true); String desc = oTrans.get("DESCRIPTION").toString(); if (desc.length() == 0) { desc = oTrans.get("NAME").toString(); } desc += " (Hootenanny Default)"; oTrans.put("DESCRIPTION", desc); Object oCanExport = oTrans.get("CANEXPORT"); // If the CANEXPORT is not available then try to determine if (oCanExport == null) { // Get the script if (oTrans.get("PATH") != null) { File fScript = new File(homeFolder + "/" + oTrans.get("PATH").toString()); if (fScript.exists()) { String sScript = FileUtils.readFileToString(fScript); boolean canExport = validateExport(sScript); oTrans.put("CANEXPORT", canExport); } } } } // validate FOUO support if (defTranslations.size() > 0) { for (Object oTrans : defTranslations) { JSONObject jsTrans = (JSONObject) oTrans; if (jsTrans.get("FOUO_PATH") != null) { // See if FOUO folder exists File fouoPath = new File(homeFolder + "/" + jsTrans.get("FOUO_PATH").toString()); if (fouoPath.exists()) { filesList.add(jsTrans); } } else { // If there is no FOUO_PATH then assume it is not FOUO translation filesList.add(jsTrans); } } } } return filesList; }
From source file:com.entertailion.java.caster.RampClient.java
public void onMessage(String message) { Log.d(LOG_TAG, "onMessage: message" + message); // http://code.google.com/p/json-simple/ JSONParser parser = new JSONParser(); try {/*from www. j av a 2 s . com*/ Object obj = parser.parse(new StringReader(message)); JSONArray array = (JSONArray) obj; if (array.get(0).equals(PROTOCOL_CM)) { Log.d(LOG_TAG, PROTOCOL_CM); JSONObject body = (JSONObject) array.get(1); // ["cm",{"type":"ping"}] if (body.get(TYPE).equals(PING)) { rampWebSocketClient.send("[\"cm\",{\"type\":\"pong\"}]"); } } else if (array.get(0).equals(PROTOCOL_RAMP)) { // ["ramp",{"cmd_id":0,"type":"STATUS","status":{"event_sequence":2,"state":0}}] Log.d(LOG_TAG, PROTOCOL_RAMP); JSONObject body = (JSONObject) array.get(1); if (body.get(TYPE).equals(STATUS)) { // Long cmd_id = (Long)body.get("cmd_id"); // commandId = cmd_id.intValue(); if (!gotStatus) { gotStatus = true; // rampWebSocketClient.send("[\"ramp\",{\"type\":\"LOAD\",\"cmd_id\":"+commandId+",\"autoplay\":true}] "); // commandId++; } } else if (body.get(TYPE).equals(RESPONSE)) { // ["ramp",{"cmd_id":7,"type":"RESPONSE","status":{"event_sequence":38,"state":2,"content_id":"http://192.168.0.50:8080/video.mp4","current_time":6.465110778808594, // "duration":27.37066650390625,"volume":1,"muted":false,"time_progress":true,"title":"Video"}}] JSONObject status = (JSONObject) body.get(RESPONSE_STATUS); if (status.get(RESPONSE_CURRENT_TIME) instanceof Double) { Double current_time = (Double) status.get(RESPONSE_CURRENT_TIME); if (current_time != null) { if (playbackListener != null) { playbackListener.updateTime(playback, current_time.intValue()); } } } else { Long current_time = (Long) status.get(RESPONSE_CURRENT_TIME); if (current_time != null) { if (playbackListener != null) { playbackListener.updateTime(playback, current_time.intValue()); } } } if (status.get(RESPONSE_DURATION) instanceof Double) { Double duration = (Double) status.get(RESPONSE_DURATION); if (duration != null) { if (playbackListener != null) { playbackListener.updateDuration(playback, duration.intValue()); } } } else { Long duration = (Long) status.get(RESPONSE_DURATION); if (duration != null) { if (playbackListener != null) { playbackListener.updateDuration(playback, duration.intValue()); } } } Long state = (Long) status.get(RESPONSE_STATE); if (playbackListener != null) { playbackListener.updateState(playback, state.intValue()); } } } else if (array.get(0).equals(PROTOCOL_CV)) { // ChromeCast default // receiver events Log.d(LOG_TAG, PROTOCOL_CV); JSONObject body = (JSONObject) array.get(1); if (body.get(TYPE).equals(ACTIVITY)) { // ["cv",{"type":"activity","message":{"type":"timeupdate","activityId":"d82cede3-ec23-4f73-8abc-343dd9ca6dbb","state":{"mediaUrl":"http://192.168.0.50:8087/cast.webm","videoUrl":"http://192.168.0.50:8087/cast.webm", // "currentTime":20.985000610351562,"duration":null,"pause":false,"muted":false,"volume":1,"paused":false}}}] JSONObject activityMessage = (JSONObject) body.get(ACTIVITY_MESSAGE); if (activityMessage != null) { JSONObject activityMessageType = (JSONObject) activityMessage.get(TYPE); if (activityMessageType.equals(ACTIVITY_TIME_UPDATE)) { JSONObject activityMessageTypeState = (JSONObject) activityMessage.get(ACTIVITY_STATE); if (activityMessageTypeState.get(RESPONSE_CURRENT_TIME) instanceof Double) { Double current_time = (Double) activityMessageTypeState.get(ACTIVITY_CURRENT_TIME); Double duration = (Double) activityMessageTypeState.get(ACTIVITY_DURATION); if (duration != null) { if (playbackListener != null) { playbackListener.updateDuration(playback, duration.intValue()); } } if (current_time != null) { if (playbackListener != null) { playbackListener.updateTime(playback, current_time.intValue()); } } } else { Long current_time = (Long) activityMessageTypeState.get(ACTIVITY_CURRENT_TIME); Double duration = (Double) activityMessageTypeState.get(ACTIVITY_DURATION); if (duration != null) { if (playbackListener != null) { playbackListener.updateDuration(playback, duration.intValue()); } } if (current_time != null) { if (playbackListener != null) { playbackListener.updateTime(playback, current_time.intValue()); } } } } } } } } catch (Exception e) { Log.e(LOG_TAG, "parse JSON", e); } }
From source file:hoot.services.controllers.job.JobResource.java
private JSONObject execReflectionSync(String jobId, String childJobId, JSONObject job, JobStatusManager jobStatusManager) throws Exception { String className = job.get("class").toString(); String methodName = job.get("method").toString(); String internalJobId = (job.get("internaljobid") == null) ? null : job.get("internaljobid").toString(); JSONArray paramsList = (JSONArray) job.get("params"); Class<?>[] paramTypes = new Class[paramsList.size()]; Object[] parameters = new Object[paramsList.size()]; for (int i = 0; i < paramsList.size(); i++) { JSONObject param = (JSONObject) paramsList.get(i); String paramType = param.get("paramtype").toString(); Object oIsPrim = param.get("isprimitivetype"); if ((oIsPrim != null) && oIsPrim.toString().equalsIgnoreCase("true")) { Class<?> classWrapper = Class.forName(paramType); paramTypes[i] = (Class<?>) classWrapper.getField("TYPE").get(null); } else {/*w w w. j av a 2 s . c o m*/ paramTypes[i] = Class.forName(paramType); } parameters[i] = param.get("value"); } Class<?> clazz = Class.forName(className); Object instance = clazz.newInstance(); JSONObject childJobInfo; String currentChildJobId = childJobId; // May be we would need create interface to guarranttee that it will // return a job id? Add internal job id to end of method call if (internalJobId != null) { currentChildJobId = internalJobId; childJobInfo = createChildInfo(currentChildJobId, JOB_STATUS.RUNNING.toString()); setJobInfo(jobInfo, childJobInfo, childrenInfo, JOB_STATUS.RUNNING.toString(), "processing"); jobStatusManager.updateJob(jobId, jobInfo.toString()); Object[] newParams = new Object[paramsList.size() + 1]; System.arraycopy(parameters, 0, newParams, 0, parameters.length); newParams[parameters.length] = internalJobId; Class<?>[] newParamTypes = new Class[paramsList.size() + 1]; System.arraycopy(paramTypes, 0, newParamTypes, 0, paramsList.size()); newParamTypes[parameters.length] = String.class; Method method = clazz.getDeclaredMethod(methodName, newParamTypes); // This will blow if the method is not designed to handle job id method.invoke(instance, newParams); } else { Method method = clazz.getDeclaredMethod(methodName, paramTypes); Object oReflectJobId = method.invoke(instance, parameters); if (oReflectJobId != null) { currentChildJobId = oReflectJobId.toString(); } // Updating job status info. Looks like we need to wait till job is // done to get job id. With this we can not canel.. childJobInfo = createChildInfo(currentChildJobId, JobStatusManager.JOB_STATUS.RUNNING.toString()); setJobInfo(jobInfo, childJobInfo, childrenInfo, JOB_STATUS.RUNNING.toString(), "processing"); jobStatusManager.updateJob(jobId, jobInfo.toString()); } return childJobInfo; }
From source file:io.personium.test.jersey.cell.ctl.BoxRoleLinkTest.java
/** * ?????.//from w w w .j a v a 2 s .c om */ @Before public final void before() { if (roleUri == null) { TResponse response = Http.request("role-list.txt").with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", CELL_NAME).returns().statusCode(HttpStatus.SC_OK); JSONObject d = (JSONObject) response.bodyAsJson().get("d"); JSONArray results = (JSONArray) d.get("results"); String name = (String) ((JSONObject) results.get(0)).get("Name"); String boxName = (String) ((JSONObject) results.get(0)).get("_Box.Name"); if (boxName == null) { roleKey = "Name='" + name + "',_Box.Name=null"; } else { roleKey = "Name='" + name + "',_Box.Name='" + boxName + "'"; } roleChangedKey = "_Box.Name=" + KEY + ",Name='" + name + "'"; roleUri = UrlUtils.cellCtlWithoutSingleQuote(CELL_NAME, ENTITY_SET_ROLE, roleKey); } }
From source file:fr.treeptik.cloudunit.docker.DockerContainerJSON.java
/** * /containers/json : not same format as an inspect of container List all * Running or Paused containers retrieve name (with cloudunit format), image * and state//from w w w. j av a 2 s . c o m * * @param hostAddress * @return * @throws DockerJSONException */ public List<DockerContainer> listAllContainers(String hostAddress) throws DockerJSONException { URI uri = null; List<DockerContainer> listContainers = new ArrayList<>(); try { uri = new URIBuilder().setScheme(dockerEndpointMode).setHost(hostAddress).setPath("/containers/json") .build(); if (logger.isDebugEnabled()) { logger.debug("uri : " + uri); } JsonResponse jsonResponse; try { jsonResponse = client.sendGet(uri); switch (jsonResponse.getStatus()) { case 400: throw new ErrorDockerJSONException("docker : bad parameter"); case 500: throw new ErrorDockerJSONException("docker : server error"); } } catch (IOException e) { e.printStackTrace(); throw new DockerJSONException("Error : listAllContainers " + e.getLocalizedMessage(), e); } if (logger.isDebugEnabled()) { logger.debug("response : " + jsonResponse); } JSONParser jsonParser = new JSONParser(); Object obj = jsonParser.parse(jsonResponse.getMessage()); JSONArray array = (JSONArray) obj; for (int i = 0; i < array.size(); i++) { String containerDescription = array.get(i).toString(); try { String firstSubString = (parser(containerDescription).get("Names").toString()).substring(4); String Names = null; // for container with link where the link name is also show if (firstSubString.lastIndexOf(",") != -1) { Names = firstSubString.substring(0, firstSubString.lastIndexOf(",") - 1); } else { Names = firstSubString.substring(0, firstSubString.lastIndexOf("\"")); } if (logger.isDebugEnabled()) { logger.debug("Names=[" + Names + "]"); } if (Names.trim().length() > 0) { DockerContainer dockerContainer = findOne(Names, hostAddress); if (dockerContainer != null) { listContainers.add(dockerContainer); } } } catch (ParseException e) { throw new DockerJSONException("Error : listAllContainers " + e.getLocalizedMessage(), e); } } } catch (NumberFormatException | URISyntaxException | ParseException e) { StringBuilder msgError = new StringBuilder(256); msgError.append(",hostIP=").append(hostAddress).append(",uri=").append(uri); logger.error("" + msgError, e); throw new FatalDockerJSONException("docker : error fatal"); } return listContainers; }
From source file:net.milkbowl.vault.Vault.java
public double updateCheck(double currentVersion) { try {/*from w w w. ja v a 2 s. c om*/ URL url = new URL("https://api.curseforge.com/servermods/files?projectids=33184"); URLConnection conn = url.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("User-Agent", "Vault Update Checker"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.getLogger().warning("No files found, or Feed URL is bad."); return currentVersion; } // Pull the last version from the JSON newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name")).replace("Vault", "") .trim(); return Double.valueOf(newVersionTitle.replaceFirst("\\.", "").trim()); } catch (Exception e) { log.info("There was an issue attempting to check for the latest version."); } return currentVersion; }
From source file:com.dsh105.commodus.data.Updater.java
private boolean read() { try {//www .java2 s .c o m final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger() .warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)) .get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger() .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
From source file:ActualizadorLocal.Clientes.ClienteDispositivos.java
/** * Funcin que procesa mediante JSON el resultado de la peticin HTTP. * * @param datos La respuesta de la peticin HTTP */// w ww .j a va2s .co m public void procesarDatos(String datos) { //Preprocesamos los datos, para darle un nombre al array, cosa que est muy mal que no venga hecha: datos = "{\"dispositivos\":" + datos + "}"; JSONParser parser = new JSONParser(); try { JSONObject obj = (JSONObject) parser.parse(datos); JSONArray lista = (JSONArray) obj.get("dispositivos"); procesados = lista.size(); int conta = 1; int lotes = procesados / MAX_CACHE_SIZE; for (int i = 0; i < lista.size(); i++) { if (i % MAX_CACHE_SIZE == 0) { conta++; } String a0 = (String) ((JSONObject) lista.get(i)).get("idDispositivo"); String a1 = (String) ((JSONObject) lista.get(i)).get("majorDeviceClass"); String a2 = (String) ((JSONObject) lista.get(i)).get("minorDeviceClass"); String a3 = (String) ((JSONObject) lista.get(i)).get("serviceClass"); String a4 = (String) ((JSONObject) lista.get(i)).get("fabricante"); this.InsertarDatos( "\"" + (String) a0 + "\",\"" + a1 + "\",\"" + a2 + "\",\"" + a3 + "\",\"" + a4 + "\""); } } catch (Exception e) { System.err.println("E>" + e.getMessage()); } syncDB(); }
From source file:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java
private ApexClassCodeCoverageBean[] processJSONResponseAndConstructCodeCoverageBeans( PartnerConnection connection, JSONObject responseJsonObject) { int classCounter = 0; int coveredLinesForTheTeam = 0; int unCoveredLinesForTheTeam = 0; String responseStr = responseJsonObject.toJSONString(); LOG.debug(responseStr);//from ww w . j av a2s . c om JSONArray recordObject = (JSONArray) responseJsonObject.get("records"); if (recordObject != null && recordObject.size() > 0) { ApexClassCodeCoverageBean[] apexClassCodeCoverageBeans = new ApexClassCodeCoverageBean[recordObject .size()]; for (int i = 0; i < recordObject.size(); ++i) { ApexClassCodeCoverageBean apexClassCodeCoverageBean = new ApexClassCodeCoverageBean(); // The object below is one record from the ApexCodeCoverage // object JSONObject rec = (JSONObject) recordObject.get(i); // ApexClassOrTriggerId - The ID of the class or trigger under // test. String apexClassOrTriggerId = (String) rec.get("ApexClassOrTriggerId").toString(); if (apexClassOrTriggerId != null) { int coveredLines = 0; if (rec.get("NumLinesCovered") != null) { coveredLines = Integer.valueOf((String) rec.get("NumLinesCovered").toString()); coveredLinesForTheTeam += coveredLines; } else { LOG.debug(apexClassOrTriggerId + " has NumLinesCovered as NULL !!!!!!!!!"); } int unCoveredLines = 0; if (rec.get("NumLinesUncovered") != null) { unCoveredLines = Integer.valueOf((String) rec.get("NumLinesUncovered").toString()); unCoveredLinesForTheTeam += unCoveredLines; } else { LOG.debug(apexClassOrTriggerId + " has NumLinesUncovered as NULL !!!!!!!!!"); } if (rec.get("Coverage") != null) { JSONObject codeCoverageLineLists = (JSONObject) rec.get("Coverage"); JSONArray coveredLinesJsonArray = (JSONArray) codeCoverageLineLists.get("coveredLines"); JSONArray uncoveredLinesJsonArray = (JSONArray) codeCoverageLineLists.get("uncoveredLines"); List<Long> coveredLinesList = new ArrayList<Long>(); for (int j = 0; j < coveredLinesJsonArray.size(); j++) { coveredLinesList.add((Long) coveredLinesJsonArray.get(j)); LOG.debug("covered " + (Long) coveredLinesJsonArray.get(j)); } if (coveredLinesList.size() > 0) { apexClassCodeCoverageBean.setCoveredLinesList(coveredLinesList); } List<Long> uncoveredLinesList = new ArrayList<Long>(); for (int k = 0; k < uncoveredLinesJsonArray.size(); k++) { uncoveredLinesList.add((Long) uncoveredLinesJsonArray.get(k)); LOG.debug("uncovered " + (Long) uncoveredLinesJsonArray.get(k)); } if (uncoveredLinesList.size() > 0) { apexClassCodeCoverageBean.setUncoveredLinesList(uncoveredLinesList); } } apexClassCodeCoverageBean.setNumLinesCovered(coveredLines); apexClassCodeCoverageBean.setNumLinesUncovered(unCoveredLines); apexClassCodeCoverageBean.setApexClassorTriggerId(apexClassOrTriggerId); HashMap<String, String> apexClassInfoMap = ApexClassFetcherUtils .fetchApexClassInfoFromId(connection, apexClassOrTriggerId); String apexClassName = apexClassInfoMap.get("Name"); String apiVersion = apexClassInfoMap.get("ApiVersion"); String lengthWithoutComments = apexClassInfoMap.get("LengthWithoutComments"); apexClassCodeCoverageBean.setApexClassName(apexClassName); apexClassCodeCoverageBean.setApiVersion(apiVersion); apexClassCodeCoverageBean.setLengthWithoutComments(lengthWithoutComments); apexClassCodeCoverageBeans[classCounter++] = apexClassCodeCoverageBean; LOG.info("Record number # " + classCounter + " : coveredLines : " + coveredLines + " : unCoveredLines : " + unCoveredLines + " : code coverage % : " + apexClassCodeCoverageBean.getCoveragePercentage() + " : apexClassOrTriggerId : " + apexClassOrTriggerId + " : apexClassName : " + apexClassName + " : apiVersion : " + apiVersion + " : lengthWithoutComments : " + lengthWithoutComments); } } double totalLines = coveredLinesForTheTeam + unCoveredLinesForTheTeam; if (totalLines > 0.0) { ApexUnitCodeCoverageResults.teamCodeCoverage = (coveredLinesForTheTeam / (totalLines)) * 100.0; } else { ApexUnitCodeCoverageResults.teamCodeCoverage = 100.0; } LOG.info( "#################################### Summary of code coverage computation for the team.. #################################### "); LOG.info("Total Covered lines : " + coveredLinesForTheTeam + "\n Total Uncovered lines : " + unCoveredLinesForTheTeam); LOG.info("Team code coverage is : " + ApexUnitCodeCoverageResults.teamCodeCoverage + "%"); return apexClassCodeCoverageBeans; } else { // no code coverage record object found in the response. return null return null; } }