Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:org.createnet.raptor.indexer.impl.ElasticSearchIndexer.java

/**
 *
 * @param file/*from  ww  w . j  a v a2  s . c  o  m*/
 * @return
 */
public static Map<String, JsonNode> loadIndicesFromFile(String file) {
    // Load indices.json to configuration
    Map<String, JsonNode> indices = new HashMap();

    ObjectMapper mapper = Indexer.getObjectMapper();
    JsonNode json;
    try {
        json = mapper.readTree(Files.readAllBytes(Paths.get(file)));
    } catch (IOException ex) {
        throw new IndexerException(ex);
    }

    Iterator<String> it = json.fieldNames();
    while (it.hasNext()) {
        String indexName = it.next();
        indices.put(indexName, json.get(indexName));
    }

    return indices;
}

From source file:com.mirth.connect.client.ui.components.rsta.RSTAPreferences.java

static RSTAPreferences fromJSON(String keyStrokesJSON, String findReplaceJSON, String toggleOptionsJSON,
        String autoCompleteJSON) {
    ObjectMapper mapper = new ObjectMapper();

    Map<String, KeyStroke> keyStrokeMap = new HashMap<String, KeyStroke>();
    if (StringUtils.isNotBlank(keyStrokesJSON)) {
        try {//from  w w  w. ja v  a2s . c om
            ObjectNode keyStrokesNode = (ObjectNode) mapper.readTree(keyStrokesJSON);

            for (Iterator<Entry<String, JsonNode>> it = keyStrokesNode.fields(); it.hasNext();) {
                Entry<String, JsonNode> entry = it.next();
                KeyStroke keyStroke = null;

                if (!entry.getValue().isNull()) {
                    ArrayNode arrayNode = (ArrayNode) entry.getValue();
                    if (arrayNode.size() > 1) {
                        keyStroke = KeyStroke.getKeyStroke(arrayNode.get(0).asInt(), arrayNode.get(1).asInt());
                    }
                }

                keyStrokeMap.put(entry.getKey(), keyStroke);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    FindReplaceProperties findReplaceProperties = FindReplaceProperties.fromJSON(findReplaceJSON);

    Map<String, Boolean> toggleOptions = new HashMap<String, Boolean>();
    if (StringUtils.isNotBlank(toggleOptionsJSON)) {
        try {
            ObjectNode toggleOptionsNode = (ObjectNode) mapper.readTree(toggleOptionsJSON);

            for (Iterator<Entry<String, JsonNode>> it = toggleOptionsNode.fields(); it.hasNext();) {
                Entry<String, JsonNode> entry = it.next();

                if (!entry.getValue().isNull()) {
                    toggleOptions.put(entry.getKey(), entry.getValue().asBoolean());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    AutoCompleteProperties autoCompleteProperties = AutoCompleteProperties.fromJSON(autoCompleteJSON);

    return new RSTAPreferences(keyStrokeMap, findReplaceProperties, toggleOptions, autoCompleteProperties);
}

From source file:eu.trentorise.opendata.commons.test.jackson.OdtJacksonTester.java

/**
* Converts {@code obj} to an {@link ObjectNode}, sets field
* {@code fieldName} to {@code newNode} and returns the json string
* representation of such new object. Also logs the json with the provided logger at FINE
* level.//from w w w .j  a  va 2  s.  c  o  m
*/
public static String changeField(ObjectMapper objectMapper, Logger logger, Object obj, String fieldName,
        JsonNode newNode) {
    checkNotNull(obj);
    checkNotEmpty(fieldName, "Invalid field name!");

    String string;
    try {
        string = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Error while jacksonizing object to json node!", ex);
    }
    TreeNode treeNode;
    try {
        treeNode = (ObjectNode) objectMapper.readTree(string);
    } catch (IOException ex) {
        throw new RuntimeException("Error while creating json tree from serialized object:" + string, ex);
    }
    if (!treeNode.isObject()) {
        throw new OdtException(
                "The provided object was jacksonized to a string which does not represent a JSON object! String is "
                        + string);
    }
    ObjectNode jo = (ObjectNode) treeNode;
    jo.put(fieldName, newNode);

    String json = jo.toString();

    logger.log(Level.FINE, "converted json = {0}", json);

    return json;

}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Tries to retrieve the content for the specified node ID.
 * /*from w w w .j  a  v  a  2s .  c o m*/
 * @param httpclient
 *            the http client
 * @param nodeID
 *            the node ID
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the node content as JSON
 * @throws CommunityAPIException
 */
public static JsonNode retrieveNodeContentAsJSON(CloseableHttpClient httpclient, String nodeID,
        Cookie authCookie) throws CommunityAPIException {
    try {
        HttpGet retrieveNodeContentGET = new HttpGet(
                CommunityConstants.NODE_CONTENT_URL_PREFIX + nodeID + ".json"); //$NON-NLS-1$
        CloseableHttpResponse resp = httpclient.execute(retrieveNodeContentGET);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());

        if (HttpStatus.SC_OK == httpRetCode) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            return jsonRoot;
        } else {
            CommunityAPIException ex = new CommunityAPIException(
                    Messages.RESTCommunityHelper_NodeContentRetrieveError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        }
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_GetMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_NodeContentRetrieveError, e);
    }
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Uploads the specified file to the community site. The return identifier
 * can be used later when composing other requests.
 * /*w  w w .ja va 2 s .c om*/
 * @param httpclient
 *            the http client
 * @param attachment
 *            the file to attach
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the identifier of the file uploaded, <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie)
        throws CommunityAPIException {
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(attachment);
        byte fileContent[] = new byte[(int) attachment.length()];
        fin.read(fileContent);

        byte[] encodedFileContent = Base64.encodeBase64(fileContent);
        FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent);

        HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL);
        EntityBuilder fileUploadEntity = EntityBuilder.create();
        fileUploadEntity.setText(uploadReq.getAsJSON());
        fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        fileuploadPOST.setEntity(fileUploadEntity.build());

        CloseableHttpResponse resp = httpclient.execute(fileuploadPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());

        if (HttpStatus.SC_OK == httpRetCode) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$
            return fid;
        } else {
            CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        }

    } catch (FileNotFoundException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } finally {
        IOUtils.closeQuietly(fin);
    }
}

From source file:org.apache.drill.test.framework.Utils.java

/**
 * Parses json string to get the node for a specified key
 * //from  ww  w  . ja  v  a2  s  .  c  o m
 * @param jsonString
 *          json string to be parsed
 * @param key
 *          key for the value to be determined
 * @return JsonNode
 * @throws IOException if jsonString is not valid
 */
public static JsonNode getJsonValue(String jsonString, String key) throws IOException {
    ObjectMapper oM = new ObjectMapper();
    JsonNode rootNode = oM.readTree(jsonString);
    // key has format key1.key2.key3
    // change to format /key1/key2/key3
    String ptrExpr = "/" + key.replace(".", "/");
    return rootNode.at(ptrExpr);
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Creates a new issue in the community tracker.
 * /*from   w ww.  j  a  va 2s .co m*/
 * @param httpclient
 *            the http client
 * @param newIssue
 *            the new issue to create on the community tracker
 * @param attachmentsIds
 *            the list of file identifiers that will be attached to the
 *            final issue
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the tracker URL of the newly created issue
 * @throws CommunityAPIException
 */
public static String createNewIssue(CloseableHttpClient httpclient, IssueRequest newIssue,
        List<String> attachmentsIds, Cookie authCookie) throws CommunityAPIException {
    try {
        // Add attachments if any
        if (!attachmentsIds.isEmpty()) {
            IssueField attachmentsField = new IssueField() {
                @Override
                protected String getValueAttributeName() {
                    return "fid"; //$NON-NLS-1$
                }

                @Override
                public boolean isArray() {
                    return true;
                }
            };
            attachmentsField.setName("field_bug_attachments"); //$NON-NLS-1$
            attachmentsField.setValues(attachmentsIds);
            newIssue.setAttachments(attachmentsField);
        }

        HttpPost issueCreationPOST = new HttpPost(CommunityConstants.ISSUE_CREATION_URL);
        EntityBuilder newIssueEntity = EntityBuilder.create();
        newIssueEntity.setText(newIssue.getAsJSON());
        newIssueEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        newIssueEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        issueCreationPOST.setEntity(newIssueEntity.build());
        HttpResponse httpResponse = httpclient.execute(issueCreationPOST);
        int httpRetCode = httpResponse.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(httpResponse.getEntity());

        if (HttpStatus.SC_OK != httpRetCode) {
            CommunityAPIException ex = new CommunityAPIException(
                    Messages.RESTCommunityHelper_IssueCreationError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        } else {
            // extract the node ID information in order
            // to retrieve the issue URL available on the tracker
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String nodeID = jsonRoot.get("nid").asText(); //$NON-NLS-1$
            JsonNode jsonNodeContent = retrieveNodeContentAsJSON(httpclient, nodeID, authCookie);
            return jsonNodeContent.get("path").asText(); //$NON-NLS-1$
        }

    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e);
    }
}

From source file:eu.trentorise.opendata.commons.test.jackson.TodJacksonTester.java

/**
 * Converts {@code obj} to an {@link ObjectNode}, sets field
 * {@code fieldName} to {@code newNode} and returns the json string
 * representation of such new object. Also logs the json with the provided
 * logger at FINE level./*from   w ww . j a  va2  s.c o  m*/
 */
public static String changeField(ObjectMapper objectMapper, Logger logger, Object obj, String fieldName,
        JsonNode newNode) {
    checkNotNull(obj);
    checkNotEmpty(fieldName, "Invalid field name!");

    String string;
    try {
        string = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Error while jacksonizing object to json node!", ex);
    }
    TreeNode treeNode;
    try {
        treeNode = (ObjectNode) objectMapper.readTree(string);
    } catch (IOException ex) {
        throw new RuntimeException("Error while creating json tree from serialized object:" + string, ex);
    }
    if (!treeNode.isObject()) {
        throw new TodException(
                "The provided object was jacksonized to a string which does not represent a JSON object! String is "
                        + string);
    }
    ObjectNode jo = (ObjectNode) treeNode;
    jo.put(fieldName, newNode);

    String json = jo.toString();

    logger.log(Level.FINE, "converted json = {0}", json);

    return json;

}

From source file:com.gsma.mobileconnect.impl.DiscoveryImplTest.java

private static JsonNode parseJson(String jsonStr) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode root = objectMapper.readTree(jsonStr);
    if (null == root) {
        throw new IOException("Invalid json");
    }/*from   w w w .j a  v a2 s .  c o m*/
    return root;
}

From source file:com.baasbox.controllers.File.java

@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class })
public static Result storeFile() throws Throwable {
    MultipartFormData body = request().body().asMultipartFormData();
    if (body == null)
        return badRequest(
                "missing data: is the body multipart/form-data? Check if it contains boundaries too! ");
    //FilePart file = body.getFile(FILE_FIELD_NAME);
    List<FilePart> files = body.getFiles();
    FilePart file = null;/*from   w w  w  . ja va  2s . c o  m*/
    if (!files.isEmpty())
        file = files.get(0);
    String ret = "";
    if (file != null) {
        Map<String, String[]> data = body.asFormUrlEncoded();
        String[] datas = data.get(DATA_FIELD_NAME);
        String[] acl = data.get(ACL_FIELD_NAME);

        /*extract attachedData */
        String dataJson = null;
        if (datas != null && datas.length > 0) {
            dataJson = datas[0];
        } else
            dataJson = "{}";

        /*extract acl*/
        /*the acl json must have the following format:
         * {
         *       "read" : {
         *                "users":[],
         *                "roles":[]
         *              }
         *       "update" : .......
         * }
         */
        String aclJsonString = null;
        if (acl != null && datas.length > 0) {
            aclJsonString = acl[0];
            ObjectMapper mapper = new ObjectMapper();
            JsonNode aclJson = null;
            try {
                aclJson = mapper.readTree(aclJsonString);
            } catch (JsonProcessingException e) {
                return status(CustomHttpCode.ACL_JSON_FIELD_MALFORMED.getBbCode(),
                        "The 'acl' field is malformed");
            }
            /*check if the roles and users are valid*/
            Iterator<Entry<String, JsonNode>> it = aclJson.fields();
            while (it.hasNext()) {
                //check for permission read/update/delete/all
                Entry<String, JsonNode> next = it.next();
                if (!PermissionsHelper.permissionsFromString.containsKey(next.getKey())) {
                    return status(CustomHttpCode.ACL_PERMISSION_UNKNOWN.getBbCode(), "The key '" + next.getKey()
                            + "' is invalid. Valid ones are 'read','update','delete','all'");
                }
                //check for users/roles
                Iterator<Entry<String, JsonNode>> it2 = next.getValue().fields();
                while (it2.hasNext()) {
                    Entry<String, JsonNode> next2 = it2.next();
                    if (!next2.getKey().equals("users") && !next2.getKey().equals("roles")) {
                        return status(CustomHttpCode.ACL_USER_OR_ROLE_KEY_UNKNOWN.getBbCode(), "The key '"
                                + next2.getKey() + "' is invalid. Valid ones are 'users' or 'roles'");
                    }
                    //check for the existance of users/roles
                    JsonNode arrNode = next2.getValue();
                    if (arrNode.isArray()) {
                        for (final JsonNode objNode : arrNode) {
                            //checks the existance users and/or roles
                            if (next2.getKey().equals("users") && !UserService.exists(objNode.asText()))
                                return status(CustomHttpCode.ACL_USER_DOES_NOT_EXIST.getBbCode(),
                                        "The user " + objNode.asText() + " does not exists");
                            if (next2.getKey().equals("roles") && !RoleService.exists(objNode.asText()))
                                return status(CustomHttpCode.ACL_ROLE_DOES_NOT_EXIST.getBbCode(),
                                        "The role " + objNode.asText() + " does not exists");

                        }
                    } else
                        return status(CustomHttpCode.JSON_VALUE_MUST_BE_ARRAY.getBbCode(),
                                "The '" + next2.getKey() + "' value must be an array");
                }

            }

        } else
            aclJsonString = "{}";

        java.io.File fileContent = file.getFile();
        String fileName = file.getFilename();
        /*String contentType = file.getContentType(); 
         if (contentType==null || contentType.isEmpty() || contentType.equalsIgnoreCase("application/octet-stream")){   //try to guess the content type
        InputStream is = new BufferedInputStream(new FileInputStream(fileContent));
        contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType==null || contentType.isEmpty()) contentType="application/octet-stream";
         }*/
        InputStream is = new FileInputStream(fileContent);
        /* extract file metadata and content */
        try {
            BodyContentHandler contenthandler = new BodyContentHandler();
            //DefaultHandler contenthandler = new DefaultHandler();
            Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, fileName);
            Parser parser = new AutoDetectParser();
            parser.parse(is, contenthandler, metadata, new ParseContext());
            String contentType = metadata.get(Metadata.CONTENT_TYPE);
            if (StringUtils.isEmpty(contentType))
                contentType = "application/octet-stream";

            HashMap<String, Object> extractedMetaData = new HashMap<String, Object>();
            for (String key : metadata.names()) {
                try {
                    if (metadata.isMultiValued(key)) {
                        if (Logger.isDebugEnabled())
                            Logger.debug(key + ": ");
                        for (String value : metadata.getValues(key)) {
                            if (Logger.isDebugEnabled())
                                Logger.debug("   " + value);
                        }
                        extractedMetaData.put(key.replace(":", "_").replace(" ", "_").trim(),
                                Arrays.asList(metadata.getValues(key)));
                    } else {
                        if (Logger.isDebugEnabled())
                            Logger.debug(key + ": " + metadata.get(key));
                        extractedMetaData.put(key.replace(":", "_").replace(" ", "_").trim(),
                                metadata.get(key));
                    }
                } catch (Throwable e) {
                    Logger.warn("Unable to extract metadata for file " + fileName + ", key " + key);
                }
            }

            if (Logger.isDebugEnabled())
                Logger.debug(".................................");
            if (Logger.isDebugEnabled())
                Logger.debug(new JSONObject(extractedMetaData).toString());

            is.close();
            is = new FileInputStream(fileContent);
            ODocument doc = FileService.createFile(fileName, dataJson, aclJsonString, contentType,
                    fileContent.length(), is, extractedMetaData, contenthandler.toString());
            ret = prepareResponseToJson(doc);
        } catch (JsonProcessingException e) {
            throw new Exception("Error parsing acl field. HINTS: is it a valid JSON string?", e);
        } catch (Throwable e) {
            throw new Exception("Error parsing uploaded file", e);
        } finally {
            if (is != null)
                is.close();
        }
    } else {
        return badRequest("missing the file data in the body payload");
    }
    return created(ret);
}