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

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

Introduction

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

Prototype

public int size() 

Source Link

Usage

From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java

private void setSecurity(final ObjectNode node, final AbstractAction action) {
    final boolean isSecurityEnabled = node.has("security");
    if (isSecurityEnabled) {
        final JsonNode security = node.get("security");

        if (security.size() == 0) {
            action.disableSecurity();//www  . j  a  v a2  s.  c o m
            return;
        }

        boolean authenticated = security.has("authenticated") && security.get("authenticated").asBoolean(false);
        boolean hasRoles = security.has("roles");

        authenticated = authenticated | hasRoles;

        final ActionSecurityCheck check = new ActionSecurityCheck();
        check.setAuthenticated(authenticated);

        if (hasRoles) {
            final ActionRoleMap.Connector[] connectors = ActionRoleMap.Connector.values();
            final JsonNode roles = security.get("roles");
            check.setRoles(this.resolveSecurityRoles(roles, connectors));
        }

        action.setSecurity(check);

    } else {
        action.disableSecurity();
    }
}

From source file:com.ericsson.eiffel.remrem.publish.config.RabbitMqPropertiesConfig.java

/***
 * Reads Spring Properties and writes RabbitMq properties to RabbitMq instances properties map object.
 */// www  . j a  v  a  2 s  .  co m
private void readSpringProperties() {
    JsonNode rabbitmqInstancesJsonListJsonArray = null;
    final ObjectMapper objMapper = new ObjectMapper();
    try {
        rabbitmqInstancesJsonListJsonArray = objMapper.readTree(rabbitmqInstancesJsonListContent);

        for (int i = 0; i < rabbitmqInstancesJsonListJsonArray.size(); i++) {
            JsonNode rabbitmqInstanceObject = rabbitmqInstancesJsonListJsonArray.get(i);
            String protocol = rabbitmqInstanceObject.get("mp").asText();
            log.info("Configuring RabbitMq instance for Eiffel message protocol: " + protocol);

            RabbitMqProperties rabbitMqProperties = new RabbitMqProperties();
            rabbitMqProperties.setHost(rabbitmqInstanceObject.get("host").asText());
            rabbitMqProperties.setPort(Integer.parseInt(rabbitmqInstanceObject.get("port").asText()));
            rabbitMqProperties.setUsername(rabbitmqInstanceObject.get("username").asText());
            rabbitMqProperties.setPassword(DecryptionUtils
                    .decryptString(rabbitmqInstanceObject.get("password").asText(), jasyptPassword));
            rabbitMqProperties.setTlsVer(rabbitmqInstanceObject.get("tls").asText());
            rabbitMqProperties.setExchangeName(rabbitmqInstanceObject.get("exchangeName").asText());
            rabbitMqProperties.setCreateExchangeIfNotExisting(
                    rabbitmqInstanceObject.get("createExchangeIfNotExisting").asBoolean());
            rabbitMqProperties.setDomainId(rabbitmqInstanceObject.get("domainId").asText());

            rabbitMqPropertiesMap.put(protocol, rabbitMqProperties);
        }
    } catch (Exception e) {
        log.error("Failure when initiating RabbitMq Java Spring properties: " + e.getMessage(), e);
    }
}

From source file:com.turn.shapeshifter.NamedSchemaSerializerTest.java

@Test
public void testSerializeWithEmptyRepeated() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union").useSchema("union_repeated", "Union");
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);/*from   ww  w.  j av  a  2  s  . c  om*/
    Union union = Union.newBuilder().setBoolValue(true).addUnionRepeated(Union.getDefaultInstance()).build();
    JsonNode result = new NamedSchemaSerializer(schema).serialize(union, registry);
    Assert.assertTrue(result.isObject());
    Assert.assertEquals(1, result.size());
    Assert.assertEquals(JsonToken.VALUE_TRUE, result.get("boolValue").asToken());
    Assert.assertEquals(true, result.get("boolValue").asBoolean());
    Assert.assertNull(result.get("unionRepeated"));
}

From source file:de.raion.xmppbot.command.TrelloCommand.java

private void validateConfiguration(final XmppContext context, TrelloConfig config) {

    println("starting validation");

    if (isConfigProper(config)) {

        // https://trello.com/1/members/me?key=substitutewithyourapplicationkey&token=substitutethispartwiththeauthorizationtokenthatyougotfromtheuser

        Client client = Client.create();
        client.addFilter(new LoggingFilter());
        WebResource resource = client//from   w  ww  .j a v a 2s . co  m
                .resource("https://trello.com/1/members/my/boards?boards=open&board_fields=name,shortUrl")
                .queryParam("key", config.getApplicationKey()).queryParam("token", config.getAccessToken());

        println("trying to access board informations");
        ClientResponse response = resource.get(ClientResponse.class);

        if (response.getClientResponseStatus() == Status.OK) {
            println("reading board infos");

            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(response.getEntityInputStream(), JsonNode.class);
                int size = rootNode.size();

                for (int i = 0; i < size; i++) {
                    JsonNode boardNode = rootNode.get(i);
                    String id = boardNode.path("id").asText();
                    String name = boardNode.path("name").asText();
                    String url = boardNode.path("shortUrl").asText();
                    boolean closed = Boolean.parseBoolean(boardNode.path("closed").asText());

                    if (!closed) {
                        println(name + " - " + url);

                        config.addBoard(id, name);
                        config.addBoardUrl(id, url);
                    }
                }

                println("validation done");

                Set<String> boardIdSet = config.getBoards().keySet();

                for (String id : boardIdSet) {
                    config = addCardInformations(id, config, client, mapper);
                }
                saveConfig(config, context);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:com.github.fge.jsonschema.syntax.checkers.helpers.DraftV3TypeKeywordSyntaxChecker.java

@Override
protected void checkValue(final Collection<JsonPointer> pointers, final ProcessingReport report,
        final SchemaTree tree) throws ProcessingException {
    final JsonNode node = tree.getNode().get(keyword);

    if (node.isTextual()) {
        if (!typeIsValid(node.textValue()))
            report.error(newMsg(tree, "incorrectPrimitiveType").put("valid", EnumSet.allOf(NodeType.class))
                    .put("found", node));
        return;//from  w  w w. ja v a2 s .com
    }

    final int size = node.size();
    final Set<Equivalence.Wrapper<JsonNode>> set = Sets.newHashSet();

    JsonNode element;
    NodeType type;
    boolean uniqueItems = true;

    for (int index = 0; index < size; index++) {
        element = node.get(index);
        type = NodeType.getNodeType(element);
        uniqueItems = set.add(EQUIVALENCE.wrap(element));
        if (type == OBJECT) {
            pointers.add(JsonPointer.of(keyword, index));
            continue;
        }
        if (type != STRING) {
            report.error(newMsg(tree, "incorrectElementType").put("index", index)
                    .put("expected", EnumSet.of(OBJECT, STRING)).put("found", type));
            continue;
        }
        if (!typeIsValid(element.textValue()))
            report.error(newMsg(tree, "incorrectPrimitiveType").put("index", index)
                    .put("valid", EnumSet.allOf(NodeType.class)).put("found", element));
    }

    if (!uniqueItems)
        report.error(newMsg(tree, "elementsNotUnique"));
}

From source file:org.apache.solr.kelvin.testcases.ValueListCondition.java

public List<ConditionFailureTestEvent> verifyConditions(ITestCase testCase, Properties queryParams,
        Map<String, Object> decodedResponses, Object testSpecificArgument) {
    List<ConditionFailureTestEvent> ret = new ArrayList<ConditionFailureTestEvent>();
    ArrayNode results = new ArrayNode(null);
    if (decodedResponses.containsKey(XmlDoclistExtractorResponseAnalyzer.DOC_LIST)) {
        results = (ArrayNode) decodedResponses.get(XmlDoclistExtractorResponseAnalyzer.DOC_LIST);
    }/*from   ww  w  .jav a2s .  c  om*/
    int lengthToCheck = getLengthToCheck(results);
    for (int i = 0; i < lengthToCheck; i++) {
        if (results.size() <= i) {
            ret.add(new MissingResultTestEvent(testCase, queryParams, "result set too short", i));
        } else {
            JsonNode row = results.get(i);
            if (!hasField(row, field)) {
                ret.add(new MissingFieldTestEvent(testCase, queryParams,
                        "missing field " + field + " from result", i));
            } else {
                JsonNode fieldValue = getField(row, field);
                fieldValue = ConfigurableLoader.assureArray(fieldValue);
                boolean found = false;
                ArrayList<String> allTextValues = new ArrayList<String>();
                for (int j = 0; j < fieldValue.size(); j++) {
                    String fieldText = fieldValue.get(j).asText();
                    allTextValues.add(fieldText);
                    if (checkContains(fieldText)) {
                        found = true;
                        break;
                    } else if (legacy) {
                        for (String cond : correctValuesList) {
                            if (cond.endsWith("*")) {
                                if (fieldText.startsWith(cond.substring(0, cond.length() - 1))) {
                                    found = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (!found && !reverseConditions)
                    ret.add(new ConditionsNotMetTestEvent(testCase, queryParams, "unexpected vaule ["
                            + StringUtils.join(allTextValues, ',') + "] not in " + correctValuesList.toString(),
                            i));
                else if (found && reverseConditions) {
                    ret.add(new ConditionsNotMetTestEvent(testCase, queryParams,
                            "[" + StringUtils.join(allTextValues, ',') + "] matches "
                                    + correctValuesList.toString(),
                            i));
                }
            }
        }
    }
    return ret;
}

From source file:com.cloudera.cdk.morphline.json.JsonMorphlineTest.java

@Test
public void testReadJson() throws Exception {
    morphline = createMorphline("test-morphlines/readJson");
    for (int j = 0; j < 3; j++) { // also test reuse of objects and low level avro buffers
        InputStream in = new FileInputStream(new File(RESOURCES_DIR + "/test-documents/stream.json"));
        Record record = new Record();
        record.put(Fields.ATTACHMENT_BODY, in);

        collector.reset();//from  ww w . j a  v  a2  s  .  c  o m
        startSession();
        assertEquals(1, collector.getNumStartEvents());
        assertTrue(morphline.process(record));
        Iterator<Record> iter = collector.getRecords().iterator();

        assertTrue(iter.hasNext());
        JsonNode node = (JsonNode) iter.next().getFirstValue(Fields.ATTACHMENT_BODY);
        assertEquals("foo", node.get("firstObject").asText());
        assertTrue(node.isObject());
        assertEquals(1, node.size());

        assertTrue(iter.hasNext());
        node = (JsonNode) iter.next().getFirstValue(Fields.ATTACHMENT_BODY);
        assertEquals("bar", node.get("secondObject").asText());
        assertTrue(node.isObject());
        assertEquals(1, node.size());

        assertFalse(iter.hasNext());
        in.close();
    }
}

From source file:org.jasig.cas.support.oauth.web.OAuth20MetadataPrincipalControllerTests.java

@Test
public void verifyEmptyPrincipalListOK() throws Exception {
    final AccessToken accessToken = mock(AccessToken.class);
    when(accessToken.getId()).thenReturn(AT_ID);

    final List<PrincipalMetadata> principalMetas = Arrays.asList();

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getToken(AT_ID, AccessToken.class)).thenReturn(accessToken);
    when(centralOAuthService.getPrincipalMetadata(accessToken)).thenReturn(principalMetas);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST",
            CONTEXT + OAuthConstants.METADATA_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, AT_ID);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertNull(modelAndView);//from  w w  w  .j ava  2s. c  o  m
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());

    final ObjectMapper mapper = new ObjectMapper();

    final String expected = "{\"data\":[]}";
    final JsonNode expectedObj = mapper.readTree(expected);
    final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString());

    final JsonNode expectedData = expectedObj.get("data");
    final JsonNode receivedData = receivedObj.get("data");
    assertEquals(expectedData.size(), receivedData.size());
    assertEquals(0, receivedData.size());
}