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

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

Introduction

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

Prototype

@Override
public ArrayNode createArrayNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:org.onosproject.sse.SseTopologyViewMessages.java

private ObjectNode json(String id, String type, Prop... props) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode result = mapper.createObjectNode().put("id", id).put("type", type);
    ObjectNode pnode = mapper.createObjectNode();
    ArrayNode porder = mapper.createArrayNode();
    for (Prop p : props) {
        porder.add(p.key);//from  w w  w.  j  av a 2  s  .c  om
        pnode.put(p.key, p.value);
    }
    result.set("propOrder", porder);
    result.set("props", pnode);
    return result;
}

From source file:com.ikanow.aleph2.data_model.utils.TestJsonUtils.java

@Test
public void test_foldTuple() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    LinkedHashMap<String, Object> test1 = new LinkedHashMap<String, Object>();
    test1.put("long", 10L);
    test1.put("double", 1.1);
    test1.put("string", "val");
    test1.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");

    final JsonNode j1 = JsonUtils.foldTuple(test1, mapper, Optional.empty());
    assertEquals("{\"misc\":true,\"long\":10,\"string\":\"val\",\"double\":1.1}", j1.toString());

    LinkedHashMap<String, Object> test2 = new LinkedHashMap<String, Object>();
    test2.put("misc", false);
    test2.put("long", 10L);
    test2.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");
    test2.put("double", 1.1);
    test2.put("string", "val");

    final JsonNode j2 = JsonUtils.foldTuple(test2, mapper, Optional.of("json"));
    assertEquals("{\"misc\":false,\"long\":10,\"string\":\"val\",\"double\":1.1}", j2.toString());

    LinkedHashMap<String, Object> test3 = new LinkedHashMap<String, Object>();
    test3.put("long", mapper.createObjectNode());
    test3.put("double", mapper.createArrayNode());
    test3.put("string", BeanTemplateUtils.build(TestBean.class).with("test1", 4).done().get());
    test3.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");

    final JsonNode j3 = JsonUtils.foldTuple(test3, mapper, Optional.of("json"));
    assertEquals("{\"misc\":true,\"long\":{},\"string\":{\"test1\":4},\"double\":[]}", j3.toString());

    LinkedHashMap<String, Object> test4 = new LinkedHashMap<String, Object>();
    test4.put("misc", BigDecimal.ONE);
    test4.put("long", (int) 10);
    test4.put("double", (float) 1.1);
    test4.put("json", "{\"misc\":true,\"long\":1, \"string\":\"\"}");
    test4.put("string", "val");

    final JsonNode j4 = JsonUtils.foldTuple(test4, mapper, Optional.of("json"));
    assertEquals("{\"misc\":1,\"long\":10,\"string\":\"val\",\"double\":1.1}",
            j4.toString().replaceFirst("1[.]1[0]{6,}[0-9]+", "1.1"));

    try {/*from w  w  w.  j  av  a 2  s  .c  o  m*/
        test4.put("json", "{\"misc\":true,\"long\":1, string\":\"\"}"); // (Added json error)
        JsonUtils.foldTuple(test4, mapper, Optional.of("json"));
        fail("Should have thrown JSON exception");
    } catch (Exception e) {
    } // json error, check

    new JsonUtils(); // (just for coverage)      
}

From source file:com.rusticisoftware.tincan.ActivityDefinition.java

@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectMapper mapper = Mapper.getInstance();
    ObjectNode node = mapper.createObjectNode();
    if (this.name != null) {
        node.put("name", this.getName().toJSONNode(version));
    }// ww  w  .ja v  a  2s.  c o  m
    if (this.description != null) {
        node.put("description", this.getDescription().toJSONNode(version));
    }
    if (this.type != null) {
        node.put("type", this.getType().toString());
    }
    if (this.moreInfo != null) {
        node.put("moreInfo", this.getMoreInfo().toString());
    }
    if (this.extensions != null) {
        node.put("extensions", this.getExtensions().toJSONNode(version));
    }
    if (this.interactionType != null) {
        node.put("interactionType", this.getInteractionType().toString());

        switch (this.interactionType) {
        case CHOICE:
        case SEQUENCING:
            if (this.choices != null && this.choices.size() > 0) {
                ArrayNode choices = mapper.createArrayNode();
                node.put("choices", choices);

                for (InteractionComponent ic : this.getChoices()) {
                    choices.add(ic.toJSONNode(version));
                }
            }
            break;

        case LIKERT:
            if (this.scale != null && this.scale.size() > 0) {
                ArrayNode scale = mapper.createArrayNode();
                node.put("scale", scale);

                for (InteractionComponent ic : this.getScale()) {
                    scale.add(ic.toJSONNode(version));
                }
            }
            break;

        case MATCHING:
            if (this.source != null && this.source.size() > 0) {
                ArrayNode source = mapper.createArrayNode();
                node.put("source", source);

                for (InteractionComponent ic : this.getSource()) {
                    source.add(ic.toJSONNode(version));
                }
            }
            if (this.target != null && this.target.size() > 0) {
                ArrayNode target = mapper.createArrayNode();
                node.put("target", target);

                for (InteractionComponent ic : this.getTarget()) {
                    target.add(ic.toJSONNode(version));
                }
            }
            break;

        case PERFORMANCE:
            if (this.steps != null && this.steps.size() > 0) {
                ArrayNode steps = mapper.createArrayNode();
                node.put("steps", steps);

                for (InteractionComponent ic : this.getSteps()) {
                    steps.add(ic.toJSONNode(version));
                }
            }
            break;

        case TRUE_FALSE:
        case FILL_IN:
        case NUMERIC:
        case OTHER:
            break;
        }
    }
    if (this.correctResponsesPattern != null && this.correctResponsesPattern.size() > 0) {
        ArrayNode responses = mapper.createArrayNode();
        node.put("correctResponsesPattern", responses);

        for (String resp : this.getCorrectResponsesPattern()) {
            responses.add(resp);
        }
    }
    return node;
}

From source file:com.ikanow.aleph2.v1.document_db.utils.TestJsonNodeBsonUtils.java

@Test
public void test_mapWritableWrapper() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final BasicDBObject m1 = new BasicDBObject();

    m1.put("test1", true);

    final BasicDBObject m2 = new BasicDBObject();
    m2.put("nested", m1);
    m2.put("test2", "test2");

    final BasicDBList a1 = new BasicDBList();
    a1.add(4);/*from   w  w w .  j a  va  2s.com*/
    a1.add(5);

    final BasicDBList a2 = new BasicDBList();
    a2.add(m1);
    a2.add(m1);

    m2.put("array", a2);
    m1.put("array", a1);

    final JsonNode j2 = JsonNodeBsonUtils.from(m2);

    assertEquals(3, j2.size());

    // Check j's contents
    assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals("test2", j2.get("test2").asText());

    final JsonNode j1 = j2.get("nested");
    assertEquals(2, j1.size());
    final JsonNode j1b = JsonNodeBsonUtils.from(m1);
    assertTrue("entrySet wrong: " + j1b.toString(), "{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString())
            || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet)
    final ArrayNode an = mapper.createArrayNode();
    an.add(mapper.convertValue(4, JsonNode.class));
    an.add(mapper.convertValue(5, JsonNode.class));
    assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));

    // OK, now test adding:

    assertEquals(2, j1.size());

    final ObjectNode o1 = (ObjectNode) j1;
    o1.put("added", "added_this");

    final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1;
    assertFalse(o1c.containsKey("not_present"));
    assertTrue(o1c.containsKey("added"));
    assertTrue(o1c.containsKey("test1"));

    assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals(
            Arrays.asList(mapper.convertValue(true, JsonNode.class), an,
                    mapper.convertValue("added_this", JsonNode.class)),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));
    assertTrue(j1.toString().contains("added_this"));
    assertTrue(j1.toString().contains("4,5"));

    assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added"));

    assertEquals(3, j1.size());

    // OK now test removing:

    assertEquals(null, o1.remove("not_present"));
    assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1"));
    assertEquals(2, o1.size());
    ObjectNode o1b = o1.remove(Arrays.asList("added", "array"));
    assertEquals(0, o1.size());
    assertEquals(0, o1b.size());

    o1.setAll(JsonNodeBsonUtils.from(m1)); // will be minus one object
    assertEquals(2, o1.size());
    assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class)));
    assertFalse(o1c.containsValue("banana"));

    final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeBsonUtils.from(m2);
    assertFalse(o2.isEmpty());
    assertTrue(o2.containsKey("array"));
    assertFalse(o2.containsValue("array"));
    assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class)));
    assertEquals(TextNode.class, o2.remove("test2").getClass());
    assertEquals(2, o2.size());
    o2.removeAll();
    assertEquals(0, o2.size());
}

From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

public static ObjectNode createSchemaDesignObjectNode(final ObjectMapper objectMapper, final Schema schema) {

    final Context context = schema.getContext();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final ObjectNode rootNode = objectMapper.createObjectNode();

    final URI schemaUri = schema.getUri();
    final Prototype prototype = schemaLoader.getPrototype(schemaUri);

    rootNode.put(PropertyName.uri.name(), syntaxLoader.formatSyntaxValue(schemaUri));
    rootNode.put(PropertyName.title.name(), schema.getTitle());
    rootNode.put(PropertyName.description.name(), schema.getDescription());
    rootNode.put(PropertyName.version.name(), schema.getVersion());

    final String titleSlotName = getTitleSlotName(schemaUri, schemaLoader);
    if (titleSlotName != null) {
        rootNode.put(PropertyName.titleSlotName.name(), titleSlotName);
    }//from  w  w  w  . j a v a2  s.c  o  m

    final UniqueName uniqueName = schema.getUniqueName();
    final ObjectNode uniqueNameNode = objectMapper.createObjectNode();
    uniqueNameNode.put(PropertyName.fullName.name(), uniqueName.getFullName());
    uniqueNameNode.put(PropertyName.namespace.name(), uniqueName.getNamespace());
    uniqueNameNode.put(PropertyName.localName.name(), uniqueName.getLocalName());
    rootNode.put(PropertyName.uniqueName.name(), uniqueNameNode);

    final Set<URI> declaredBaseSchemaUris = prototype.getDeclaredBaseSchemaUris();
    if (declaredBaseSchemaUris != null && !declaredBaseSchemaUris.isEmpty()) {
        final Set<URI> addedBaseSchemaUris = new LinkedHashSet<>();
        final ArrayNode baseSchemasNode = objectMapper.createArrayNode();
        rootNode.put(PropertyName.baseSchemas.name(), baseSchemasNode);

        for (final URI baseSchemaUri : declaredBaseSchemaUris) {
            if (!addedBaseSchemaUris.contains(baseSchemaUri)) {
                final ObjectNode baseSchemaNode = buildSchemaNode(objectMapper, baseSchemaUri, schemaLoader,
                        addedBaseSchemaUris);
                baseSchemasNode.add(baseSchemaNode);
                addedBaseSchemaUris.add(baseSchemaUri);
            }
        }
    }

    final Set<String> keySlotNames = prototype.getDeclaredKeySlotNames();
    if (keySlotNames != null && !keySlotNames.isEmpty()) {
        final ArrayNode keyPropertyNamesNode = objectMapper.createArrayNode();

        for (final String keySlotName : keySlotNames) {
            keyPropertyNamesNode.add(keySlotName);
        }

        if (keyPropertyNamesNode.size() > 0) {
            rootNode.put(PropertyName.keyPropertyNames.name(), keyPropertyNamesNode);
        }
    }

    final Set<String> allKeySlotNames = prototype.getAllKeySlotNames();
    final ArrayNode allKeySlotNamesNode = objectMapper.createArrayNode();
    rootNode.put(PropertyName.allKeySlotNames.name(), allKeySlotNamesNode);

    final ObjectNode keySlotMap = objectMapper.createObjectNode();
    rootNode.put(PropertyName.keys.name(), keySlotMap);

    final String uriSlotName = PropertyName.uri.name();
    if (allKeySlotNames.contains(uriSlotName)) {
        allKeySlotNamesNode.add(uriSlotName);

        final ObjectNode slot = createSlot(objectMapper, prototype, uriSlotName);
        keySlotMap.put(uriSlotName, slot);
    }

    for (final String keySlotName : allKeySlotNames) {
        if (!Document.SLOT_NAME_URI.equals(keySlotName)) {
            allKeySlotNamesNode.add(keySlotName);

            final ObjectNode slot = createSlot(objectMapper, prototype, keySlotName);
            keySlotMap.put(keySlotName, slot);
        }
    }

    rootNode.put(PropertyName.keyCount.name(), keySlotMap.size());

    final SortedSet<String> allSlotNames = prototype.getAllSlotNames();

    if (allSlotNames != null && !allSlotNames.isEmpty()) {

        final ObjectNode slotMapNode = objectMapper.createObjectNode();
        rootNode.put(PropertyName.slots.name(), slotMapNode);

        final ArrayNode propertyNamesNode = objectMapper.createArrayNode();

        for (final String slotName : allSlotNames) {
            final ProtoSlot protoSlot = prototype.getProtoSlot(slotName);
            if (protoSlot instanceof LinkProtoSlot) {
                continue;
            }

            if (allKeySlotNames.contains(slotName)) {
                // Skip key slots (handled separately)
                continue;
            }

            if (protoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                propertyNamesNode.add(slotName);
            }

            final ObjectNode slotNode = createSlot(objectMapper, prototype, slotName);

            if (slotNode != null) {
                slotMapNode.put(slotName, slotNode);
            }

        }
        if (propertyNamesNode.size() > 0) {
            rootNode.put(PropertyName.propertyNames.name(), propertyNamesNode);
        }

        rootNode.put(PropertyName.slotCount.name(), slotMapNode.size());
    }

    final Set<String> comparablePropertyNames = prototype.getComparableSlotNames();
    if (comparablePropertyNames != null && !comparablePropertyNames.isEmpty()) {
        final ArrayNode comparablePropertyNamesNode = objectMapper.createArrayNode();

        for (final String comparablePropertyName : comparablePropertyNames) {
            comparablePropertyNamesNode.add(comparablePropertyName);
        }

        if (comparablePropertyNamesNode.size() > 0) {
            rootNode.put(PropertyName.comparablePropertyNames.name(), comparablePropertyNamesNode);
        }
    }

    final Collection<LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots().values();
    if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) {
        final ArrayNode linkNamesNode = objectMapper.createArrayNode();
        final ObjectNode linksMapNode = objectMapper.createObjectNode();
        rootNode.put(PropertyName.links.name(), linksMapNode);

        for (final LinkProtoSlot linkProtoSlot : linkProtoSlots) {

            if (linkProtoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                linkNamesNode.add(linkProtoSlot.getName());
            }

            final ObjectNode linkNode = objectMapper.createObjectNode();

            String linkTitle = linkProtoSlot.getTitle();
            if (linkTitle == null) {
                linkTitle = linkProtoSlot.getName();
            }

            linkNode.put(PropertyName.name.name(), linkProtoSlot.getName());
            linkNode.put(PropertyName.title.name(), linkTitle);

            final Method method = linkProtoSlot.getMethod();
            final URI linkRelationUri = linkProtoSlot.getLinkRelationUri();
            final URI declaringSchemaUri = linkProtoSlot.getDeclaringSchemaUri();

            linkNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));

            final Keys linkRelationKeys = context.getApiLoader().buildDocumentKeys(linkRelationUri,
                    schemaLoader.getLinkRelationSchemaUri());
            final LinkRelation linkRelation = context.getModel(linkRelationKeys,
                    schemaLoader.getLinkRelationDimensions());

            linkNode.put(PropertyName.relationTitle.name(), linkRelation.getTitle());
            linkNode.put(PropertyName.description.name(), linkProtoSlot.getDescription());
            linkNode.put(PropertyName.method.name(), method.getProtocolGivenName());
            linkNode.put(PropertyName.declaringSchemaUri.name(),
                    syntaxLoader.formatSyntaxValue(declaringSchemaUri));

            URI requestSchemaUri = linkProtoSlot.getRequestSchemaUri();
            if (schemaLoader.getDocumentSchemaUri().equals(requestSchemaUri)) {
                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)
                        || SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    requestSchemaUri = schemaUri;
                }
            }

            if (requestSchemaUri == null && method == Method.Save) {
                requestSchemaUri = schemaUri;
            }

            if (requestSchemaUri != null) {
                linkNode.put(PropertyName.requestSchemaUri.name(),
                        syntaxLoader.formatSyntaxValue(requestSchemaUri));

                final Schema requestSchema = schemaLoader.load(requestSchemaUri);
                if (requestSchema != null) {
                    linkNode.put(PropertyName.requestSchemaTitle.name(), requestSchema.getTitle());
                }
            }

            URI responseSchemaUri = linkProtoSlot.getResponseSchemaUri();
            if (schemaLoader.getDocumentSchemaUri().equals(responseSchemaUri)) {
                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)
                        || SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    responseSchemaUri = schemaUri;
                }
            }

            if (responseSchemaUri != null) {
                linkNode.put(PropertyName.responseSchemaUri.name(),
                        syntaxLoader.formatSyntaxValue(responseSchemaUri));

                final Schema responseSchema = schemaLoader.load(responseSchemaUri);
                if (responseSchema != null) {
                    linkNode.put(PropertyName.responseSchemaTitle.name(), responseSchema.getTitle());
                }
            }

            linksMapNode.put(linkTitle, linkNode);

        }

        if (linkNamesNode.size() > 0) {
            rootNode.put(PropertyName.linkNames.name(), linkNamesNode);
        }

        rootNode.put(PropertyName.linkCount.name(), linksMapNode.size());

    }

    return rootNode;
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.TestJsonNodeWritableUtils.java

@SuppressWarnings("deprecation")
@Test//from w  w w. j  a va  2s  .  c  o  m
public void test_mapWritableWrapper() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final MapWritable m1 = new MapWritable();

    m1.put(new Text("test1"), new BooleanWritable(true));

    final MapWritable m2 = new MapWritable();
    m2.put(new Text("nested"), m1);
    m2.put(new Text("test2"), new Text("test2"));

    final ArrayWritable a1 = new ArrayWritable(IntWritable.class);
    a1.set(new Writable[] { new IntWritable(4), new IntWritable(5) });

    final ArrayWritable a2 = new ArrayWritable(MapWritable.class);
    a2.set(new Writable[] { m1, m1 });

    m2.put(new Text("array"), a2);
    m1.put(new Text("array"), a1);

    final JsonNode j2 = JsonNodeWritableUtils.from(m2);

    assertEquals(3, j2.size());

    // Check j's contents
    assertEquals(Stream.of("nested", "test2", "array").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j2.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals("test2", j2.get("test2").asText());

    final JsonNode j1 = j2.get("nested");
    assertEquals(2, j1.size());
    final JsonNode j1b = JsonNodeWritableUtils.from(m1);
    assertTrue("{\"test1\":true,\"array\":[4,5]}".equals(j1b.toString())
            || "{\"array\":[4,5],\"test1\":true}".equals(j1b.toString())); //(tests entrySet)
    final ArrayNode an = mapper.createArrayNode();
    an.add(mapper.convertValue(4, JsonNode.class));
    an.add(mapper.convertValue(5, JsonNode.class));
    assertEquals(Arrays.asList(mapper.convertValue(true, JsonNode.class), an),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));

    // OK, now test adding:

    assertEquals(2, j1.size());

    final ObjectNode o1 = (ObjectNode) j1;
    o1.put("added", "added_this");

    final ObjectNodeWrapper o1c = (ObjectNodeWrapper) o1;
    assertFalse(o1c.containsKey("not_present"));
    assertTrue(o1c.containsKey("added"));
    assertTrue(o1c.containsKey("test1"));

    assertEquals(Stream.of("test1", "array", "added").sorted().collect(Collectors.toList()),
            Optionals.streamOf(j1.fieldNames(), false).sorted().collect(Collectors.toList()));
    assertEquals(
            Arrays.asList(mapper.convertValue(true, JsonNode.class), an,
                    mapper.convertValue("added_this", JsonNode.class)),
            Optionals.streamOf(((ObjectNode) j1).elements(), false).collect(Collectors.toList()));
    assertTrue(j1.toString().contains("added_this"));
    assertTrue(j1.toString().contains("4,5"));

    assertEquals(mapper.convertValue("added_this", JsonNode.class), j1.get("added"));

    assertEquals(3, j1.size());

    // OK now test removing:

    assertEquals(null, o1.remove("not_present"));
    assertEquals(mapper.convertValue(true, JsonNode.class), o1.remove("test1"));
    assertEquals(2, o1.size());
    ObjectNode o1b = o1.remove(Arrays.asList("added", "array"));
    assertEquals(0, o1.size());
    assertEquals(0, o1b.size());

    o1.putAll(JsonNodeWritableUtils.from(m1)); // will be minus one object
    assertEquals(2, o1.size());
    assertTrue(o1c.containsValue(mapper.convertValue(true, JsonNode.class)));
    assertFalse(o1c.containsValue("banana"));

    final ObjectNodeWrapper o2 = (ObjectNodeWrapper) JsonNodeWritableUtils.from(m2);
    assertFalse(o2.isEmpty());
    assertTrue(o2.containsKey("array"));
    assertFalse(o2.containsValue("array"));
    assertTrue(o2.containsValue(mapper.convertValue("test2", JsonNode.class)));
    assertEquals(TextNode.class, o2.remove("test2").getClass());
    assertEquals(2, o2.size());
    o2.removeAll();
    assertEquals(0, o2.size());
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ArrayNode buildReferencesArrayNode(final ObjectMapper objectMapper,
        final Map<URI, ObjectNode> schemaNodes, final Map<URI, LinkRelation> linkRelationCache,
        final Resource resource, final Prototype defaultPrototype) {

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();

    final URI defaultSchemaUri = (defaultPrototype != null) ? defaultPrototype.getSchemaUri() : null;
    final String defaultSchemaName = (defaultPrototype != null)
            ? defaultPrototype.getUniqueName().getLocalName()
            : null;//from w  w  w.j  a  v  a 2 s  .  c  o m

    final ArrayNode referencesNode = objectMapper.createArrayNode();

    final ConcurrentHashMap<URI, LinkTemplate> referenceTemplates = resource.getReferenceTemplates();
    final Set<URI> referenceRelationUris = referenceTemplates.keySet();

    if (referenceTemplates != null && !referenceTemplates.isEmpty()) {

        String selfResponseSchemaName = null;

        List<String> resourceParameterList = null;
        final UriTemplate uriTemplate = resource.getUriTemplate();
        final String[] parameterNames = uriTemplate.getParameterNames();
        if (parameterNames != null && parameterNames.length > 0) {

            resourceParameterList = new ArrayList<>();

            for (int i = 0; i < parameterNames.length; i++) {
                final String parameterName = parameterNames[i];

                URI keyedSchemaUri = null;

                if (defaultPrototype != null) {
                    final Set<String> allKeySlotNames = defaultPrototype.getAllKeySlotNames();
                    if (allKeySlotNames != null && allKeySlotNames.contains(parameterName)) {
                        keyedSchemaUri = defaultSchemaUri;
                    }
                }

                if (keyedSchemaUri == null) {

                    final Set<URI> referenceLinkRelationUris = resource
                            .getReferenceLinkRelationUris(Method.Get);
                    if (referenceLinkRelationUris != null && !referenceLinkRelationUris.isEmpty()) {
                        for (URI linkRelationUri : referenceLinkRelationUris) {
                            final LinkTemplate referenceTemplate = referenceTemplates.get(linkRelationUri);
                            final URI responseSchemaUri = referenceTemplate.getResponseSchemaUri();
                            final Prototype responseSchemaPrototype = schemaLoader
                                    .getPrototype(responseSchemaUri);
                            if (responseSchemaPrototype != null) {
                                final Set<String> allKeySlotNames = responseSchemaPrototype
                                        .getAllKeySlotNames();
                                if (allKeySlotNames != null && allKeySlotNames.contains(parameterName)) {
                                    keyedSchemaUri = responseSchemaUri;
                                    break;
                                }
                            }
                        }
                    }
                }

                String parameterTypeString = "?";

                if (keyedSchemaUri != null) {

                    final Prototype keyedPrototype = schemaLoader.getPrototype(keyedSchemaUri);
                    final ProtoSlot keyProtoSlot = keyedPrototype.getProtoSlot(parameterName);
                    if (keyProtoSlot instanceof PropertyProtoSlot) {
                        final PropertyProtoSlot keyPropertyProtoSlot = (PropertyProtoSlot) keyProtoSlot;
                        final ValueType parameterValueType = keyPropertyProtoSlot.getValueType();
                        final Type parameterHeapType = keyPropertyProtoSlot.getHeapValueType();
                        switch (parameterValueType) {
                        case Text: {
                            if (!String.class.equals(parameterHeapType)) {
                                final Class<?> syntaxClass = (Class<?>) parameterHeapType;
                                parameterTypeString = syntaxClass.getSimpleName();
                            } else {
                                parameterTypeString = parameterValueType.name();
                            }

                            break;
                        }
                        case SingleSelect: {
                            final Class<?> choicesEnumClass = (Class<?>) parameterHeapType;

                            if (choicesEnumClass.isEnum()) {
                                parameterTypeString = choicesEnumClass.getSimpleName();
                            } else {
                                // ?
                                parameterTypeString = parameterValueType.name();
                            }

                            break;
                        }
                        default: {
                            parameterTypeString = parameterValueType.name();
                            break;
                        }
                        }
                    }

                }

                resourceParameterList.add(parameterTypeString + " " + parameterName);
            }
        }

        for (final Method method : Method.values()) {
            for (final URI linkRelationUri : referenceRelationUris) {

                final LinkTemplate referenceTemplate = referenceTemplates.get(linkRelationUri);
                final LinkRelation linkRelation = getLinkRelation(linkRelationCache, linkRelationUri);

                if (method != linkRelation.getMethod()) {
                    continue;
                }

                final ObjectNode referenceNode = objectMapper.createObjectNode();
                referencesNode.add(referenceNode);

                referenceNode.put(PropertyName.method.name(), method.getProtocolGivenName());
                referenceNode.put(PropertyName.rel.name(), syntaxLoader.formatSyntaxValue(linkRelationUri));

                final String relationTitle = linkRelation.getTitle();
                referenceNode.put(PropertyName.relationTitle.name(), relationTitle);

                final URI responseSchemaUri = referenceTemplate.getResponseSchemaUri();
                String responseSchemaName = null;
                if (responseSchemaUri != null) {
                    final ObjectNode responseSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                            responseSchemaUri, schemaLoader);
                    referenceNode.put(PropertyName.responseSchema.name(), responseSchemaNode);

                    responseSchemaName = responseSchemaNode
                            .get(SchemaDesignFormatter.PropertyName.localName.name()).asText();
                }

                final URI requestSchemaUri = referenceTemplate.getRequestSchemaUri();

                String requestSchemaName = null;
                if (requestSchemaUri != null) {
                    final ObjectNode requestSchemaNode = getSchemaNode(objectMapper, schemaNodes,
                            requestSchemaUri, schemaLoader);
                    referenceNode.put(PropertyName.requestSchema.name(), requestSchemaNode);

                    requestSchemaName = requestSchemaNode
                            .get(SchemaDesignFormatter.PropertyName.localName.name()).asText();
                }

                final StringBuilder signatureBuilder = new StringBuilder();

                if (responseSchemaName != null) {
                    signatureBuilder.append(responseSchemaName);
                } else {
                    signatureBuilder.append("void");
                }

                signatureBuilder.append(" ");

                String functionName = relationTitle;

                if (SystemLinkRelation.self.getUri().equals(linkRelationUri)) {
                    functionName = "get" + responseSchemaName;
                    selfResponseSchemaName = responseSchemaName;
                } else if (SystemLinkRelation.save.getUri().equals(linkRelationUri)) {
                    functionName = "save" + responseSchemaName;
                } else if (SystemLinkRelation.delete.getUri().equals(linkRelationUri)) {
                    functionName = "delete";
                    if (defaultSchemaName != null) {
                        functionName += defaultSchemaName;
                    } else if (selfResponseSchemaName != null) {
                        functionName += selfResponseSchemaName;
                    }
                }

                signatureBuilder.append(functionName).append(" ( ");

                String parameterString = null;
                if (resourceParameterList != null) {
                    final StringBuilder parameterStringBuilder = new StringBuilder();
                    final int parameterCount = resourceParameterList.size();
                    for (int i = 0; i < parameterCount; i++) {
                        final String parameter = resourceParameterList.get(i);
                        parameterStringBuilder.append(parameter);
                        if (i < parameterCount - 1) {
                            parameterStringBuilder.append(" , ");
                        }
                    }

                    parameterString = parameterStringBuilder.toString();
                    signatureBuilder.append(parameterString);
                }

                if (requestSchemaName != null) {
                    if (StringUtils.isNotBlank(parameterString)) {
                        signatureBuilder.append(" , ");
                    }

                    signatureBuilder.append(requestSchemaName);

                    signatureBuilder.append(" ");

                    final String parameterName = Character.toLowerCase(requestSchemaName.charAt(0))
                            + requestSchemaName.substring(1);
                    signatureBuilder.append(parameterName);
                }

                signatureBuilder.append(" ) ");

                final String signature = signatureBuilder.toString();
                referenceNode.put(PropertyName.signature.name(), signature);
            }

        }

    }

    return referencesNode;
}

From source file:org.apache.asterix.test.common.TestExecutor.java

public void cleanup(String testCase, List<String> badtestcases) throws Exception {
    try {//from   w  ww . java  2  s  .  c o  m
        ArrayList<String> toBeDropped = new ArrayList<>();
        InputStream resultStream = executeQueryService(
                "select dv.DataverseName from Metadata.`Dataverse` as dv;", getEndpoint(Servlets.QUERY_SERVICE),
                OutputFormat.CLEAN_JSON);
        String out = IOUtils.toString(resultStream);
        ObjectMapper om = new ObjectMapper();
        om.setConfig(
                om.getDeserializationConfig().with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT));
        JsonNode result;
        try {
            result = om.readValue(out, ObjectNode.class).get("results");
        } catch (JsonMappingException e) {
            result = om.createArrayNode();
        }
        for (int i = 0; i < result.size(); i++) {
            JsonNode json = result.get(i);
            if (json != null) {
                String dvName = json.get("DataverseName").asText();
                if (!dvName.equals("Metadata") && !dvName.equals("Default")) {
                    toBeDropped.add(dvName);
                }
            }
        }
        if (!toBeDropped.isEmpty()) {
            badtestcases.add(testCase);
            LOGGER.warning(
                    "Last test left some garbage. Dropping dataverses: " + StringUtils.join(toBeDropped, ','));
            StringBuilder dropStatement = new StringBuilder();
            for (String dv : toBeDropped) {
                dropStatement.append("drop dataverse ");
                dropStatement.append(dv);
                dropStatement.append(";\n");
            }
            resultStream = executeQueryService(dropStatement.toString(), getEndpoint(Servlets.QUERY_SERVICE),
                    OutputFormat.CLEAN_JSON);
            ResultExtractor.extract(resultStream);
        }
    } catch (Throwable th) {
        th.printStackTrace();
        throw th;
    }
}

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

public JsonNode constructJSONCollectionMetadata(String... col) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode mNode = mapper.createObjectNode();
    ArrayNode aNode = mapper.createArrayNode();

    for (String c : col) {
        aNode.add(c);//from  w  ww.  jav a  2 s.  c o m
    }
    mNode.withArray("collections").addAll(aNode);
    return mNode;
}

From source file:org.wrml.runtime.format.text.html.WrmldocFormatter.java

protected ObjectNode buildApiNode(final ObjectMapper objectMapper, final Model model) {

    final ObjectNode apiNode = objectMapper.createObjectNode();
    if (!(model instanceof Document)) {
        return apiNode;
    }//  w  ww.  j a  va 2s  .  co m

    final Context context = getContext();

    final Document document = (Document) model;
    final URI uri = document.getUri();
    final ApiLoader apiLoader = context.getApiLoader();
    final ApiNavigator apiNavigator = apiLoader.getParentApiNavigator(uri);
    final Api api = apiNavigator.getApi();
    final Resource endpointResource = apiNavigator.getResource(uri);

    final URI apiUri = api.getUri();

    apiNode.put(PropertyName.uri.name(), apiUri.toString());
    apiNode.put(PropertyName.title.name(), api.getTitle());
    apiNode.put(PropertyName.description.name(), api.getDescription());
    apiNode.put(PropertyName.version.name(), api.getVersion());

    final Map<URI, ObjectNode> schemaNodes = new HashMap<>();
    final Map<URI, LinkRelation> linkRelationCache = new HashMap<>();

    if (document instanceof Api) {

        final Map<UUID, Resource> allResources = apiNavigator.getAllResources();
        final SortedMap<String, Resource> orderedResources = new TreeMap<>();

        for (final Resource resource : allResources.values()) {
            orderedResources.put(resource.getPathText(), resource);
        }

        final ArrayNode allResourcesNode = objectMapper.createArrayNode();
        for (final Resource resource : orderedResources.values()) {
            final ObjectNode resourceNode = buildResourceNode(objectMapper, schemaNodes, linkRelationCache,
                    apiNavigator, resource);
            allResourcesNode.add(resourceNode);
        }

        apiNode.put(PropertyName.allResources.name(), allResourcesNode);
    } else {
        final ObjectNode endpointResourceNode = buildResourceNode(objectMapper, schemaNodes, linkRelationCache,
                apiNavigator, endpointResource);
        apiNode.put(PropertyName.resource.name(), endpointResourceNode);
    }

    return apiNode;
}