List of usage examples for com.fasterxml.jackson.databind JsonNode toString
public abstract String toString();
From source file:com.evrythng.java.wrapper.mapping.BatchPopulatingTaskInputParametersDeserializer.java
@Override public BatchPopulatingTask.InputParameters deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException { ObjectMapper mapper = JSONUtils.OBJECT_MAPPER; JsonNode node = mapper.readTree(jp); JsonNode typeNode = node.get(BatchPopulatingTask.InputParameters.FIELD_TYPE); if (typeNode == null) { throw new JsonMappingException("Cannot deserialize adi generation input parameters without type field"); }// w w w. j a v a 2 s . c om String typeRaw = getFieldValue(typeNode); Class<? extends BatchPopulatingTask.InputParameters> subtypeClass = classForType( BatchPopulatingTask.InputParameters.Type.valueOf(typeRaw.toUpperCase())); return mapper.readValue(node.toString(), subtypeClass); }
From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializer.java
protected void deserializeConnections(TransMeta transMeta, JsonNode node, ObjectMapper mapper) { ArrayNode connectionsArrayNode = (ArrayNode) node.get(TransMetaJsonSerializer.JSON_PROPERTY_CONNECTIONS); IExternalResourceInfo conn = null;// ww w . jav a2s . c o m for (int i = 0; i < connectionsArrayNode.size(); i++) { JsonNode connNode = connectionsArrayNode.get(i); String className = connNode.get(IInfo.JSON_PROPERTY_CLASS).asText(); try { Class clazz = this.getClass().getClassLoader().loadClass(className); conn = (IExternalResourceInfo) clazz.newInstance(); conn = mapper.readValue(connNode.toString(), conn.getClass()); DatabaseMeta dbMeta = null; if (conn instanceof JdbcResourceInfo) { JdbcResourceInfo db = (JdbcResourceInfo) conn; dbMeta = new DatabaseMeta(db.getName(), db.getPluginId(), DatabaseMeta.getAccessTypeDesc(DatabaseMeta.TYPE_ACCESS_NATIVE), db.getServer(), db.getDatabaseName(), String.valueOf(db.getPort()), db.getUsername(), db.getPassword()); } else if (conn instanceof JndiResourceInfo) { JndiResourceInfo db = (JndiResourceInfo) conn; dbMeta = new DatabaseMeta(db.getName(), db.getPluginId(), DatabaseMeta.getAccessTypeDesc(DatabaseMeta.TYPE_ACCESS_JNDI), null, null, null, null, null); } transMeta.addDatabase(dbMeta); } catch (Exception e) { LOGGER.warn(Messages.getString("WARNING.Deserialization.Trans.Connections", conn.getName(), transMeta.getName()), e); } } }
From source file:com.github.fge.jsonschema.servlets.SyntaxValidateServlet.java
@Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final Set<String> params = Sets.newHashSet(); /*// ww w . j a v a 2 s. c om * First, check our parameters */ /* * Why, in 2013, doesn't servlet-api provide an Iterator<String>? * * Well, at least, Jetty's implementation has a generified Enumeration. * Still, that sucks. */ final Enumeration<String> enumeration = req.getParameterNames(); // FIXME: no duplicates, it seems, but I cannot find the spec which // guarantees that while (enumeration.hasMoreElements()) params.add(enumeration.nextElement()); // We have required parameters if (!params.containsAll(Request.required())) { log.warn("Missing parameters! Someone using me as a web service?"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters"); return; } // We don't want extraneous parameters params.removeAll(Request.valid()); if (!params.isEmpty()) { log.warn("Invalid parameters! Someone using me as a web service?"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters"); return; } final String rawSchema = req.getParameter(Request.SCHEMA); // Set correct content type resp.setContentType(MediaType.JSON_UTF_8.toString()); final JsonNode ret; try { ret = buildResult(rawSchema); } catch (ProcessingException e) { // Should not happen! log.error("Uh, syntax validation failed!", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } final OutputStream out = resp.getOutputStream(); try { out.write(ret.toString().getBytes(Charset.forName("UTF-8"))); out.flush(); } finally { Closeables.closeQuietly(out); } }
From source file:io.seldon.external.ExternalPredictionServer.java
public JsonNode predict(String client, JsonNode jsonNode, OptionsHolder options) { long timeNow = System.currentTimeMillis(); URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME)); try {//from w w w . j ava2 s. c o m URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setParameter("client", client) .setParameter("json", jsonNode.toString()); uri = builder.build(); } catch (URISyntaxException e) { throw new APIException(APIException.GENERIC_ERROR); } HttpContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(uri); try { if (logger.isDebugEnabled()) logger.debug("Requesting " + httpGet.getURI().toString()); CloseableHttpResponse resp = httpClient.execute(httpGet, context); try { if (resp.getStatusLine().getStatusCode() == 200) { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = factory.createParser(resp.getEntity().getContent()); JsonNode actualObj = mapper.readTree(parser); return actualObj; } else { logger.error( "Couldn't retrieve prediction from external prediction server -- bad http return code: " + resp.getStatusLine().getStatusCode()); throw new APIException(APIException.GENERIC_ERROR); } } finally { if (resp != null) resp.close(); if (logger.isDebugEnabled()) logger.debug( "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms"); } } catch (IOException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } catch (Exception e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } finally { } }
From source file:com.googlecode.jsonrpc4j.JsonRpcClient.java
/** * Reads a JSON-PRC response from the server. This blocks until * a response is received.// w ww . j a va 2 s . c om * * @param returnType the expected return type * @param ips the {@link InputStream} to read from * @return the object returned by the JSON-RPC response * @throws Throwable on error */ public Object readResponse(Type returnType, InputStream ips) throws Throwable { // get node iterator ReadContext ctx = ReadContext.getReadContext(ips, mapper); // read the response ctx.assertReadable(); JsonNode response = ctx.nextValue(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "JSON-PRC Response: " + response.toString()); } // bail on invalid response if (!response.isObject()) { throw new JsonRpcClientException(0, "Invalid JSON-RPC response", response); } ObjectNode jsonObject = ObjectNode.class.cast(response); // show to listener if (this.requestListener != null) { this.requestListener.onBeforeResponseProcessed(this, jsonObject); } // detect errors if (jsonObject.has("error") && jsonObject.get("error") != null && !jsonObject.get("error").isNull()) { // resolve and throw the exception if (exceptionResolver == null) { throw DefaultExceptionResolver.INSTANCE.resolveException(jsonObject); } else { throw exceptionResolver.resolveException(jsonObject); } } // convert it to a return object if (jsonObject.has("result") && !jsonObject.get("result").isNull() && jsonObject.get("result") != null) { if (returnType == null) { LOGGER.warning("Server returned result but returnType is null"); return null; } JsonParser returnJsonParser = mapper.treeAsTokens(jsonObject.get("result")); JavaType returnJavaType = TypeFactory.defaultInstance().constructType(returnType); return mapper.readValue(returnJsonParser, returnJavaType); } // no return type return null; }
From source file:com.evrythng.java.wrapper.mapping.BatchPopulatingTaskOutputParametersDeserializer.java
@Override public BatchPopulatingTask.OutputParameters deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException { ObjectMapper mapper = JSONUtils.OBJECT_MAPPER; JsonNode node = mapper.readTree(jp); JsonNode typeNode = node.get(BatchPopulatingTask.OutputParameters.FIELD_TYPE); if (typeNode == null) { throw new JsonMappingException( "Cannot deserialize adi generation output parameters without type field"); }//from ww w . j a v a2 s . com String typeRaw = getFieldValue(typeNode); Class<? extends BatchPopulatingTask.OutputParameters> subtypeClass = classForType( BatchPopulatingTask.OutputParameters.Type.valueOf(typeRaw.toUpperCase())); return mapper.readValue(node.toString(), subtypeClass); }
From source file:org.springframework.social.facebook.api.impl.FacebookTemplate.java
@SuppressWarnings("unchecked") private <T> List<T> deserializeDataList(JsonNode jsonNode, final Class<T> elementType) { try {/* w w w. java 2s . co m*/ CollectionType listType = TypeFactory.defaultInstance().constructCollectionType(List.class, elementType); return (List<T>) objectMapper.reader(listType).readValue(jsonNode.toString()); // TODO: EXTREMELY HACKY--TEMPORARY UNTIL I FIGURE OUT HOW JACKSON 2 DOES THIS } catch (IOException e) { throw new UncategorizedApiException("facebook", "Error deserializing data from Facebook: " + e.getMessage(), e); } }
From source file:com.baasbox.commands.DocumentsResource.java
private String getCollectionName(JsonNode command) throws CommandParsingException { JsonNode params = command.get(ScriptCommand.PARAMS); JsonNode collNode = params.get(COLLECTION); if (collNode == null || !collNode.isTextual()) { throw new CommandParsingException(command, "invalid collection param: " + (collNode == null ? "null" : collNode.toString())); }/*www . ja va 2 s.c o m*/ return collNode.asText(); }
From source file:org.flowable.admin.service.engine.ProcessInstanceService.java
public void changeActivityState(ServerConfig serverConfig, String processInstanceId, JsonNode changeActivityBody) throws FlowableServiceException { try {/* ww w .j a v a 2 s. c o m*/ URIBuilder builder = clientUtil.createUriBuilder( MessageFormat.format(RUNTIME_PROCESS_INSTANCE_CHANGE_STATE_URL, processInstanceId)); HttpPost post = clientUtil.createPost(builder.build().toString(), serverConfig); post.setEntity(clientUtil.createStringEntity(changeActivityBody.toString())); clientUtil.executeRequestNoResponseBody(post, serverConfig, HttpStatus.SC_OK); } catch (Exception e) { throw new FlowableServiceException(e.getMessage(), e); } }