Example usage for com.fasterxml.jackson.databind.node ArrayNode elements

List of usage examples for com.fasterxml.jackson.databind.node ArrayNode elements

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node ArrayNode elements.

Prototype

public Iterator<JsonNode> elements() 

Source Link

Usage

From source file:com.rmn.qa.servlet.BmpServlet.java

/**
 * Starts a new BrowserMobProxy. Note that either recordHar must be set to true or some credentials are provided or
 * a proxy will not be created.//from w w  w. j  a va  2 s  .  c o m
 *
 * Content should be a json object in the following form.
 * 
 * <pre>
{
  "uuid": "my-uuid",//required
  "recordHar" : "true",
  "credentials": [{
    "domain" : "",
    "username" : "",
    "password" : "",
  }]
}
 * </pre>
 * 
 * @return Responds with a 201 Created and the url ins the Location header if proxy is created.
 * 
 * @return Responds with a 400 Bad Request if the uuid is not specified or there is no reason to create the proxy
 *         (see above).
 * 
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // if (request.getContentType().equals("application/json"))
    try {
        JsonNode input = getNodeFromRequest(request);
        String uuid = getJsonString(input, "uuid");
        if (StringUtils.isBlank(uuid)) {
            log.error("uuid not  present");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "uuid must be specified in json");
            return;
        }

        JsonNode harRecording = input.get("recordHar");
        boolean recorrdingHar = harRecording != null && harRecording.asBoolean(false);
        BrowserMobProxy proxy = null;
        if (recorrdingHar) {
            proxy = new BrowserMobProxyServer();
            Set<CaptureType> set = new HashSet<CaptureType>(CaptureType.getRequestCaptureTypes());
            set.addAll(CaptureType.getResponseCaptureTypes());
            set.removeAll(CaptureType.getBinaryContentCaptureTypes());
            proxy.setHarCaptureTypes(set);
        }
        JsonNode creds = input.get("credentials");
        if (creds != null) {
            if (proxy == null) {
                proxy = new BrowserMobProxyServer();
            }
            if (creds.isArray()) {
                ArrayNode array = (ArrayNode) creds;
                Iterator<JsonNode> elements = array.elements();
                while (elements.hasNext()) {
                    JsonNode cred = elements.next();
                    addCredentials(proxy, cred);
                }
            } else {
                addCredentials(proxy, creds);
            }
        }
        if (proxy == null) {
            log.error("Nothing for proxy to do");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Har recording or credentials not specified. There is no reason to start a proxy.");
            return;
        } else {
            String localhostname;
            // Try and get the IP address from the system property
            String runTimeHostName = System.getProperty(AutomationConstants.IP_ADDRESS);
            try {
                if (runTimeHostName == null) {
                    log.warn("Host name could not be determined from system property.");
                }
                localhostname = (runTimeHostName != null) ? runTimeHostName
                        : InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                log.error("Error parsing out host name", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Host name could not be determined: " + e);
                return;
            }

            // build the response
            BmpProxyRegistry.getInstance().addProxy(uuid, proxy);
            proxy.start();
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader("Location", localhostname + ":" + proxy.getPort());
        }
    } catch (Exception e) {
        log.error("Error starting proxy: " + e, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error starting proxy: " + e);
    }
}

From source file:com.redhat.lightblue.eval.ArrayProjector.java

/**
 * Sorts the given array node using the sort criteria given in this ArrayProjector
 *
 * @param array The array node to sort//from  w  ww.  j ava  2 s.co m
 * @param factory Json node factory
 *
 * If there is a sort criteria defined in <code>this</code>, the array elements are
 * sorted using that.
 *
 * @return A new ArrayNode containing the sorted elements, or if
 * there is no sort defined, the <code>array</code> itself
 */
public ArrayNode sortArray(ArrayNode array, JsonNodeFactory factory) {
    if (sort == null) {
        return array;
    } else {
        List<SortableElement> list = new ArrayList<>(array.size());
        for (Iterator<JsonNode> itr = array.elements(); itr.hasNext();) {
            list.add(new SortableElement(itr.next(), sortFields));
        }
        Collections.sort(list);
        ArrayNode newNode = factory.arrayNode();
        for (SortableElement x : list)
            newNode.add(x.node);
        return newNode;
    }
}

From source file:org.opendaylight.alto.core.northbound.route.costmap.impl.AltoNorthboundRouteCostmap.java

protected List<String> arrayNode2List(String field, ArrayNode node) {
    HashSet<String> retval = new HashSet<String>();

    for (Iterator<JsonNode> itr = node.elements(); itr.hasNext();) {
        JsonNode data = itr.next();/*from   w  ww .  j ava 2 s.c  om*/

        retval.add(data.asText());
    }
    return new LinkedList<String>(retval);
}

From source file:ws.salient.session.Session.java

public List inserts(ArrayNode inserts) {
    MDC.put("sessionId", sessionId);
    List objects = new LinkedList();
    inserts.elements().forEachRemaining((node) -> {
        node.fieldNames().forEachRemaining((className) -> {
            try {
                Object insert = knowledgeBase.getJson().convertValue(node.get(className),
                        knowledgeBase.getContainer().getClassLoader().loadClass(className));
                objects.add(insert);/*  www. ja  v  a2s.  c  o m*/
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            }
        });
    });
    return objects;
}

From source file:com.palominolabs.crm.sf.rest.RestConnectionImpl.java

@Override
@Nonnull//  ww  w  .ja  v  a 2  s  .com
public BasicSObjectMetadataResult getBasicObjectInfo(String sObjectType) throws IOException {
    Timer.Context context = basicSObjectInfoTimer.time();
    String jsonStr;
    try {
        jsonStr = this.getHttpApiClient().basicSObjectInfo(sObjectType);
    } finally {
        context.stop();
    }
    ObjectNode objectNode = this.objectReader.withType(ObjectNode.class).readValue(jsonStr);

    BasicSObjectMetadata metadata = this.objectReader.withType(BasicSObjectMetadata.class)
            .readValue(objectNode.get("objectDescribe"));

    ArrayNode recentItems = this.objectReader.withType(ArrayNode.class)
            .readValue(objectNode.get("recentItems"));

    List<SObject> sObjects = getSObjects(recentItems.elements());

    return new BasicSObjectMetadataResult(metadata, sObjects);
}

From source file:com.palominolabs.crm.sf.rest.RestConnectionImpl.java

@Override
@Nonnull/*from w w w. j  ava 2  s .  c om*/
public DescribeGlobalResult describeGlobal() throws IOException {
    Timer.Context context = describeGlobalTimer.time();
    String describeGlobalJson;
    try {
        describeGlobalJson = this.getHttpApiClient().describeGlobal();
    } finally {
        context.stop();
    }

    ObjectNode objectNode = this.objectReader.withType(ObjectNode.class).readValue(describeGlobalJson);
    String encoding = objectNode.get("encoding").textValue();
    int maxBatchSize = objectNode.get("maxBatchSize").intValue();

    ArrayNode descriptionsNode = this.objectReader.withType(ArrayNode.class)
            .readValue(objectNode.get("sobjects"));

    Iterator<JsonNode> elements = descriptionsNode.elements();

    List<GlobalSObjectDescription> descriptions = Lists.newArrayList();
    while (elements.hasNext()) {
        JsonNode node = elements.next();

        descriptions.add(this.objectReader.readValue(node.traverse(), BasicSObjectMetadata.class));
    }

    return new DescribeGlobalResult(encoding, maxBatchSize, descriptions);
}

From source file:kz.nurlan.kaspandr.KaspandrWindow.java

@Override
public void initialize(Map<String, Object> namespace, URL location, Resources resources) {
    mapper = new ObjectMapper();
    jsonMergeButton.getButtonPressListeners().add(new ButtonPressListener() {
        @Override//w  w  w.j  ava  2s  .  c  o  m
        public void buttonPressed(Button button) {
            ApplicationContext.scheduleCallback(new Runnable() {
                @Override
                public void run() {
                    activityIndicatorBoxPane.setVisible(true);
                }
            }, 0);
            ApplicationContext.scheduleCallback(new Runnable() {
                @Override
                public void run() {
                    activityIndicatorBoxPane.setVisible(false);
                }
            }, 2000);

            try {
                String finalJson = "";

                int firstID = 0;

                HashSet<String> groupNameSet = new HashSet<String>();

                HashMap<String, ArrayNode> grouppedLessonsByGroupMap1 = groupByLessonsByGroup(
                        firstJson.getText().replaceAll("'", "\""));
                HashMap<String, ArrayNode> grouppedLessonsByGroupMap2 = groupByLessonsByGroup(
                        secondJson.getText().replaceAll("'", "\""));
                HashMap<String, Integer> lessonCountByGroupMap1 = getCountedLessonsByGroup(
                        firstJson.getText().replaceAll("'", "\""));
                HashMap<String, Integer> lessonCountByGroupMap2 = getCountedLessonsByGroup(
                        secondJson.getText().replaceAll("'", "\""));

                for (String groupName : grouppedLessonsByGroupMap1.keySet()) {
                    groupNameSet.add(groupName);
                }
                for (String groupName : grouppedLessonsByGroupMap2.keySet()) {
                    groupNameSet.add(groupName);
                }

                Iterator<String> it = groupNameSet.iterator();

                HashMap<String, ArrayNode> linkForGrouppedLessonsByGroupMap = grouppedLessonsByGroupMap1;
                while (it.hasNext()) {
                    String groupName = it.next();

                    if (lessonCountByGroupMap1.get(groupName) != null
                            && lessonCountByGroupMap2.get(groupName) == null)
                        linkForGrouppedLessonsByGroupMap = grouppedLessonsByGroupMap1;
                    else if (lessonCountByGroupMap1.get(groupName) == null
                            && lessonCountByGroupMap2.get(groupName) != null)
                        linkForGrouppedLessonsByGroupMap = grouppedLessonsByGroupMap2;
                    else if (lessonCountByGroupMap1.get(groupName) > lessonCountByGroupMap2.get(groupName))
                        linkForGrouppedLessonsByGroupMap = grouppedLessonsByGroupMap1;
                    else
                        linkForGrouppedLessonsByGroupMap = grouppedLessonsByGroupMap2;

                    ArrayNode lessonArrayNode = linkForGrouppedLessonsByGroupMap.get(groupName);

                    Iterator<JsonNode> lanIt = lessonArrayNode.elements();

                    while (lanIt.hasNext()) {
                        if (!finalJson.isEmpty())
                            finalJson += ",";

                        ObjectNode lesson = (ObjectNode) lanIt.next();

                        lesson.put("id", "" + firstID++);

                        finalJson += mapper.writeValueAsString(lesson).replace('"', '\'');
                    }
                }

                finalLessonSequence.setText("" + (firstID));
                finalJsonText.setText(finalJson);
                checkGroupText3.setText(checkLessonCountByGroup(finalJsonText.getText().replaceAll("'", "\"")));
            } catch (JsonParseException e) {
                Alert.alert(MessageType.ERROR, "Incorrect JSON format!", "JsonParseException", null,
                        KaspandrWindow.this, null);
                e.printStackTrace();
            } catch (JsonMappingException e) {
                Alert.alert(MessageType.ERROR,
                        "JsonMappingException. Make bug report to Nurlan Rakhimzhanov(nurlan.rakhimzhanov@bee.kz).",
                        KaspandrWindow.this);
                e.printStackTrace();
            } catch (IOException e) {
                Alert.alert(MessageType.ERROR,
                        "IOException. Make bug report to Nurlan Rakhimzhanov(nurlan.rakhimzhanov@bee.kz).",
                        KaspandrWindow.this);
                e.printStackTrace();
            }
        }
    });

    checkGroupButton1.getButtonPressListeners().add(new ButtonPressListener() {
        @Override
        public void buttonPressed(Button button) {
            try {
                checkGroupText1.setText(checkLessonCountByGroup(firstJson.getText().replaceAll("'", "\"")));
            } catch (JsonParseException e) {
                Alert.alert(MessageType.ERROR, "Incorrect JSON format!", "JsonParseException", null,
                        KaspandrWindow.this, null);
                e.printStackTrace();
            } catch (JsonMappingException e) {
                Alert.alert(MessageType.ERROR,
                        "Make bug report to Nurlan Rakhimzhanov\n(nurlan.rakhimzhanov@bee.kz).",
                        "JsonMappingException", null, KaspandrWindow.this, null);
                e.printStackTrace();
            } catch (IOException e) {
                Alert.alert(MessageType.ERROR,
                        "Make bug report to Nurlan Rakhimzhanov\n(nurlan.rakhimzhanov@bee.kz).", "IOException",
                        null, KaspandrWindow.this, null);
                e.printStackTrace();
            }
        }
    });

    checkGroupButton2.getButtonPressListeners().add(new ButtonPressListener() {
        @Override
        public void buttonPressed(Button button) {
            try {
                checkGroupText2.setText(checkLessonCountByGroup(secondJson.getText().replaceAll("'", "\"")));
            } catch (JsonParseException e) {
                Alert.alert(MessageType.ERROR, "Incorrect JSON format!", "JsonParseException", null,
                        KaspandrWindow.this, null);
                e.printStackTrace();
            } catch (JsonMappingException e) {
                Alert.alert(MessageType.ERROR,
                        "Make bug report to Nurlan Rakhimzhanov\n(nurlan.rakhimzhanov@bee.kz).",
                        "JsonMappingException", null, KaspandrWindow.this, null);
                e.printStackTrace();
            } catch (IOException e) {
                Alert.alert(MessageType.ERROR,
                        "Make bug report to Nurlan Rakhimzhanov\n(nurlan.rakhimzhanov@bee.kz).", "IOException",
                        null, KaspandrWindow.this, null);
                e.printStackTrace();
            }
        }
    });

    nextButton.getButtonPressListeners().add(new ButtonPressListener() {
        @Override
        public void buttonPressed(Button button) {
            try {
                firstJson.setText(finalJsonText.getText());
                secondJson.setText("");
                finalJsonText.setText("");
                checkGroupText1.setText("");
                checkGroupText2.setText("");
                checkGroupText3.setText("");
            } catch (Exception e) {
                Alert.alert(MessageType.ERROR,
                        "Make bug report to Nurlan Rakhimzhanov\n(nurlan.rakhimzhanov@bee.kz).",
                        "Unknown error", null, KaspandrWindow.this, null);
                e.printStackTrace();
            }
        }
    });
}

From source file:com.alliander.osgp.shared.usermanagement.KeycloakClient.java

private String determineSessionIdWithLoginClient(final ArrayNode sessionRepresentationArray) {
    final Iterator<JsonNode> elements = sessionRepresentationArray.elements();
    final boolean sessionFound = false;
    while (!sessionFound && elements.hasNext()) {
        final JsonNode sessionRepresentation = elements.next();
        final JsonNode sessionId = sessionRepresentation.get("id");
        if (sessionId == null || !sessionId.isTextual()) {
            LOGGER.warn("sessionId is not a JSON text node for a user session");
            continue;
        }/*  w ww  .  j  ava 2  s.c om*/
        final JsonNode clients = sessionRepresentation.get("clients");
        if (clients == null || !clients.isObject()) {
            LOGGER.warn("clients is not a JSON object node for a user session");
            continue;
        }
        if (this.useSessionIdForClients(clients)) {
            return sessionId.textValue();
        }
    }
    return null;
}

From source file:org.jsonschema2pojo.rules.OneOfRule.java

/**
 * Add "oneOf" option./* www  .  j  a  v a 2  s .  c om*/
 * 
 * @param nodeName
 *            The "oneOf" field name.
 * @param node
 *            The option node.
 * @param _package
 * @param schema
 * @param oneOfOptions
 *            The defined enum.
 */
private void addOneOves(final String nodeName, JsonNode node, JPackage _package, Schema schema,
        JDefinedClass oneOfOptions) {
    schema.setJavaTypeIfEmpty(oneOfOptions);
    JFieldVar enumFields = addEnumFields(oneOfOptions);
    addToString(oneOfOptions, enumFields);

    // List options ...
    ArrayNode oneOfs = (ArrayNode) node.path(ONE_OF);
    Iterator<JsonNode> it = oneOfs.elements();
    while (it.hasNext()) {
        final JsonNode optionNode = it.next();
        if (optionNode.has(REF)) {
            // Parsing reference ...
            JsonNode n = resolveRefs(optionNode, schema);
            if (isObject(n)) {
                String referType = optionNode.get(REF).asText();
                referType = referType.substring(referType.lastIndexOf('/') + 1);
                JType type = ruleFactory.getObjectRule().apply(referType, n, _package, schema);
                addOption(referType, type, oneOfOptions);
            } else {
                throw new GenerationException(
                        "Only object type supported, '" + n + "' cannot be used as an oneOf option.");
            }
        } else {
            // For anonymous object, create index ..
            AtomicInteger index = INDICES.get(nodeName);
            if (index == null) {
                INDICES.put(nodeName, index = new AtomicInteger(0));
            }

            // Create unique class name ...
            final String className = makeUnique(nodeName + index.incrementAndGet(), _package);
            // Convert ...
            JType type = ruleFactory.getObjectRule().apply(className, optionNode, _package, schema);
            addOption(className, type, oneOfOptions);
        }

    }
}