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:com.mirth.connect.client.core.ConnectServiceUtil.java

public static List<Notification> getNotifications(String serverId, String mirthVersion,
        Map<String, String> extensionVersions, String[] protocols, String[] cipherSuites) throws Exception {
    CloseableHttpClient client = null;/*  ww w . j  a v  a 2s .co  m*/
    HttpPost post = new HttpPost();
    CloseableHttpResponse response = null;

    List<Notification> allNotifications = new ArrayList<Notification>();

    try {
        ObjectMapper mapper = new ObjectMapper();
        String extensionVersionsJson = mapper.writeValueAsString(extensionVersions);
        NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_GET),
                new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion),
                new BasicNameValuePair("extensionVersions", extensionVersionsJson) };
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET));
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));

        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        client = getClient(protocols, cipherSuites);
        response = client.execute(post, postContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode == HttpStatus.SC_OK)) {
            HttpEntity responseEntity = response.getEntity();
            Charset responseCharset = null;
            try {
                responseCharset = ContentType.getOrDefault(responseEntity).getCharset();
            } catch (Exception e) {
                responseCharset = ContentType.TEXT_PLAIN.getCharset();
            }

            String responseContent = IOUtils.toString(responseEntity.getContent(), responseCharset).trim();
            JsonNode rootNode = mapper.readTree(responseContent);

            for (JsonNode childNode : rootNode) {
                Notification notification = new Notification();
                notification.setId(childNode.get("id").asInt());
                notification.setName(childNode.get("name").asText());
                notification.setDate(childNode.get("date").asText());
                notification.setContent(childNode.get("content").asText());
                allNotifications.add(notification);
            }
        } else {
            throw new ClientException("Status code: " + statusCode);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }

    return allNotifications;
}

From source file:models.DataSet.java

private static DataSet deserializeJsonToDataSet(JsonNode json) {
    DataSet newDataSet = new DataSet();
    newDataSet.setId(json.get("id").asText());
    newDataSet.setDataSetName(json.get("name").asText());
    newDataSet.setAgencyId(json.get("agencyId").asText());
    newDataSet.setInstrument(json.get("instrument").get("name").asText());
    newDataSet.setPhysicalVariable(json.get("physicalVariable").asText());
    newDataSet.setCMIP5VarName(json.get("CMIP5VarName").asText());
    newDataSet.setUnits(json.get("units").asText());
    newDataSet.setGridDimension(json.get("gridDimension").asText());
    newDataSet.setSource(json.get("source").asText());
    newDataSet.setStatus(json.get("status").asText());
    newDataSet.setResponsiblePerson(json.get("responsiblePerson").asText());
    newDataSet.setDataSourceName(json.get("dataSourceNameinWebInterface").asText());
    newDataSet.setVariableName(json.get("variableNameInWebInterface").asText());
    newDataSet.setDataSourceInput(json.get("dataSourceInputParameterToCallScienceApplicationCode").asText());
    newDataSet// www. java  2 s .  c  o m
            .setVariableNameInput(json.get("variableNameInputParameterToCallScienceApplicationCode").asText());
    String startTime = json.findPath("startTime").asText();
    String endTime = json.findPath("endTime").asText();
    Date tmpTime = null;

    try {
        tmpTime = (new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a")).parse(startTime);

        if (tmpTime != null) {
            newDataSet.setStartTime(new SimpleDateFormat("YYYYMM").format(tmpTime));
        }
    } catch (ParseException e) {
    }

    try {
        tmpTime = (new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a")).parse(endTime);

        if (tmpTime != null) {
            newDataSet.setEndTime(new SimpleDateFormat("YYYYMM").format(tmpTime));
        }
    } catch (ParseException e) {

    }
    return newDataSet;
}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.STrainData.java

public static ArrayList<ITransportationInfo> getNext3Arrivals(String stationFrom, String stationTo, String line,
        Context context) {/*w  ww  .java 2 s  . c o m*/
    ArrayList<ITransportationInfo> ret = new ArrayList<ITransportationInfo>();
    try {
        String bufferString = Util.stringFromJsonAssets(context, "stations/" + filename);
        JsonNode actualObj = Util.stringToJsonNode(bufferString);
        JsonNode lines = actualObj.get("timetable");

        // find the data for the current transportation line
        for (int i = 0; i < lines.size(); i++) {
            JsonNode lineJson = lines.get(i);
            String[] sublines = line.split(",");
            for (int ii = 0; ii < sublines.length; ii++) {
                if (lineJson.get("line").asText().equalsIgnoreCase(sublines[ii].trim())) {
                    int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
                    if (day == 1)
                        day = 6;
                    else
                        day -= 2;
                    int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                    int minute = Calendar.getInstance().get(Calendar.MINUTE);
                    JsonNode stationData = null;
                    if ((day == 4 || day == 5)
                            && isFridaySaturdayNight(lineJson.get("night-after-friday-saturday"), hour)) {
                        // night after Friday or Saturday
                        stationData = lineJson.get("night-after-friday-saturday");
                    } else if (day < 5) {
                        // weekdays
                        stationData = lineJson.get("weekdays");
                    } else {
                        // weekend
                        stationData = lineJson.get("weekend");
                    }
                    JsonNode stations = stationData.get("data");
                    int[] AStationMinutes = null, BStationMinutes = null;
                    // find the data for the start and end station and choose the direction
                    direction = NOT_SET;
                    for (int j = 0; j < stations.size(); j++) {
                        JsonNode st = stations.get(j);
                        if (st.get("station").asText().equalsIgnoreCase(stationFrom) && direction == NOT_SET
                                && AStationMinutes == null) {
                            direction = DEPARTURE;
                            AStationMinutes = getMinutesArray(st.get("departure").asText());
                        } else if (st.get("station").asText().equalsIgnoreCase(stationFrom)
                                && AStationMinutes == null) {
                            AStationMinutes = getMinutesArray(st.get("arrival").asText());
                            break;
                        } else if (st.get("station").asText().equalsIgnoreCase(stationTo)
                                && direction == NOT_SET && BStationMinutes == null) {
                            direction = ARRIVAL;
                            BStationMinutes = getMinutesArray(st.get("departure").asText());
                        } else if (st.get("station").asText().equalsIgnoreCase(stationTo)
                                && BStationMinutes == null) {
                            BStationMinutes = getMinutesArray(st.get("arrival").asText());
                            break;
                        }
                    }
                    if (AStationMinutes == null || BStationMinutes == null)
                        continue;
                    JsonNode subLines = direction == DEPARTURE ? stationData.get("departure")
                            : stationData.get("arrival");
                    JsonNode subLine = subLines.get(0);
                    if (hasTrain(hour, subLine.get("night").asText(), subLine.get("day").asText())) {
                        int count = 0;
                        for (int k = 0; k < AStationMinutes.length; k++) {
                            if (minute <= AStationMinutes[k]) {
                                int arrivalHour = hour;
                                int time = BStationMinutes[k] - AStationMinutes[k];
                                if (AStationMinutes[k] > BStationMinutes[k]) {
                                    arrivalHour++;
                                    time = 60 - AStationMinutes[k] + BStationMinutes[k];
                                }
                                ret.add(new STrainData(
                                        (hour < 10 ? "0" + hour : "" + hour) + ":"
                                                + (AStationMinutes[k] < 10 ? "0" + AStationMinutes[k]
                                                        : "" + AStationMinutes[k]),
                                        (arrivalHour < 10 ? "0" + arrivalHour : "" + arrivalHour) + ":"
                                                + (BStationMinutes[k] < 10 ? "0" + BStationMinutes[k]
                                                        : "" + BStationMinutes[k]),
                                        time));
                                if (++count == 3)
                                    break;
                            }
                        }
                        // second pass to get the times for the next hour
                        hour++;
                        for (int k = 0; k < AStationMinutes.length && count < 3; k++) {
                            int arrivalHour = hour;
                            int time = BStationMinutes[k] - AStationMinutes[k];
                            if (AStationMinutes[k] > BStationMinutes[k]) {
                                arrivalHour++;
                                time = 60 - AStationMinutes[k] + BStationMinutes[k];
                            }
                            ret.add(new STrainData(
                                    (hour < 10 ? "0" + hour : "" + hour) + ":"
                                            + (AStationMinutes[k] < 10 ? "0" + AStationMinutes[k]
                                                    : "" + AStationMinutes[k]),
                                    (arrivalHour < 10 ? "0" + arrivalHour : "" + arrivalHour) + ":"
                                            + (BStationMinutes[k] < 10 ? "0" + BStationMinutes[k]
                                                    : "" + BStationMinutes[k]),
                                    time));
                        }
                    }
                    return ret;
                }
            }
        }
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null)
            LOG.e(e.getLocalizedMessage());
    }

    return ret;
}

From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java

public static boolean deleteAgenda(String agendaID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(agendaID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.DELETE);
    addRequestHeader(conn, false);//from w w w.  j  a  v a2 s  .  co  m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    boolean result = false;
    JsonNode tree = MAPPER.readTree(response);
    if (!response.isEmpty()) {
        if (!tree.has(Keys.DELETED)) {
            result = true;
        } else {
            Log.e(TAG, String.format("ErrorID: [%s] %s", tree.get(Keys.ERROR_ID).asText(),
                    tree.get(Keys.ERROR_MESSAGE).asText()));
        }
    }

    conn.disconnect();
    return result;

}

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

private static void validateBody(JsonNode body) throws ScriptException {
    if (body == null) {
        throw new ScriptException("Missing body");
    }/* ww  w .  j  a  v a2s.c om*/
    JsonNode name = body.get(ScriptsDao.NAME);
    if (name == null || (!name.isTextual()) || name.asText().trim().length() == 0) {
        throw new ScriptException("Missing required 'name' property");
    }
    JsonNode code = body.get(ScriptsDao.CODE);
    if (code == null || (!code.isTextual()) || code.asText().trim().length() == 0) {
        throw new ScriptException("Missing required 'code' property");
    }
    JsonNode lang = body.get(ScriptsDao.LANG);
    if (lang == null || (!lang.isTextual()) || lang.asText().trim().length() == 0) {
        throw new ScriptException("Missing required 'lang' property or it is not a string");
    }
    if (ScriptLanguage.forName(lang.asText()) == null) {
        throw new ScriptException("Language '" + lang.asText() + "' is not supported");
    }
    JsonNode encoded = body.get(ScriptsDao.ENCODED);
    if (encoded != null) {
        if (!encoded.isTextual()) {
            throw new ScriptException("The field 'encoded' must be a String");
        }
        try {
            ScriptsDao.ENCODED_TYPE.valueOf(encoded.asText().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new ScriptException("The specified 'encoded' value is not valid");
        }
    }
}

From source file:com.github.tomakehurst.wiremock.matching.EqualToJsonPattern.java

private static JsonNode getNode(JsonNode ret, List<String> path, int pos) {
    if (pos >= path.size()) {
        return ret;
    }/*from   w  w w .  j  av a  2s  .co  m*/
    String key = path.get(pos);
    if (ret.isArray()) {
        int keyInt = Integer.parseInt(key.replaceAll("\"", ""));
        return getNode(ret.get(keyInt), path, ++pos);
    } else if (ret.isObject()) {
        if (ret.has(key)) {
            return getNode(ret.get(key), path, ++pos);
        }
        return null;
    } else {
        return ret;
    }
}

From source file:com.ning.metrics.serialization.event.SmileEnvelopeEvent.java

public static DateTime getEventDateTimeFromJson(final JsonNode node) {
    final JsonNode eventDateTimeNode = node.get(SMILE_EVENT_DATETIME_TOKEN_NAME);
    return (eventDateTimeNode == null) ? new DateTime() : new DateTime(eventDateTimeNode.longValue());
}

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

@SuppressLint("NewApi")
public static List<JsonNode> getFoursquareAutocomplete(Address address, Context context, Location location) {

    double lat;/*  ww  w  .  j a  va 2 s . co  m*/
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }

    String urlString;
    List<JsonNode> list = null;
    try {
        String query = URLEncoder.encode(normalizeToAlphabet(address.street), "UTF-8");

        String near = null;
        if (address.zip != null && !address.zip.equals("")) {
            if (address.city != null && !address.city.equals("")) {
                near = address.zip + " " + address.city;
            } else {
                near = address.zip + ", Denmark";
            }
        } else {
            if (address.city != null && !address.city.equals("")) {
                near = address.city;
            }
        }

        if (near != null && !near.equals("")) {
            urlString = "https://api.foursquare.com/v2/venues/search?intent=browse&near="
                    + URLEncoder.encode(near, "UTF-8") + "&client_id=" + FOURSQUARE_ID + "&client_secret="
                    + FOURSQUARE_SECRET + "&query=" + URLEncoder.encode(query, "UTF-8") + "&v=20130301&radius="
                    + FOURSQUARE_SEARCH_RADIUS + "&limit=" + FOURSQUARE_LIMIT + "&categoryId="
                    + FOURSQUARE_CATEGORIES;
        } else {
            urlString = "https://api.foursquare.com/v2/venues/search?intent=browse&ll=" + lat + "," + lon
                    + "&client_id=" + FOURSQUARE_ID + "&client_secret=" + FOURSQUARE_SECRET + "&query="
                    + URLEncoder.encode(query, "UTF-8") + "&v=" + 20130301 + "&radius="
                    + FOURSQUARE_SEARCH_RADIUS + "&limit=" + FOURSQUARE_LIMIT + "&categoryId="
                    + FOURSQUARE_CATEGORIES;
        }

        JsonNode rootNode = performGET(urlString);

        if (rootNode != null && rootNode.has("response")) {
            if (rootNode.get("response").has("minivenues")) {
                list = Util.JsonNodeToList(rootNode.get("response").get("minivenues"));
            } else if (rootNode.get("response").has("venues")) {
                list = Util.JsonNodeToList(rootNode.get("response").get("venues"));
            }
        }

    } catch (UnsupportedEncodingException e) {
        LOG.e(e.getLocalizedMessage());
    }

    return list;
}

From source file:com.amazonaws.services.kinesis.aggregators.StreamAggregatorUtils.java

public static JsonNode readJsonValue(JsonNode json, String atPath) {
    if (!atPath.contains(".")) {
        return json.get(atPath);
    } else {/*from w  w w.  j ava2 s  . c  o m*/
        String[] path = atPath.split("\\.");

        JsonNode node = json.get(path[0]);
        for (int i = 1; i < path.length; i++) {
            node = node.path(path[i]);
        }

        return node;
    }
}

From source file:com.gsma.mobileconnect.utils.JsonUtils.java

/**
 * Return the string value of an optional child node.
 * <p>//  ww w. jav a  2s.c  o  m
 * Check the parent node for the named child, if found return the string contents of the child node, return null otherwise.
 *
 * @param parentNode The node to check.
 * @param name Name of the optional child node.
 * @return Text value of child node, if found, null otherwise.
 */
static String getOptionalStringValue(JsonNode parentNode, String name) {
    JsonNode childNode = parentNode.get(name);
    if (null == childNode) {
        return null;
    } else {
        return childNode.textValue();
    }
}