@Test public void filters_criteria_can_be_refined() throws Exception { ObjectNode check = JsonNodeFactory.instance.objectNode(); check.put("string", "foo"); check.putNull("string_null"); check.put("int", 10); check.put("long", 1L); check.put("double", 1.12D); Filter filter = filter(where("string").is("foo")); assertTrue(filter.accept(check)); Criteria criteria = where("string").is("not eq"); filter.addCriteria(criteria); assertFalse(filter.accept(check)); filter = filter(where("string").is("foo").and("string").is("not eq")); assertFalse(filter.accept(check)); filter = filter(where("string").is("foo").and("string").is("foo")); assertTrue(filter.accept(check)); }
@RequestMapping(value = "/getGRNFromOderId", method = RequestMethod.GET) public void getGRNFromOderId( HttpServletResponse httpservletResponse, @RequestParam String oderId, @RequestParam String status) { try { List<GrnVO> valueObj = grnManager.getGRNFromOderId(oderId, status); if (valueObj != null && valueObj.size() > 0) { ObjectMapper mapper = new ObjectMapper(); ObjectNode objectNode = new ObjectNode(mapper.getNodeFactory()); JsonObjectUtil<GrnVO> jsonUtil = new JsonObjectUtil<GrnVO>(); String m = jsonUtil.getJsonObjectDataDetail(valueObj, 1); ArrayNode node = mapper.readValue(m, ArrayNode.class); objectNode.put("Data", node); objectNode.put("success", true); writeJson(httpservletResponse, objectNode, mapper); } else { writeJsonString(httpservletResponse, "{\"Data\":\"Empty\",\"success\":false}"); } } catch (Exception e) { getLogger().error(e.getMessage()); writeJsonString( httpservletResponse, "{\"Data\":\"" + e.getMessage() + "\",\"success\":false}"); } }
/** data set attributes can load values just like report attributes */ @Test public void loadAttributeValues() { ObjectNode node = builder.buildDataSetNode(dataSetId, name, description, owner, lastChange); node.put( "attributes", new ObjectMapper() .createArrayNode() .add(builder.buildAttributeNode(id, name, code, "string"))); server.register(dataSetsUri + "/" + dataSetId, node.toString()); DataSet dataSet = service.loadDataSet(dataSetId); Attribute attribute = dataSet.getAttributes().get(0); String label = "label"; String value = "value"; final ObjectNode valueNode = new ObjectMapper().createObjectNode(); valueNode.put( "values", new ObjectMapper().createArrayNode().add(builder.buildAttributeValueNode(label, value))); server.register( dataSetsUri + "/" + dataSetId + "/attributes/" + code + "/values", valueNode.toString()); List<AttributeValue> values = attribute.getValues().load().get(); assertEquals(values.size(), 1); assertEquals(values.get(0).getLabel(), label); assertEquals(values.get(0).getValue(), value); assertEquals(attribute.toString(), name); assertEquals(values.get(0).toString(), label); }
@At("/?/json") @Ok("raw") public ObjectNode getEditorJson(String modelId) { ObjectNode modelNode = null; Model model = repositoryService.getModel(modelId); if (model != null) { try { ObjectMapper objectMapper = new ObjectMapper(); if (StringUtils.isNotEmpty(model.getMetaInfo())) { modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo()); } else { modelNode = objectMapper.createObjectNode(); modelNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName()); } modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId()); ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree( new String(repositoryService.getModelEditorSource(model.getId()), "utf-8")); modelNode.put("model", editorJsonNode); } catch (Exception e) { log.error("Error creating model JSON", e); throw new ActivitiException("Error creating model JSON", e); } } return modelNode; }
@Test public void addToInvalidRestaurant() { running( fakeApplication(), () -> { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("text", "text of review"); node.put("rating", 4); JsonNode json = null; try { json = (JsonNode) new ObjectMapper().readTree(node.toString()); } catch (IOException e) { e.printStackTrace(); } Http.RequestBuilder rb = new Http.RequestBuilder() .method(POST) .uri("/v1/restaurants/3213123/reviews") .bodyJson(json); Result result = route(rb); assertEquals(Http.Status.NOT_FOUND, result.status()); }); }
// Checks whether javaClass has a path tag associated with it and if it does // processes its methods and creates a tag for the class on the root void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags) { // If the class does not have a Path tag then ignore it JavaAnnotation annotation = getPathAnnotation(javaClass); if (annotation == null) { return; } String path = getPath(annotation); if (path == null) { return; } String resourcePath = "/" + path; String tagPath = path.isEmpty() ? "/" : path; // Create tag node for this class. ObjectNode tagObject = mapper.createObjectNode(); tagObject.put("name", tagPath); if (javaClass.getComment() != null) { tagObject.put("description", shortText(javaClass.getComment())); } tags.add(tagObject); // Create an array node add to all methods from this class. ArrayNode tagArray = mapper.createArrayNode(); tagArray.add(tagPath); processAllMethods(javaClass, resourcePath, paths, tagArray); }
/** * Create a new Nominatim Geo Node to be added to the local Elasticsearch index * * @param aQuery The query that is used to get the information from wikidata * @return The Geo Node for geo information * @throws JSONException Thrown if Json cannot be read from URL or first Json Object cannot be * returned from result set * @throws IOException Thrown if Json cannot be read from URL */ public static ObjectNode createGeoNode(final String aQuery) throws JSONException, IOException { // grid data of this geo node: ObjectNode geoNode = buildGeoNode(aQuery); // data enrichment to this geo node: JSONObject wikidata = getFirstHit(aQuery); if (wikidata != null) { String id = getId(wikidata); geoNode.put(Constants.ID, id); String label = getLabel(wikidata, id); geoNode.put(Constants.LABEL, label); double latitude = getLat(wikidata, id); double longitude = getLong(wikidata, id); geoNode.put( Constants.GEOCODE, new ObjectMapper() .readTree( // String.format( "{\"latitude\":\"%s\",\"longitude\":\"%s\"}", latitude, longitude))); } return geoNode; }
/** * 群组批量添加成员 * * @param toAddBacthChatgroupid * @param usernames * @return */ private static ObjectNode addUsersToGroupBatch( String toAddBacthChatgroupid, ObjectNode usernames) { ObjectNode objectNode = factory.objectNode(); // check appKey format if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) { LOGGER.error("Bad format of Appkey: " + APPKEY); objectNode.put("message", "Bad format of Appkey"); return objectNode; } if (StringUtils.isBlank(toAddBacthChatgroupid.trim())) { LOGGER.error("Property that named toAddBacthChatgroupid must be provided ."); objectNode.put("message", "Property that named toAddBacthChatgroupid must be provided ."); return objectNode; } // check properties that must be provided if (null != usernames && !usernames.has("usernames")) { LOGGER.error("Property that named usernames must be provided ."); objectNode.put("message", "Property that named usernames must be provided ."); return objectNode; } try { objectNode = JerseyUtils.sendRequest( EndPoints.CHATGROUPS_TARGET.path(toAddBacthChatgroupid).path("users"), usernames, credential, HTTPMethod.METHOD_POST, null); } catch (Exception e) { e.printStackTrace(); } return objectNode; }
@Test public void addValidReview() { running( fakeApplication(), () -> { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("text", "text of review"); node.put("rating", 4); JsonNode json = null; try { json = (JsonNode) new ObjectMapper().readTree(node.toString()); } catch (IOException e) { e.printStackTrace(); } Http.RequestBuilder rb = new Http.RequestBuilder() .method(POST) .uri("/v1/restaurants/1601994/reviews") .bodyJson(json); Result result = route(rb); assertEquals(Http.Status.OK, result.status()); assertTrue(PersistenceManager.getRestaurantById(1601994).getReviews().size() != 0); assertTrue( PersistenceManager.getRestaurantById(1601994) .getReviews() .get(0) .getText() .equals("text of review")); }); }
/** * 获取一个用户参与的所有群组 * * @param username * @return */ private static ObjectNode getJoinedChatgroupsForIMUser(String username) { ObjectNode objectNode = factory.objectNode(); // check appKey format if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) { LOGGER.error("Bad format of Appkey: " + APPKEY); objectNode.put("message", "Bad format of Appkey"); return objectNode; } if (StringUtils.isBlank(username.trim())) { LOGGER.error("Property that named username must be provided ."); objectNode.put("message", "Property that named username must be provided ."); return objectNode; } try { URL getJoinedChatgroupsForIMUserUrl = HTTPClientUtils.getURL( Constants.APPKEY.replace("#", "/") + "/users/" + username + "/joined_chatgroups"); objectNode = HTTPClientUtils.sendHTTPRequest( getJoinedChatgroupsForIMUserUrl, credential, null, HTTPMethod.METHOD_GET); } catch (Exception e) { e.printStackTrace(); } return objectNode; }
public Result addComentario() { DynamicForm form = new DynamicForm().bindFromRequest(); ObjectNode response = Json.newObject(); try { if (AuthManager.authCheck(session(), form)) { String msg = form.get("mensagem"); String projecto = form.get("projecto"); Projecto p = projectos.byId(Long.valueOf(projecto)); String user_id = AuthManager.currentUsername(session("jwt")); Comentario c = new Comentario(msg, user_id, p); c.save(); response.put("result", Json.toJson(c)); return ok(response); } else { response.put("result", "Authorization missing or wrong"); return forbidden(response); } } catch (Exception e) { response.put("exception", e.getMessage()); return internalServerError(response); } }
@Test public void testCreateDocument() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", TEST_USER, TEST_USER); ObjectNode params = MAPPER.createObjectNode(); ObjectNode doc = MAPPER.createObjectNode(); doc.put("fresh", "fresh"); params.put("collection", TEST_COLLECTION); params.put("data", doc); ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params); JsonNode exec = CommandRegistry.execute(cmd, null); assertNotNull(exec); assertTrue(exec.isObject()); assertNotNull(exec.get("id")); assertEquals(TEST_COLLECTION, exec.get("@class").asText()); } catch (Throwable t) { fail(ExceptionUtils.getFullStackTrace(t)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
/** Returns a json representation of this */ @Override public JsonNode toJson() { ObjectNode node = getFactory().objectNode(); node.put("timeLimit", timeLimit); node.put("asynchronous", asynchronous); return node; }
/** * Sends a message envelope on this socket * * @param envelope The message envelope * @return This socket instance * @throws IOException Thrown if the message cannot be sent */ public Socket push(final Envelope envelope) throws IOException { LOG.log(Level.FINE, "Pushing envelope: {0}", envelope); final ObjectNode node = objectMapper.createObjectNode(); node.put("topic", envelope.getTopic()); node.put("event", envelope.getEvent()); node.put("ref", envelope.getRef()); node.set( "payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); final String json = objectMapper.writeValueAsString(node); LOG.log(Level.FINE, "Sending JSON: {0}", json); RequestBody body = RequestBody.create(WebSocket.TEXT, json); if (this.isConnected()) { try { webSocket.sendMessage(body); } catch (IllegalStateException e) { LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e); } } else { this.sendBuffer.add(body); } return this; }
/** * 获取一个用户参与的所有群组 * * @param username * @return */ private static ObjectNode getJoinedChatgroupsForIMUser(String username) { ObjectNode objectNode = factory.objectNode(); // check appKey format if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) { LOGGER.error("Bad format of Appkey: " + APPKEY); objectNode.put("message", "Bad format of Appkey"); return objectNode; } if (StringUtils.isBlank(username.trim())) { LOGGER.error("Property that named username must be provided ."); objectNode.put("message", "Property that named username must be provided ."); return objectNode; } try { objectNode = JerseyUtils.sendRequest( EndPoints.USERS_TARGET.path(username).path("joined_chatgroups"), null, credential, HTTPMethod.METHOD_GET, null); } catch (Exception e) { e.printStackTrace(); } return objectNode; }
/** * 图片语音文件下载 * * @param fileUUID 文件在DB的UUID * @param shareSecret 文件在DB中保存的shareSecret * @param localPath 下载后文件存放地址 * @param isThumbnail 是否下载缩略图 true:缩略图 false:非缩略图 * @return */ public static ObjectNode mediaDownload( String fileUUID, String shareSecret, File localPath, Boolean isThumbnail) { ObjectNode objectNode = factory.objectNode(); File downLoadedFile = null; if (!JerseyUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) { LOGGER.error("Bad format of Appkey: " + APPKEY); objectNode.put("message", "Bad format of Appkey"); return objectNode; } try { JerseyWebTarget webTarget = EndPoints.CHATFILES_TARGET .resolveTemplate("org_name", APPKEY.split("#")[0]) .resolveTemplate("app_name", APPKEY.split("#")[1]) .path(fileUUID); List<NameValuePair> headers = new ArrayList<NameValuePair>(); headers.add(new BasicNameValuePair("share-secret", shareSecret)); headers.add(new BasicNameValuePair("Accept", "application/octet-stream")); if (isThumbnail != null && isThumbnail) { headers.add(new BasicNameValuePair("thumbnail", String.valueOf(isThumbnail))); } downLoadedFile = JerseyUtils.downLoadFile(webTarget, credential, headers, localPath); LOGGER.error( "File download successfully,file path : " + downLoadedFile.getAbsolutePath() + "."); } catch (Exception e) { e.printStackTrace(); } objectNode.put("message", "File download successfully ."); return objectNode; }
private void storeConnection(String agentId, String username, String password, String resource) throws JSONRPCException, IOException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { State state = agentHost.getStateFactory().get(agentId); String conns = (String) state.get(CONNKEY); ArrayNode newConns; if (conns != null) { newConns = (ArrayNode) JOM.getInstance().readTree(conns); } else { newConns = JOM.createArrayNode(); } ObjectNode params = JOM.createObjectNode(); params.put("username", EncryptionUtil.encrypt(username)); params.put("password", EncryptionUtil.encrypt(password)); if (resource != null && !resource.isEmpty()) { params.put("resource", EncryptionUtil.encrypt(resource)); } for (JsonNode item : newConns) { if (item.get("username").equals(params.get("username"))) { return; } } newConns.add(params); if (!state.putIfUnchanged(CONNKEY, JOM.getInstance().writeValueAsString(newConns), conns)) { // recursive retry storeConnection(agentId, username, password, resource); } }
public F.Promise<Result> status() { ObjectNode status = Json.newObject(); status.put("status", "ok"); status.put("version", API_VERSION); F.Promise<JsonNode> responsePromise = F.Promise.promise(() -> status); return responsePromise.map(Results::ok); }
public static JsonNode build(final JsonProcessingException e, final boolean crlf) { final JsonLocation location = e.getLocation(); final ObjectNode ret = JsonNodeFactory.instance.objectNode(); /* * Unfortunately, for some reason, Jackson botches the column number in * its JsonPosition -- I cannot figure out why exactly. However, it does * have a correct offset into the buffer. * * The problem is that if the input has CR/LF line terminators, its * offset will be "off" by the number of lines minus 1 with regards to * what JavaScript sees as positions in text areas. Make the necessary * adjustments so that the caret jumps at the correct position in this * case. */ final int lineNr = location.getLineNr(); int offset = (int) location.getCharOffset(); if (crlf) offset = offset - lineNr + 1; ret.put(LINE, lineNr); ret.put(OFFSET, offset); // Finally, put the message ret.put(MESSAGE, e.getOriginalMessage()); return ret; }
@Test public void testCommandGetSingleDocument() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", TEST_USER, TEST_USER); ObjectNode cmd = MAPPER.createObjectNode(); ObjectNode p = MAPPER.createObjectNode(); p.put("collection", TEST_COLLECTION); p.put("id", sGenIds.get(0)); cmd.put(ScriptCommand.RESOURCE, "documents"); cmd.put(ScriptCommand.NAME, "get"); cmd.put(ScriptCommand.PARAMS, p); JsonNode node = CommandRegistry.execute(cmd, null); assertNotNull(node); assertTrue(node.isObject()); assertNotNull(node.get("generated")); assertNotNull(node.get("id")); assertEquals(node.get("id").asText(), sGenIds.get(0)); assertEquals(node.get("@class").asText(), TEST_COLLECTION); } catch (Throwable t) { fail(ExceptionUtils.getFullStackTrace(t)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
@Override protected void encodeResponse(ObjectNode json, DescribeSensorResponse t) throws OwsExceptionReport { json.put(JSONConstants.PROCEDURE_DESCRIPTION_FORMAT, t.getOutputFormat()); json.put( JSONConstants.PROCEDURE_DESCRIPTION, encodeDescriptions(t.getProcedureDescriptions(), t.getOutputFormat())); }
public static ObjectNode createResponse(Object response, boolean ok) { ObjectNode result = Json.newObject(); result.put("isSuccessfull", ok); if (response instanceof String) result.put("body", (String) response); else result.put("body", (JsonNode) response); return result; }
private ObjectNode getNewPointJson( String name, String opening_hours, double latitude, double longitude) { ObjectNode newPoint = Json.newObject(); newPoint.put("name", name); newPoint.put("opening_hours", opening_hours); newPoint.putObject("location").put("lat", latitude).put("lon", longitude); return newPoint; }
@Override public String toBulkJson(final ObjectNode node) { ObjectNode index = node.putObject("delete"); index.put("_index", this.index); index.put("_type", type); index.put("_id", id); return node.toString(); }
protected void sendError(int code, String message) throws IOException { ObjectNode root = this.mapper.createObjectNode(); root.put(TYPE, ERROR); ObjectNode data = root.putObject(ERROR); data.put(TYPE, PROGRAMMER); data.put(CODE, code); data.put(MESSAGE, message); this.connection.sendMessage(this.mapper.writeValueAsString(root)); }
private ObjectNode encodeSweBooleanField(SweField field) { ObjectNode jfield = createField(field); jfield.put(JSONConstants.TYPE, JSONConstants.BOOLEAN_TYPE); SweBoolean sweBoolean = (SweBoolean) field.getElement(); if (sweBoolean.isSetValue()) { jfield.put(JSONConstants.VALUE, sweBoolean.getValue()); } return jfield; }
/** api接口用的 */ public static String getResponseResult4Value(ObjectMapper objectMapper, JsonNode jsonNode) { ObjectNode resultObjectNode = objectMapper.createObjectNode(); resultObjectNode.put("status", 200); if (jsonNode != null) { resultObjectNode.put("data", jsonNode); } resultObjectNode.put("statusText", "OK"); return resultObjectNode.toString(); }
private ObjectNode encodeSweTextField(SweField field) { ObjectNode jfield = createField(field); jfield.put(JSONConstants.TYPE, JSONConstants.TEXT_TYPE); SweText sweText = (SweText) field.getElement(); if (sweText.isSetValue()) { jfield.put(JSONConstants.VALUE, sweText.getValue()); } return jfield; }
private ObjectNode encodeSweObservableProperyField(SweField field) { ObjectNode jfield = createField(field); jfield.put(JSONConstants.TYPE, JSONConstants.OBSERVABLE_PROPERTY_TYPE); SweObservableProperty sweObservableProperty = (SweObservableProperty) field.getElement(); if (sweObservableProperty.isSetValue()) { jfield.put(JSONConstants.VALUE, sweObservableProperty.getValue()); } return jfield; }
private ObjectNode encodeSweCategoryField(SweField field) { ObjectNode jfield = createField(field); jfield.put(JSONConstants.TYPE, JSONConstants.CATEGORY_TYPE); SweCategory sweCategory = (SweCategory) field.getElement(); jfield.put(JSONConstants.CODESPACE, sweCategory.getCodeSpace()); if (sweCategory.isSetValue()) { jfield.put(JSONConstants.VALUE, sweCategory.getValue()); } return jfield; }