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:io.gs2.matchmaking.Gs2MatchmakingClient.java

/**
 * ?????<br>/*from   w  w w  .j  av  a 2s .  c o m*/
 * <br>
 * - : 10<br>
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public RoomCreateGatheringResult roomCreateGathering(RoomCreateGatheringRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (request.getMeta() != null)
        body.put("meta", request.getMeta());

    HttpPost post = createHttpPost(
            Gs2Constant.ENDPOINT_HOST + "/matchmaking/"
                    + (request.getMatchmakingName() == null || request.getMatchmakingName().equals("") ? "null"
                            : request.getMatchmakingName())
                    + "/room",
            credential, ENDPOINT, RoomCreateGatheringRequest.Constant.MODULE,
            RoomCreateGatheringRequest.Constant.FUNCTION, body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    post.setHeader("X-GS2-ACCESS-TOKEN", request.getAccessToken());

    return doRequest(post, RoomCreateGatheringResult.class);

}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static void createRESTUserWithPermissions(String usrName, String pass, ObjectNode perm,
        ObjectNode colections, String... roleNames) {
    try {/*from  ww  w  . j av  a  2 s .  com*/
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet("http://localhost:8002" + "/manage/v2/users/" + usrName);
        HttpResponse resp = client.execute(getrequest);

        if (resp.getStatusLine().getStatusCode() == 200) {
            System.out.println("User already exist");
        } else {
            System.out.println("User dont exist");
            client = new DefaultHttpClient();
            client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                    new UsernamePasswordCredentials("admin", "admin"));

            ObjectMapper mapper = new ObjectMapper();
            ObjectNode mainNode = mapper.createObjectNode();
            //         ObjectNode childNode = mapper.createObjectNode();
            ArrayNode childArray = mapper.createArrayNode();
            mainNode.put("user-name", usrName);
            mainNode.put("description", "user discription");
            mainNode.put("password", pass);
            for (String rolename : roleNames)
                childArray.add(rolename);
            mainNode.withArray("role").addAll(childArray);
            mainNode.setAll(perm);
            mainNode.setAll(colections);
            //System.out.println(type + mainNode.path("range-element-indexes").path("range-element-index").toString());
            System.out.println(mainNode.toString());
            HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/users?format=json");
            post.addHeader("Content-type", "application/json");
            post.setEntity(new StringEntity(mainNode.toString()));

            HttpResponse response = client.execute(post);
            HttpEntity respEntity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 400) {
                System.out.println("Bad User creation request");
            } else if (respEntity != null) {
                // EntityUtils to get the response content
                String content = EntityUtils.toString(respEntity);
                System.out.println(content);
            } else {
                System.out.println("No Proper Response");
            }
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:org.apache.streams.hbase.HbasePersistWriter.java

@Override
public void write(StreamsDatum streamsDatum) {

    ObjectNode node;
    byte[] row;// w ww  . ja v a 2 s.  c o m
    if (StringUtils.isNotBlank(streamsDatum.getId())) {
        row = streamsDatum.getId().getBytes();
    } else {
        row = GuidUtils.generateGuid(streamsDatum.toString()).getBytes();
    }
    Put put = new Put(row);
    if (streamsDatum.getDocument() instanceof String) {
        try {
            node = mapper.readValue((String) streamsDatum.getDocument(), ObjectNode.class);
        } catch (IOException ex) {
            ex.printStackTrace();
            LOGGER.warn("Invalid json: {}", streamsDatum.getDocument().toString());
            return;
        }
        try {
            byte[] value = node.binaryValue();
            put.add(config.getFamily().getBytes(), config.getQualifier().getBytes(), value);
        } catch (IOException ex) {
            ex.printStackTrace();
            LOGGER.warn("Failure adding object: {}", streamsDatum.getDocument().toString());
            return;
        }
    } else {
        try {
            node = mapper.valueToTree(streamsDatum.getDocument());
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.warn("Invalid json: {}", streamsDatum.getDocument().toString());
            return;
        }
        put.setId(GuidUtils.generateGuid(node.toString()));
        try {
            byte[] value = node.binaryValue();
            put.add(config.getFamily().getBytes(), config.getQualifier().getBytes(), value);
        } catch (IOException ex) {
            ex.printStackTrace();
            LOGGER.warn("Failure preparing put: {}", streamsDatum.getDocument().toString());
            return;
        }

    }
    try {
        table.put(put);
    } catch (IOException ex) {
        ex.printStackTrace();
        LOGGER.warn("Failure executin put: {}", streamsDatum.getDocument().toString());
    }

}

From source file:io.gs2.ranking.Gs2RankingClient.java

/**
 * ????<br>//from w  ww.  ja v  a 2s .  c  o  m
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public UpdateGameModeResult updateGameMode(UpdateGameModeRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("calcInterval", request.getCalcInterval());
    if (request.getPutScoreTriggerScript() != null)
        body.put("putScoreTriggerScript", request.getPutScoreTriggerScript());
    if (request.getPutScoreDoneTriggerScript() != null)
        body.put("putScoreDoneTriggerScript", request.getPutScoreDoneTriggerScript());
    if (request.getCalculateRankingDoneTriggerScript() != null)
        body.put("calculateRankingDoneTriggerScript", request.getCalculateRankingDoneTriggerScript());
    HttpPut put = createHttpPut(Gs2Constant.ENDPOINT_HOST + "/ranking/"
            + (request.getRankingTableName() == null || request.getRankingTableName().equals("") ? "null"
                    : request.getRankingTableName())
            + "/mode/"
            + (request.getGameMode() == null || request.getGameMode().equals("") ? "null"
                    : request.getGameMode())
            + "", credential, ENDPOINT, UpdateGameModeRequest.Constant.MODULE,
            UpdateGameModeRequest.Constant.FUNCTION, body.toString());
    if (request.getRequestId() != null) {
        put.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    return doRequest(put, UpdateGameModeResult.class);

}

From source file:org.apache.geode.tools.pulse.internal.controllers.PulseController.java

@RequestMapping(value = "/dataBrowserExport", method = RequestMethod.GET)
public void dataBrowserExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // get query string
    String query = request.getParameter("query");
    String members = request.getParameter("members");
    int limit = 0;

    try {//w  w w .  java 2  s. c  o  m
        limit = Integer.valueOf(request.getParameter("limit"));
    } catch (NumberFormatException e) {
        limit = 0;
        if (LOGGER.finerEnabled()) {
            LOGGER.finer(e.getMessage());
        }
    }

    ObjectNode queryResult = mapper.createObjectNode();
    try {

        if (StringUtils.isNotNullNotEmptyNotWhiteSpace(query)) {
            // get cluster object
            Cluster cluster = Repository.get().getCluster();
            String userName = request.getUserPrincipal().getName();

            // Call execute query method
            queryResult = cluster.executeQuery(query, members, limit);

            // Add query in history if query is executed successfully
            if (!queryResult.has("error")) {
                // Add html escaped query to history
                String escapedQuery = StringEscapeUtils.escapeHtml(query);
                cluster.addQueryInHistory(escapedQuery, userName);
            }
        }
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }

    response.setContentType("application/json");
    response.setHeader("Content-Disposition", "attachment; filename=results.json");
    response.getOutputStream().write(queryResult.toString().getBytes());
}

From source file:org.bimserver.plugins.web.AbstractWebModulePlugin.java

@Override
public boolean service(String requestUri, HttpServletResponse response) {
    try {//from  w  ww.  j av  a2 s  .c  o m
        if (requestUri.startsWith(getDefaultContextPath())) {
            requestUri = requestUri.substring(getDefaultContextPath().length());
        }
        while (requestUri.startsWith("/")) {
            requestUri = requestUri.substring(1);
        }
        if (requestUri.equals("")) {
            requestUri = "index.html";
        }
        if (requestUri.endsWith("plugin.version")) {
            ObjectNode version = OBJECT_MAPPER.createObjectNode();
            version.put("groupId", pluginContext.getPluginBundle().getPluginBundleVersion().getGroupId());
            version.put("artifactId", pluginContext.getPluginBundle().getPluginBundleVersion().getArtifactId());
            version.put("version", pluginContext.getPluginBundle().getPluginBundleVersion().getVersion());
            version.put("description",
                    pluginContext.getPluginBundle().getPluginBundleVersion().getDescription());
            version.put("icon", pluginContext.getPluginBundle().getPluginBundleVersion().getIcon());
            version.put("name", pluginContext.getPluginBundle().getPluginBundleVersion().getName());
            version.put("organization",
                    pluginContext.getPluginBundle().getPluginBundleVersion().getOrganization());

            if (getPluginContext().getPluginType() == PluginSourceType.INTERNAL) {
                // Probably the default plugin
                return false;
            } else if (getPluginContext().getPluginType() == PluginSourceType.ECLIPSE_PROJECT) {
                // We don't want to cache in Eclipse, because we change files without changing the plugin version everytime
                version.put("nonce", System.nanoTime());
                response.setContentType("application/json");
                response.getOutputStream().write(version.toString().getBytes(Charsets.UTF_8));
                return true;
            } else if (getPluginContext().getPluginType() == PluginSourceType.JAR_FILE) {
                version.put("nonce", pluginContext.getPluginBundle().getPluginBundleVersion().getVersion());
                response.setContentType("application/json");
                response.getOutputStream().write(version.toString().getBytes(Charsets.UTF_8));
                return true;
            }
        }
        if (!requestUri.equals("index.html")) {
            response.setHeader("Expires", FAR_FUTURE_EXPIRE_DATE);
        }
        Path resolved = pluginContext.getRootPath().resolve(getInternalPath() + requestUri);
        InputStream resourceAsInputStream = Files.newInputStream(resolved);
        //         LOGGER.info("Getting " + getSubDir() + path + " results in: " + resourceAsInputStream);
        if (resourceAsInputStream != null) {
            try {
                IOUtils.copy(resourceAsInputStream, response.getOutputStream());
            } finally {
                resourceAsInputStream.close();
            }
            return true;
        } else {
            return false;
        }
    } catch (FileNotFoundException e) {
        LOGGER.error("", e);
    } catch (IOException e) {
        // Skip those, they make the log file look like there are many things wrong, probably just a browser disconnect
    }
    return false;
}

From source file:org.onosproject.ecord.co.BigSwitchDeviceProvider.java

private boolean postNetworkConfig(String subject, ObjectNode cfg) {
    // TODO Slice out REST Client code as library?
    Client client = ClientBuilder.newClient();

    client.property(ClientProperties.FOLLOW_REDIRECTS, true);

    // Trying to do JSON processing using Jackson triggered OSGi nightmare
    //client.register(JacksonFeature.class);

    final Map<String, String> env = System.getenv();
    // TODO Where should we get the user/password from?
    String user = env.getOrDefault("ONOS_WEB_USER", "onos");
    String pass = env.getOrDefault("ONOS_WEB_PASS", "rocks");
    HttpAuthenticationFeature auth = HttpAuthenticationFeature.basic(user, pass);
    client.register(auth);/*  w ww  .  j  av  a2s .c o m*/

    // TODO configurable base path
    WebTarget target = client.target("http://" + metroIp + ":8181/onos/v1/").path("network/configuration/")
            .path(subject);

    Response response = target.request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(cfg.toString(), MediaType.APPLICATION_JSON));

    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        log.error("POST failed {}\n{}", response, cfg.toString());
        return false;
    }
    return true;
}

From source file:org.apache.olingo.fit.utils.JSONUtilities.java

@Override
public InputStream readEntities(final List<String> links, final String linkName, final String next,
        final boolean forceFeed) throws IOException {

    if (links.isEmpty()) {
        throw new NotFoundException();
    }/*from  w  w  w.j a va2s . c o  m*/

    final ObjectNode node = mapper.createObjectNode();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if (forceFeed || links.size() > 1) {
        bos.write("[".getBytes());
    }

    for (String link : links) {
        try {
            final Map.Entry<String, String> uriMap = Commons.parseEntityURI(link);
            final Map.Entry<String, InputStream> entity = readEntity(uriMap.getKey(), uriMap.getValue(),
                    Accept.JSON_FULLMETA);

            if (bos.size() > 1) {
                bos.write(",".getBytes());
            }

            IOUtils.copy(entity.getValue(), bos);
        } catch (Exception e) {
            // log and ignore link
            LOG.warn("Error parsing uri {}", link, e);
        }
    }

    if (forceFeed || links.size() > 1) {
        bos.write("]".getBytes());
    }

    node.set(Constants.get(ConstantKey.JSON_VALUE_NAME),
            mapper.readTree(new ByteArrayInputStream(bos.toByteArray())));

    if (StringUtils.isNotBlank(next)) {
        node.set(Constants.get(ConstantKey.JSON_NEXTLINK_NAME), new TextNode(next));
    }

    return IOUtils.toInputStream(node.toString(), Constants.ENCODING);
}

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

@GET
@POST//from w  w w.  j  a v a  2s  . com
@Path("/headers")
@ResponseBody
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public byte[] headers(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    Map<String, Object> params = RequestUtils.getParameterMap(request);
    String tableName = ParamUtils.getString(params, "tableName");
    String tableName_enc = request.getParameter("tableName_enc");
    if (StringUtils.isNotEmpty(tableName_enc)) {
        tableName = RequestUtils.decodeString(tableName_enc);
    }
    QueryHelper helper = new QueryHelper();
    Connection connection = null;
    List<ColumnDefinition> columns = null;
    try {
        connection = DBConnectionFactory.getConnection();
        String sql = "select * from " + tableName + " where 1=0 ";
        columns = helper.getColumns(connection, sql, params);
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        JdbcUtils.close(connection);
    }

    ObjectNode responseJSON = new ObjectMapper().createObjectNode();

    ArrayNode rowsJSON = new ObjectMapper().createArrayNode();
    if (columns != null && !columns.isEmpty()) {
        ObjectNode rowJSON = new ObjectMapper().createObjectNode();
        for (ColumnDefinition column : columns) {
            if (column.getColumnName() != null) {
                rowJSON.put("columnName", column.getColumnName());
            }
            if (column.getTitle() != null) {
                rowJSON.put("title", column.getTitle());
            }
            if (column.getName() != null) {
                rowJSON.put("name", column.getName());
            }
            if (column.getJavaType() != null) {
                rowJSON.put("javaType", column.getJavaType());
            }
        }
        rowsJSON.add(rowJSON);
    }

    responseJSON.set("rows", rowsJSON);

    try {
        return responseJSON.toString().getBytes("UTF-8");
    } catch (IOException e) {
        return responseJSON.toString().getBytes();
    }
}