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

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

Introduction

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

Prototype

public Iterator<JsonNode> elements() 

Source Link

Usage

From source file:org.talend.dataprep.api.filter.SimpleFilterService.java

private Predicate<DataSetRow> buildOperationFilter(JsonNode currentNode, //
        RowMetadata rowMetadata, //
        String columnId, //
        String operation, //
        String value) {//from w w w.  j ava  2 s .  c o  m
    switch (operation) {
    case EQ:
        return createEqualsPredicate(currentNode, columnId, value);
    case GT:
        return createGreaterThanPredicate(currentNode, columnId, value);
    case LT:
        return createLowerThanPredicate(currentNode, columnId, value);
    case GTE:
        return createGreaterOrEqualsPredicate(currentNode, columnId, value);
    case LTE:
        return createLowerOrEqualsPredicate(currentNode, columnId, value);
    case CONTAINS:
        return createContainsPredicate(currentNode, columnId, value);
    case MATCHES:
        return createMatchesPredicate(currentNode, columnId, value);
    case INVALID:
        return createInvalidPredicate(columnId);
    case VALID:
        return createValidPredicate(columnId);
    case EMPTY:
        return createEmptyPredicate(columnId);
    case RANGE:
        return createRangePredicate(columnId, currentNode.elements().next(), rowMetadata);
    case AND:
        return createAndPredicate(currentNode.elements().next(), rowMetadata);
    case OR:
        return createOrPredicate(currentNode.elements().next(), rowMetadata);
    case NOT:
        return createNotPredicate(currentNode.elements().next(), rowMetadata);
    default:
        throw new UnsupportedOperationException(
                "Unsupported query, unknown filter '" + operation + "': " + currentNode.toString());
    }
}

From source file:com.microsoft.rest.serializer.FlatteningSerializer.java

@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    if (value == null) {
        jgen.writeNull();/*from  w  w w .  j av a2s  .c  om*/
        return;
    }

    // BFS for all collapsed properties
    ObjectNode root = mapper.valueToTree(value);
    ObjectNode res = root.deepCopy();
    Queue<ObjectNode> source = new LinkedBlockingQueue<ObjectNode>();
    Queue<ObjectNode> target = new LinkedBlockingQueue<ObjectNode>();
    source.add(root);
    target.add(res);
    while (!source.isEmpty()) {
        ObjectNode current = source.poll();
        ObjectNode resCurrent = target.poll();
        Iterator<Map.Entry<String, JsonNode>> fields = current.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> field = fields.next();
            ObjectNode node = resCurrent;
            String key = field.getKey();
            JsonNode outNode = resCurrent.get(key);
            if (field.getKey().matches(".+[^\\\\]\\..+")) {
                String[] values = field.getKey().split("((?<!\\\\))\\.");
                for (int i = 0; i < values.length; ++i) {
                    values[i] = values[i].replace("\\.", ".");
                    if (i == values.length - 1) {
                        break;
                    }
                    String val = values[i];
                    if (node.has(val)) {
                        node = (ObjectNode) node.get(val);
                    } else {
                        ObjectNode child = new ObjectNode(JsonNodeFactory.instance);
                        node.put(val, child);
                        node = child;
                    }
                }
                node.set(values[values.length - 1], resCurrent.get(field.getKey()));
                resCurrent.remove(field.getKey());
                outNode = node.get(values[values.length - 1]);
            }
            if (field.getValue() instanceof ObjectNode) {
                source.add((ObjectNode) field.getValue());
                target.add((ObjectNode) outNode);
            } else if (field.getValue() instanceof ArrayNode && (field.getValue()).size() > 0
                    && (field.getValue()).get(0) instanceof ObjectNode) {
                Iterator<JsonNode> sourceIt = field.getValue().elements();
                Iterator<JsonNode> targetIt = outNode.elements();
                while (sourceIt.hasNext()) {
                    source.add((ObjectNode) sourceIt.next());
                    target.add((ObjectNode) targetIt.next());
                }
            }
        }
    }
    jgen.writeTree(res);
}

From source file:org.opendaylight.alto.core.northbound.route.endpointproperty.impl.AltoNorthboundRouteEndpointpropertyTest.java

@Test
public void testPrepareInput() {

    AltoNorthboundRouteEndpointproperty anbreSpy = spy(anbre);
    InstanceIdentifier<ContextTag> ctagIID = InstanceIdentifier.create(ContextTag.class);
    JsonNode filterNode = EndpointpropertyRouteChecker.checkJsonSyntax(ENDPOINTPROPERTY_FILTER);
    JsonNode _properties = filterNode.get(AltoNorthboundRouteEndpointproperty.FIELD_PROPERTIES);
    JsonNode _endpoints = filterNode.get(AltoNorthboundRouteEndpointproperty.FIELD_ENDPOINTS);

    doReturn(ctagIID).when(anbreSpy).getResourceByPath(eq(PATH), (ReadOnlyTransaction) anyObject());
    anbreSpy.setDataBroker(new DataBroker() {
        @Override/*from   ww w .j  av a2 s . c  o  m*/
        public ReadOnlyTransaction newReadOnlyTransaction() {
            return null;
        }

        @Override
        public ReadWriteTransaction newReadWriteTransaction() {
            return null;
        }

        @Override
        public WriteTransaction newWriteOnlyTransaction() {
            return null;
        }

        @Override
        public ListenerRegistration<DataChangeListener> registerDataChangeListener(
                LogicalDatastoreType logicalDatastoreType, InstanceIdentifier<?> instanceIdentifier,
                DataChangeListener dataChangeListener, DataChangeScope dataChangeScope) {
            return null;
        }

        @Override
        public BindingTransactionChain createTransactionChain(
                TransactionChainListener transactionChainListener) {
            return null;
        }

        @Nonnull
        @Override
        public <T extends DataObject, L extends DataTreeChangeListener<T>> ListenerRegistration<L> registerDataTreeChangeListener(
                @Nonnull DataTreeIdentifier<T> dataTreeIdentifier, @Nonnull L l) {
            return null;
        }
    });

    anbreSpy.init();
    QueryInput input = anbreSpy.prepareInput(PATH, _properties.elements(), _endpoints.elements());
    EndpointpropertyRequest request = (EndpointpropertyRequest) input.getRequest();
    EndpointpropertyParams params = request.getEndpointpropertyParams();
    List<PropertyFilter> listProperty = ((EndpointpropertyFilterData) params.getFilter())
            .getEndpointpropertyFilter().getPropertyFilter();
    List<EndpointFilter> listEndpoint = ((EndpointpropertyFilterData) params.getFilter())
            .getEndpointpropertyFilter().getEndpointFilter();
    List<PropertyFilter> expectedListProperty = new LinkedList<>();
    List<EndpointFilter> expectedListEndpoint = new LinkedList<>();

    expectedListProperty.add(new PropertyFilterBuilder().setProperty(new InputResourceSpecificPropertyBuilder()
            .setResourceSpecificProperty(new SpecificEndpointProperty(RESOURCE_SPECIFIC_PROPERTY)).build())
            .build());
    expectedListProperty.add(new PropertyFilterBuilder().setProperty(new InputGlobalPropertyBuilder()
            .setGlobalProperty(new GlobalEndpointProperty(GLOBAL_PROPERTY)).build()).build());

    expectedListEndpoint.add(new EndpointFilterBuilder()
            .setAddress(new Ipv4Builder().setIpv4(new Ipv4Address(THE_FIRST_IPv4_ADDRESS)).build()).build());
    expectedListEndpoint.add(new EndpointFilterBuilder()
            .setAddress(new Ipv4Builder().setIpv4(new Ipv4Address(THE_SECOND_IPv4_ADDRESS)).build()).build());

    assertEquals(expectedListProperty, listProperty);
    assertEquals(expectedListEndpoint, listEndpoint);
}

From source file:com.appdynamics.analytics.processor.event.ElasticSearchEventService.java

private void stripExplicitAnalyzedStrings(JsonNode node)
/*      */ {//from   ww  w  .  j a  v a2s. co  m
    /*  301 */ if ((node.isObject()) && (node.get("index") != null)
            && (node.get("index").asText().equals("analyzed"))) {
        /*  302 */ ((ObjectNode) node).remove("index");
        /*  303 */ return;
        /*      */ }
    /*  305 */ Iterator<JsonNode> nodeIterator = node.elements();
    /*  306 */ while (nodeIterator.hasNext()) {
        /*  307 */ JsonNode childNode = (JsonNode) nodeIterator.next();
        /*  308 */ stripExplicitAnalyzedStrings(childNode);
        /*      */ }
    /*      */ }

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scan() {
    WebTarget t = extractWebTarget(dockerScanner.getDockerClient());
    logger.info("Scanning {}", t);
    JsonNode response = t.path("/info").request().buildGet().invoke(JsonNode.class);

    JsonNode swarm = response.path("Swarm");
    JsonNode cluster = swarm.path("Cluster");
    String swarmClusterId = cluster.path("ID").asText();

    // need to parse these dates
    String createdAt = cluster.path("CreatedAt").asText();
    String updatedAt = cluster.path("UpdatedAt").asText();
    ObjectNode props = mapper.createObjectNode();
    props.put("swarmClusterId", swarmClusterId);
    props.put("createdAt", createdAt);
    props.put("updatedAt", updatedAt);

    JsonNode swarmNode = dockerScanner.getNeoRxClient().execCypher(
            "merge (c:DockerSwarm {swarmClusterId:{id}}) set c+={props},c.updateTs=timestamp() return c", "id",
            swarmClusterId, "props", props).blockingFirst(MissingNode.getInstance());

    if (isUnixDomainScoket(t.getUri().toString())) {
        // Only set managerApiUrl to a unix domain socket if it has not
        // already been set.
        // This is useful for trident
        if (!isUnixDomainScoket(swarmNode.path("managerApiUrl").asText())) {

            String LOCAL_DOCKER_DAEMON_SOCKET_URL = "unix:///var/run/docker.sock";
            logger.info("setting mangerApiUrl to {} for swarm {}", LOCAL_DOCKER_DAEMON_SOCKET_URL,
                    swarmClusterId);/*from  w ww.j  av  a 2 s .  com*/

            String name = "local";
            dockerScanner.getNeoRxClient()
                    .execCypher("match (c:DockerSwarm {name:{name}}) return c", "name", name).forEach(it -> {
                        String oldSwarmClusterId = it.path("swarmClusterId").asText();
                        if (!swarmClusterId.equals(oldSwarmClusterId)) {
                            dockerScanner.getNeoRxClient().execCypher(
                                    "match (c:DockerSwarm {swarmClusterId:{swarmClusterId}}) detach delete c",
                                    "swarmClusterId", oldSwarmClusterId);
                        }
                    });

            dockerScanner.getNeoRxClient().execCypher(
                    "match (c:DockerSwarm {swarmClusterId:{id}}) set c.managerApiUrl={managerApiUrl},c.name={name},c.tridentClusterId={name} return c",
                    "id", swarmClusterId, "managerApiUrl", LOCAL_DOCKER_DAEMON_SOCKET_URL, "name", name);

        }
    }

    AtomicBoolean fail = new AtomicBoolean(false);
    response = t.path("/nodes").request().buildGet().invoke(JsonNode.class);
    AtomicLong earliestTimestamp = new AtomicLong(Long.MAX_VALUE);
    response.elements().forEachRemaining(it -> {
        try {
            earliestTimestamp.set(
                    Math.min(earliestTimestamp.get(), saveDockerNode(swarmClusterId, flattenSwarmNode(it))));
        } catch (RuntimeException e) {
            logger.warn("problem", e);
            fail.set(true);
        }
    });

    if (!fail.get()) {
        if (earliestTimestamp.get() < System.currentTimeMillis()) {
            logger.info("deleting DockerHost nodes before with updateTs<{}", earliestTimestamp.get());
            dockerScanner.getNeoRxClient().execCypher(
                    "match (s:DockerSwarm {swarmClusterId:{id}})--(x:DockerHost) where s.updateTs>x.updateTs detach delete x",
                    "id", swarmClusterId);
        }
    }
    scanServicesForSwarm(swarmClusterId);
    scanTasksForSwarm(swarmClusterId);
}

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

@Test
public void testNamedExecuteSelectQuery() throws IOException, SAXException, ParserConfigurationException {
    System.out.println("In SPARQL Query Manager Test testNamedExecuteSelectQuery method");
    SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager();
    StringBuffer sparqlQuery = new StringBuffer().append("PREFIX foaf: <http://xmlns.com/foaf/0.1/>");
    sparqlQuery.append("SELECT ?name from <http://marklogic.com/qatests/ntriples/foaf1.nt>");
    sparqlQuery.append("WHERE { ?alum foaf:schoolHomepage <http://www.ucsb.edu/> .");
    sparqlQuery.append("?alum foaf:knows ?person .");
    sparqlQuery.append("?person foaf:name ?name }");
    sparqlQuery.append("ORDER BY ?name");

    SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString());
    JacksonHandle jacksonHandle = new JacksonHandle();
    jacksonHandle.setMimetype("application/json");
    JsonNode jsonResults = sparqlQmgr.executeSelect(qdef, jacksonHandle).get();

    JsonNode jsonBindingsNodes = jsonResults.path("results").path("bindings");

    // Should have 2 nodes returned.
    assertEquals("Two names not returned from testNamedExecuteSelectQuery method ", 2,
            jsonBindingsNodes.size());//w  w  w  .j a va2s .  c  om

    Iterator<JsonNode> nameNodesItr = jsonBindingsNodes.elements();
    JsonNode jsonNameNode = null;
    if (nameNodesItr.hasNext()) {
        jsonNameNode = nameNodesItr.next();
        // Verify result 1's values.
        assertEquals("Element 1 name value incorrect", "Karen Schouten",
                jsonNameNode.path("name").path("value").asText());
        assertEquals("Element 1 type is incorrect", "literal", jsonNameNode.path("name").path("type").asText());
    }

    if (nameNodesItr.hasNext()) {
        // Verify result 2's values.
        jsonNameNode = nameNodesItr.next();
        assertEquals("Element 2 name value incorrect", "Nick Aster",
                jsonNameNode.path("name").path("value").asText());
        assertEquals("Element 2 type is incorrect", "literal", jsonNameNode.path("name").path("type").asText());
    }
}

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

@Test
public void testDefaultExecuteSelectQuery() throws IOException, SAXException, ParserConfigurationException {
    System.out.println("In SPARQL Query Manager Test testDefaultExecuteSelectQuery method");
    SPARQLQueryManager sparqlQmgr = readclient.newSPARQLQueryManager();
    StringBuffer sparqlQuery = new StringBuffer().append(
            "select ?name ?lives ?city from <http://marklogic.com/semantics#default-graph>{ ?name ?lives ?city } ORDER BY ?name");

    SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlQuery.toString());
    JsonNode jsonResults = sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get();
    JsonNode jsonBindingsNodes = jsonResults.path("results").path("bindings");

    // Should have 3 nodes returned.
    assertEquals("Three results not returned from testDefaultExecuteSelectQuery method ", 3,
            jsonBindingsNodes.size());//www  .j av  a2s  .c o  m

    Iterator<JsonNode> nameNodesItr = jsonBindingsNodes.elements();
    JsonNode jsonNameNode = null;
    if (nameNodesItr.hasNext()) {
        jsonNameNode = nameNodesItr.next();
        // Verify result 1 values.         
        assertEquals("Element 1 name value incorrect", "http://example.org/ml/people/Jack_Smith",
                jsonNameNode.path("name").path("value").asText());
        assertEquals("Element 1 lives is incorrect", "livesIn",
                jsonNameNode.path("lives").path("value").asText());
        assertEquals("Element 1 city is incorrect", "Glasgow",
                jsonNameNode.path("city").path("value").asText());
    }
    if (nameNodesItr.hasNext()) {
        // Verify result 2 values.
        jsonNameNode = nameNodesItr.next();
        assertEquals("Element 2 name value incorrect", "http://example.org/ml/people/Jane_Smith",
                jsonNameNode.path("name").path("value").asText());
        assertEquals("Element 2 lives is incorrect", "livesIn",
                jsonNameNode.path("lives").path("value").asText());
        assertEquals("Element 2 city is incorrect", "London", jsonNameNode.path("city").path("value").asText());
    }
    if (nameNodesItr.hasNext()) {
        // Verify result 3 values.
        jsonNameNode = nameNodesItr.next();
        assertEquals("Element 3 name value incorrect", "http://example.org/ml/people/John_Smith",
                jsonNameNode.path("name").path("value").asText());
        assertEquals("Element 3 lives is incorrect", "livesIn",
                jsonNameNode.path("lives").path("value").asText());
        assertEquals("Element 3 city is incorrect", "London", jsonNameNode.path("city").path("value").asText());
    }
}

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

@Test
public void testExecuteUpdateCreateSilent() throws IOException, SAXException, ParserConfigurationException {
    System.out.println("In SPARQL Query Manager Test testExecuteUpdateCreateSilent method");
    // Form a query
    SPARQLQueryManager sparqlQmgr = writeclient.newSPARQLQueryManager();

    StringBuffer sparqlCreateGraphQuery = new StringBuffer().append("CREATE GRAPH <DOMICLE>;");
    sparqlCreateGraphQuery.append(newline);

    SPARQLQueryDefinition qdef = sparqlQmgr.newQueryDefinition(sparqlCreateGraphQuery.toString());
    // Create an empty graph.
    sparqlQmgr.executeUpdate(qdef);/*from   w w  w . j a  va2 s  .c o  m*/
    qdef = null;

    // Insert triple into graph using INSERT DATA
    StringBuffer sparqlInsertData = new StringBuffer().append("PREFIX : <http://example.org/>");
    sparqlInsertData.append(newline);
    sparqlInsertData.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ");
    sparqlInsertData.append(newline);
    sparqlInsertData.append("PREFIX foaf: <http://xmlns.com/foaf/0.1/>");
    sparqlInsertData.append("INSERT DATA { GRAPH <DOMICLE> { ");
    sparqlInsertData.append(newline);
    sparqlInsertData.append(":alice  rdf:type   foaf:Person .");
    sparqlInsertData.append(newline);
    sparqlInsertData.append(":alice  foaf:name  \"Alice\" . ");
    sparqlInsertData.append(newline);
    sparqlInsertData.append(":bob    rdf:type   foaf:Person . ");
    sparqlInsertData.append(newline);
    sparqlInsertData.append("} } ");

    qdef = sparqlQmgr.newQueryDefinition(sparqlInsertData.toString());
    // Insert Data into the  empty graph.
    sparqlQmgr.executeUpdate(qdef);
    // Wait for index 
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    qdef = null;

    //Check for EXIST.
    StringBuffer sparqlExists = new StringBuffer();
    sparqlExists.append("PREFIX  rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
    sparqlExists.append(newline);
    sparqlExists.append("PREFIX  foaf:   <http://xmlns.com/foaf/0.1/>");
    sparqlExists.append(newline);
    sparqlExists.append("SELECT ?person ");
    sparqlExists.append(newline);
    sparqlExists.append("FROM <DOMICLE>");
    sparqlExists.append(newline);
    sparqlExists.append("WHERE");
    sparqlExists.append(newline);
    sparqlExists.append("{");
    sparqlExists.append("?person rdf:type  foaf:Person .");
    sparqlExists.append(newline);
    sparqlExists.append("FILTER EXISTS { ?person foaf:name ?name }");
    sparqlExists.append(newline);
    sparqlExists.append("}");
    qdef = sparqlQmgr.newQueryDefinition(sparqlExists.toString());

    // Perform Exists query.      
    JsonNode jsonResults = sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get();
    JsonNode jsonBindingsNodes = jsonResults.path("results").path("bindings");

    // Should have 1 node returned.
    assertEquals("One result not returned from testExecuteUpdateCreateSilent method ", 1,
            jsonBindingsNodes.size());
    Iterator<JsonNode> nameNodesItr = jsonBindingsNodes.elements();
    JsonNode jsonPersonNode = null;
    if (nameNodesItr.hasNext()) {
        jsonPersonNode = nameNodesItr.next();
        assertEquals("Exist query solution returned is incorrect", "http://example.org/alice",
                jsonPersonNode.path("person").path("value").asText());
    }
    qdef = null;

    // Test to see if FailedRequestException is thrown.
    qdef = sparqlQmgr.newQueryDefinition(sparqlCreateGraphQuery.toString());

    String expectedException = "FailedRequestException";
    String exception = "";
    try {
        // Create same graph.
        sparqlQmgr.executeUpdate(qdef);
    } catch (Exception e) {
        exception = e.toString();
    }
    System.out.println(exception);
    assertTrue("Test testExecuteUpdateCreateSilent exception is not thrown",
            exception.contains(expectedException));

    qdef = null;

    // Create the same graph again silently. Should not expect exception.
    StringBuffer sparqlCreateGraphSilentQuery = new StringBuffer().append("CREATE SILENT GRAPH <DOMICLE>;");
    sparqlCreateGraphQuery.append(newline);

    qdef = sparqlQmgr.newQueryDefinition(sparqlCreateGraphSilentQuery.toString());
    String expectedSilentException = "";
    String exceptionSilent = "";
    try {
        // Create same graph.
        sparqlQmgr.executeUpdate(qdef);
    } catch (Exception e) {
        exceptionSilent = e.toString();
    }

    assertTrue("Test testExecuteUpdateCreateSilent exception is not thrown",
            exceptionSilent.equals(expectedSilentException));
    qdef = null;

    // Verify the EXISTS again. Should have one solution returned.
    qdef = sparqlQmgr.newQueryDefinition(sparqlExists.toString());

    // Perform Exists query again      
    JsonNode jsonResultsSil = sparqlQmgr.executeSelect(qdef, new JacksonHandle()).get();
    JsonNode jsonBindingsNodesSilent = jsonResultsSil.path("results").path("bindings");

    // Should have 1 node returned.
    assertEquals("One result not returned from testExecuteUpdateCreateSilent method ", 1,
            jsonBindingsNodesSilent.size());

    Iterator<JsonNode> nameNodesSilentItr = jsonBindingsNodesSilent.elements();
    JsonNode jsonPersonNodeSilent = null;
    if (nameNodesSilentItr.hasNext()) {
        jsonPersonNodeSilent = nameNodesSilentItr.next();
        assertEquals("Exist query solution returned is incorrect", "http://example.org/alice",
                jsonPersonNodeSilent.path("person").path("value").asText());
    }
}

From source file:controllers.EntryController.java

@Transactional
@BodyParser.Of(BodyParser.Json.class)
public Result enter() {
    Entry entry = new Entry();
    ArrayList<String> missing = new ArrayList<String>();
    JsonNode json = request().body().asJson();
    Logger.debug("GOT: " + json.toString());
    boolean retServerId = false;
    JsonNode value;
    value = json.findValue("tech_id");
    if (value == null) {
        missing.add("tech_id");
    } else {//  w  w w  . j a v  a2  s  .c o m
        entry.tech_id = value.intValue();
    }
    value = json.findValue("date");
    if (value == null) {
        missing.add("date");
    } else {
        entry.entry_time = new Date(value.longValue());
    }
    value = json.findValue("server_id");
    if (value != null) {
        entry.id = value.longValue();
        retServerId = true;
        Entry existing;
        if (entry.id > 0) {
            existing = Entry.find.byId(entry.id);
            existing.entry_time = entry.entry_time;
            existing.tech_id = entry.tech_id;
        } else {
            existing = Entry.findByDate(entry.tech_id, entry.entry_time);
        }
        if (existing != null) {
            entry = existing;
        }
    }
    int truck_number;
    String license_plate;
    value = json.findValue("truck_number");
    if (value != null) {
        truck_number = value.intValue();
    } else {
        truck_number = 0;
    }
    value = json.findValue("license_plate");
    if (value != null) {
        license_plate = value.textValue();
    } else {
        license_plate = null;
    }
    if (truck_number == 0 && license_plate == null) {
        missing.add("truck_number");
        missing.add("license_plate");
    } else {
        // Note: I don't call Version.inc(Version.VERSION_TRUCK) intentionally.
        // The reason is that other techs don't need to know about a local techs truck updates.
        Truck truck = Truck.add(truck_number, license_plate, entry.tech_id);
        entry.truck_id = truck.id;
    }
    value = json.findValue("project_id");
    if (value == null) {
        missing.add("project_id");
    } else {
        entry.project_id = value.longValue();
    }
    value = json.findValue("status");
    if (value != null) {
        entry.status = Entry.Status.from(value.textValue());
    }
    value = json.findValue("address_id");
    if (value == null) {
        value = json.findValue("address");
        if (value == null) {
            missing.add("address_id");
        } else {
            String address = value.textValue().trim();
            if (address.length() > 0) {
                try {
                    Company company = Company.parse(address);
                    Company existing = Company.has(company);
                    if (existing != null) {
                        company = existing;
                    } else {
                        company.created_by = entry.tech_id;
                        company.save();
                        Version.inc(Version.VERSION_COMPANY);
                    }
                    entry.company_id = company.id;
                } catch (Exception ex) {
                    return badRequest2("address: " + ex.getMessage());
                }
            } else {
                return badRequest2("address");
            }
        }
    } else {
        entry.company_id = value.longValue();
    }
    value = json.findValue("equipment");
    if (value != null) {
        if (value.getNodeType() != JsonNodeType.ARRAY) {
            Logger.error("Expected array for element 'equipment'");
        } else {
            int collection_id;
            if (entry.equipment_collection_id > 0) {
                collection_id = (int) entry.equipment_collection_id;
                EntryEquipmentCollection.deleteByCollectionId(entry.equipment_collection_id);
            } else {
                collection_id = Version.inc(Version.NEXT_EQUIPMENT_COLLECTION_ID);
            }
            boolean newEquipmentCreated = false;
            Iterator<JsonNode> iterator = value.elements();
            while (iterator.hasNext()) {
                JsonNode ele = iterator.next();
                EntryEquipmentCollection collection = new EntryEquipmentCollection();
                collection.collection_id = (long) collection_id;
                JsonNode subvalue = ele.findValue("equipment_id");
                if (subvalue == null) {
                    subvalue = ele.findValue("equipment_name");
                    if (subvalue == null) {
                        missing.add("equipment_id");
                        missing.add("equipment_name");
                    } else {
                        String name = subvalue.textValue();
                        List<Equipment> equipments = Equipment.findByName(name);
                        Equipment equipment;
                        if (equipments.size() == 0) {
                            equipment = new Equipment();
                            equipment.name = name;
                            equipment.created_by = entry.tech_id;
                            equipment.save();
                        } else {
                            if (equipments.size() > 1) {
                                Logger.error("Too many equipments found with name: " + name);
                            }
                            equipment = equipments.get(0);
                        }
                        collection.equipment_id = equipment.id;
                        newEquipmentCreated = true;
                    }
                } else {
                    collection.equipment_id = subvalue.longValue();
                }
                collection.save();
            }
            entry.equipment_collection_id = collection_id;
            if (newEquipmentCreated) {
                Version.inc(Version.VERSION_EQUIPMENT);
            }
        }
    }
    value = json.findValue("picture");
    if (value != null) {
        if (value.getNodeType() != JsonNodeType.ARRAY) {
            Logger.error("Expected array for element 'picture'");
        } else {
            int collection_id;
            if (entry.picture_collection_id > 0) {
                collection_id = (int) entry.picture_collection_id;
                PictureCollection.deleteByCollectionId(entry.picture_collection_id, null);
            } else {
                collection_id = Version.inc(Version.NEXT_PICTURE_COLLECTION_ID);
            }
            Iterator<JsonNode> iterator = value.elements();
            while (iterator.hasNext()) {
                JsonNode ele = iterator.next();
                PictureCollection collection = new PictureCollection();
                collection.collection_id = (long) collection_id;
                JsonNode subvalue = ele.findValue("note");
                if (subvalue != null) {
                    collection.note = subvalue.textValue();
                }
                subvalue = ele.findValue("filename");
                if (subvalue == null) {
                    missing.add("filename");
                } else {
                    collection.picture = subvalue.textValue();
                    collection.save();
                }
            }
            entry.picture_collection_id = collection_id;
        }
    }
    value = json.findValue("notes");
    if (value != null) {
        if (value.getNodeType() != JsonNodeType.ARRAY) {
            Logger.error("Expected array for element 'notes'");
        } else {
            int collection_id;
            if (entry.note_collection_id > 0) {
                collection_id = (int) entry.note_collection_id;
                EntryNoteCollection.deleteByCollectionId(entry.note_collection_id);
            } else {
                collection_id = Version.inc(Version.NEXT_NOTE_COLLECTION_ID);
            }
            Iterator<JsonNode> iterator = value.elements();
            while (iterator.hasNext()) {
                JsonNode ele = iterator.next();
                EntryNoteCollection collection = new EntryNoteCollection();
                collection.collection_id = (long) collection_id;
                JsonNode subvalue = ele.findValue("id");
                if (subvalue == null) {
                    subvalue = ele.findValue("name");
                    if (subvalue == null) {
                        missing.add("note:id, note:name");
                    } else {
                        String name = subvalue.textValue();
                        List<Note> notes = Note.findByName(name);
                        if (notes == null || notes.size() == 0) {
                            missing.add("note:" + name);
                        } else if (notes.size() > 1) {
                            Logger.error("Too many notes with name: " + name);
                            missing.add("note:" + name);
                        } else {
                            collection.note_id = notes.get(0).id;
                        }
                    }
                } else {
                    collection.note_id = subvalue.longValue();
                }
                subvalue = ele.findValue("value");
                if (value == null) {
                    missing.add("note:value");
                } else {
                    collection.note_value = subvalue.textValue();
                }
                collection.save();
            }
            entry.note_collection_id = collection_id;
        }
    }
    if (missing.size() > 0) {
        return missingRequest(missing);
    }
    if (entry.id != null && entry.id > 0) {
        entry.update();
        Logger.debug("Updated entry " + entry.id);
    } else {
        entry.save();
        Logger.debug("Created new entry " + entry.id);
    }
    long ret_id;
    if (retServerId) {
        ret_id = entry.id;
    } else {
        ret_id = 0;
    }
    return ok(Long.toString(ret_id));
}

From source file:org.walkmod.conf.providers.yml.AddTransformationYMLAction.java

@Override
public void doAction(JsonNode chainsNode) throws Exception {

    ArrayNode transformationsNode = null;

    boolean isMultiModule = chainsNode.has("modules");
    ObjectMapper mapper = provider.getObjectMapper();
    if (!isMultiModule) {
        boolean validChainName = chain != null && !"".equals(chain) && !"default".equals(chain);
        if (!chainsNode.has("chains")) {
            if (chainsNode.has("transformations")) {
                JsonNode aux = chainsNode.get("transformations");
                if (aux.isArray()) {
                    transformationsNode = (ArrayNode) aux;
                }/*from w  w w  .j  ava 2s  .c om*/

                if (!validChainName) {
                    ObjectNode auxRoot = (ObjectNode) chainsNode;
                    if (transformationsNode == null) {
                        transformationsNode = new ArrayNode(mapper.getNodeFactory());
                    }
                    auxRoot.set("transformations", transformationsNode);
                } else {
                    // reset the root
                    chainsNode = new ObjectNode(mapper.getNodeFactory());
                    ObjectNode auxRoot = (ObjectNode) chainsNode;

                    // the default chain list added
                    ObjectNode chainObject = new ObjectNode(mapper.getNodeFactory());
                    chainObject.set("name", new TextNode("default"));
                    chainObject.set("transformations", transformationsNode);
                    ArrayNode chainsListNode = new ArrayNode(mapper.getNodeFactory());

                    // the requested chain added
                    ObjectNode newChain = new ObjectNode(mapper.getNodeFactory());
                    newChain.set("name", new TextNode(chain));
                    if (path != null && !"".equals(path.trim())) {

                        ObjectNode readerNode = new ObjectNode(mapper.getNodeFactory());
                        newChain.set("reader", readerNode);

                        populateWriterReader(readerNode, path, null, null, null, null);

                        ObjectNode writerNode = new ObjectNode(mapper.getNodeFactory());
                        newChain.set("writer", writerNode);
                        populateWriterReader(writerNode, path, null, null, null, null);
                    }

                    transformationsNode = new ArrayNode(mapper.getNodeFactory());
                    newChain.set("transformations", transformationsNode);

                    if (before == null || !"default".equals(before)) {
                        chainsListNode.add(chainObject);
                    }
                    chainsListNode.add(newChain);
                    if (before != null && "default".equals(before)) {
                        chainsListNode.add(chainObject);
                    }
                    auxRoot.set("chains", chainsListNode);

                }
            } else {
                ObjectNode auxRoot = (ObjectNode) chainsNode;
                transformationsNode = new ArrayNode(mapper.getNodeFactory());
                boolean writeChainInfo = validChainName;
                if (!writeChainInfo) {
                    writeChainInfo = path != null && !"".equals(path.trim());
                    chain = "default";
                }
                if (writeChainInfo) {
                    ArrayNode auxChainsList = new ArrayNode(mapper.getNodeFactory());
                    ObjectNode aux = new ObjectNode(mapper.getNodeFactory());
                    auxChainsList.add(aux);
                    aux.set("name", new TextNode(chain));
                    if (path != null && !"".equals(path.trim())) {

                        ObjectNode readerNode = new ObjectNode(mapper.getNodeFactory());
                        aux.set("reader", readerNode);
                        populateWriterReader(readerNode, path, null, null, null, null);

                    }
                    auxRoot.set("chains", auxChainsList);
                    if (path != null && !"".equals(path.trim())) {

                        ObjectNode writerNode = new ObjectNode(mapper.getNodeFactory());
                        aux.set("writer", writerNode);
                        populateWriterReader(writerNode, path, null, null, null, null);
                    }

                    auxRoot = aux;
                }
                auxRoot.set("transformations", transformationsNode);
            }

        } else {
            if (validChainName) {
                JsonNode aux = chainsNode.get("chains");
                boolean found = false;
                if (aux.isArray()) {
                    Iterator<JsonNode> it = aux.elements();
                    while (it.hasNext()) {
                        JsonNode next = it.next();
                        if (next.has("name")) {
                            String id = next.get("name").asText();
                            if (chain.equals(id)) {
                                found = true;
                                if (next.has("transformations")) {
                                    JsonNode auxTrans = next.get("transformations");
                                    if (auxTrans.isArray()) {
                                        transformationsNode = (ArrayNode) auxTrans;
                                    } else {
                                        throw new Exception("The chain [" + chain
                                                + "] does not have a valid transformations node");
                                    }
                                } else if (next.isObject()) {
                                    ObjectNode auxNext = (ObjectNode) next;
                                    transformationsNode = new ArrayNode(mapper.getNodeFactory());
                                    auxNext.set("transformations", transformationsNode);
                                } else {
                                    throw new Exception(
                                            "The chain [" + chain + "] does not have a valid structure");
                                }
                            }
                        }

                    }
                    if (!found) {
                        ChainConfig chainCfg = new ChainConfigImpl();
                        chainCfg.setName(chain);
                        WalkerConfig walkerCfg = new WalkerConfigImpl();
                        List<TransformationConfig> transfs = new LinkedList<TransformationConfig>();
                        transfs.add(transformationCfg);
                        walkerCfg.setTransformations(transfs);
                        chainCfg.setWalkerConfig(walkerCfg);
                        provider.addChainConfig(chainCfg, false, before);
                        return;
                    }
                }
            } else {

                ObjectNode node = new ObjectNode(mapper.getNodeFactory());
                node.set("name", new TextNode(chain));
                ArrayNode transNodes = new ArrayNode(mapper.getNodeFactory());

                node.set("transformations", transNodes);
                ArrayNode array = (ArrayNode) chainsNode.get("chains");
                array.add(node);

                ObjectNode transformationNode = new ObjectNode(mapper.getNodeFactory());
                transNodes.add(transformationNode);

                createTransformation(transformationNode, transformationCfg);

                return;
            }
        }
        if (transformationsNode != null) {
            ObjectNode transformationNode = new ObjectNode(mapper.getNodeFactory());

            if (order != null && order < transformationsNode.size()) {
                transformationsNode.insert(order, transformationNode);
            } else {
                transformationsNode.add(transformationNode);
            }

            createTransformation(transformationNode, transformationCfg);
            provider.write(chainsNode);
            return;
        } else if (chain != null) {
            throw new Exception("The chain [" + chain + "] does not exists");
        }
    }

}