private JSONArray enrichProperties(String operatorClass, JSONArray properties) throws JSONException { JSONArray result = new JSONArray(); for (int i = 0; i < properties.length(); i++) { JSONObject propJ = properties.getJSONObject(i); String propName = WordUtils.capitalize(propJ.getString("name")); String getPrefix = (propJ.getString("type").equals("boolean") || propJ.getString("type").equals("java.lang.Boolean")) ? "is" : "get"; String setPrefix = "set"; OperatorClassInfo oci = getOperatorClassWithGetterSetter( operatorClass, setPrefix + propName, getPrefix + propName); if (oci == null) { result.put(propJ); continue; } MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName); MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName); if ((getterInfo != null && getterInfo.omitFromUI) || (setterInfo != null && setterInfo.omitFromUI)) { continue; } if (setterInfo != null) { addTagsToProperties(setterInfo, propJ); } else if (getterInfo != null) { addTagsToProperties(getterInfo, propJ); } result.put(propJ); } return result; }
public JSONArray toJSONArray() throws JSONException { JSONArray json = new JSONArray(); for (Iterator<ExportValue> i = values.values().iterator(); i.hasNext(); ) { json.put(i.next().toJSONObject()); } return json; }
public JSONObject asJSONTreeAux(ConcurrentHashMap<DomainConcept, DomainConcept> written) { JSONObject jsonObj = new JSONObject(); try { jsonObj.put("class", "ClassModel"); jsonObj.put("id", id); if (written.contains(this)) { return jsonObj; } written.put(this, this); if (getHasArcs() != null) { JSONArray jsonHasArcs = new JSONArray(); for (Arc row : getHasArcs()) { jsonHasArcs.put(row.asJSONTreeAux(written)); } jsonObj.put("hasArcs", jsonHasArcs); } if (getHasPropertySet() != null) { jsonObj.put("hasPropertySet", getHasPropertySet().asJSONTreeAux(written)); } jsonObj.put("id", getId()); if (getHasDomainNodes() != null) { jsonObj.put("hasDomainNodes", getHasDomainNodes().asJSONTreeAux(written)); } written.remove(this); } catch (Exception e1) { logWriter.error("Error in marshalling to JSON ", e1); } return jsonObj; }
/** * Produce a JSONArray containing the names of the elements of this JSONObject. * * @return A JSONArray containing the key strings, or null if the JSONObject is empty. */ public JSONArray names() { final JSONArray ja = new JSONArray(); final Iterator keys = this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; }
/** * Produce a JSONArray containing the values of the members of this JSONObject. * * @param names A JSONArray containing a list of key strings. This determines the sequence of the * values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if ((names == null) || (names.length() == 0)) { return null; } final JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; }
/** * Accumulate values under a key. It is similar to the put method except that if there is already * an object stored under the key then a JSONArray is stored under the key to hold all of the * accumulated values. If there is already a JSONArray, then the new value is appended to it. In * contrast, the put method replaces the previous value. * * <p>If only one value is accumulated that is not a JSONArray, then the result will be the same * as using put. But if multiple values are accumulated, then the result will be like append. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { JSONObject.testValidity(value); final Object object = this.opt(key); if (object == null) { this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (object instanceof JSONArray) { ((JSONArray) object).put(value); } else { this.put(key, new JSONArray().put(object).put(value)); } return this; }
/** * Accumulate values under a key. It is similar to the put method except that if there is already * an object stored under the key then a JSONArray is stored under the key to hold all of the * accumulated values. If there is already a JSONArray, then the new value is appended to it. In * contrast, the put method replaces the previous value. * * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (o instanceof JSONArray) { ((JSONArray) o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; }
@POST @Path("/view") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String viewAllNotes(String inputData) { JSONObject inputJSON = new JSONObject(inputData); if ((inputJSON.has("sessionID")) && UsersController.checkLogin(inputJSON.getString("sessionID"))) { hibernate.controllers.NotesController notesController = new hibernate.controllers.NotesController(); List<Note> notes = notesController.readAllNotes(); JSONArray results = new JSONArray(); JSONObject jsonNote; for (Note note : notes) { jsonNote = getJSONNote(note); results.put(jsonNote); } return results.toString(); } else return "Invalid session!"; }
private void makeAttributeJSONArray(final SimpleFeatureType layerSft) throws JSONException { List<ConfiguredAttribute> cas = applicationLayer.getAttributes(); // Sort the attributes, by featuretype and the featuretyp Collections.sort( cas, new Comparator<ConfiguredAttribute>() { @Override public int compare(ConfiguredAttribute o1, ConfiguredAttribute o2) { if (o1.getFeatureType() == null) { return -1; } if (o2.getFeatureType() == null) { return 1; } if (o1.getFeatureType().getId().equals(layerSft.getId())) { return -1; } if (o2.getFeatureType().getId().equals(layerSft.getId())) { return 1; } return o1.getFeatureType().getId().compareTo(o2.getFeatureType().getId()); } }); for (ConfiguredAttribute ca : cas) { JSONObject j = ca.toJSONObject(); // Copy alias over from feature type SimpleFeatureType sft = ca.getFeatureType(); if (sft == null) { sft = layerSft; } AttributeDescriptor ad = sft.getAttribute(ca.getAttributeName()); j.put("alias", ad.getAlias()); j.put("featureTypeAttribute", ad.toJSONObject()); attributesJSON.put(j); } }
@RequestMapping( value = "/getCityApi", method = {RequestMethod.GET, RequestMethod.POST}) public String getCityApi( HttpServletRequest request, @RequestParam(value = "locationname") String locationname, ModelMap model) { Map<Object, Object> map = new HashMap<Object, Object>(); JSONArray jSONArray = new JSONArray(); try { String status = "active"; List<City> cityList = cityService.getCityApi(locationname, status); if (cityList != null && cityList.size() > 0) { for (int i = 0; i < cityList.size(); i++) { City city = (City) cityList.get(i); String cityName = (String) city.getCity(); String stateName = (String) city.getState(); int ID = (Integer) (city.getId()); JSONObject jSONObject = new JSONObject(); jSONObject.put("id", ID); jSONObject.put("text", cityName); jSONArray.put(jSONObject); } utilities.setSuccessResponse(response, jSONArray.toString()); } else { throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA); } } catch (Exception ex) { logger.error("getCity :" + ex.getMessage()); utilities.setErrResponse(ex, response); } model.addAttribute("model", jSONArray.toString()); return "home"; }
/** method to marshall data from caching layer object to JSON * */ public JSONObject asJSON() { JSONObject jsonObj = new JSONObject(); try { jsonObj.put("class", "ClassModel"); jsonObj.put("id", id); if (getHasArcs() != null) { JSONArray jsonHasArcs = new JSONArray(); for (Arc row : getHasArcs()) { jsonHasArcs.put(row.getId()); } jsonObj.put("hasArcs", jsonHasArcs); } if (getHasPropertySet() != null) { jsonObj.put("hasPropertySet", getHasPropertySet().getId()); } jsonObj.put("id", getId()); if (getHasDomainNodes() != null) { jsonObj.put("hasDomainNodes", getHasDomainNodes().getId()); } } catch (Exception e1) { logWriter.error("Error in marshalling to JSON ", e1); } return jsonObj; }
private boolean handleGet( HttpServletRequest request, HttpServletResponse response, String pathString) throws IOException, JSONException, ServletException, URISyntaxException, CoreException { IPath path = pathString == null ? Path.EMPTY : new Path(pathString); URI baseLocation = getURI(request); String user = request.getRemoteUser(); // expected path format is 'workspace/{workspaceId}' or // 'file/{workspaceId}/{projectName}/{path}]' if ("workspace".equals(path.segment(0)) && path.segmentCount() == 2) { // $NON-NLS-1$ // all clones in the workspace if (WebWorkspace.exists(path.segment(1))) { WebWorkspace workspace = WebWorkspace.fromId(path.segment(1)); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); for (WebProject webProject : workspace.getProjects()) { // this is the location of the project metadata if (isAccessAllowed(user, webProject)) { IPath projectPath = GitUtils.pathFromProject(workspace, webProject); Map<IPath, File> gitDirs = GitUtils.getGitDirs(projectPath, Traverse.GO_DOWN); for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) { children.put(new Clone().toJSON(entry, baseLocation)); } } } result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE); result.put(ProtocolConstants.KEY_CHILDREN, children); OrionServlet.writeJSONResponse(request, response, result); return true; } String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } else if ("file".equals(path.segment(0)) && path.segmentCount() > 1) { // $NON-NLS-1$ // clones under given path WebProject webProject = GitUtils.projectFromPath(path); IPath projectRelativePath = path.removeFirstSegments(3); if (webProject != null && isAccessAllowed(user, webProject) && webProject.getProjectStore().getFileStore(projectRelativePath).fetchInfo().exists()) { Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_DOWN); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); for (Map.Entry<IPath, File> entry : gitDirs.entrySet()) { children.put(new Clone().toJSON(entry, baseLocation)); } result.put(ProtocolConstants.KEY_TYPE, Clone.TYPE); result.put(ProtocolConstants.KEY_CHILDREN, children); OrionServlet.writeJSONResponse(request, response, result); return true; } String msg = NLS.bind("Nothing found for the given ID: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } // else the request is malformed String msg = NLS.bind("Invalid clone request: {0}", path); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }
private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException { JSONArray arr = new JSONArray(); TypeDiscoverer td = new TypeDiscoverer(); try { for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); if (readMethod != null) { if (readMethod.getDeclaringClass() == java.lang.Enum.class) { // skip getDeclaringClass continue; } else if ("class".equals(pd.getName())) { // skip getClass continue; } } else { // yields com.datatorrent.api.Context on JDK6 and // com.datatorrent.api.Context.OperatorContext with JDK7 if ("up".equals(pd.getName()) && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) { continue; } } // LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType()); Class<?> propertyType = pd.getPropertyType(); if (propertyType != null) { JSONObject propertyObj = new JSONObject(); propertyObj.put("name", pd.getName()); propertyObj.put("canGet", readMethod != null); propertyObj.put("canSet", pd.getWriteMethod() != null); if (readMethod != null) { for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { OperatorClassInfo oci = classInfo.get(c.getName()); if (oci != null) { MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName()); if (getMethodInfo != null) { addTagsToProperties(getMethodInfo, propertyObj); break; } } } // type can be a type symbol or parameterized type td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj); } else { if (pd.getWriteMethod() != null) { td.setTypeArguments( clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj); } } // if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && // !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) { // propertyObj.put("properties", getClassProperties(propertyType, level + 1)); // } arr.put(propertyObj); } } } catch (JSONException ex) { throw new RuntimeException(ex); } return arr; }
public JSONObject describeOperator(String clazz) throws Exception { TypeGraphVertex tgv = typeGraph.getTypeGraphVertex(clazz); if (tgv.isInstantiable()) { JSONObject response = new JSONObject(); JSONArray inputPorts = new JSONArray(); JSONArray outputPorts = new JSONArray(); // Get properties from ASM JSONObject operatorDescriptor = describeClassByASM(clazz); JSONArray properties = operatorDescriptor.getJSONArray("properties"); properties = enrichProperties(clazz, properties); JSONArray portTypeInfo = operatorDescriptor.getJSONArray("portTypeInfo"); List<CompactFieldNode> inputPortfields = typeGraph.getAllInputPorts(clazz); List<CompactFieldNode> outputPortfields = typeGraph.getAllOutputPorts(clazz); try { for (CompactFieldNode field : inputPortfields) { JSONObject inputPort = setFieldAttributes(clazz, field); if (!inputPort.has("optional")) { inputPort.put( "optional", false); // input port that is not annotated is default to be not optional } if (!inputPort.has(SCHEMA_REQUIRED_KEY)) { inputPort.put(SCHEMA_REQUIRED_KEY, false); } inputPorts.put(inputPort); } for (CompactFieldNode field : outputPortfields) { JSONObject outputPort = setFieldAttributes(clazz, field); if (!outputPort.has("optional")) { outputPort.put( "optional", true); // output port that is not annotated is default to be optional } if (!outputPort.has("error")) { outputPort.put("error", false); } if (!outputPort.has(SCHEMA_REQUIRED_KEY)) { outputPort.put(SCHEMA_REQUIRED_KEY, false); } outputPorts.put(outputPort); } response.put("name", clazz); response.put("properties", properties); response.put(PORT_TYPE_INFO_KEY, portTypeInfo); response.put("inputPorts", inputPorts); response.put("outputPorts", outputPorts); OperatorClassInfo oci = classInfo.get(clazz); if (oci != null) { if (oci.comment != null) { String[] descriptions; // first look for a <p> tag String keptPrefix = "<p>"; descriptions = oci.comment.split("<p>", 2); if (descriptions.length == 0) { keptPrefix = ""; // if no <p> tag, then look for a blank line descriptions = oci.comment.split("\n\n", 2); } if (descriptions.length > 0) { response.put("shortDesc", descriptions[0]); } if (descriptions.length > 1) { response.put("longDesc", keptPrefix + descriptions[1]); } } response.put("category", oci.tags.get("@category")); String displayName = oci.tags.get("@displayName"); if (displayName == null) { displayName = decamelizeClassName(ClassUtils.getShortClassName(clazz)); } response.put("displayName", displayName); String tags = oci.tags.get("@tags"); if (tags != null) { JSONArray tagArray = new JSONArray(); for (String tag : StringUtils.split(tags, ',')) { tagArray.put(tag.trim().toLowerCase()); } response.put("tags", tagArray); } String doclink = oci.tags.get("@doclink"); if (doclink != null) { response.put("doclink", doclink + "?" + getDocName(clazz)); } else if (clazz.startsWith("com.datatorrent.lib.") || clazz.startsWith("com.datatorrent.contrib.")) { response.put("doclink", DT_OPERATOR_DOCLINK_PREFIX + "?" + getDocName(clazz)); } } } catch (JSONException ex) { throw new RuntimeException(ex); } return response; } else { throw new UnsupportedOperationException(); } }