Java Code Examples for com.fasterxml.jackson.databind.node.ArrayNode#toString()
The following examples show how to use
com.fasterxml.jackson.databind.node.ArrayNode#toString() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestGoogle.java From bidder with Apache License 2.0 | 6 votes |
@Test public void testVerticals() throws Exception { String proto = Charset.defaultCharset() .decode(ByteBuffer .wrap(Files.readAllBytes(Paths.get("./SampleBids/nositedomain.proto")))) .toString(); byte[] data = DatatypeConverter.parseBase64Binary(proto); InputStream is = new ByteArrayInputStream(data); GoogleBidRequest r = new GoogleBidRequest(is); Object s = r.interrogate("site.domain"); String test = s.toString(); assertTrue(test.contains("mobile.sabq.org")); ArrayNode node = (ArrayNode)r.interrogate("site.cat"); test = node.toString(); assertTrue(test.contains("5098")); assertTrue(test.contains("702")); assertTrue(test.contains("666")); assertTrue(test.contains("16")); }
Example 2
Source File: FactoidListResource.java From scava with Eclipse Public License 2.0 | 6 votes |
public Representation doRepresent() { ArrayNode node = mapper.createArrayNode(); for (IMetricProvider imp : platform.getMetricProviderManager().getMetricProviders()) { if (imp instanceof AbstractFactoidMetricProvider) { ObjectNode factoid = mapper.createObjectNode(); factoid.put("id", imp.getIdentifier()); factoid.put("name", imp.getFriendlyName()); factoid.put("summary", imp.getSummaryInformation()); ArrayNode uses = mapper.createArrayNode(); if (imp.getIdentifiersOfUses() != null && imp.getIdentifiersOfUses().size() > 0) { for (String use : imp.getIdentifiersOfUses()) { uses.add(use); } } factoid.put("dependencies", uses); node.add(factoid); } } getResponse().setStatus(Status.SUCCESS_OK); StringRepresentation resp = new StringRepresentation(node.toString()); resp.setMediaType(MediaType.APPLICATION_JSON); return resp; }
Example 3
Source File: TypesJerseyResourceIT.java From atlas with Apache License 2.0 | 5 votes |
@Test(dependsOnMethods = "testSubmit") public void testGetTypeNames() throws Exception { ObjectNode response = atlasClientV1.callAPIWithBodyAndParams(AtlasClient.API_V1.LIST_TYPES, null, (String[]) null); Assert.assertNotNull(response); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); final ArrayNode list = (ArrayNode) response.get(AtlasClient.RESULTS); Assert.assertNotNull(list); //Verify that primitive and core types are not returned String typesString = list.toString(); Assert.assertFalse(typesString.contains(" \"__IdType\" ")); Assert.assertFalse(typesString.contains(" \"string\" ")); }
Example 4
Source File: MonitoringController.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Gives suggestions when a Monitor searches for Learners and staff members. */ @RequestMapping("/autocomplete") @ResponseBody public String autocomplete(HttpServletRequest request, HttpServletResponse response) throws Exception { long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!securityService.isLessonMonitor(lessonId, getUserId(), "autocomplete in monitoring", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); return null; } String searchPhrase = request.getParameter("term"); boolean isOrganisationSearch = WebUtil.readStrParam(request, "scope").equalsIgnoreCase("organisation"); Collection<User> users = null; if (isOrganisationSearch) { // search for Learners in the organisation Map<User, Boolean> result = lessonService.getUsersWithLessonParticipation(lessonId, Role.LEARNER, searchPhrase, MonitoringController.USER_PAGE_SIZE, null, true); users = result.keySet(); } else { // search for Learners in the lesson users = lessonService.getLessonLearners(lessonId, searchPhrase, MonitoringController.USER_PAGE_SIZE, null, true); } ArrayNode responseJSON = JsonNodeFactory.instance.arrayNode(); for (User user : users) { ObjectNode userJSON = JsonNodeFactory.instance.objectNode(); userJSON.put("label", user.getFirstName() + " " + user.getLastName() + " " + user.getLogin()); userJSON.put("value", user.getUserId()); responseJSON.add(userJSON); } response.setContentType("application/json;charset=utf-8"); return responseJSON.toString(); }
Example 5
Source File: OutcomeController.java From lams with GNU General Public License v2.0 | 5 votes |
@RequestMapping("/outcomeGetMappings") @ResponseBody public String outcomeGetMappings(HttpServletRequest request, HttpServletResponse response) throws Exception { Long lessonId = WebUtil.readLongParam(request, "lessonId", true); Long toolContentId = WebUtil.readLongParam(request, "toolContentId", true); if (lessonId == null && toolContentId == null) { throw new IllegalArgumentException( "Either lesson ID or tool content ID must not be null when fetching outcome mappings"); } Long itemId = WebUtil.readLongParam(request, "itemId", true); Integer userId = getUserDTO().getUserID(); if (!request.isUserInRole(Role.SYSADMIN) && !request.isUserInRole(Role.AUTHOR)) { String error = "User " + userId + " is not sysadmin nor an author and can not map outcome"; log.error(error); throw new SecurityException(error); } List<OutcomeMapping> outcomeMappings = outcomeService.getOutcomeMappings(lessonId, toolContentId, itemId); ArrayNode responseJSON = JsonNodeFactory.instance.arrayNode(); for (OutcomeMapping outcomeMapping : outcomeMappings) { ObjectNode outcomeJSON = JsonNodeFactory.instance.objectNode(); outcomeJSON.put("mappingId", outcomeMapping.getMappingId()); outcomeJSON.put("outcomeId", outcomeMapping.getOutcome().getOutcomeId()); outcomeJSON.put("label", outcomeMapping.getOutcome().getName() + " (" + outcomeMapping.getOutcome().getCode() + ")"); responseJSON.add(outcomeJSON); } response.setContentType("application/json;charset=utf-8"); return responseJSON.toString(); }
Example 6
Source File: ContentManifest.java From cordova-hot-code-push with MIT License | 5 votes |
private String generateJson() { final JsonNodeFactory nodeFactory = JsonNodeFactory.instance; ArrayNode filesListNode = nodeFactory.arrayNode(); for (ManifestFile fileEntry : files) { ObjectNode fileNode = nodeFactory.objectNode(); fileNode.set(JsonKeys.FILE_PATH, nodeFactory.textNode(fileEntry.name)); fileNode.set(JsonKeys.FILE_HASH, nodeFactory.textNode(fileEntry.hash)); filesListNode.add(fileNode); } return filesListNode.toString(); }
Example 7
Source File: PinotSchemaRestletResource.java From incubator-pinot with Apache License 2.0 | 5 votes |
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/schemas") @ApiOperation(value = "List all schema names", notes = "Lists all schema names") public String listSchemaNames() { List<String> schemaNames = _pinotHelixResourceManager.getSchemaNames(); ArrayNode ret = JsonUtils.newArrayNode(); if (schemaNames != null) { for (String schema : schemaNames) { ret.add(schema); } } return ret.toString(); }
Example 8
Source File: TraceContext.java From incubator-pinot with Apache License 2.0 | 5 votes |
/** * Get the trace information added so far. */ public static String getTraceInfo() { ArrayNode jsonTraces = JsonUtils.newArrayNode(); for (Trace trace : REQUEST_TO_TRACES_MAP.get(TRACE_ENTRY_THREAD_LOCAL.get()._requestId)) { jsonTraces.add(trace.toJson()); } return jsonTraces.toString(); }
Example 9
Source File: NxApiRequest.java From onos with Apache License 2.0 | 5 votes |
/** * Generates a NX-API request message to execute on the Cisco NXOS device. * @param commands list of commands to execute * @param type response message format * @return the NX-API request string */ public static String generate(List<String> commands, CommandType type) { ObjectMapper om = new ObjectMapper(); ArrayNode aryNode = om.createArrayNode(); if (commands == null) { return aryNode.toString(); } IntStream.range(0, commands.size()).forEach(idx -> { ObjectNode parm = om.createObjectNode(); parm.put(CMD, commands.get(idx)); parm.put(VERSION, ONE); ObjectNode node = om.createObjectNode(); node.put(JSONRPC, TWO_POINT_ZERO); switch (type) { case CLI_ASCII: node.put(METHOD, CLI_ASCII); break; case CLI: default: node.put(METHOD, CLI); break; } node.set(PARAMS, parm); node.put(ID, idx + 1); aryNode.add(node); }); return aryNode.toString(); }
Example 10
Source File: PrometheusQueryResponseParse.java From presto with Apache License 2.0 | 4 votes |
private boolean parse() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); JsonParser parser = new JsonFactory().createParser(response); while (!parser.isClosed()) { JsonToken jsonToken = parser.nextToken(); if (JsonToken.FIELD_NAME.equals(jsonToken)) { if (parser.getCurrentName().equals("status")) { parser.nextToken(); if (parser.getValueAsString().equals("success")) { this.status = true; while (!parser.isClosed()) { parser.nextToken(); if (JsonToken.FIELD_NAME.equals(jsonToken)) { if (parser.getCurrentName().equals("resultType")) { parser.nextToken(); resultType = parser.getValueAsString(); } if (parser.getCurrentName().equals("result")) { parser.nextToken(); ArrayNode node = mapper.readTree(parser); result = node.toString(); break; } } } } else { //error path String parsedStatus = parser.getValueAsString(); parser.nextToken(); parser.nextToken(); this.errorType = parser.getValueAsString(); parser.nextToken(); parser.nextToken(); error = parser.getValueAsString(); throw new PrestoException(PROMETHEUS_PARSE_ERROR, "Unable to parse Prometheus response: " + parsedStatus + " " + errorType + " " + error); } } } if (result != null) { break; } } if (result != null && resultType != null) { switch (resultType) { case "matrix": case "vector": results = mapper.readValue(result, new TypeReference<List<PrometheusMetricResult>>() {}); break; case "scalar": case "string": stringOrScalarResult = mapper.readValue(result, new TypeReference<PrometheusTimeSeriesValue>() {}); Map<String, String> madeUpMetricHeader = new HashMap<>(); madeUpMetricHeader.put("__name__", resultType); PrometheusTimeSeriesValueArray timeSeriesValues = new PrometheusTimeSeriesValueArray(Arrays.asList(stringOrScalarResult)); results = Arrays.asList(new PrometheusMetricResult(madeUpMetricHeader, timeSeriesValues)); } } return true; }
Example 11
Source File: JdbcQueryService.java From poli with MIT License | 4 votes |
private String resultSetToJsonString(ResultSet rs, ResultSetMetaData metadata, int maxQueryResult) throws SQLException { int columnCount = metadata.getColumnCount(); ObjectMapper mapper = new ObjectMapper(); ArrayNode array = mapper.createArrayNode(); int rowCount = 0; while (rs.next()) { ObjectNode node = mapper.createObjectNode(); for (int i = 1; i <= columnCount; i++) { String columnLabel = metadata.getColumnLabel(i); int columnType = metadata.getColumnType(i); switch (columnType) { case java.sql.Types.VARCHAR: case java.sql.Types.CHAR: case java.sql.Types.LONGVARCHAR: node.put(columnLabel, rs.getString(i)); break; case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: node.put(columnLabel, rs.getInt(i)); break; case java.sql.Types.NUMERIC: case java.sql.Types.DECIMAL: node.put(columnLabel, rs.getBigDecimal(i)); break; case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: node.put(columnLabel, rs.getDouble(i)); break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: node.put(columnLabel, rs.getBoolean(i)); break; case java.sql.Types.BIGINT: node.put(columnLabel, rs.getLong(i)); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: node.put(columnLabel, rs.getNString(i)); break; default: // Unhandled types node.put(columnLabel, rs.getString(i)); break; } } array.add(node); rowCount++; if (maxQueryResult != Constants.QUERY_RESULT_NOLIMIT && rowCount >= maxQueryResult) { break; } } return array.toString(); }
Example 12
Source File: LearningWebsocketServer.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Feeds opened websockets with messages and roster. */ private static void send(Long toolSessionId) { // update the timestamp lastSendTimes.put(toolSessionId, System.currentTimeMillis()); ChatSession chatSession = LearningWebsocketServer.getChatService().getSessionBySessionId(toolSessionId); List<ChatMessage> messages = LearningWebsocketServer.getChatService().getLastestMessages(chatSession, null, true); Set<Websocket> sessionWebsockets = LearningWebsocketServer.websockets.get(toolSessionId); Roster roster = null; ArrayNode rosterJSON = null; String rosterString = null; for (Websocket websocket : sessionWebsockets) { // the connection is valid, carry on ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); // fetch roster only once, but messages are personalised try { if (rosterJSON == null) { roster = LearningWebsocketServer.rosters.get(toolSessionId); if (roster == null) { // build a new roster object roster = new Roster(toolSessionId); LearningWebsocketServer.rosters.put(toolSessionId, roster); } rosterJSON = roster.getRosterJSON(); rosterString = rosterJSON.toString(); } String userName = websocket.userName; ArrayNode messagesJSON = LearningWebsocketServer.getMessages(chatSession, messages, userName); // if hash of roster and messages is the same as before, do not send the message, save the bandwidth String hash = HashUtil.sha1(rosterString + messagesJSON.toString()); if ((websocket.hash == null) || !websocket.hash.equals(hash)) { websocket.hash = hash; responseJSON.set("messages", messagesJSON); responseJSON.set("roster", rosterJSON); // send the payload to the Learner's browser if (websocket.session.isOpen()) { websocket.session.getBasicRemote().sendText(responseJSON.toString()); } } } catch (Exception e) { LearningWebsocketServer.log.error("Error while building message JSON", e); } } }
Example 13
Source File: ProjectListResource.java From scava with Eclipse Public License 2.0 | 4 votes |
public Representation doRepresent() { // Ready query params String _page = getQueryValue("page"); String _size = getQueryValue("size"); ProjectRepository projectRepo = platform.getProjectRepositoryManager().getProjectRepository(); DBCursor cursor; if(_page != null && !"".equals(_page) && isInteger(_page) && _size != null && !"".equals(_size) && isInteger(_size)) { int page = Integer.valueOf(_page); int pageSize = Integer.valueOf(_size); cursor = projectRepo.getProjects().getDbCollection().find().skip(page*pageSize).limit(pageSize); } else { cursor = projectRepo.getProjects().getDbCollection().find(); } ArrayNode projects = mapper.createArrayNode(); while (cursor.hasNext()) { try { DBObject p = cursor.next(); p.removeField("storage"); p.removeField("metricProviderData"); p.removeField("_superTypes"); p.removeField("_id"); // FIXME: Temporary solution p.removeField("licenses"); p.removeField("persons"); projects.add(mapper.readTree(p.toString())); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); ObjectNode m = mapper.createObjectNode(); m.put("apicall", "list-all-projects"); return Util.generateErrorMessageRepresentation(m, e.getMessage()); } } cursor.close(); StringRepresentation resp = new StringRepresentation(projects.toString()); resp.setMediaType(MediaType.APPLICATION_JSON); return resp; }
Example 14
Source File: PinotTableRestletResource.java From incubator-pinot with Apache License 2.0 | 4 votes |
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/tables/{tableName}") @ApiOperation(value = "Get/Enable/Disable/Drop a table", notes = "Get/Enable/Disable/Drop a table. If table name is the only parameter specified " + ", the tableconfig will be printed") public String alterTableStateOrListTableConfig( @ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "enable|disable|drop") @QueryParam("state") String stateStr, @ApiParam(value = "realtime|offline") @QueryParam("type") String tableTypeStr) { try { if (stateStr == null) { return listTableConfigs(tableName, tableTypeStr); } StateType stateType = Constants.validateState(stateStr); TableType tableType = Constants.validateTableType(tableTypeStr); ArrayNode ret = JsonUtils.newArrayNode(); boolean tableExists = false; if (tableType != TableType.REALTIME && _pinotHelixResourceManager.hasOfflineTable(tableName)) { String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(tableName); ObjectNode offline = JsonUtils.newObjectNode(); tableExists = true; offline.put("tableName", offlineTableName); offline.set("state", JsonUtils.objectToJsonNode(_pinotHelixResourceManager.toggleTableState(offlineTableName, stateType))); ret.add(offline); } if (tableType != TableType.OFFLINE && _pinotHelixResourceManager.hasRealtimeTable(tableName)) { String realtimeTableName = TableNameBuilder.REALTIME.tableNameWithType(tableName); ObjectNode realtime = JsonUtils.newObjectNode(); tableExists = true; realtime.put("tableName", realtimeTableName); realtime.set("state", JsonUtils.objectToJsonNode(_pinotHelixResourceManager.toggleTableState(realtimeTableName, stateType))); ret.add(realtime); } if (tableExists) { return ret.toString(); } else { throw new ControllerApplicationException(LOGGER, "Table '" + tableName + "' does not exist", Response.Status.BAD_REQUEST); } } catch (Exception e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR, e); } }