List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:hoot.services.nativeInterfaces.ProcessStreamInterface.java
@Override public JSONObject exec(JSONObject cmd) throws NativeInterfaceException { log.debug("Executing command : " + cmd.toJSONString()); String[] commandArr = null;/*from w ww .ja va 2 s . c om*/ JSONObject ret = new JSONObject(); CommandResult res = null; boolean addedToQ = false; try { String exec = cmd.get("exectype").toString(); if (exec.equalsIgnoreCase("hoot")) { commandArr = createCmdArray(cmd); } else if (exec.equalsIgnoreCase("make")) { commandArr = createScriptCmdArray(cmd); } else if (exec.equalsIgnoreCase("bash")) { commandArr = createBashScriptCmdArray(cmd); } else { log.error("Failed to parse params: " + cmd.toJSONString()); throw new NativeInterfaceException("Failed to parse params.", NativeInterfaceException.HttpCode.BAD_RQUEST); } String commandStr = ArrayUtils.toString(commandArr); log.debug("Native call: " + commandStr); if (commandArr == null || commandArr.length == 0) { throw new NativeInterfaceException("Failed to parse params.", NativeInterfaceException.HttpCode.BAD_RQUEST); } ICommandRunner cmdRunner = new CommandRunner(); addedToQ = addToProcessQ(cmd, cmdRunner); log.debug("Start: " + new Date().getTime()); res = cmdRunner.exec(commandArr); log.debug("End: " + new Date().getTime()); if (res != null) { if (res.getExitStatus() == 0) { String stdOut = res.getStdout(); log.debug("stdout: " + stdOut); ret.put("stdout", stdOut); String warnings = ""; List<String> stdLines = IOUtils.readLines(new StringReader(stdOut)); for (String ln : stdLines) { if (ln.indexOf(" WARN ") > -1) { warnings += ln; warnings += "\n"; } // we will cap the maximum length of warnings to 1k if (warnings.length() > 1028) { warnings += " more .."; break; } } if (warnings.length() > 0) { System.out.println(stdOut); ret.put("warnings", warnings); } } else { String err = res.getStderr(); if (res.getExitStatus() == -9999) { throw new Exception("User requested termination."); } else { boolean doThrowException = true; if (cmd.containsKey("throwerror")) { doThrowException = Boolean.parseBoolean(cmd.get("throwerror").toString()); } if (doThrowException) { throw new Exception(err); } else { String stdOut = res.getStdout(); ret.put("stdout", stdOut); ret.put("stderr", err); } } } } } catch (Exception e) { if (res.getExitStatus() == -9999) { throw new NativeInterfaceException("Failed to execute." + e.getMessage(), NativeInterfaceException.HttpCode.USER_CANCEL); } else { throw new NativeInterfaceException("Failed to execute." + e.getMessage(), NativeInterfaceException.HttpCode.SERVER_ERROR); } } finally { if (addedToQ) { removeFromProcessQ(cmd); } } return ret; }
From source file:au.org.emii.portal.composer.MapComposer.java
public void setupMapLayerAsDistributionArea(MapLayer mapLayer) { try {/*w ww . j a v a 2s .c o m*/ //identify the spcode from the url String spcode = mapLayer.getSPCode(); String url = CommonData.getLayersServer() + "/distribution/" + spcode; String jsontxt = Util.readUrl(url); if (jsontxt == null || jsontxt.length() == 0) { url = CommonData.getLayersServer() + "/checklist/" + spcode; jsontxt = Util.readUrl(url); } if (jsontxt == null || jsontxt.length() == 0) { LOGGER.debug("******** failed to find wkt for " + mapLayer.getUri() + " > " + spcode); return; } JSONParser jp = new JSONParser(); JSONObject jo = (JSONObject) jp.parse(jsontxt); if (!jo.containsKey(StringConstants.GEOMETRY)) { return; } mapLayer.setWKT(jo.get(StringConstants.GEOMETRY).toString()); mapLayer.setPolygonLayer(true); Facet facet = null; if (jo.containsKey(StringConstants.PID) && jo.containsKey(StringConstants.AREA_NAME)) { JSONObject object = (JSONObject) jp.parse(Util .readUrl(CommonData.getLayersServer() + "/object/" + jo.containsKey(StringConstants.PID))); //only get field data if it is an intersected layer (to exclude layers containing points) if (CommonData.getLayer((String) object.get(StringConstants.FID)) != null) { facet = Util.getFacetForObject(jo.get(StringConstants.AREA_NAME).toString(), (String) object.get(StringConstants.FID)); } } if (facet != null) { List<Facet> facets = new ArrayList<Facet>(); facets.add(facet); mapLayer.setFacets(facets); } MapLayerMetadata md = mapLayer.getMapLayerMetadata(); try { List<Double> bbox; if (jo.containsKey("bounding_box")) { bbox = Util.getBoundingBox(jo.get("bounding_box").toString()); } else { bbox = Util.getBoundingBox(jo.get(StringConstants.GEOMETRY).toString()); } md.setBbox(bbox); } catch (Exception e) { LOGGER.error("failed to parse wkt in : " + url, e); } //add colour! int colour = Util.nextColour(); int r = (colour >> 16) & 0x000000ff; int g = (colour >> 8) & 0x000000ff; int b = (colour) & 0x000000ff; mapLayer.setRedVal(r); mapLayer.setGreenVal(g); mapLayer.setBlueVal(b); mapLayer.setDynamicStyle(true); getMapComposer().applyChange(mapLayer); warnForLargeWKT(mapLayer); } catch (Exception e) { LOGGER.error("error setting up distributions map layer", e); } }
From source file:au.org.emii.portal.composer.MapComposer.java
/** * Adds a object as a layer to the map./* w w w . j av a 2 s . co m*/ * * @param pid * @param displayName * @param radiusKm for use when the pid refers to a point not a polygon * @return */ public MapLayer addObjectByPid(String pid, String displayName, double radiusKm) { JSONParser jp = new JSONParser(); JSONObject obj = null; try { obj = (JSONObject) jp.parse(Util.readUrl(CommonData.getLayersServer() + "/object/" + pid)); } catch (ParseException e) { LOGGER.error("failed to parse for object: " + pid); } //add feature to the map as a new layer String areaName = obj.get(StringConstants.NAME).toString(); MapLayer mapLayer = null; boolean pointLayer = false; List<Double> dbb = null; try { dbb = Util.getBoundingBox(obj.get(StringConstants.BBOX).toString()); //if the layer is a point create a radius if (dbb.get(0).floatValue() == dbb.get(2).floatValue() && dbb.get(1).floatValue() == dbb.get(3).floatValue()) { double radius = radiusKm * 1000.0; String wkt = Util.createCircleJs(dbb.get(0).floatValue(), dbb.get(1).floatValue(), radius); mapLayer = getMapComposer().addWKTLayer(wkt, displayName, displayName); pointLayer = true; } } catch (Exception e) { } if (mapLayer == null) { //not a point layer mapLayer = getMapComposer().addWMSLayer("PID:" + pid, displayName == null ? areaName : displayName, obj.get(StringConstants.WMSURL).toString(), 0.6f, null, null, LayerUtilitiesImpl.WKT, null, null); mapLayer.setAreaSqKm(obj.get(StringConstants.AREA_KM).toString()); } if (mapLayer == null) { return null; } if (dbb != null) { mapLayer.getMapLayerMetadata().setBbox(dbb); } mapLayer.setPid(pid); mapLayer.setPolygonLayer(true); //if the layer is a point create a radius String fid = obj.get(StringConstants.FID).toString(); MapLayerMetadata md = mapLayer.getMapLayerMetadata(); Facet facet = null; if (!pointLayer && CommonData.getLayer(fid) != null && CommonData.getFacetLayerNameDefault(fid) != null) { JSONObject field = CommonData.getLayer(fid); if (field.containsKey("indb") && StringConstants.TRUE.equalsIgnoreCase(field.get("indb").toString())) { String spid = field.get("spid").toString(); md.setMoreInfo(CommonData.getLayersServer() + "/layers/view/more/" + spid); facet = Util.getFacetForObject(areaName, fid); } } if (facet != null) { List<Facet> facets = new ArrayList<Facet>(); facets.add(facet); mapLayer.setFacets(facets); //do not set WKT for grids as shapefiles if (!((JSONObject) CommonData.getLayer(fid).get("layer")).get("path_orig").toString() .contains("diva")) { mapLayer.setWktUrl(CommonData.getLayersServer() + "/shape/wkt/" + pid); } } else if (!pointLayer) { //not in biocache, so add as WKT mapLayer.setWKT(Util.readUrl(CommonData.getLayersServer() + "/shape/wkt/" + pid)); } int colour = Util.nextColour(); int r = (colour >> 16) & 0x000000ff; int g = (colour >> 8) & 0x000000ff; int b = (colour) & 0x000000ff; mapLayer.setRedVal(r); mapLayer.setGreenVal(g); mapLayer.setBlueVal(b); mapLayer.setDynamicStyle(true); getMapComposer().applyChange(mapLayer); getMapComposer().updateLayerControls(); return mapLayer; }
From source file:au.org.emii.portal.composer.MapComposer.java
private void loadDistributionMap(String lsids, String wkt) { String newWkt = wkt;//from w ww .jav a 2 s.c om if (CommonData.WORLD_WKT.equals(newWkt)) { newWkt = null; } //test for a valid lsid match String[] wmsNames = CommonData.getSpeciesDistributionWMS(lsids); String[] spcode = CommonData.getSpeciesDistributionSpcode(lsids); MapLayer ml; JSONParser jp = new JSONParser(); if (wmsNames.length > 0 && (newWkt == null || newWkt.equals(CommonData.WORLD_WKT))) { //add all for (int i = 0; i < wmsNames.length; i++) { if (getMapLayerWMS(wmsNames[i]) == null) { //map this layer with its recorded scientific name try { JSONObject jo = ((JSONObject) jp.parse(Util.readUrl( CommonData.getLayersServer() + "/distribution/" + spcode[i] + "?nowkt=true"))); String scientific = jo.get(StringConstants.SCIENTIFIC).toString(); String distributionAreaName = jo.get("area_name").toString(); String layerName = getNextAreaLayerName(scientific); String html = Util.getMetadataHtmlForDistributionOrChecklist(spcode[i], null, layerName); ml = addWMSLayer(layerName, getNextAreaLayerName(distributionAreaName), wmsNames[i], 0.35f, html, null, LayerUtilitiesImpl.WKT, null, null); ml.setSPCode(spcode[i]); setupMapLayerAsDistributionArea(ml); } catch (Exception e) { LOGGER.error("failed to parse for distribution: " + spcode[i]); } } } } else if (wmsNames.length > 0 && newWkt != null && !newWkt.equals(CommonData.WORLD_WKT)) { String url = CommonData.getLayersServer() + "/distributions"; try { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addParameter(StringConstants.WKT, newWkt); post.addParameter(StringConstants.LSIDS, lsids); post.addRequestHeader(StringConstants.ACCEPT, StringConstants.JSON_JAVASCRIPT_ALL); int result = client.executeMethod(post); if (result == 200) { String txt = post.getResponseBodyAsString(); JSONArray ja = (JSONArray) jp.parse(txt); List<String> found = new ArrayList(); for (int i = 0; i < ja.size(); i++) { JSONObject jo = (JSONObject) ja.get(i); if (jo.containsKey(StringConstants.WMSURL)) { found.add(jo.get(StringConstants.WMSURL).toString()); } } for (int i = 0; i < wmsNames.length; i++) { if (getMapLayerWMS(wmsNames[i]) == null) { String scientific = ((JSONObject) jp.parse(Util.readUrl( CommonData.getLayersServer() + "/distribution/" + spcode[i] + "?nowkt=true"))) .get(StringConstants.SCIENTIFIC).toString(); String layerName = getNextAreaLayerName(scientific + " area " + (i + 1)); String html = Util.getMetadataHtmlForDistributionOrChecklist(spcode[i], null, layerName); ml = addWMSLayer(layerName, getNextAreaLayerName("Expert distribution: " + scientific), found.get(i), 0.35f, html, null, LayerUtilitiesImpl.WKT, null, null); ml.setSPCode(spcode[i]); setupMapLayerAsDistributionArea(ml); } } } } catch (Exception e) { LOGGER.error("error posting distributions: " + url); } } openChecklistSpecies(lsids, newWkt, true); }
From source file:net.techcable.jplayerindex.ProfileUtils.java
private static PlayerProfile deserializeProfile(JSONObject json) { if (!json.containsKey("name") || !json.containsKey("id")) return null; if (!(json.get("name") instanceof String) || !(json.get("id") instanceof String)) return null; String name = (String) json.get("name"); UUID id = toUUID((String) json.get("id")); if (id == null) return null; PlayerProfile profile = new PlayerProfile(id, name); if (json.containsKey("properties") && json.get("properties") instanceof JSONArray) { profile.properties = (JSONArray) json.get("properties"); }// w w w . j av a2s . c o m return profile; }
From source file:net.techcable.sonarpet.utils.ProfileUtils.java
private static PlayerProfile deserializeProfile(JSONObject json) { if (!json.containsKey("name") || !json.containsKey("id")) return null; if (!(json.get("name") instanceof String) || !(json.get("id") instanceof String)) return null; String name = (String) json.get("name"); if (json.get("id") == null) return null; UUID id = UUIDUtils.fromString((String) json.get("id")); PlayerProfile profile = new PlayerProfile(id, name); if (json.containsKey("properties") && json.get("properties") instanceof JSONArray) { profile.properties = (JSONArray) json.get("properties"); }//from w w w . j av a 2 s .c o m return profile; }
From source file:net.tsquery.TsdbServlet.java
protected long getRequiredTimeStamp(JSONObject obj, String key) { if (!obj.containsKey(key)) throw new IllegalArgumentException( "Required timestamp '" + key + "' missing. Please add it to the query string."); long val; try {//from w w w. j ava 2s. co m Object o = obj.get(key); if (o instanceof Long) { val = (Long) o; } else { val = ISO8601DateParser.parse(o.toString()).getTime(); } } catch (Exception e) { throw new IllegalArgumentException("Required timestamp '" + key + "' must be either an epoch timestamp or an ISO 8601 formatted date."); } if (val > 1000000000000L) val = val / 1000L; return val; }
From source file:nl.b3p.geotools.data.arcgis.ArcGISDataStore.java
public JSONObject getServerJSONResponse(String extraUrl) throws IOException { String requestUrl = url + (extraUrl.startsWith("/") ? "" : "/") + extraUrl; log.debug("request: " + requestUrl); HTTPResponse response = client.get(new URL(requestUrl)); try {/*from ww w.j a va 2 s. c o m*/ String json = IOUtils.toString(response.getResponseStream(), "UTF-8"); JSONObject j = (JSONObject) JSONValue.parse(json); if (j == null) { int endIndex = Math.min(json.length(), 30); throw new IOException( "ArcGIS server returned invalid JSON response: " + json.substring(0, endIndex)); } if (j.containsKey("error")) { throw new ArcGISException(requestUrl, j); } return j; } finally { response.dispose(); } }
From source file:nl.b3p.geotools.data.arcgis.ArcGISDataStore.java
public JSONObject getLayerJSON(String id) throws IOException { if (layersById.containsKey(id)) { if (getCurrentMajorVersion() > 9) { // Full layer JSON always available return layersById.get(id); } else {/*www .j a v a 2s. c o m*/ // Layer JSON must be fetched per layer in 9.x, but do this on // demand // If the current JSON object has a "type", the full layer JSON // was already fetched JSONObject layer = layersById.get(id); if (!layer.containsKey("type")) { layer = requestLayerJSON(id); layersById.put(id, layer); } return layer; } } else { return requestLayerJSON(id); } }
From source file:nl.b3p.geotools.data.arcgis.ArcGISFeatureReader.java
public List getObjectIds() throws IOException { if (objectIds != null) { return objectIds; }/*from w w w .j av a 2 s . co m*/ if (fs.getArcGISDataStore().getCurrentMajorVersion() < 10) { throw new UnsupportedOperationException("Object id queries not supported in ArcGIS REST version 9.x"); } Map<String, String> params = null; try { params = createQueryParams(); } catch (FilterToSQLException ex) { throw new IOException(ex); } params.put("returnIdsOnly", "true"); try { JSONObject idsResponse = fs.getArcGISDataStore().getServerJSONResponse(typeName + "/query", params); if (!idsResponse.containsKey("objectIds") || !idsResponse.containsKey("objectIdFieldName")) { throw new Exception("Requested returnIdsOnly but no objectIds or objectIdFieldName in response"); } objectIdFieldName = (String) idsResponse.get("objectIdFieldName"); objectIds = (JSONArray) idsResponse.get("objectIds"); if (objectIds == null) { return Collections.EMPTY_LIST; } // Ensure consistent startIndex by sorting the objectIds Collections.sort(objectIds); int originalSize = objectIds.size(); if (query.getStartIndex() != null) { objectIds = objectIds.subList(Math.min(query.getStartIndex(), objectIds.size()), objectIds.size()); } if (objectIds.size() > query.getMaxFeatures()) { objectIds = objectIds.subList(0, query.getMaxFeatures()); } if (log.isDebugEnabled()) { log.debug(String.format( "Object ids count for layer %s: %d; when adjusted for startIndex %s and maxFeatures %s the count is %d", typeName, originalSize, query.getStartIndex() + "", query.isMaxFeaturesUnlimited() ? "unlimited" : query.getMaxFeatures() + "", objectIds.size())); } return objectIds; } catch (Exception e) { throw new IOException("Error retrieving feature count from ArcGIS: " + e.toString(), e); } }