Example usage for com.fasterxml.jackson.databind.node ObjectNode toString

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ObjectNode toString.

Prototype

public String toString() 

Source Link

Usage

From source file:org.apache.streams.mongo.MongoPersistWriter.java

protected DBObject prepareObject(StreamsDatum streamsDatum) {
    DBObject dbObject = null;//from   ww  w . j  ava  2 s  .  c om
    if (streamsDatum.getDocument() instanceof String) {
        dbObject = (DBObject) JSON.parse((String) streamsDatum.getDocument());
    } else {
        try {
            ObjectNode node = mapper.valueToTree(streamsDatum.getDocument());
            dbObject = (DBObject) JSON.parse(node.toString());
        } catch (Exception ex) {
            LOGGER.error("Unsupported type: " + streamsDatum.getDocument().getClass(), ex);
        }
    }
    return dbObject;
}

From source file:com.dotweblabs.friendscube.rest.resources.gae.GaeFileServerResource.java

@Override
public String upload(Representation entity) throws Exception {
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            Request restletRequest = getRequest();
            HttpServletRequest servletRequest = ServletUtils.getRequest(restletRequest);
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator fileIterator = upload.getItemIterator(servletRequest);
            getLogger().info("content type: " + servletRequest.getContentType());
            getLogger().info("content: " + new ServletRequestContext(servletRequest).getContentLength());

            getLogger().info("iterator: " + fileIterator.hasNext());
            while (fileIterator.hasNext()) {
                FileItemStream item = fileIterator.next();

                String name = item.getName();
                String fileName = getQueryValue("client_token") + "_" + name; // TODO note storing client_token is dangerous
                GcsFilename gcsFilename = new GcsFilename(getBucketName(), fileName);
                getLogger().info("using bucket.. " + getBucketName());
                byte[] byteContent = ByteStreams.toByteArray(item.openStream());
                // TODO byteContent is basicallly the file uploaded

                getLogger().info("contentType: " + item.getContentType());
                GcsOutputChannel outputChannel = gcsService.createOrReplace(gcsFilename,
                        GcsFileOptions.getDefaultInstance());
                outputChannel.write(ByteBuffer.wrap(byteContent));
                outputChannel.close();//from   w w  w. java2  s.  c om
                getLogger().info("uploaded");

                BlobKey blobKey = blobstoreService.createGsBlobKey(
                        "/gs/" + gcsFilename.getBucketName() + "/" + gcsFilename.getObjectName());

                ObjectNode result = JsonNodeFactory.instance.objectNode();
                processFile(blobKey, getQueryValue("client_token"), getQueryValue("upload_type"), result);
                return result.toString();
            }
        } else {
            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        }
    } else {
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
    return null;
}

From source file:com.glaf.dts.web.rest.MxQueryResource.java

@GET
@POST/*from ww w .  j  a  va2  s .  c o m*/
@Path("/view/{queryId}")
@ResponseBody
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public byte[] view(@PathParam("queryId") String queryId, @Context HttpServletRequest request) {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    TableDefinitionQuery query = new TableDefinitionQuery();
    Tools.populate(query, params);
    QueryDefinition q = queryDefinitionService.getQueryDefinition(queryId);
    ObjectNode responseJSON = q.toObjectNode();
    try {
        return responseJSON.toString().getBytes("UTF-8");
    } catch (IOException e) {
        return responseJSON.toString().getBytes();
    }
}

From source file:org.attribyte.api.pubsub.impl.server.APIServlet.java

/**
 * Sends a JSON response.// w  w  w  .  ja v a2 s .  c  o  m
 * @param response The HTTP response.
 * @param responseNode The JSON node to send.
 * @throws IOException on write error.
 */
private void sendJSONResponse(HttpServletResponse response, ObjectNode responseNode) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(JSON_CONTENT_TYPE);
    response.getOutputStream().write(responseNode.toString().getBytes(Charsets.UTF_8));
}

From source file:io.macgyver.neorx.rest.NeoRxClient.java

protected ObjectNode execRawCypher(String cypher, ObjectNode params) {

    Response response = null;/*  w  ww . j  a  v  a  2  s.  co  m*/

    try {

        ObjectNode payload = formatPayload(cypher, params);

        String payloadString = payload.toString();
        OkHttpClient c = getOkHttpClient();
        checkNotNull(c);
        String requestId = newRequestId();
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("request[%s]:\n%s", requestId,
                    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(payload)));
        }
        Builder builder = new Request.Builder().addHeader("X-Stream", Boolean.toString(streamResponse))
                .addHeader("Accept", "application/json").url(getUrl() + "/db/data/transaction/commit")
                .post(RequestBody.create(MediaType.parse("application/json"), payloadString));

        response = c.newCall(builder.build()).execute();

        ObjectNode jsonResponse = (ObjectNode) mapper.readTree(response.body().charStream());

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("response[%s]:\n%s", requestId,
                    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonResponse)));
        }
        ObjectNode n = jsonResponse;
        JsonNode error = n.path("errors").path(0);

        if (error instanceof ObjectNode) {

            throw new NeoRxException(((ObjectNode) error));
        }

        return n;

    } catch (IOException e) {
        throw new NeoRxException(e);
    } finally {
        if (response != null) {
            response.body().close();
        }
    }
}

From source file:org.onosproject.tvue.TopologyResource.java

@javax.ws.rs.Path("/graph")
@GET//from   ww w. j av  a2 s . co m
@Produces("application/json")
public Response graph() {
    ObjectMapper mapper = new ObjectMapper();

    // Fetch the services we'll be using.
    DeviceService deviceService = get(DeviceService.class);
    HostService hostService = get(HostService.class);
    TopologyService topologyService = get(TopologyService.class);

    // Fetch the current topology and its graph that we'll use to render.
    Topology topo = topologyService.currentTopology();
    TopologyGraph graph = topologyService.getGraph(topo);

    // Build all interior vertexes, i.e. no end-station hosts yet
    ArrayNode vertexesNode = mapper.createArrayNode();
    for (TopologyVertex vertex : graph.getVertexes()) {
        vertexesNode.add(json(mapper, vertex.deviceId(), 2, vertex.deviceId().uri().getSchemeSpecificPart(),
                deviceService.isAvailable(vertex.deviceId())));
    }

    // Now scan all links and count number of them between the same devices
    // using a normalized link key.
    Map<String, AggLink> linkRecords = aggregateLinks();

    // Now build all interior edges using the aggregated links.
    ArrayNode edgesNode = mapper.createArrayNode();
    for (AggLink lr : linkRecords.values()) {
        edgesNode.add(json(mapper, lr.links.size(), lr.link.src(), lr.link.dst()));
    }

    // Merge the exterior and interior vertexes and inject host links as
    // the exterior edges.
    for (Host host : hostService.getHosts()) {
        Set<IpAddress> ipAddresses = host.ipAddresses();
        IpAddress ipAddress = ipAddresses.isEmpty() ? null : ipAddresses.iterator().next();
        String label = ipAddress != null ? ipAddress.toString() : host.mac().toString();
        vertexesNode.add(json(mapper, host.id(), 3, label, true));
        edgesNode.add(json(mapper, 1, host.location(), new ConnectPoint(host.id(), portNumber(-1))));
    }

    // Now put the vertexes and edges into a root node and ship them off
    ObjectNode rootNode = mapper.createObjectNode();
    rootNode.set("vertexes", vertexesNode);
    rootNode.set("edges", edgesNode);
    return Response.ok(rootNode.toString()).build();
}

From source file:org.apache.manifoldcf.elasticsearch.MCFAuthorizerUtils.java

public static SearchRequest parseSearchRequestMCF(RestRequest request) throws MCFAuthorizerException {
    SearchRequest searchRequest;/*from   w  w  w .  j  a v a2s.c om*/
    String username = request.param("u");
    //if(username==null) throw new MCFAuthorizerException("Username not passed.");
    if (username != null) {
        String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
        searchRequest = new SearchRequest(indices);
        boolean isTemplateRequest = request.path().endsWith("/template");
        if (request.hasContent() || request.hasParam("source")) {
            FilterBuilder authorizationFilter = buildAuthorizationFilter(username);
            FilteredQueryBuilder filteredQueryBuilder;

            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode modifiedJSON, innerJSON;
            JsonNode requestJSON;

            try {
                requestJSON = objectMapper.readTree(RestActions.getRestContent(request).toBytes());
                if (isTemplateRequest) {
                    modifiedJSON = (ObjectNode) requestJSON;
                    innerJSON = (ObjectNode) requestJSON.findValue("template");
                    filteredQueryBuilder = QueryBuilders.filteredQuery(
                            QueryBuilders.wrapperQuery(innerJSON.findValue("query").toString()),
                            authorizationFilter);
                    modifiedJSON.replace("template", innerJSON.set("query",
                            objectMapper.readTree(filteredQueryBuilder.buildAsBytes().toBytes())));
                    searchRequest.templateSource(modifiedJSON.toString());
                } else {
                    filteredQueryBuilder = QueryBuilders.filteredQuery(
                            QueryBuilders.wrapperQuery(requestJSON.findValue("query").toString()),
                            authorizationFilter);
                    modifiedJSON = (ObjectNode) requestJSON;
                    modifiedJSON.set("query",
                            objectMapper.readTree(filteredQueryBuilder.buildAsBytes().toBytes()));
                    searchRequest.source(modifiedJSON.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new MCFAuthorizerException("JSON parser error");
            }
        }

        searchRequest.extraSource(parseSearchSourceMCF(request));
        searchRequest.searchType(request.param("search_type"));
        searchRequest.queryCache(request.paramAsBoolean("query_cache", null));

        String scroll = request.param("scroll");
        if (scroll != null) {
            searchRequest.scroll(new Scroll(parseTimeValue(scroll, null)));
        }

        searchRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
        searchRequest.routing(request.param("routing"));
        searchRequest.preference(request.param("preference"));
        searchRequest.indicesOptions(IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
    } else {
        searchRequest = RestSearchAction.parseSearchRequest(request);
    }
    return searchRequest;
}

From source file:dao.SearchDAO.java

public static ObjectNode getPagedMetricByKeyword(final String category, String keyword, int page, int size) {
    List<Metric> pagedMetrics = new ArrayList<Metric>();
    final JdbcTemplate jdbcTemplate = getJdbcTemplate();
    javax.sql.DataSource ds = jdbcTemplate.getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);

    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    ObjectNode result;//  w  w w  . j  a  va2s. c o  m
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {
            String query = SEARCH_METRIC_WITH_PAGINATION.replace("$keyword", keyword);
            List<Map<String, Object>> rows = null;
            rows = jdbcTemplate.queryForList(query, (page - 1) * size, size);
            for (Map row : rows) {

                Metric metric = new Metric();
                metric.id = (Integer) row.get(MetricRowMapper.METRIC_ID_COLUMN);
                metric.name = (String) row.get(MetricRowMapper.METRIC_NAME_COLUMN);
                metric.refID = (String) row.get(MetricRowMapper.METRIC_REF_ID_COLUMN);
                metric.refIDType = (String) row.get(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN);
                metric.description = (String) row.get(MetricRowMapper.METRIC_DESCRIPTION_COLUMN);
                metric.dashboardName = (String) row.get(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN);
                metric.category = (String) row.get(MetricRowMapper.METRIC_CATEGORY_COLUMN);
                metric.group = (String) row.get(MetricRowMapper.METRIC_GROUP_COLUMN);
                metric.source = "metric";
                metric.urn = "";
                if (StringUtils.isNotBlank(metric.dashboardName)) {
                    metric.urn += metric.dashboardName + "/";
                }
                if (StringUtils.isNotBlank(metric.group)) {
                    metric.urn += metric.group + "/";
                }
                if (StringUtils.isNotBlank(metric.name)) {
                    metric.urn += metric.name;
                }

                ObjectNode schema = Json.newObject();
                schema.put(MetricRowMapper.METRIC_REF_ID_COLUMN, metric.refID);
                schema.put(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN, metric.refIDType);
                schema.put(MetricRowMapper.METRIC_DESCRIPTION_COLUMN, metric.description);
                schema.put(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN, metric.dashboardName);
                schema.put(MetricRowMapper.METRIC_CATEGORY_COLUMN, metric.category);
                schema.put(MetricRowMapper.METRIC_GROUP_COLUMN, metric.group);
                metric.schema = schema.toString();
                pagedMetrics.add(metric);
            }
            long count = 0;
            try {
                count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("category", category);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
            resultNode.set("data", Json.toJson(pagedMetrics));

            return resultNode;
        }
    });

    return result;
}

From source file:org.activiti.app.service.editor.AppDefinitionPublishService.java

protected String getAppDefinitionJson(AppDefinition appDefinition) {
    ObjectNode appDefinitionNode = objectMapper.createObjectNode();
    appDefinitionNode.put("theme", appDefinition.getTheme());
    appDefinitionNode.put("icon", appDefinition.getIcon());
    return appDefinitionNode.toString();
}

From source file:api.Status.java

public static Result getStatus() {
    ObjectNode metrics = Json.newObject();

    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
    TreeMap<String, Object> values = new TreeMap<String, Object>();
    for (Method method : os.getClass().getDeclaredMethods()) {
        method.setAccessible(true);/*w  ww  .j  ava2 s.  com*/
        if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
            Object value;
            try {
                value = method.invoke(os);
                values.put(method.getName(), value);
            } catch (Exception e) {
                Logger.warn("Error when invoking " + os.getClass().getName()
                        + " (OperatingSystemMXBean) method " + method.getName() + ": " + e);
            } // try
        } // if
    } // for

    metrics.put("jvmLoad", (Double) values.get("getProcessCpuLoad"));
    metrics.put("cpuLoad", (Double) values.get("getSystemCpuLoad"));
    metrics.put("openFD", (Long) values.get("getOpenFileDescriptorCount"));
    metrics.put("maxFD", (Long) values.get("getMaxFileDescriptorCount"));
    metrics.put("freeMemory", (Long) values.get("getFreePhysicalMemorySize"));
    metrics.put("totalMemory", (Long) values.get("getTotalPhysicalMemorySize"));

    return ok(metrics.toString());
}