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

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

Introduction

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

Prototype

public JsonNode get(String paramString) 

Source Link

Usage

From source file:software.uncharted.util.JSONUtil.java

private static JsonNode get(JsonNode obj, String accessor) {
    int keyIdx = accessor.indexOf(".");
    if (keyIdx == -1) {

        String key = accessor;//www  .  j  av a2s .  c  om

        if (key.contains("[")) {
            String arrayKey = getArrayKey(key);
            int arrayIdx = getArrayIndex(key);
            JsonNode a = obj.get(arrayKey);
            return a.get(arrayIdx);
        } else {
            return obj.get(key);
        }

    } else {
        String key = accessor.substring(0, keyIdx);
        String remainingAccessor = accessor.substring(keyIdx + 1);

        if (key.contains("[")) {
            String arrayKey = getArrayKey(key);
            int arrayIdx = getArrayIndex(key);
            JsonNode a = obj.get(arrayKey);
            return get(a.get(arrayIdx), remainingAccessor);

        } else {
            return get(obj.get(key), remainingAccessor);
        }
    }
}

From source file:org.activiti.designer.eclipse.navigator.cloudrepo.sync.SyncUtil.java

public static void startUploadNewVersionBackgroundJob(final Shell shell, final String modelId,
        final String targetFileName, final IFile sourceFile) {

    Job uploadJob = new Job("Uploading file") {

        protected IStatus run(IProgressMonitor monitor) {
            try {
                JsonNode modelNode = ActivitiCloudEditorUtil.uploadNewVersion(modelId, sourceFile.getName(),
                        IOUtils.toByteArray(sourceFile.getContents()), true);
                if (modelNode != null && modelNode.get("id") != null) {
                    ActivitiCloudEditorUtil.downloadProcessModel(modelNode.get("id").asText(), sourceFile,
                            false);//www .j a  v  a  2s.com
                    showSuccessMessage(shell);

                } else {
                    showErrorMessage(shell);
                }

            } catch (ActivitiCloudEditorSameContentException e) {
                showCloudEditorErrorMessage(shell, "Already in-sync", e);

            } catch (ActivitiCloudEditorException e) {
                showCloudEditorErrorMessage(shell, "Process upload failed", e);

            } catch (Exception e) {
                Logger.logError(e);
                return Status.CANCEL_STATUS;
            }
            return Status.OK_STATUS;
        }
    };
    uploadJob.setUser(true);
    uploadJob.schedule();
}

From source file:com.spoiledmilk.ibikecph.search.HTTPAutocompleteHandler.java

public static List<JsonNode> getKortforsyningenAutocomplete(Location currentLocation, Address address) {
    String urlString;/*from  www . j a va  2 s .c  om*/
    List<JsonNode> list = new ArrayList<JsonNode>();
    try {

        urlString = "http://kortforsyningen.kms.dk/?servicename=RestGeokeys_v2&method=";

        if ((address.number == null || address.number.equals(""))
                && (address.zip == null || address.zip.equals(""))
                && (address.city == null || address.city.equals("") || address.city.equals(address.street))) {
            urlString += "vej"; // street search
        } else {
            urlString += "adresse"; // address search
        }

        urlString += "&vejnavn=*" + URLEncoder.encode(address.street, "UTF-8") + "*";

        if (!(address.number == null || address.number.equals(""))) {
            urlString += "&husnr=" + address.number;
        }

        urlString += "&geop=" + Util.limitDecimalPlaces(currentLocation.getLongitude(), 6) + "" + ","
                + Util.limitDecimalPlaces(currentLocation.getLatitude(), 6) + ""
                + "&georef=EPSG:4326&outgeoref=EPSG:4326&login=ibikecph&password=Spoiledmilk123&hits=10";

        if (address.zip != null & !address.zip.equals("")) {
            urlString = urlString + "&postnr=" + address.zip;
        }
        if (address.city != null & !address.city.equals("") && !address.city.equals(address.street)) {
            // urlString = urlString + "&by=" + URLEncoder.encode(address.city.trim(), "UTF-8") + "*";
            urlString = urlString + "&postdist=*" + URLEncoder.encode(address.city.trim(), "UTF-8") + "*";
        }

        urlString += "&geometry=true";

        JsonNode rootNode = performGET(urlString);
        if (rootNode.has("features")) {
            JsonNode features = rootNode.get("features");
            for (int i = 0; i < features.size(); i++) {
                if (features.get(i).has("properties") && (features.get(i).get("properties").has("vej_navn")
                        || features.get(i).get("properties").has("navn")))
                    list.add(features.get(i));
            }
        }
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null)
            LOG.e(e.getLocalizedMessage());
    }
    return list;
}

From source file:org.springframework.cloud.aws.messaging.support.converter.NotificationRequestConverter.java

private static Map<String, Object> getMessageAttributesAsMessageHeaders(JsonNode message) {
    Map<String, Object> messageHeaders = new HashMap<>();
    Iterator<String> fieldNames = message.fieldNames();
    while (fieldNames.hasNext()) {
        String attributeName = fieldNames.next();
        String attributeValue = message.get(attributeName).get("Value").asText();
        String attributeType = message.get(attributeName).get("Type").asText();
        if (MessageHeaders.CONTENT_TYPE.equals(attributeName)) {
            messageHeaders.put(MessageHeaders.CONTENT_TYPE, MimeType.valueOf(attributeValue));
        } else if (MessageHeaders.ID.equals(attributeName)) {
            messageHeaders.put(MessageHeaders.ID, UUID.fromString(attributeValue));
        } else {/* w w w  .ja  v  a 2  s .c o m*/
            if (MessageAttributeDataTypes.STRING.equals(attributeType)) {
                messageHeaders.put(attributeName, attributeValue);
            } else if (attributeType.startsWith(MessageAttributeDataTypes.NUMBER)) {
                Object numberValue = getNumberValue(attributeType, attributeValue);
                if (numberValue != null) {
                    messageHeaders.put(attributeName, numberValue);
                }
            } else if (MessageAttributeDataTypes.BINARY.equals(attributeName)) {
                messageHeaders.put(attributeName, ByteBuffer.wrap(attributeType.getBytes()));
            }
        }
    }

    return messageHeaders;
}

From source file:com.github.fge.jsonschema.core.tree.BaseSchemaTree.java

/**
 * Build a JSON Reference from a node//from   w  w  w.  j av  a2  s . co m
 *
 * <p>This will return {@code null} if the reference could not be built. The
 * conditions for a successful build are as follows:</p>
 *
 * <ul>
 *     <li>the node is an object;</li>
 *     <li>it has a member named {@code id};</li>
 *     <li>the value of this member is a string;</li>
 *     <li>this string is a valid URI.</li>
 * </ul>
 *
 * @param node the node
 * @return a JSON Reference, or {@code null}
 */
@Nullable
protected static JsonRef idFromNode(final JsonNode node) {
    if (!node.path("id").isTextual())
        return null;

    try {
        return JsonRef.fromString(node.get("id").textValue());
    } catch (JsonReferenceException ignored) {
        return null;
    }
}

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

/**
 * Creates a new issue in the community tracker.
 * //from  www.  j a  v  a  2  s . 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:com.github.fge.jsonpatch.diff.JsonDiff.java

private static void computeArray(final Map<JsonPointer, JsonNode> ret, final JsonPointer pointer,
        final JsonNode source, final JsonNode target) {
    final int size = Math.min(source.size(), target.size());

    for (int i = 0; i < size; i++)
        computeUnchanged(ret, pointer.append(i), source.get(i), target.get(i));
}

From source file:com.spoiledmilk.ibikecph.util.HttpUtils.java

public static Message JSONtoMessage(JsonNode result) {
    Message ret = new Message();
    Bundle data = new Bundle();
    if (result != null) {
        data.putBoolean("success", result.get("success").asBoolean());
        data.putString("info", result.get("info").asText());
        if (result.has("errors"))
            data.putString("errors", result.get("errors").asText());
        JsonNode dataNode = result.get("data");
        if (dataNode != null) {
            if (dataNode.has("id"))
                data.putInt("id", dataNode.get("id").asInt());
            if (dataNode.has("auth_token"))
                data.putString("auth_token", dataNode.get("auth_token").asText());
        }/*w  ww .  jav  a2  s  .  c  o m*/
    }
    ret.setData(data);
    return ret;
}

From source file:org.primaldev.ppm.util.ChartTypeGenerator.java

protected static Component createChart(JsonNode dataNode, String[] names, Number[] values) {
    String type = dataNode.get("type").textValue();

    JsonNode xAxisNode = dataNode.get("xaxis");
    String xAxis = null;//w w w . ja  v a  2 s  .c o m
    if (xAxisNode != null) {
        xAxis = xAxisNode.textValue();
    }

    JsonNode yAxisNode = dataNode.get("yaxis");
    String yAxis = null;
    if (yAxisNode != null) {
        yAxis = yAxisNode.textValue();
    }

    Component chart = null;
    if (CHART_TYPE_BAR_CHART.equals(type)) {

        DataSeries dataSeries = new DataSeries().add((Object[]) values);
        SeriesDefaults seriesDefaults = new SeriesDefaults().setRenderer(SeriesRenderers.BAR);
        Axes axes = new Axes().addAxis(
                new XYaxis().setRenderer(AxisRenderers.CATEGORY).setTicks(new Ticks().add((Object[]) names)));
        Highlighter highlighter = new Highlighter().setShow(false);

        Options options = new Options().setSeriesDefaults(seriesDefaults).setAxes(axes)
                .setHighlighter(highlighter);
        options.setAnimate(true);
        options.setAnimateReplot(true);

        chart = new DCharts().setDataSeries(dataSeries).setOptions(options);

    } else if (CHART_TYPE_PIE_CHART.equals(type)) {

        DataSeries dataSeries = new DataSeries().newSeries();
        for (int i = 0; i < names.length; i++) {
            dataSeries.add(names[i], values[i]);
        }
        SeriesDefaults seriesDefaults = new SeriesDefaults().setRenderer(SeriesRenderers.PIE);

        Options options = new Options().setSeriesDefaults(seriesDefaults);
        options.setAnimate(true);
        options.setAnimateReplot(true);

        Legend legend = new Legend().setShow(true).setPlacement(LegendPlacements.INSIDE);
        options.setLegend(legend);

        Highlighter highlighter = new Highlighter().setShow(true);
        options.setHighlighter(highlighter);

        chart = new DCharts().setDataSeries(dataSeries).setOptions(options);

    } else if (CHART_TYPE_LINE_CHART.equals(type)) {

        AxesDefaults axesDefaults = new AxesDefaults().setLabelRenderer(LabelRenderers.CANVAS);
        Axes axes = new Axes()
                .addAxis(new XYaxis().setLabel(xAxis != null ? xAxis : "").setMin(names[0])
                        .setMax(names[values.length - 1]).setDrawMajorTickMarks(true))
                .addAxis(new XYaxis(XYaxes.Y).setLabel(yAxis != null ? yAxis : "").setDrawMajorTickMarks(true));
        Options options = new Options().setAxesDefaults(axesDefaults).setAxes(axes);
        DataSeries dataSeries = new DataSeries().newSeries();
        for (int i = 0; i < names.length; i++) {

            //        if (parseLong(names[i]) != null) {
            //          dataSeries.add(parseLong(names[i]), values[i]);
            //        } else if (parseDouble(names[i]) != null) {
            //          dataSeries.add(parseDouble(names[i]), values[i]);
            //        } else {
            //          dataSeries.add(names[i], values[i]);
            //        }

            dataSeries.add(names[i], values[i]);

        }

        Series series = new Series().addSeries(new XYseries().setShowLine(true).setMarkerOptions(
                new MarkerRenderer().setShadow(true).setSize(7).setStyle(MarkerStyles.CIRCLE)));
        options.setSeries(series);

        options.setAnimate(true);
        options.setAnimateReplot(true);

        Highlighter highlighter = new Highlighter().setShow(true);
        options.setHighlighter(highlighter);

        chart = new DCharts().setDataSeries(dataSeries).setOptions(options);

    } else if (CHART_TYPE_LIST.equals(type)) {

        GridLayout grid = new GridLayout(2, names.length);
        grid.setSpacing(true);

        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            Label nameLabel = new Label(name);
            nameLabel.addStyleName(Reindeer.LABEL_H2);
            grid.addComponent(nameLabel, 0, i);

            Number value = values[i];
            Label valueLabel = new Label(value + "");
            grid.addComponent(valueLabel, 1, i);
        }

        chart = grid;

    }

    if (chart instanceof DCharts) {
        // Needed, otherwise the chart will not be shown
        ((DCharts) chart).show();
    }

    return chart;
}

From source file:volker.streaming.music.lastfm.LastFmTrackFactory.java

/**
 * Check if the JSON representation of the track is valid.
 * @param track the JsonNode.//from w  ww .  j av  a 2s  . co  m
 * @return true iff the structure is valid.
 */
public static boolean isValid(JsonNode track) {
    LOG.debug("Checking validity of track : \n" + track);
    boolean result = false;
    if (track == null)
        LOG.warn("Track is invalid: null.");
    else if (!track.hasNonNull(ARTIST))
        LOG.warn("Track is invalid: no artist attribute.");
    else if (!track.get(ARTIST).has(TEXT_KEY))
        LOG.warn("Track is invalid: artist had no text.");
    else if (!track.hasNonNull(NAME))
        LOG.warn("Track is invalid: no name attribute.");
    else if (!track.hasNonNull(ALBUM))
        LOG.warn("Track is invalid: no album attribute.");
    else if (!track.get(ALBUM).has(TEXT_KEY))
        LOG.warn("Track is invalid: album had no text.");
    else {
        result = true;
        LOG.debug("Given track is valid.");
    }
    return result;
}