Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Usage

From source file:org.obiba.mica.micaConfig.service.MicaConfigService.java

public String getTranslations(@NotNull String locale, boolean _default) throws IOException {
    File translations;/*w w  w.  j a v  a2  s.  c  om*/

    try {
        translations = getTranslationsResource(locale).getFile();
    } catch (IOException e) {
        locale = "en";
        translations = getTranslationsResource(locale).getFile();
    }

    if (_default) {
        return FileUtils.readFileToString(translations, "utf-8");
    }

    MicaConfig config = getOrCreateMicaConfig();
    JsonNode builtTranslations = objectMapper.readTree(translations);

    builtTranslations = addTaxonomies(builtTranslations, locale);

    if (config.hasTranslations() && config.getTranslations().get(locale) != null) {
        JsonNode custom = objectMapper.readTree(config.getTranslations().get(locale));
        return mergeJson(builtTranslations, custom).toString();
    }

    return builtTranslations.toString();
}

From source file:net.opentsdb.tools.ConfigArgP.java

/**
 * Creates a new ConfigArgP/*from   w ww. jav  a2s  . co  m*/
 * @param args The command line arguments
 */
public ConfigArgP(String... args) {
    InputStream is = null;

    try {
        final Config loadConfig = new NoLoadConfig();
        is = ConfigArgP.class.getClassLoader().getResourceAsStream("opentsdb.conf.json");
        ObjectMapper jsonMapper = new ObjectMapper();
        JsonNode root = jsonMapper.reader().readTree(is);
        JsonNode configRoot = root.get("config-items");
        scriptEngine.eval("var config = " + configRoot.toString() + ";");
        processBindings(jsonMapper, root);
        final ConfigurationItem[] loadedItems = jsonMapper.reader(ConfigurationItem[].class)
                .readValue(configRoot);
        final TreeSet<ConfigurationItem> items = new TreeSet<ConfigurationItem>(Arrays.asList(loadedItems));
        LOG.info("Loaded [{}] Configuration Items from opentsdb.conf.json", items.size());
        //         if(LOG.isDebugEnabled()) {
        StringBuilder b = new StringBuilder("Configs:");
        for (ConfigurationItem ci : items) {
            b.append("\n\t").append(ci.toString());
        }
        b.append("\n");
        LOG.info(b.toString());
        //         }
        for (ConfigurationItem ci : items) {
            LOG.debug("Processing CI [{}]", ci.getKey());
            if (ci.meta != null) {
                argp.addOption(ci.clOption, ci.meta, ci.description);
                if ("default".equals(ci.help))
                    dargp.addOption(ci.clOption, ci.meta, ci.description);
            } else {
                argp.addOption(ci.clOption, ci.description);
                if ("default".equals(ci.help))
                    dargp.addOption(ci.clOption, ci.description);
            }
            if (!configItemsByKey.add(ci)) {
                throw new RuntimeException("Duplicate configuration key [" + ci.key
                        + "] in opentsdb.conf.json. Programmer Error.");
            }
            if (!configItemsByCl.add(ci)) {
                throw new RuntimeException("Duplicate configuration command line option [" + ci.clOption
                        + "] in opentsdb.conf.json. Programmer Error.");
            }
            if (ci.getDefaultValue() != null) {
                ci.setValue(processConfigValue(ci.getDefaultValue()));
                loadConfig.overrideConfig(ci.key, processConfigValue(ci.getValue()));
            }
        }
        //loadConfig.loadStaticVariables();
        // find --config and --include-config in argp and load into config 
        //      validate
        //argp.parse(args);
        this.config = new Config(loadConfig);
        nonOptionArgs = applyArgs(args);
    } catch (Exception ex) {
        if (ex instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) ex;
        }
        throw new RuntimeException("Failed to read opentsdb.conf.json", ex);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (Exception x) {
                /* No Op */ }
    }
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenDeserializer.java

/**
 * This method construct {@link UsernamePasswordAuthenticationToken} object from serialized json.
 *///  w w  w.jav  a  2s. com
@Override
public UsernamePasswordAuthenticationToken deserialize(JsonParser jsonParser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    UsernamePasswordAuthenticationToken token;
    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    JsonNode jsonNode = mapper.readTree(jsonParser);
    Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
    JsonNode principalNode = readJsonNode(jsonNode, "principal");
    Object principal;
    if (principalNode.isObject()) {
        Class principalClass = LinkedHashMap.class;
        if (principalNode.hasNonNull("@class")) {
            try {
                principalClass = Class.forName(principalNode.get("@class").asText());
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(
                        "Could not load principal class [" + principalNode.get("@class").asText() + "]", e);
            }
        }
        principal = mapper.readValue(principalNode.toString(), principalClass);
    } else {
        principal = principalNode.asText();
    }
    Object credentials = readJsonNode(jsonNode, "credentials").asText();
    List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").toString(),
            new TypeReference<List<GrantedAuthority>>() {
            });
    if (authenticated) {
        token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    } else {
        token = new UsernamePasswordAuthenticationToken(principal, credentials);
    }
    token.setDetails(readJsonNode(jsonNode, "details"));
    return token;
}

From source file:com.marklogic.client.functionaltest.TestBulkSearchEWithQBE.java

public void loadJSONDocuments() throws JsonProcessingException, IOException {
    int count = 1;
    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    DocumentWriteSet writeset = docMgr.newWriteSet();

    HashMap<String, String> map = new HashMap<String, String>();

    for (int i = 0; i < 102; i++) {
        JsonNode jn = new ObjectMapper().readTree("{\"animal\":\"dog " + i + "\", \"says\":\"woof\"}");
        JacksonHandle jh = new JacksonHandle();
        jh.set(jn);/*from   w w  w.j av a 2s .co  m*/
        writeset.add(DIRECTORY + "dog" + i + ".json", jh);
        map.put(DIRECTORY + "dog" + i + ".json", jn.toString());
        if (count % BATCH_SIZE == 0) {
            docMgr.write(writeset);
            writeset = docMgr.newWriteSet();
        }
        count++;
        //         System.out.println(jn.toString());
    }
    if (count % BATCH_SIZE > 0) {
        docMgr.write(writeset);
    }
}

From source file:org.auscope.portal.server.web.service.TemplateLintService.java

/**
 * Parse pylint results into LintResult objects.
 *
 * @param input InputStream with results text
 * @return List<LintResult> with issues
 *///  w  ww .j av a  2  s .  c om
private List<LintResult> parsePylintResults(String input) throws PortalServiceException {
    List<LintResult> lints = new ArrayList<LintResult>();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = null;

    if (!input.trim().isEmpty()) {
        try {
            root = mapper.readTree(input);
        } catch (Exception ex) {
            throw new PortalServiceException("Failed to parse pylint result json", ex);
        }
        if (root == null) {
            throw new PortalServiceException("No JSON content found in pylint results");
        } else if (!root.isArray()) {
            throw new PortalServiceException(String.format("Unsupported pylint results: {}", root.toString()));
        }

        // Parsed json, so extract LintResult objects
        for (JsonNode result : root) {
            LintResult.Severity severity = result.get("type").asText().equals("error")
                    ? LintResult.Severity.ERROR
                    : LintResult.Severity.WARNING;
            lints.add(new LintResult(severity, result.get("message").asText(),

                    // pylint returns 1-based line count.
                    new LintResult.Location(result.get("line").asInt() - 1, result.get("column").asInt())));
        }
    }

    return lints;
}

From source file:org.jboss.aerogear.sync.server.wildfly.SyncEndpoint.java

@OnMessage
public String onMessage(String message, Session webSocketSession) {
    final JsonNode json = JsonMapper.asJsonNode(message);

    switch (MessageType.from(json.get("msgType").asText())) {
    case ADD://  w  w w.  ja  v  a  2  s. c om
        final Document<JsonNode> doc = syncEngine.documentFromJson(json);
        final String clientId = json.get("clientId").asText();
        final PatchMessage<JsonPatchEdit> patchMessage = addSubscriber(doc, clientId, webSocketSession);
        webSocketSession.getUserProperties().put(DOC_ADD, true);
        return (patchMessage.asJson());

    case PATCH:
        final PatchMessage<JsonPatchEdit> clientPatchMessage = syncEngine.patchMessageFromJson(json.toString());
        checkForReconnect(clientPatchMessage.documentId(), clientPatchMessage.clientId(), webSocketSession);
        patch(clientPatchMessage);
        break;
    case DETACH:
        // detach the client from a specific document.
        break;
    case UNKNOWN:
        return "{\"result\": \"Unknown msgType '" + json.get("msgType").asText() + "'\"}";

    }

    return message;
}

From source file:com.redhat.lightblue.metadata.parser.JSONMetadataParserTest.java

License:asdf

@Test
public void testConvertEnums_WithDescription() throws IOException, JSONException {
    String enumName = "FakeEnum";
    String enumValue1 = "FakeEnumValue1";
    String enumDescription1 = "this is a fake description of enum value 1";
    String enumValue2 = "FakeEnumValue2";
    String enumDescription2 = "this is a fake description of enum value 2";

    Enum e = new Enum(enumName);
    e.setValues(new HashSet<EnumValue>(Arrays.asList(new EnumValue(enumValue1, enumDescription1),
            new EnumValue(enumValue2, enumDescription2))));

    Enums enums = new Enums();
    enums.addEnum(e);//from  ww  w  . jav  a 2  s  .  c o m

    JsonNode enumsNode = json("{}");
    parser.convertEnums(enumsNode, enums);

    String jsonString = enumsNode.toString();
    JSONAssert.assertEquals(
            "{enums:[{name:\"" + enumName + "\"," + "values:[\"" + enumValue1 + "\",\"" + enumValue2 + "\"],"
                    + "annotatedValues:[{name:\"" + enumValue1 + "\",description:\"" + enumDescription1
                    + "\"},{name:\"" + enumValue2 + "\",description:\"" + enumDescription2 + "\"}]}]}",
            jsonString, false);
}

From source file:com.redhat.lightblue.metadata.parser.JSONMetadataParserTest.java

License:asdf

@Test
public void testConvertEnums() throws IOException, JSONException {
    String enumName = "FakeEnum";
    String enumValue1 = "FakeEnumValue1";
    String enumValue2 = "FakeEnumValue2";

    Enum e = new Enum(enumName);
    e.setValues(new HashSet<EnumValue>(
            Arrays.asList(new EnumValue(enumValue1, null), new EnumValue(enumValue2, null))));

    Enums enums = new Enums();
    enums.addEnum(e);// w  w  w  .java 2 s .  c o m

    JsonNode enumsNode = json("{}");
    parser.convertEnums(enumsNode, enums);

    String jsonString = enumsNode.toString();
    JSONAssert.assertEquals(
            "{enums:[{name:\"" + enumName + "\",values:[\"" + enumValue1 + "\",\"" + enumValue2 + "\"]}]}",
            jsonString, false);

    //Should just be string elements, not a complex objects.
    Assert.assertFalse(jsonString.matches(".*\"annotatedValues\":\\[.*"));
    Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue1 + "\""));
    Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue2 + "\""));
}

From source file:com.activiti.service.activiti.ActivitiClientService.java

public StringEntity createStringEntity(JsonNode json) {

    // add//from   w ww  .ja  v  a  2 s.  c  o m

    try {
        return new StringEntity(json.toString());
    } catch (Exception e) {
        log.warn("Error translation json to http client entity " + json, e);
    }
    return null;
}

From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java

public StringEntity createStringEntity(JsonNode json) {

    // add// w w  w .j a  va 2 s  .  co m

    try {
        return new StringEntity(json.toString());
    } catch (Exception e) {
        LOGGER.warn("Error translation json to http client entity {}", json, e);
    }
    return null;
}