Java Examples for com.fasterxml.jackson.databind.node.ArrayNode

The following java examples will help you to understand the usage of com.fasterxml.jackson.databind.node.ArrayNode. These source code samples are taken from different open source projects.

Example 1
Project: spring-data-mongodb-master  File: GeoJsonModule.java View source code
/**
		 * Get the points nested within given {@link ArrayNode}.
		 * 
		 * @param node can be {@literal null}.
		 * @return {@literal empty list} when given a {@code null} value.
		 */
protected List<Point> toPoints(ArrayNode node) {
    if (node == null) {
        return Collections.emptyList();
    }
    List<Point> points = new ArrayList<Point>(node.size());
    for (JsonNode coordinatePair : node) {
        if (coordinatePair.isArray()) {
            points.add(toPoint((ArrayNode) coordinatePair));
        }
    }
    return points;
}
Example 2
Project: batfish-master  File: AssertQuestionPlugin.java View source code
@Override
public AnswerElement answer() {
    ConfigurationBuilder b = new ConfigurationBuilder();
    b.jsonProvider(new JacksonJsonNodeJsonProvider());
    b.options(Option.ALWAYS_RETURN_LIST);
    Configuration c = b.build();
    AssertQuestion question = (AssertQuestion) _question;
    List<Assertion> assertions = question.getAssertions();
    _batfish.checkConfigurations();
    NodesQuestion nodesQuestion = new NodesQuestion();
    nodesQuestion.setSummary(false);
    NodesAnswerer nodesAnswerer = new NodesAnswerer(nodesQuestion, _batfish);
    AnswerElement nodesAnswer = nodesAnswerer.answer();
    BatfishObjectMapper mapper = new BatfishObjectMapper();
    String nodesAnswerStr = null;
    try {
        nodesAnswerStr = mapper.writeValueAsString(nodesAnswer);
    } catch (IOException e) {
        throw new BatfishException("Could not get JSON string from nodes answer", e);
    }
    Object jsonObject = JsonPath.parse(nodesAnswerStr, c).json();
    Map<Integer, Assertion> failing = new ConcurrentHashMap<>();
    Map<Integer, Assertion> passing = new ConcurrentHashMap<>();
    List<Integer> indices = new ArrayList<>();
    for (int i = 0; i < assertions.size(); i++) {
        indices.add(i);
    }
    final boolean[] fail = new boolean[1];
    ConcurrentMap<String, ArrayNode> pathCache = new ConcurrentHashMap<>();
    indices.parallelStream().forEach( i -> {
        Assertion assertion = assertions.get(i);
        String assertionText = assertion.getAssertion();
        AssertionAst ast = _batfish.parseAssertion(assertionText);
        if (ast.execute(_batfish, jsonObject, pathCache, c)) {
            passing.put(i, assertion);
        } else {
            failing.put(i, assertion);
            synchronized (fail) {
                fail[0] = true;
            }
        }
    });
    AssertAnswerElement answerElement = new AssertAnswerElement();
    answerElement.setFail(fail[0]);
    answerElement.getFailing().putAll(failing);
    answerElement.getPassing().putAll(passing);
    return answerElement;
}
Example 3
Project: cloudbreak-master  File: AmbariClustersHostsResponse.java View source code
@Override
public Object handle(Request request, Response response) throws Exception {
    response.type("text/plain");
    ObjectNode rootNode = JsonNodeFactory.instance.objectNode();
    ArrayNode items = rootNode.putArray("items");
    for (String instanceId : instanceMap.keySet()) {
        CloudVmMetaDataStatus status = instanceMap.get(instanceId);
        if (InstanceStatus.STARTED == status.getCloudVmInstanceStatus().getStatus()) {
            ObjectNode item = items.addObject();
            item.putObject("Hosts").put("host_name", HostNameUtil.generateHostNameByIp(status.getMetaData().getPrivateIp()));
            ArrayNode components = item.putArray("host_components");
            components.addObject().putObject("HostRoles").put("component_name", "DATANODE").put("state", state);
            components.addObject().putObject("HostRoles").put("component_name", "NODEMANAGER").put("state", state);
        }
    }
    return rootNode;
}
Example 4
Project: open-data-service-master  File: HttpSenderTest.java View source code
@Test
public final void testSuccess() throws Throwable {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(200));
    server.play();
    String path = "/foo/bar/data/";
    String callbackUrl = server.getUrl(path).toString();
    ObjectNode sentData = new ObjectNode(JsonNodeFactory.instance);
    sentData.put("sourceId", SOURCE_ID);
    ArrayNode data = sentData.putArray("data");
    data.addObject().put("hello", "world");
    data.addObject().put("and", "again");
    setupSender(new HttpClient(SOURCE_ID, callbackUrl, true));
    sender.onNewDataStart();
    for (JsonNode item : data) sender.onNewDataItem((ObjectNode) item);
    sender.onNewDataComplete();
    assertEquals(SenderResult.Status.SUCCESS, sender.getSenderResult().getStatus());
    RecordedRequest request = server.takeRequest();
    assertEquals(path, request.getPath());
    assertEquals(sentData.toString(), request.getUtf8Body());
    server.shutdown();
}
Example 5
Project: spring-security-oauth-master  File: FacebookController.java View source code
@RequestMapping("/facebook/info")
public String photos(Model model) throws Exception {
    ObjectNode result = facebookRestTemplate.getForObject("https://graph.facebook.com/me/friends", ObjectNode.class);
    ArrayNode data = (ArrayNode) result.get("data");
    ArrayList<String> friends = new ArrayList<String>();
    for (JsonNode dataNode : data) {
        friends.add(dataNode.get("name").asText());
    }
    model.addAttribute("friends", friends);
    return "facebook";
}
Example 6
Project: verjson-master  File: Transformations.java View source code
/**
	 * Creates an ArrayNode from the given nodes. Returns an empty ArrayNode if no elements are provided and
	 * fallbackToEmptyArray is true, null if false.
	 */
public static ArrayNode createArray(boolean fallbackToEmptyArray, JsonNode... nodes) {
    ArrayNode array = null;
    for (JsonNode element : nodes) {
        if (element != null) {
            if (array == null) {
                array = new ArrayNode(JsonNodeFactory.instance);
            }
            array.add(element);
        }
    }
    if ((array == null) && fallbackToEmptyArray) {
        array = new ArrayNode(JsonNodeFactory.instance);
    }
    return array;
}
Example 7
Project: Activiti-master  File: TableDataResourceTest.java View source code
/**
   * Test getting a single table's row data. GET
   * management/tables/{tableName}/data
   */
public void testGetTableColumns() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);
        taskService.setVariable(task.getId(), "var1", 123);
        taskService.setVariable(task.getId(), "var2", 456);
        taskService.setVariable(task.getId(), "var3", 789);
        // We use variable-table as a reference
        String tableName = managementService.getTableName(VariableInstanceEntity.class);
        CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TABLE_DATA, tableName)), HttpStatus.SC_OK);
        // Check paging result
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals(3, responseNode.get("total").intValue());
        assertEquals(3, responseNode.get("size").intValue());
        assertEquals(0, responseNode.get("start").intValue());
        assertTrue(responseNode.get("order").isNull());
        assertTrue(responseNode.get("sort").isNull());
        // Check variables are actually returned
        ArrayNode rows = (ArrayNode) responseNode.get("data");
        assertNotNull(rows);
        assertEquals(3, rows.size());
        // Check sorting, ascending
        response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TABLE_DATA, tableName) + "?orderAscendingColumn=LONG_"), HttpStatus.SC_OK);
        responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals(3, responseNode.get("total").intValue());
        assertEquals(3, responseNode.get("size").intValue());
        assertEquals(0, responseNode.get("start").intValue());
        assertEquals("asc", responseNode.get("order").textValue());
        assertEquals("LONG_", responseNode.get("sort").textValue());
        rows = (ArrayNode) responseNode.get("data");
        assertNotNull(rows);
        assertEquals(3, rows.size());
        assertEquals("var1", rows.get(0).get("NAME_").textValue());
        assertEquals("var2", rows.get(1).get("NAME_").textValue());
        assertEquals("var3", rows.get(2).get("NAME_").textValue());
        // Check sorting, descending
        response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TABLE_DATA, tableName) + "?orderDescendingColumn=LONG_"), HttpStatus.SC_OK);
        responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals(3, responseNode.get("total").intValue());
        assertEquals(3, responseNode.get("size").intValue());
        assertEquals(0, responseNode.get("start").intValue());
        assertEquals("desc", responseNode.get("order").textValue());
        assertEquals("LONG_", responseNode.get("sort").textValue());
        rows = (ArrayNode) responseNode.get("data");
        assertNotNull(rows);
        assertEquals(3, rows.size());
        assertEquals("var3", rows.get(0).get("NAME_").textValue());
        assertEquals("var2", rows.get(1).get("NAME_").textValue());
        assertEquals("var1", rows.get(2).get("NAME_").textValue());
        // Finally, check result limiting
        response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TABLE_DATA, tableName) + "?orderAscendingColumn=LONG_&start=1&size=1"), HttpStatus.SC_OK);
        responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals(3, responseNode.get("total").intValue());
        assertEquals(1, responseNode.get("size").intValue());
        assertEquals(1, responseNode.get("start").intValue());
        rows = (ArrayNode) responseNode.get("data");
        assertNotNull(rows);
        assertEquals(1, rows.size());
        assertEquals("var2", rows.get(0).get("NAME_").textValue());
    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}
Example 8
Project: auth0-java-master  File: UsersPageDeserializer.java View source code
@Override
public UsersPage deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    JsonNode node = p.getCodec().readTree(p);
    ObjectMapper mapper = new ObjectMapper();
    if (node.isArray()) {
        return new UsersPage(getArrayElements((ArrayNode) node, mapper));
    }
    Integer start = getIntegerValue(node.get("start"));
    Integer length = getIntegerValue(node.get("length"));
    Integer total = getIntegerValue(node.get("total"));
    Integer limit = getIntegerValue(node.get("limit"));
    ArrayNode array = (ArrayNode) node.get("users");
    return new UsersPage(start, length, total, limit, getArrayElements(array, mapper));
}
Example 9
Project: aws-dynamodb-mars-json-demo-master  File: DynamoDBMissionWorker.java View source code
/**
     * Retrieves and parses a mission manifest to a map of sol numbers to sol URLs.
     *
     * @param url
     *            Location of the mission manifest
     * @param connectTimeout
     *            Timeout for retrieving the mission manifest
     * @return Map of sol number to sol URL contained in the mission manifest
     * @throws IOException
     *             Invalid URL, invalid JSON data, or connection error
     */
public static Map<Integer, String> getSolJSON(final URL url, final int connectTimeout) throws IOException {
    final Map<Integer, String> map = new HashMap<Integer, String>();
    // Retrieve the JSON data
    final JsonNode manifest = JSONParser.getJSONFromURL(url, connectTimeout);
    // Validate the JSON data version
    if (!manifest.has(RESOURCE_TYPE_KEY) || !SUPPORTED_TYPES.contains(manifest.get(RESOURCE_TYPE_KEY).asText())) {
        throw new IllegalArgumentException("Manifest version verification failed");
    }
    // Validate that the JSON data contains a sol list
    if (!manifest.has(SOLS_LIST_KEY)) {
        throw new IllegalArgumentException("Manifest does not contain a sol list");
    }
    final ArrayNode sols = (ArrayNode) manifest.get(SOLS_LIST_KEY);
    // Process each sol in the sol list
    for (int i = 0; i < sols.size(); i++) {
        final JsonNode sol = sols.path(i);
        if (sol.has(SOL_ID_KEY) && sol.has(SOL_URL_KEY)) {
            final Integer solID = sol.get(SOL_ID_KEY).asInt();
            final String solURL = sol.get(SOL_URL_KEY).asText();
            if (solID != null && solURL != null) {
                // Add valid sol to the map
                map.put(solID, solURL);
            } else {
                LOGGER.warning("Sol contains unexpected values: " + sol);
            }
        } else {
            LOGGER.warning("Sol missing required keys: ");
        }
    }
    return map;
}
Example 10
Project: beakerx-master  File: XYGraphicsSerializerTest.java View source code
@Test
public void serializeBigIntXWithNanoPlotType_resultJsonHasStringX() throws IOException {
    //when
    line.setX(Arrays.asList(new BigInteger("12345678901234567891000"), new BigInteger("12345678901234567891000")));
    line.setPlotType(NanoPlot.class);
    xyGraphicsSerializer.serialize(line, jgen, new DefaultSerializerProvider.Impl());
    jgen.flush();
    //then
    JsonNode actualObj = mapper.readTree(sw.toString());
    Assertions.assertThat(actualObj.has("x")).isTrue();
    ArrayNode arrayNode = (ArrayNode) actualObj.get("x");
    Assertions.assertThat(arrayNode.get(1).isTextual()).isTrue();
}
Example 11
Project: belladati-sdk-java-master  File: PaginatedListImpl.java View source code
private PaginatedList<T> addFrom(String parameterizedUri) {
    JsonNode json = service.getAsJson(parameterizedUri);
    size = json.get("size").asInt();
    page = json.get("offset").asInt() / size;
    ArrayNode nodes = (ArrayNode) json.get(field);
    for (JsonNode node : nodes) {
        currentData.add(parse(service, node));
    }
    return this;
}
Example 12
Project: celos-master  File: JSONWorkflowListServletTest.java View source code
@Test
public void jsonCorrectlyProduced() throws Exception {
    WorkflowConfiguration cfg = WorkflowConfigurationParserTest.parseDir("json-workflow-list-servlet-test");
    ArrayNode list = Util.MAPPER.createArrayNode();
    list.add(new String("workflow-1"));
    list.add(new String("workflow-2"));
    ObjectNode obj = Util.MAPPER.createObjectNode();
    obj.put("ids", list);
    Assert.assertEquals(obj, new JSONWorkflowListServlet().createJSONObject(cfg));
}
Example 13
Project: clc-java-sdk-master  File: ActionSettingsDeserializer.java View source code
@Override
public ActionSettingsMetadata deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    TreeNode node = jsonParser.getCodec().readTree(jsonParser);
    //email settings
    if (node.get(RECIPIENTS).isArray()) {
        ArrayNode recipientsNode = ((ArrayNode) node.get(RECIPIENTS));
        List<String> recipients = new ArrayList<>(recipientsNode.size());
        recipientsNode.forEach( recipient -> recipients.add(recipient.asText()));
        return new ActionSettingsEmailMetadata().recipients(recipients);
    }
    return null;
}
Example 14
Project: degraphmalizer-master  File: ExceptionHandler.java View source code
public static ObjectNode renderException(ObjectMapper om, Throwable t) {
    final ArrayNode ss = om.createArrayNode();
    for (StackTraceElement elt : t.getStackTrace()) ss.add(elt.toString());
    final ObjectNode ex = om.createObjectNode();
    ex.put("message", t.getMessage());
    ex.put("class", t.getClass().getSimpleName());
    ex.put("stacktrace", ss);
    return ex;
}
Example 15
Project: demoapps-master  File: ConferenceCloudAgent.java View source code
/**
	 * Inits the Conference Cloud Agent.
	 * 
	 * @param id
	 *            the id
	 */
public void init(String id) {
    final AgentConfig config = new AgentConfig(id);
    final ArrayNode transports = JOM.createArrayNode();
    final WebsocketTransportConfig serverConfig = new WebsocketTransportConfig();
    serverConfig.setServer(true);
    serverConfig.setDoAuthentication(false);
    serverConfig.setAddress(WSBASEURL + id);
    serverConfig.setServletLauncher("JettyLauncher");
    final ObjectNode jettyParms = JOM.createObjectNode();
    jettyParms.put("port", 8082);
    serverConfig.set("jetty", jettyParms);
    transports.add(serverConfig);
    final HttpTransportConfig httpConfig = new HttpTransportConfig();
    httpConfig.setServletUrl(BASEURL);
    httpConfig.setServletClass(DebugServlet.class.getName());
    httpConfig.setDoAuthentication(false);
    httpConfig.setServletLauncher("JettyLauncher");
    httpConfig.set("jetty", jettyParms);
    transports.add(httpConfig);
    config.setTransport(transports);
    setConfig(config);
    myInfo = new Info(getId());
}
Example 16
Project: eve-java-master  File: TestGraph.java View source code
/**
	 * Write visGraph.
	 *
	 * @param agents
	 *            the agents
	 * @return the string
	 */
private String writeVisGraph(List<NodeAgent> agents) {
    final ObjectNode result = JOM.createObjectNode();
    final ArrayNode nodes = JOM.createArrayNode();
    final ArrayNode edges = JOM.createArrayNode();
    for (NodeAgent agent : agents) {
        final ObjectNode node = JOM.createObjectNode();
        node.put("id", agent.getId());
        node.put("label", agent.getId());
        nodes.add(node);
        for (Edge edge : agent.getGraph().getEdges()) {
            final ObjectNode edgeNode = JOM.createObjectNode();
            edgeNode.put("from", agent.getId());
            edgeNode.put("to", edge.getAddress().toASCIIString().replace("local:", ""));
            edges.add(edgeNode);
        }
    }
    result.set("nodes", nodes);
    result.set("edges", edges);
    return result.toString();
}
Example 17
Project: evrythng-java-sdk-master  File: ActionsDeserializer.java View source code
@Override
public Actions deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    if (node.isArray()) {
        return mapper.readValue(node.toString(), ActionsImpl.class);
    } else {
        ArrayNode array = mapper.createArrayNode();
        array.add(node);
        return mapper.readValue(array.toString(), ActionsImpl.class);
    }
}
Example 18
Project: json-data-generator-master  File: JsonUtils.java View source code
public void flattenJsonIntoMap(String currentPath, JsonNode jsonNode, Map<String, Object> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            flattenJsonIntoMap(pathPrefix + entry.getKey(), entry.getValue(), map);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            flattenJsonIntoMap(currentPath + "[" + i + "]", arrayNode.get(i), map);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        Object value = null;
        if (valueNode.isNumber()) {
            value = valueNode.numberValue();
        } else if (valueNode.isBoolean()) {
            value = valueNode.asBoolean();
        } else if (valueNode.isTextual()) {
            value = valueNode.asText();
        }
        map.put(currentPath, value);
    }
}
Example 19
Project: json-schema-avro-master  File: RecordTranslator.java View source code
@Override
protected void doTranslate(final Schema avroSchema, final MutableTree jsonSchema, final ProcessingReport report) throws ProcessingException {
    final List<Schema.Field> fields = avroSchema.getFields();
    if (fields.isEmpty()) {
        final ArrayNode node = FACTORY.arrayNode();
        node.add(FACTORY.objectNode());
        jsonSchema.getCurrentNode().put("enum", node);
        return;
    }
    final JsonPointer pwd = jsonSchema.getPointer();
    if (avroSchema.getDoc() != null)
        jsonSchema.getCurrentNode().put("description", avroSchema.getDoc());
    jsonSchema.setType(NodeType.OBJECT);
    final ArrayNode required = FACTORY.arrayNode();
    jsonSchema.getCurrentNode().put("required", required);
    jsonSchema.getCurrentNode().put("additionalProperties", false);
    final ObjectNode properties = FACTORY.objectNode();
    jsonSchema.getCurrentNode().put("properties", properties);
    String fieldName;
    Schema fieldSchema;
    Schema.Type fieldType;
    AvroTranslator translator;
    JsonPointer ptr;
    ObjectNode propertyNode;
    String s;
    /*
         * FIXME: "default" and readers'/writers' schema? Here, even with a
         * default value, the record field is marked as required.
         */
    for (final Schema.Field field : fields) {
        fieldName = field.name();
        fieldSchema = field.schema();
        fieldType = fieldSchema.getType();
        translator = AvroTranslators.getTranslator(fieldType);
        required.add(fieldName);
        ptr = JsonPointer.of("properties", fieldName);
        propertyNode = FACTORY.objectNode();
        properties.put(fieldName, propertyNode);
        injectDefault(propertyNode, field);
        jsonSchema.setPointer(pwd.append(ptr));
        translator.translate(fieldSchema, jsonSchema, report);
        jsonSchema.setPointer(pwd);
    }
}
Example 20
Project: keycloak-master  File: OutputUtil.java View source code
public static void printAsCsv(Object object, ReturnFields fields, boolean unquoted) throws IOException {
    JsonNode node = convertToJsonNode(object);
    if (!node.isArray()) {
        ArrayNode listNode = MAPPER.createArrayNode();
        listNode.add(node);
        node = listNode;
    }
    for (JsonNode item : node) {
        StringBuilder buffer = new StringBuilder();
        printObjectAsCsv(buffer, item, fields, unquoted);
        printOut(buffer.length() > 0 ? buffer.substring(1) : "");
    }
}
Example 21
Project: lightblue-client-master  File: LightblueClientTestHarness.java View source code
/**
     * Helper method to be able to collect all the versions of the provided
     * entity that currently exist in lightblue.
     *
     * @param entityName - name of entity to to find versions for.
     * @return Set of entity versions
     * @throws LightblueException
     */
public Set<String> getEntityVersions(String entityName) throws LightblueException {
    MetadataGetEntityVersionsRequest versionRequest = new MetadataGetEntityVersionsRequest(entityName);
    try (LightblueHttpClient client = getLightblueClient()) {
        LightblueResponse response = client.metadata(versionRequest);
        ArrayNode versionNodes = (ArrayNode) response.getJson();
        Set<String> versions = new HashSet<>();
        for (JsonNode node : versionNodes) {
            versions.add(node.get("version").textValue());
        }
        return versions;
    } catch (IOException ex) {
        throw new LightblueException("Unable to close HttpClient", ex);
    }
}
Example 22
Project: lightblue-core-master  File: UnsetExpression.java View source code
/**
     * Parses an unset expression using the given json object
     */
public static UnsetExpression fromJson(ObjectNode node) {
    if (node.size() == 1) {
        JsonNode val = node.get(UpdateOperator._unset.toString());
        if (val != null) {
            List<Path> fields = new ArrayList<>();
            if (val instanceof ArrayNode) {
                for (Iterator<JsonNode> itr = ((ArrayNode) val).elements(); itr.hasNext(); ) {
                    fields.add(new Path(itr.next().asText()));
                }
            } else if (val.isValueNode()) {
                fields.add(new Path(val.asText()));
            }
            return new UnsetExpression(fields);
        }
    }
    throw Error.get(QueryConstants.ERR_INVALID_UNSET_EXPRESSION, node.toString());
}
Example 23
Project: lightblue-migrator-master  File: AbstractMigratorController.java View source code
/**
     * Work around method until a way to pass in security access level is found.
     */
protected ObjectNode grantAnyoneAccess(ObjectNode node) {
    ObjectNode schema = (ObjectNode) node.get("schema");
    ObjectNode access = (ObjectNode) schema.get("access");
    Iterator<JsonNode> children = access.iterator();
    while (children.hasNext()) {
        ArrayNode child = (ArrayNode) children.next();
        child.removeAll();
        child.add("anyone");
    }
    return node;
}
Example 24
Project: log-synth-master  File: SequenceSampler.java View source code
@Override
public JsonNode sample() {
    Preconditions.checkState(array != null || base != null, "Need to specify either base or array");
    ArrayNode r = nodeFactory.arrayNode();
    if (base != null) {
        int n = (int) length.sample().asDouble();
        for (int i = 0; i < n; i++) {
            r.add(base.sample());
        }
    } else {
        for (FieldSampler sampler : array) {
            r.add(sampler.sample());
        }
    }
    return r;
}
Example 25
Project: mobile-master  File: RealmListNYTimesMultimediumDeserializer.java View source code
@Override
public List<NYTimesMultimedium> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    RealmList<NYTimesMultimedium> list = new RealmList<>();
    TreeNode treeNode = jp.getCodec().readTree(jp);
    if (!(treeNode instanceof ArrayNode)) {
        return list;
    }
    ArrayNode arrayNode = (ArrayNode) treeNode;
    for (JsonNode node : arrayNode) {
        NYTimesMultimedium nyTimesMultimedium = objectMapper.treeToValue(node, NYTimesMultimedium.class);
        list.add(nyTimesMultimedium);
    }
    return list;
}
Example 26
Project: onos-master  File: ClusterWebResource.java View source code
/**
     * Forms cluster of ONOS instances.
     * Forms ONOS cluster using the uploaded JSON definition.
     *
     * @param config cluster definition
     * @return 200 OK
     * @throws IOException to signify bad request
     * @onos.rsModel ClusterPost
     */
@POST
@Path("configuration")
@Produces(MediaType.APPLICATION_JSON)
public Response formCluster(InputStream config) throws IOException {
    JsonCodec<ControllerNode> codec = codec(ControllerNode.class);
    ObjectNode root = (ObjectNode) mapper().readTree(config);
    List<ControllerNode> nodes = codec.decode((ArrayNode) root.path("nodes"), this);
    JsonNode partitionSizeNode = root.get("partitionSize");
    if (partitionSizeNode != null) {
        int partitionSize = partitionSizeNode.asInt();
        if (partitionSize == 0) {
            return Response.notAcceptable(null).build();
        }
        get(ClusterAdminService.class).formCluster(new HashSet<>(nodes), partitionSize);
    } else {
        get(ClusterAdminService.class).formCluster(new HashSet<>(nodes));
    }
    return Response.ok().build();
}
Example 27
Project: realm-java-master  File: RealmListNYTimesMultimediumDeserializer.java View source code
@Override
public List<NYTimesMultimedium> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    RealmList<NYTimesMultimedium> list = new RealmList<>();
    TreeNode treeNode = jp.getCodec().readTree(jp);
    if (!(treeNode instanceof ArrayNode)) {
        return list;
    }
    ArrayNode arrayNode = (ArrayNode) treeNode;
    for (JsonNode node : arrayNode) {
        NYTimesMultimedium nyTimesMultimedium = objectMapper.treeToValue(node, NYTimesMultimedium.class);
        list.add(nyTimesMultimedium);
    }
    return list;
}
Example 28
Project: Singularity-master  File: MergingSourceProvider.java View source code
private static void merge(ObjectNode to, ObjectNode from) {
    Iterator<String> newFieldNames = from.fieldNames();
    while (newFieldNames.hasNext()) {
        String newFieldName = newFieldNames.next();
        JsonNode oldVal = to.get(newFieldName);
        JsonNode newVal = from.get(newFieldName);
        if (oldVal == null || oldVal.isNull()) {
            to.put(newFieldName, newVal);
        } else if (oldVal.isArray() && newVal.isArray()) {
            ((ArrayNode) oldVal).removeAll();
            ((ArrayNode) oldVal).addAll((ArrayNode) newVal);
        } else if (oldVal.isObject() && newVal.isObject()) {
            merge((ObjectNode) oldVal, (ObjectNode) newVal);
        } else if (!(newVal == null || newVal.isNull())) {
            to.put(newFieldName, newVal);
        }
    }
}
Example 29
Project: Slipstream-Mod-Manager-master  File: JacksonCatalogWriter.java View source code
/**
	 * Writes collated catalog entries to a file, as condensed json.
	 */
public static void write(List<ModsInfo> modsInfoList, File dstFile) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();
    ObjectNode catalogsNode = rootNode.objectNode();
    rootNode.put("catalog_versions", catalogsNode);
    ArrayNode catalogNode = rootNode.arrayNode();
    catalogsNode.put("1", catalogNode);
    for (ModsInfo modsInfo : modsInfoList) {
        ObjectNode infoNode = rootNode.objectNode();
        catalogNode.add(infoNode);
        infoNode.put("title", modsInfo.getTitle());
        infoNode.put("author", modsInfo.getAuthor());
        infoNode.put("desc", modsInfo.getDescription());
        infoNode.put("url", modsInfo.getThreadURL());
        infoNode.put("thread_hash", modsInfo.threadHash);
        ArrayNode versionsNode = rootNode.arrayNode();
        infoNode.put("versions", versionsNode);
        for (Map.Entry<String, String> entry : modsInfo.getVersionsMap().entrySet()) {
            String versionFileHash = entry.getKey();
            String versionString = entry.getValue();
            ObjectNode versionNode = rootNode.objectNode();
            versionNode.put("hash", versionFileHash);
            versionNode.put("version", versionString);
            versionsNode.add(versionNode);
        }
    }
    OutputStream os = null;
    try {
        os = new FileOutputStream(dstFile);
        OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("US-ASCII"));
        mapper.writeValue(writer, rootNode);
    } finally {
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }
    }
}
Example 30
Project: spring-security-master  File: UnmodifiableSetDeserializer.java View source code
@Override
public Set deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode node = mapper.readTree(jp);
    Set<Object> resultSet = new HashSet<Object>();
    if (node != null) {
        if (node instanceof ArrayNode) {
            ArrayNode arrayNode = (ArrayNode) node;
            Iterator<JsonNode> nodeIterator = arrayNode.iterator();
            while (nodeIterator.hasNext()) {
                JsonNode elementNode = nodeIterator.next();
                resultSet.add(mapper.readValue(elementNode.toString(), Object.class));
            }
        } else {
            resultSet.add(mapper.readValue(node.toString(), Object.class));
        }
    }
    return Collections.unmodifiableSet(resultSet);
}
Example 31
Project: stormpath-sdk-java-master  File: JSONPropertiesSource.java View source code
private void getFlattenedMap(String currentPath, JsonNode jsonNode, Map<String, String> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            getFlattenedMap(pathPrefix + entry.getKey(), entry.getValue(), map);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            getFlattenedMap(currentPath + "[" + i + "]", arrayNode.get(i), map);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        map.put(currentPath, valueNode.asText());
    }
}
Example 32
Project: swagger-parser-master  File: ApiObjectMigrator.java View source code
@Nonnull
@Override
public JsonNode migrate(@Nonnull final JsonNode input) throws SwaggerMigrationException {
    ObjectNode on = (ObjectNode) input;
    if (on.get("type") == null) {
        JsonNode responseMessages = on.get("responseMessages");
        JsonNode type = null;
        if (responseMessages != null && responseMessages instanceof ArrayNode) {
            // look for a 200 response
            ArrayNode arrayNode = (ArrayNode) responseMessages;
            Iterator<JsonNode> itr = arrayNode.elements();
            while (itr.hasNext()) {
                JsonNode rm = itr.next();
                JsonNode code = rm.get("code");
                if (code != null) {
                    if ("200".equals(code.toString())) {
                        type = rm;
                    }
                }
            }
        }
        if (type != null) {
            if (type.get("type") == null) {
                on.put("type", "void");
            } else {
                on.put("type", type.get("type"));
            }
        } else {
            on.put("type", "void");
        }
    }
    // if there are no parameters, we can insert an empty array
    if (on.get("parameters") == null) {
        on.put("parameters", Json.mapper().createArrayNode());
    }
    // see if there's a response
    final MutableJsonTree tree = new MutableJsonTree(input);
    tree.applyMigrator(renameMember("httpMethod", "method"));
    tree.applyMigrator(renameMember("errorResponses", "responseMessages"));
    /*
         * Migrate response messages, if any
         */
    JsonPointer ptr = JsonPointer.of("responseMessages");
    if (!ptr.path(tree.getBaseNode()).isMissingNode()) {
        tree.setPointer(ptr);
        tree.applyMigratorToElements(renameMember("reason", "message"));
    }
    /*
         * Migrate parameters
         */
    ptr = JsonPointer.of("parameters");
    tree.setPointer(ptr);
    tree.applyMigratorToElements(parametersMigrator);
    return tree.getBaseNode();
}
Example 33
Project: telegraph-master  File: NodeDeserializer.java View source code
@Override
public Node deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    JsonNode node = mapper.readTree(jsonParser);
    if (node instanceof TextNode) {
        return new NodeText(node.asText());
    } else {
        JsonNode childrenNode = node.get(NodeElement.CHILDREN_FIELD);
        JsonNode tagNode = node.get(NodeElement.TAG_FIELD);
        JsonNode attrsNode = node.get(NodeElement.ATTRS_FIELD);
        NodeElement element = new NodeElement();
        element.setTag(tagNode.asText());
        if (attrsNode != null && attrsNode instanceof ObjectNode) {
            Map<String, String> attributes = new HashMap<>();
            for (Iterator<String> it = attrsNode.fieldNames(); it.hasNext(); ) {
                String field = it.next();
                attributes.put(field, attrsNode.get(field).asText());
            }
            element.setAttrs(attributes);
        }
        if (childrenNode != null && childrenNode instanceof ArrayNode) {
            List<Node> childNodes = new ArrayList<>();
            for (Iterator<JsonNode> it = childrenNode.elements(); it.hasNext(); ) {
                childNodes.add(mapper.treeToValue(it.next(), Node.class));
            }
            element.setChildren(childNodes);
        }
        return element;
    }
}
Example 34
Project: TinCanJava-master  File: StatementsResult.java View source code
@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectNode node = Mapper.getInstance().createObjectNode();
    if (this.getStatements() != null) {
        ArrayNode statementsNode = Mapper.getInstance().createArrayNode();
        for (Statement statement : this.getStatements()) {
            statementsNode.add(statement.toJSONNode(version));
        }
        node.put("statements", statementsNode);
    }
    if (this.getMoreURL() != null) {
        node.put("more", this.getMoreURL());
    }
    return node;
}
Example 35
Project: xmlsh-master  File: array.java View source code
@Override
public XValue run(Shell shell, List<XValue> args) throws InvalidArgumentException {
    ArrayList<Object> list = new ArrayList<Object>();
    ObjectMapper mapper = JSONUtils.getJsonObjectMapper();
    ArrayNode node = mapper.createArrayNode();
    for (XValue arg : args) {
        node.add(JSONUtils.toJsonType(arg));
    }
    return XValue.newXValue(TypeFamily.JSON, node);
}
Example 36
Project: arangodb-objectmapper-master  File: Cursor.java View source code
/**
     * updates the state
     *  
     * @param root         the cursor root node
     *  
     * @return true,       if the state was updated successfully 
     */
private boolean setValues(JsonNode root) {
    if (root == null) {
        hasNext = false;
        id = "";
        index = 0;
        count = 0;
        return false;
    }
    if (root.has("result")) {
        JsonNode jn = root.get("result");
        if (jn.isArray()) {
            resultNode = (ArrayNode) jn;
        }
    }
    if (root.has("hasMore")) {
        hasNext = root.get("hasMore").asBoolean();
    }
    if (root.has("id")) {
        id = root.get("id").asText();
    }
    if (root.has("count")) {
        count = root.get("count").asInt();
    }
    index = 0;
    return true;
}
Example 37
Project: baasbox-master  File: PermissionJsonWrapper.java View source code
public void check() throws AclNotValidException {
    if (this.aclJson == null)
        return;
    //cycle through the _allow* fields
    Iterator<Entry<String, JsonNode>> itAllows = aclJson.fields();
    while (itAllows.hasNext()) {
        Entry<String, JsonNode> allow = itAllows.next();
        ArrayNode elementsToCheck = (ArrayNode) allow.getValue();
        Iterator<JsonNode> itElements = elementsToCheck.elements();
        while (itElements.hasNext()) {
            JsonNode elemToCheck = itElements.next();
            if (!elemToCheck.isObject())
                throw new AclNotValidException(Type.ACL_NOT_OBJECT, allow.getKey() + " must contains array of objects");
            String name = ((ObjectNode) elemToCheck).get("name").asText();
            if (StringUtils.isEmpty(name))
                throw new AclNotValidException(Type.ACL_KEY_NOT_VALID, "An element of the " + allow.getKey() + " ACL field has no name");
            boolean isRole = isARole((ObjectNode) elemToCheck);
            if (!isRole) {
                if (!UserService.exists(name))
                    throw new AclNotValidException(Type.ACL_USER_DOES_NOT_EXIST, "The user " + name + " does not exist");
            } else if (!RoleService.exists(name))
                throw new AclNotValidException(Type.ACL_ROLE_DOES_NOT_EXIST, "The role " + name + " does not exist");
        }
    }
}
Example 38
Project: bard-master  File: AnnotationUtils.java View source code
public static JsonNode getAnnotationJson(List<CAPAnnotation> a) throws ClassNotFoundException, IOException, SQLException {
    DBUtils db = new DBUtils();
    CAPDictionary dict = db.getCAPDictionary();
    // lets group these annotations and construct our JSON response
    CAPDictionaryElement node;
    Map<Integer, List<CAPAnnotation>> contexts = new HashMap<Integer, List<CAPAnnotation>>();
    for (CAPAnnotation anno : a) {
        Integer id = anno.id;
        // corresponds to dynamically generated annotations (from non-CAP sources)
        if (id == null)
            id = -1;
        // go from dict key to label
        if (anno.key != null && Util.isNumber(anno.key)) {
            node = dict.getNode(new BigInteger(anno.key));
            anno.key = node != null ? node.getLabel() : anno.key;
        }
        if (anno.value != null && Util.isNumber(anno.value)) {
            node = dict.getNode(new BigInteger(anno.value));
            anno.value = node != null ? node.getLabel() : anno.value;
        }
        if (contexts.containsKey(id)) {
            List<CAPAnnotation> la = contexts.get(id);
            la.add(anno);
            contexts.put(id, la);
        } else {
            List<CAPAnnotation> la = new ArrayList<CAPAnnotation>();
            la.add(anno);
            contexts.put(id, la);
        }
    }
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode docNode = mapper.createArrayNode();
    ArrayNode contextNode = mapper.createArrayNode();
    ArrayNode measureNode = mapper.createArrayNode();
    ArrayNode miscNode = mapper.createArrayNode();
    for (Integer contextId : contexts.keySet()) {
        List<CAPAnnotation> comps = contexts.get(contextId);
        Collections.sort(comps, new Comparator<CAPAnnotation>() {

            @Override
            public int compare(CAPAnnotation o1, CAPAnnotation o2) {
                if (o1.displayOrder == o2.displayOrder)
                    return 0;
                return o1.displayOrder < o2.displayOrder ? -1 : 1;
            }
        });
        JsonNode arrayNode = mapper.valueToTree(comps);
        ObjectNode n = mapper.createObjectNode();
        n.put("id", comps.get(0).id);
        n.put("name", comps.get(0).contextRef);
        n.put("group", comps.get(0).contextGroup);
        n.put("comps", arrayNode);
        if (comps.get(0).source.equals("cap-doc"))
            docNode.add(n);
        else if (comps.get(0).source.equals("cap-context"))
            contextNode.add(n);
        else if (comps.get(0).source.equals("cap-measure"))
            measureNode.add(n);
        else {
            for (CAPAnnotation misca : comps) miscNode.add(mapper.valueToTree(misca));
        }
    }
    ObjectNode topLevel = mapper.createObjectNode();
    topLevel.put("contexts", contextNode);
    topLevel.put("measures", measureNode);
    topLevel.put("docs", docNode);
    topLevel.put("misc", miscNode);
    return topLevel;
}
Example 39
Project: constellation-master  File: ImageStatisticDeserializer.java View source code
@Override
public ImageStatistics deserialize(JsonParser parser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    JsonNode node = parser.getCodec().readTree(parser);
    JsonNode bandsNode = node.get("bands");
    if (bandsNode.isArray()) {
        ArrayNode bandArray = (ArrayNode) bandsNode;
        int nbBands = bandArray.size();
        final ImageStatistics stats = new ImageStatistics(nbBands);
        Iterator<JsonNode> bandIte = bandArray.iterator();
        // band index
        int b = 0;
        while (bandIte.hasNext()) {
            JsonNode bandNode = bandIte.next();
            if (bandNode.isObject()) {
                int idx = ((IntNode) bandNode.get("index")).intValue();
                JsonNode nameNode = bandNode.get("name");
                if (nameNode != null) {
                    stats.getBand(b).setName(nameNode.textValue());
                }
                JsonNode dataTypeNode = bandNode.get("dataType");
                if (dataTypeNode != null) {
                    stats.getBand(b).setDataType(SampleType.valueOf(dataTypeNode.textValue()));
                }
                String minStr = bandNode.get("min").asText();
                String maxStr = bandNode.get("max").asText();
                stats.getBand(b).setMin(Double.valueOf(minStr));
                stats.getBand(b).setMax(Double.valueOf(maxStr));
                JsonNode meanNode = bandNode.get("mean");
                if (meanNode != null) {
                    stats.getBand(b).setMean(meanNode.doubleValue());
                }
                JsonNode stdNode = bandNode.get("std");
                if (stdNode != null) {
                    stats.getBand(b).setStd(stdNode.doubleValue());
                }
                JsonNode noDataNode = bandNode.get("noData");
                if (noDataNode != null && noDataNode.isArray()) {
                    ArrayNode noDataArray = (ArrayNode) noDataNode;
                    double[] noData = new double[noDataArray.size()];
                    Iterator<JsonNode> noDataIte = noDataArray.iterator();
                    int i = 0;
                    while (noDataIte.hasNext()) {
                        noData[i++] = Double.valueOf(noDataIte.next().asText());
                    }
                    stats.getBand(b).setNoData(noData);
                }
                JsonNode histogramNode = bandNode.get("histogram");
                if (histogramNode != null && histogramNode.isArray()) {
                    ArrayNode histogramArray = (ArrayNode) histogramNode;
                    int size = histogramArray.size();
                    long[] histogram = new long[size];
                    Iterator<JsonNode> histogramIte = histogramArray.iterator();
                    int i = 0;
                    while (histogramIte.hasNext()) {
                        histogram[i++] = histogramIte.next().longValue();
                    }
                    stats.getBand(b).setHistogram(histogram);
                } else {
                    throw new IOException("Invalid JSON");
                }
            }
            b++;
        }
        return stats;
    }
    throw new IOException("Invalid JSON");
}
Example 40
Project: droidtowers-master  File: Migration_GameSave_UnhappyrobotToDroidTowers.java View source code
@Override
protected void process(ObjectNode node, String fileName) {
    ObjectNode gameSaveNode = getGameSaveUnlessFileFormatIsNewer(node, "com.unhappyrobot.gamestate.GameSave", 1);
    if (gameSaveNode == null) {
        return;
    }
    ArrayNode gridObjects = gameSaveNode.withArray("gridObjects");
    for (JsonNode gridObjectNode : gridObjects) {
        ObjectNode gridObject = (ObjectNode) gridObjectNode;
        if (gridObject == null) {
            throw new RuntimeException("Error converting: " + gridObject);
        } else if (!gridObject.has("typeId")) {
            String typeName = gridObject.get("typeName").asText();
            String typeId = transformTypeNameToTypeId(typeName);
            gridObject.put("typeId", typeId);
            gridObject.remove("typeClass");
            gridObject.remove("typeName");
        }
    }
    gameSaveNode.remove("objectCounts");
    gameSaveNode.put("gridObjects", gridObjects);
    node.removeAll();
    if (!gameSaveNode.has("baseFilename")) {
        gameSaveNode.put("baseFilename", fileName);
    }
    if (!gameSaveNode.has("towerName")) {
        gameSaveNode.put("towerName", "Untitled Tower");
    }
    gameSaveNode.put("fileFormat", 2);
    node.put("GameSave", gameSaveNode);
}
Example 41
Project: fastjson-master  File: Bug_0_Test.java View source code
private void f_jackson() throws Exception {
    long startNano = System.nanoTime();
    for (int i = 0; i < COUNT; ++i) {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode node = (ArrayNode) mapper.readTree(text);
        JsonNode head = node.get(0);
        JsonNode body = node.get(1);
    }
    long nano = System.nanoTime() - startNano;
    System.out.println(NumberFormat.getInstance().format(nano));
}
Example 42
Project: flink-master  File: SubtasksAllAccumulatorsHandlerTest.java View source code
private static void compareSubtaskAccumulators(AccessExecutionJobVertex originalTask, String json) throws IOException {
    JsonNode result = ArchivedJobGenerationUtils.mapper.readTree(json);
    Assert.assertEquals(originalTask.getJobVertexId().toString(), result.get("id").asText());
    Assert.assertEquals(originalTask.getParallelism(), result.get("parallelism").asInt());
    ArrayNode subtasks = (ArrayNode) result.get("subtasks");
    Assert.assertEquals(originalTask.getTaskVertices().length, subtasks.size());
    for (int x = 0; x < originalTask.getTaskVertices().length; x++) {
        JsonNode subtask = subtasks.get(x);
        AccessExecutionVertex expectedSubtask = originalTask.getTaskVertices()[x];
        Assert.assertEquals(x, subtask.get("subtask").asInt());
        Assert.assertEquals(expectedSubtask.getCurrentExecutionAttempt().getAttemptNumber(), subtask.get("attempt").asInt());
        Assert.assertEquals(expectedSubtask.getCurrentAssignedResourceLocation().getHostname(), subtask.get("host").asText());
        ArchivedJobGenerationUtils.compareStringifiedAccumulators(expectedSubtask.getCurrentExecutionAttempt().getUserAccumulatorsStringified(), (ArrayNode) subtask.get("user-accumulators"));
    }
}
Example 43
Project: gennai-master  File: ShowUsersTask.java View source code
@Override
public String execute() throws TaskExecuteException {
    if (owner.getName().equals(ROOT_USER_NAME)) {
        List<UserEntity> users = null;
        try {
            users = GungnirManager.getManager().getMetaStore().findUserAccounts();
        } catch (MetaStoreException e) {
            throw new TaskExecuteException(e);
        }
        ArrayNode usersNode = mapper.createArrayNode();
        for (UserEntity user : users) {
            ObjectNode userNode = mapper.createObjectNode();
            userNode.put("id", user.getId());
            userNode.put("name", user.getName());
            userNode.putPOJO("createTime", user.getCreateTime());
            if (user.getLastModifyTime() != null) {
                userNode.putPOJO("lastModifyTime", user.getLastModifyTime());
            }
            usersNode.add(userNode);
        }
        try {
            return mapper.writeValueAsString(usersNode);
        } catch (Exception e) {
            LOG.error("Failed to convert json format", e);
            throw new TaskExecuteException("Failed to convert json format", e);
        }
    } else {
        LOG.warn("Permission denied {}", owner.getName());
        throw new TaskExecuteException("Permission denied");
    }
}
Example 44
Project: geode-master  File: MemberClientsService.java View source code
public ObjectNode execute(final HttpServletRequest request) throws Exception {
    // get cluster object
    Cluster cluster = Repository.get().getCluster();
    // json object to be sent as response
    ObjectNode responseJSON = mapper.createObjectNode();
    JsonNode requestDataJSON = mapper.readTree(request.getParameter("pulseData"));
    String memberName = requestDataJSON.get("MemberClients").get("memberName").textValue();
    ArrayNode clientListJson = mapper.createArrayNode();
    Cluster.Member clusterMember = cluster.getMember(StringUtils.makeCompliantName(memberName));
    if (clusterMember != null) {
        responseJSON.put("memberId", clusterMember.getId());
        responseJSON.put(this.NAME, clusterMember.getName());
        responseJSON.put(this.HOST, clusterMember.getHost());
        // member's clients
        Cluster.Client[] memberClients = clusterMember.getMemberClients();
        for (Cluster.Client memberClient : memberClients) {
            ObjectNode regionJSON = mapper.createObjectNode();
            regionJSON.put("clientId", memberClient.getId());
            regionJSON.put(this.NAME, memberClient.getName());
            regionJSON.put(this.HOST, memberClient.getHost());
            regionJSON.put("queueSize", memberClient.getQueueSize());
            regionJSON.put("clientCQCount", memberClient.getClientCQCount());
            regionJSON.put("isConnected", memberClient.isConnected() ? "Yes" : "No");
            regionJSON.put("isSubscriptionEnabled", memberClient.isSubscriptionEnabled() ? "Yes" : "No");
            regionJSON.put("uptime", TimeUtils.convertTimeSecondsToHMS(memberClient.getUptime()));
            regionJSON.put("cpuUsage", String.format("%.4f", memberClient.getCpuUsage()).toString());
            // regionJSON.put("cpuUsage", memberClient.getCpuUsage());
            regionJSON.put("threads", memberClient.getThreads());
            regionJSON.put("gets", memberClient.getGets());
            regionJSON.put("puts", memberClient.getPuts());
            clientListJson.add(regionJSON);
        }
        responseJSON.put("memberClients", clientListJson);
    }
    // Send json response
    return responseJSON;
}
Example 45
Project: graphhopper-master  File: NearestServletWithEleIT.java View source code
@Test
public void testWithEleQuery() throws Exception {
    JsonNode json = nearestQuery("point=43.730864,7.420771&elevation=true");
    assertFalse(json.has("error"));
    ArrayNode point = (ArrayNode) json.get("coordinates");
    assertTrue("returned point is not 3D: " + point, point.size() == 3);
    double lon = point.get(0).asDouble();
    double lat = point.get(1).asDouble();
    double ele = point.get(2).asDouble();
    assertTrue("nearest point wasn't correct: lat=" + lat + ", lon=" + lon + ", ele=" + ele, lat == 43.73070006215647 && lon == 7.421392181993846 && ele == 66.0);
}
Example 46
Project: iiif-presentation-api-master  File: PropertyValueDeserializer.java View source code
@Override
public PropertyValue deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    TreeNode node = mapper.readTree(jp);
    if (TextNode.class.isAssignableFrom(node.getClass())) {
        return new PropertyValueSimpleImpl(((TextNode) node).textValue());
    } else if (ObjectNode.class.isAssignableFrom(node.getClass())) {
        ObjectNode obj = (ObjectNode) node;
        String language = ((TextNode) node.get("@language")).textValue();
        String value = ((TextNode) node.get("@value")).textValue();
        return new PropertyValueLocalizedImpl(Locale.forLanguageTag(language), value);
    } else if (ArrayNode.class.isAssignableFrom(node.getClass())) {
        ArrayNode arr = (ArrayNode) node;
        ObjectNode curObj;
        PropertyValueLocalizedImpl propVal = new PropertyValueLocalizedImpl();
        for (int i = 0; i < arr.size(); i++) {
            if (ObjectNode.class.isAssignableFrom(arr.get(i).getClass())) {
                curObj = (ObjectNode) arr.get(i);
                propVal.addValue(((TextNode) curObj.get("@language")).textValue(), ((TextNode) curObj.get("@value")).textValue());
            } else if (TextNode.class.isAssignableFrom(arr.get(i).getClass())) {
                propVal.addValue("", ((TextNode) arr.get(i)).asText());
            }
        }
        return propVal;
    }
    return null;
}
Example 47
Project: jlibs-master  File: ClientOperator.java View source code
public ResultMessage call(ObjectNode options, String procedure, ArrayNode arguments, ObjectNode argumentsKw) throws Throwable {
    final AtomicReference<Object> atomic = new AtomicReference<Object>();
    client.call(options, procedure, arguments, argumentsKw, new CallListener() {

        @Override
        public void onResult(WAMPClient client, ResultMessage result) {
            atomic.set(result);
        }

        @Override
        public void onError(WAMPClient client, WAMPException error) {
            atomic.set(error);
        }
    });
    return Await.getResult(atomic);
}
Example 48
Project: json-schema-validation-master  File: OneOfValidatorTest.java View source code
@Override
protected void checkOkOk(final ProcessingReport report) throws ProcessingException {
    final ArgumentCaptor<ProcessingMessage> captor = ArgumentCaptor.forClass(ProcessingMessage.class);
    verify(report).error(captor.capture());
    final ProcessingMessage message = captor.getValue();
    final ObjectNode reports = FACTORY.objectNode();
    final ArrayNode oneReport = FACTORY.arrayNode();
    reports.put(ptr1.toString(), oneReport);
    reports.put(ptr2.toString(), oneReport);
    assertMessage(message).isValidationError(keyword, BUNDLE.printf("err.draftv4.oneOf.fail", 2, 2)).hasField("reports", reports).hasField("nrSchemas", 2).hasField("matched", 2);
}
Example 49
Project: json-schema-validator-master  File: OneOfValidatorTest.java View source code
@Override
protected void checkOkOk(final ProcessingReport report) throws ProcessingException {
    final ArgumentCaptor<ProcessingMessage> captor = ArgumentCaptor.forClass(ProcessingMessage.class);
    verify(report).error(captor.capture());
    final ProcessingMessage message = captor.getValue();
    final ObjectNode reports = FACTORY.objectNode();
    final ArrayNode oneReport = FACTORY.arrayNode();
    reports.put(ptr1.toString(), oneReport);
    reports.put(ptr2.toString(), oneReport);
    assertMessage(message).isValidationError(keyword, BUNDLE.printf("err.draftv4.oneOf.fail", 2, 2)).hasField("reports", reports).hasField("nrSchemas", 2).hasField("matched", 2);
}
Example 50
Project: Kore-master  File: Favourites.java View source code
@Override
public ApiList<FavouriteType.DetailsFavourite> resultFromJson(ObjectNode jsonObject) throws ApiException {
    ListType.LimitsReturned limits = new ListType.LimitsReturned(jsonObject);
    JsonNode resultNode = jsonObject.get(RESULT_NODE);
    ArrayNode items = resultNode.has(LIST_NODE) && !resultNode.get(LIST_NODE).isNull() ? (ArrayNode) resultNode.get(LIST_NODE) : null;
    if (items == null) {
        return new ApiList<>(Collections.<FavouriteType.DetailsFavourite>emptyList(), limits);
    }
    ArrayList<FavouriteType.DetailsFavourite> result = new ArrayList<>(items.size());
    for (JsonNode item : items) {
        result.add(new FavouriteType.DetailsFavourite(item));
    }
    return new ApiList<>(result, limits);
}
Example 51
Project: map-matching-master  File: MatchResultToJson.java View source code
static JsonNode convertToTree(MatchResult result, ObjectMapper objectMapper) {
    ObjectNode root = objectMapper.createObjectNode();
    ObjectNode diary = root.putObject("diary");
    ArrayNode entries = diary.putArray("entries");
    ObjectNode route = entries.addObject();
    ArrayNode links = route.putArray("links");
    for (int emIndex = 0; emIndex < result.getEdgeMatches().size(); emIndex++) {
        ObjectNode link = links.addObject();
        EdgeMatch edgeMatch = result.getEdgeMatches().get(emIndex);
        PointList pointList = edgeMatch.getEdgeState().fetchWayGeometry(emIndex == 0 ? 3 : 2);
        final ObjectNode geometry = link.putObject("geometry");
        if (pointList.size() < 2) {
            geometry.putArray("coordinates").add(objectMapper.convertValue(pointList.toGeoJson().get(0), JsonNode.class));
            geometry.put("type", "Point");
        } else {
            geometry.putArray("coordinates").addAll(objectMapper.convertValue(pointList.toGeoJson(), ArrayNode.class));
            geometry.put("type", "LineString");
        }
        link.put("id", edgeMatch.getEdgeState().getEdge());
        ArrayNode wpts = link.putArray("wpts");
        for (GPXExtension extension : edgeMatch.getGpxExtensions()) {
            ObjectNode wpt = wpts.addObject();
            wpt.put("x", extension.getQueryResult().getSnappedPoint().lon);
            wpt.put("y", extension.getQueryResult().getSnappedPoint().lat);
            wpt.put("timestamp", extension.getEntry().getTime());
        }
    }
    return root;
}
Example 52
Project: monasca-common-master  File: Configurations.java View source code
private static void buildConfigFor(String path, Map<String, String> config, JsonNode node) {
    for (Iterator<Map.Entry<String, JsonNode>> i = node.fields(); i.hasNext(); ) {
        Map.Entry<String, JsonNode> field = i.next();
        if (field.getValue() instanceof ValueNode) {
            ValueNode valueNode = (ValueNode) field.getValue();
            config.put(DOT_JOINER.join(path, field.getKey()), valueNode.asText());
        } else if (field.getValue() instanceof ArrayNode) {
            StringBuilder combinedValue = new StringBuilder();
            ArrayNode arrayNode = (ArrayNode) field.getValue();
            for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) {
                String value = it.next().asText().replaceAll("^\"|\"$", "");
                if (combinedValue.length() > 0)
                    combinedValue.append(',');
                combinedValue.append(value);
            }
            config.put(DOT_JOINER.join(path, field.getKey()), combinedValue.toString());
        }
        buildConfigFor(DOT_JOINER.join(path, field.getKey()), config, field.getValue());
    }
}
Example 53
Project: oerworldmap-master  File: GeoJsonExporter.java View source code
@Override
public String export(ResourceList aResourceList) {
    ObjectNode node = new ObjectNode(JsonNodeFactory.instance);
    ArrayNode features = new ArrayNode(JsonNodeFactory.instance);
    node.put("type", "FeatureCollection");
    for (Resource resource : aResourceList.getItems()) {
        JsonNode feature = toGeoJson(resource);
        if (feature != null) {
            features.add(feature);
        }
    }
    node.set("features", features);
    return node.toString();
}
Example 54
Project: pac4j-master  File: CasOAuthWrapperProfileDefinition.java View source code
@Override
public CasOAuthWrapperProfile extractUserProfile(final String body) throws HttpAction {
    final CasOAuthWrapperProfile profile = newProfile();
    JsonNode json = JsonHelper.getFirstNode(body);
    if (json != null) {
        profile.setId(JsonHelper.getElement(json, "id"));
        json = json.get("attributes");
        if (json != null) {
            // CAS <= v4.2
            if (json instanceof ArrayNode) {
                final Iterator<JsonNode> nodes = json.iterator();
                while (nodes.hasNext()) {
                    json = nodes.next();
                    final String attribute = json.fieldNames().next();
                    convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute));
                }
            // CAS v5
            } else if (json instanceof ObjectNode) {
                final Iterator<String> keys = json.fieldNames();
                while (keys.hasNext()) {
                    final String key = keys.next();
                    convertAndAdd(profile, key, JsonHelper.getElement(json, key));
                }
            }
        }
    }
    return profile;
}
Example 55
Project: sfc-master  File: SbRestSfstTaskTest.java View source code
private ObjectNode buildServiceFunctionSchedulerTypeObjectNode() {
    ObjectNode topNode = mapper.createObjectNode();
    ObjectNode sfstNode = mapper.createObjectNode();
    sfstNode.put(SfstExporterFactory.NAME, SFST_NAME);
    ArrayNode arrayNode = mapper.createArrayNode();
    arrayNode.add(sfstNode);
    topNode.put(SfstExporterFactory.SERVICE_FUNCTION_SCHEDULE_TYPE, arrayNode);
    return topNode;
}
Example 56
Project: SOS-master  File: ValidationMatchers.java View source code
protected boolean describeProcessingReport(ProcessingReport report, JsonNode item, Description mismatchDescription) throws JsonProcessingException {
    if (!report.isSuccess()) {
        ObjectNode objectNode = JacksonUtils.nodeFactory().objectNode();
        objectNode.put(JSONConstants.INSTANCE, item);
        ArrayNode errors = objectNode.putArray(JSONConstants.ERRORS);
        for (ProcessingMessage m : report) {
            errors.add(m.asJson());
        }
        mismatchDescription.appendText(JacksonUtils.prettyPrint(objectNode));
    }
    return report.isSuccess();
}
Example 57
Project: sphere-snowflake-master  File: ListProducts.java View source code
public static ObjectNode getJson(SearchResult<Product> search, Category category, String sort) {
    ObjectNode json = Json.newObject();
    // Pager attributes
    json.put("offsetProducts", search.getOffset());
    json.put("countProducts", search.getCount());
    json.put("totalProducts", search.getTotal());
    json.put("currentPage", search.getCurrentPage());
    json.put("totalPages", search.getTotalPages());
    // Next page URL
    Call url = getProductListUrl(search, sort, category);
    if (url != null) {
        json.put("nextPageUrl", url.absoluteURL(Http.Context.current().request()));
    }
    // Product list
    ArrayNode products = json.putArray("product");
    int i = search.getOffset();
    for (Product product : search.getResults()) {
        products.add(getJson(product, category, i));
        i++;
    }
    return json;
}
Example 58
Project: syncope-master  File: SAML2IdPsResource.java View source code
@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {
    ResourceResponse response = new ResourceResponse();
    response.setContentType(MediaType.APPLICATION_JSON);
    response.setTextEncoding(StandardCharsets.UTF_8.name());
    try {
        final ArrayNode result = MAPPER.createArrayNode();
        for (SAML2IdPTO idp : SyncopeEnduserSession.get().getService(SAML2IdPService.class).list()) {
            ObjectNode idpNode = MAPPER.createObjectNode();
            idpNode.put("name", idp.getName());
            idpNode.put("entityID", idp.getEntityID());
            idpNode.put("logout", idp.isLogoutSupported());
            result.add(idpNode);
        }
        response.setWriteCallback(new AbstractResource.WriteCallback() {

            @Override
            public void writeData(final Attributes attributes) throws IOException {
                attributes.getResponse().write(MAPPER.writeValueAsString(result));
            }
        });
        response.setStatusCode(Response.Status.OK.getStatusCode());
    } catch (Exception e) {
        LOG.error("Error retrieving available SAML 2.0 Identity Providers", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "ErrorMessage{{ " + e.getMessage() + "}}");
    }
    return response;
}
Example 59
Project: unravl-master  File: TestJsonPath.java View source code
@Test
public void testJsonPath() throws UnRAVLException {
    // drives configuration
    UnRAVLRuntime r = new UnRAVLRuntime();
    assertNotNull(r);
    String document = "{ \"s\": \"string\", \"b\": true, \"i\": 100, \"n\": 0.5, \"o\": { \"x\": 0, \"y\" : 0 }, \"a\": [ 0,1,2,3,4,5] }";
    JsonNode node = Json.parse(document);
    ObjectMapper m = new ObjectMapper();
    Object jo;
    if (node instanceof ObjectNode)
        jo = m.convertValue(node, Map.class);
    else
        // (node instanceof ArrayNode)
        jo = m.convertValue(node, List.class);
    // JsonPath parses strings into java.util.Map and java.util.List
    // objects.
    // If we have a Jackson JsonNode (an ObjectNode or an ArrayNode), we
    // must convert the Jackson types to Maps or Lists to use JsonPath.
    JsonProvider jp = Configuration.defaultConfiguration().jsonProvider();
    assertNotNull(jo);
    String s = JsonPath.read(jo, "$.s");
    Object o = JsonPath.read(jo, "$.o");
    Object a = JsonPath.read(jo, "$.a");
    assertTrue(s.equals("string"));
    assertNotNull(o);
    assertNotNull(a);
    assertTrue(jp.isMap(o));
    assertTrue(jp.isArray(a));
    ObjectNode on = m.valueToTree(o);
    ArrayNode an = m.valueToTree(a);
    assertNotNull(on);
    assertNotNull(an);
    assertEquals(2, on.size());
    assertEquals(6, an.size());
}
Example 60
Project: aerogear-unifiedpush-server-master  File: RequestTransformer.java View source code
private JsonNode transformJson(JsonNode patch, StringBuilder json) throws IOException, JsonPatchException {
    JsonNode jsonNode = convertToJsonNode(json);
    for (JsonNode operation : patch) {
        try {
            final ArrayNode nodes = JsonNodeFactory.instance.arrayNode();
            nodes.add(operation);
            JsonPatch patchOperation = JsonPatch.fromJson(nodes);
            jsonNode = patchOperation.apply(jsonNode);
        } catch (JsonPatchException e) {
            logger.trace("ignore field not found");
        }
    }
    return jsonNode;
}
Example 61
Project: anti-piracy-android-app-master  File: GeometryDeserializer.java View source code
public Geometry parseGeometry(JsonParser parser) throws JsonParseException, IOException {
    if (parser.getCurrentToken() != JsonToken.START_OBJECT)
        return null;
    String typeName = null;
    ArrayNode coordinates = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        if ("type".equals(name)) {
            parser.nextToken();
            typeName = parser.getText();
        } else if ("coordinates".equals(name)) {
            parser.nextToken();
            coordinates = parser.readValueAsTree();
        } else {
            parser.nextToken();
            parser.skipChildren();
        }
    }
    Geometry geometry = null;
    if (typeName.equals("Point")) {
        geometry = geometryFactory.createPoint(new Coordinate(coordinates.get(0).asDouble(), coordinates.get(1).asDouble()));
    } else if (typeName.equals("MultiPoint")) {
        geometry = geometryFactory.createMultiPoint(parseLineString(coordinates));
    } else if (typeName.equals("LineString")) {
        geometry = geometryFactory.createLineString(parseLineString(coordinates));
    } else if (typeName.equals("MultiLineString")) {
        geometry = geometryFactory.createMultiLineString(parseLineStrings(coordinates));
    } else if (typeName.equals("Polygon")) {
        geometry = parsePolygonCoordinates(coordinates);
    } else if (typeName.equals("MultiPolygon")) {
        geometry = geometryFactory.createMultiPolygon(parsePolygons(coordinates));
    } else if (typeName.equals("GeometryCollection")) {
        geometry = geometryFactory.createGeometryCollection(parseGeometries(coordinates));
    }
    return geometry;
}
Example 62
Project: apiman-master  File: Version122FinalMigrator.java View source code
/**
     * @see io.apiman.manager.api.migrator.IVersionMigrator#migrateOrg(com.fasterxml.jackson.databind.node.ObjectNode)
     */
@Override
public void migrateOrg(ObjectNode node) {
    //$NON-NLS-1$
    ArrayNode clients = (ArrayNode) node.get("Clients");
    if (clients != null && clients.size() > 0) {
        for (JsonNode clientNode : clients) {
            ObjectNode client = (ObjectNode) clientNode;
            //$NON-NLS-1$
            ArrayNode versions = (ArrayNode) client.get("Versions");
            if (versions != null && versions.size() > 0) {
                for (JsonNode versionNode : versions) {
                    ObjectNode version = (ObjectNode) versionNode;
                    //$NON-NLS-1$
                    ObjectNode clientVersionBean = (ObjectNode) version.get("ClientVersionBean");
                    //$NON-NLS-1$
                    clientVersionBean.put("apikey", keyGenerator.generate());
                    //$NON-NLS-1$
                    ArrayNode contracts = (ArrayNode) version.get("Contracts");
                    if (contracts != null && contracts.size() > 0) {
                        for (JsonNode contractNode : contracts) {
                            ObjectNode contract = (ObjectNode) contractNode;
                            //$NON-NLS-1$
                            contract.remove("apikey");
                        }
                    }
                }
            }
        }
    }
}
Example 63
Project: axelor-business-suite-master  File: MapRest.java View source code
@Path("/lead")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonNode getLeads() {
    List<? extends Lead> leads = leadRepo.all().fetch();
    JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode mainNode = factory.objectNode();
    ArrayNode arrayNode = factory.arrayNode();
    for (Lead lead : leads) {
        String fullName = lead.getFirstName() + " " + lead.getName();
        if (lead.getEnterpriseName() != null) {
            fullName = lead.getEnterpriseName() + "</br>" + fullName;
        }
        ObjectNode objectNode = factory.objectNode();
        objectNode.put("fullName", fullName);
        objectNode.put("fixedPhone", lead.getFixedPhone() != null ? lead.getFixedPhone() : " ");
        if (lead.getEmailAddress() != null) {
            objectNode.put("emailAddress", lead.getEmailAddress().getAddress());
        }
        StringBuilder addressString = new StringBuilder();
        if (lead.getPrimaryAddress() != null) {
            addressString.append(lead.getPrimaryAddress() + "</br>");
        }
        if (lead.getPrimaryCity() != null) {
            addressString.append(lead.getPrimaryCity() + "</br>");
        }
        if (lead.getPrimaryPostalCode() != null) {
            addressString.append(lead.getPrimaryPostalCode() + "</br>");
        }
        if (lead.getPrimaryState() != null) {
            addressString.append(lead.getPrimaryState() + "</br>");
        }
        if (lead.getPrimaryCountry() != null) {
            addressString.append(lead.getPrimaryCountry().getName());
        }
        String qString = addressString.toString().replaceAll("</br>", " ");
        Map<String, Object> latlng = mapService.getMapGoogle(qString);
        objectNode.put("address", addressString.toString());
        objectNode.put("pinColor", "yellow");
        objectNode.put("pinChar", "L");
        arrayNode.add(objectNode);
    }
    mainNode.put("status", 0);
    mainNode.put("data", arrayNode);
    return mainNode;
}
Example 64
Project: breakerbox-master  File: RancherInstanceDiscovery.java View source code
private Collection<Instance> createServiceInstanceList(String rancherServiceApiResponse) throws IOException {
    JsonNode serviceJsonResponseNode = mapper.readValue(rancherServiceApiResponse, JsonNode.class);
    List<JsonNode> dataList = convertJsonArrayToList((ArrayNode) serviceJsonResponseNode.get("data"));
    Collection<Instance> instances = dataList.stream().filter(this::isServiceDashboardEnabled).map(this::createInstanceList).flatMap(Collection::stream).collect(Collectors.toList());
    instances.addAll(createProductionDashboard(instances));
    return instances;
}
Example 65
Project: che-master  File: CommandDeserializer.java View source code
/**
     * Parse command field from the compose yaml file to list command words.
     *
     * @param jsonParser
     *         json parser
     * @param ctxt
     *         deserialization context
     * @throws IOException
     *         in case I/O error. For example element to parsing contains
     *         invalid yaml field type defined for this field by yaml document model.
     * @throws JsonProcessingException
     */
@Override
public List<String> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    TreeNode tree = jsonParser.readValueAsTree();
    if (tree.isArray()) {
        return toCommand((ArrayNode) tree, ctxt);
    }
    if (tree instanceof TextNode) {
        TextNode textNode = (TextNode) tree;
        return asList(textNode.asText().trim().split(SPLIT_COMMAND_REGEX));
    }
    throw ctxt.mappingException((format("Field '%s' must be simple text or string array.", jsonParser.getCurrentName())));
}
Example 66
Project: DevTools-master  File: CommandDeserializer.java View source code
/**
     * Parse command field from the compose yaml file to list command words.
     *
     * @param jsonParser
     *         json parser
     * @param ctxt
     *         deserialization context
     * @throws IOException
     *         in case I/O error. For example element to parsing contains
     *         invalid yaml field type defined for this field by yaml document model.
     * @throws JsonProcessingException
     */
@Override
public List<String> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    TreeNode tree = jsonParser.readValueAsTree();
    if (tree.isArray()) {
        return toCommand((ArrayNode) tree, ctxt);
    }
    if (tree instanceof TextNode) {
        TextNode textNode = (TextNode) tree;
        return asList(textNode.asText().trim().split(SPLIT_COMMAND_REGEX));
    }
    throw ctxt.mappingException((format("Field '%s' must be simple text or string array.", jsonParser.getCurrentName())));
}
Example 67
Project: disconnected-content-explorer-android-master  File: GeometryDeserializer.java View source code
public Geometry parseGeometry(JsonParser parser) throws JsonParseException, IOException {
    if (parser.getCurrentToken() != JsonToken.START_OBJECT)
        return null;
    String typeName = null;
    ArrayNode coordinates = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        if ("type".equals(name)) {
            parser.nextToken();
            typeName = parser.getText();
        } else if ("coordinates".equals(name)) {
            parser.nextToken();
            coordinates = parser.readValueAsTree();
        } else {
            parser.nextToken();
            parser.skipChildren();
        }
    }
    Geometry geometry = null;
    if (typeName.equals("Point")) {
        geometry = geometryFactory.createPoint(new Coordinate(coordinates.get(0).asDouble(), coordinates.get(1).asDouble()));
    } else if (typeName.equals("MultiPoint")) {
        geometry = geometryFactory.createMultiPoint(parseLineString(coordinates));
    } else if (typeName.equals("LineString")) {
        geometry = geometryFactory.createLineString(parseLineString(coordinates));
    } else if (typeName.equals("MultiLineString")) {
        geometry = geometryFactory.createMultiLineString(parseLineStrings(coordinates));
    } else if (typeName.equals("Polygon")) {
        geometry = parsePolygonCoordinates(coordinates);
    } else if (typeName.equals("MultiPolygon")) {
        geometry = geometryFactory.createMultiPolygon(parsePolygons(coordinates));
    } else if (typeName.equals("GeometryCollection")) {
        geometry = geometryFactory.createGeometryCollection(parseGeometries(coordinates));
    }
    return geometry;
}
Example 68
Project: eManga-master  File: MangaDeserializer.java View source code
@Override
public Manga deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonNode node = jp.getCodec().readTree(jp);
    String _id = node.get("_id").get("$oid").asText();
    String title = null;
    JsonNode titleNode = node.get("title");
    if (titleNode != null && !(titleNode instanceof NullNode)) {
        title = titleNode.asText();
    }
    List<Author> authors = null;
    JsonNode authorsNode = node.get("authors");
    if (authorsNode != null && !(authorsNode instanceof NullNode)) {
        ArrayNode authorsNames = (ArrayNode) authorsNode;
        authors = new ArrayList<Author>(authorsNames.size());
        for (int i = 0; i < authorsNames.size(); i++) {
            authors.add(new Author(authorsNames.get(i).asText()));
        }
    }
    String summary = null;
    JsonNode summaryNode = node.get("summary");
    if (summaryNode != null && !(summaryNode instanceof NullNode)) {
        summary = summaryNode.asText();
    }
    String cover = null;
    JsonNode coverNode = node.get("cover");
    if (coverNode != null && !(coverNode instanceof NullNode)) {
        cover = coverNode.asText();
    }
    List<Genre> genres = null;
    JsonNode genresNode = node.get("genres");
    if (genresNode != null && !(genresNode instanceof NullNode)) {
        ArrayNode genresNames = (ArrayNode) genresNode;
        genres = new ArrayList<Genre>(genresNames.size());
        for (int i = 0; i < genresNames.size(); i++) {
            genres.add(new Genre(genresNames.get(i).asText()));
        }
    }
    Date created_at = null;
    JsonNode created_atNode = node.get("created_at");
    if (created_atNode != null && !(created_atNode instanceof NullNode)) {
        try {
            created_at = Dates.sdf.parse(created_atNode.asText());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    Date modified_at = null;
    JsonNode modified_atNode = node.get("modify_at");
    if (modified_atNode != null && !(modified_atNode instanceof NullNode)) {
        try {
            modified_at = Dates.sdf.parse(modified_atNode.asText());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    int numberChapters = 0;
    JsonNode n_chapters_atNode = node.get("n_chapters");
    if (n_chapters_atNode != null && !(n_chapters_atNode instanceof NullNode)) {
        numberChapters = n_chapters_atNode.asInt();
    }
    Manga manga = new Manga(_id, title, authors, cover, summary, created_at, modified_at, genres, numberChapters);
    JsonNode chaptersNode = node.get("chapters");
    if (chaptersNode != null && !(chaptersNode instanceof NullNode)) {
        manga.chapters = App.getInstance().mMapper.readValue(chaptersNode.toString(), new TypeReference<Collection<Chapter>>() {
        });
        if (manga.chapters != null) {
            Iterator<Chapter> it = manga.chapters.iterator();
            while (it.hasNext()) {
                it.next().manga = manga;
            }
        }
    }
    return manga;
}
Example 69
Project: emfjson-jackson-master  File: UuidSaveTest.java View source code
@Test
public void testSerializeOneRootWithTwoChildHavingOneReference() throws IOException {
    Resource resource = createUuidResource("test.xmi", mapper);
    Container root = ModelFactory.eINSTANCE.createContainer();
    ConcreteTypeOne one = ModelFactory.eINSTANCE.createConcreteTypeOne();
    ConcreteTypeOne two = ModelFactory.eINSTANCE.createConcreteTypeOne();
    one.setName("one");
    two.setName("two");
    one.getRefProperty().add(two);
    root.getElements().add(one);
    root.getElements().add(two);
    resource.getContents().add(root);
    JsonNode node = mapper.valueToTree(root);
    assertNotNull(node);
    assertNotNull(node.get("@id"));
    assertEquals(uuid(root), uuid(node));
    assertTrue(node.get("elements").isArray());
    ArrayNode elements = (ArrayNode) node.get("elements");
    assertEquals(2, elements.size());
    JsonNode node1 = elements.get(0);
    JsonNode node2 = elements.get(1);
    assertNotNull(node1.get("@id"));
    assertEquals(uuid(one), uuid(node1));
    assertNotNull(node2.get("@id"));
    assertEquals(uuid(two), uuid(node2));
    assertNotNull(node1.get("refProperty"));
    assertNull(node2.get("refProperty"));
    assertTrue(node1.get("refProperty").isArray());
    ArrayNode refProperty = (ArrayNode) node1.get("refProperty");
    assertEquals(1, refProperty.size());
    JsonNode ref = refProperty.get(0);
    assertNotNull(ref.get("$ref"));
    assertEquals(uuid(two), ref.get("$ref").asText());
}
Example 70
Project: incubator-taverna-language-master  File: ApiConsomerActivityParser.java View source code
@Override
public Configuration parseConfiguration(T2FlowParser t2FlowParser, ConfigBean configBean, ParserState parserState) throws ReaderException {
    ApiConsumerConfig config = unmarshallConfig(t2FlowParser, configBean, "xstream", ApiConsumerConfig.class);
    Configuration configuration = new Configuration();
    configuration.setParent(parserState.getCurrentProfile());
    ObjectNode json = (ObjectNode) configuration.getJson();
    configuration.setType(ACTIVITY_URI.resolve("#Config"));
    json.put("apiConsumerDescription", config.getApiConsumerDescription());
    json.put("apiConsumerName", config.getApiConsumerName());
    json.put("description", config.getDescription());
    json.put("className", config.getClassName());
    json.put("methodName", config.getMethodName());
    ArrayNode parameterNames = json.arrayNode();
    json.put("parameterNames", parameterNames);
    for (String parameterName : config.getParameterNames().getString()) parameterNames.add(parameterName);
    ArrayNode parameterDimensions = json.arrayNode();
    json.put("parameterDimensions", parameterDimensions);
    for (BigInteger parameterDimension : config.getParameterDimensions().getInt()) parameterDimensions.add(parameterDimension.intValue());
    ArrayNode parameterTypes = json.arrayNode();
    json.put("parameterTypes", parameterTypes);
    for (String parameterType : config.getParameterTypes().getString()) parameterTypes.add(parameterType);
    json.put("returnType", config.getReturnType());
    json.put("returnDimension", config.getReturnDimension().intValue());
    json.put("isMethodConstructor", config.isIsMethodConstructor());
    json.put("isMethodStatic", config.isIsMethodStatic());
    return configuration;
}
Example 71
Project: jackson-databind-master  File: NodeMergeTest.java View source code
public void testObjectDeepUpdate() throws Exception {
    ObjectNode base = MAPPER.createObjectNode();
    ObjectNode props = base.putObject("props");
    props.put("base", 123);
    props.put("value", 456);
    ArrayNode a = props.putArray("array");
    a.add(true);
    base.putNull("misc");
    assertSame(base, MAPPER.readerForUpdating(base).readValue(aposToQuotes("{'props':{'value':true, 'extra':25.5, 'array' : [ 3 ]}}")));
    assertEquals(2, base.size());
    ObjectNode resultProps = (ObjectNode) base.get("props");
    assertEquals(4, resultProps.size());
    assertEquals(123, resultProps.path("base").asInt());
    assertTrue(resultProps.path("value").asBoolean());
    assertEquals(25.5, resultProps.path("extra").asDouble());
    JsonNode n = resultProps.get("array");
    assertEquals(ArrayNode.class, n.getClass());
    assertEquals(2, n.size());
    assertEquals(3, n.get(1).asInt());
}
Example 72
Project: jackson-datatype-protobuf-master  File: PropertyNamingTest.java View source code
@Test
public void testMultipleSnakeCaseToCamelCase() {
    List<PropertyNamingSnakeCased> messages = ProtobufCreator.create(PropertyNamingSnakeCased.class, 10);
    JsonNode tree = toTree(camelCase(), messages);
    assertThat(tree).isInstanceOf(ArrayNode.class);
    assertThat(tree.size()).isEqualTo(10);
    for (int i = 0; i < 10; i++) {
        JsonNode subTree = tree.get(i);
        assertThat(subTree.isObject()).isTrue();
        assertThat(subTree.size()).isEqualTo(1);
        assertThat(subTree.get("stringAttribute")).isNotNull();
        assertThat(subTree.get("stringAttribute").textValue()).isEqualTo(messages.get(i).getStringAttribute());
    }
}
Example 73
Project: jml-master  File: CategoricalFeaturesMap.java View source code
public void save(final File file) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = mapper.createObjectNode();
    ArrayNode jsonList = mapper.createArrayNode();
    inverse.forEach(jsonList::add);
    node.set("inverse_index", jsonList);
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write(new JsonProgress(this).toJson());
        writer.flush();
        writer.close();
    } catch (IOException e) {
        log.log(Level.WARNING, "Can't save cat feature index to file");
        e.printStackTrace();
    }
}
Example 74
Project: jsonschema2pojo-master  File: RequiredArrayRuleTest.java View source code
@Test
public void shouldUpdateJavaDoc() throws JClassAlreadyExistsException {
    JDefinedClass jclass = new JCodeModel()._class(TARGET_CLASS_NAME);
    jclass.field(JMod.PRIVATE, jclass.owner().ref(String.class), "fooBar");
    jclass.field(JMod.PRIVATE, jclass.owner().ref(String.class), "foo");
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode requiredNode = mapper.createArrayNode().add("fooBar");
    rule.apply("Class", requiredNode, jclass, new Schema(null, requiredNode, requiredNode));
    JDocComment fooBarJavaDoc = jclass.fields().get("fooBar").javadoc();
    JDocComment fooJavaDoc = jclass.fields().get("foo").javadoc();
    assertThat(fooBarJavaDoc.size(), is(1));
    assertThat((String) fooBarJavaDoc.get(0), is("\n(Required)"));
    assertThat(fooJavaDoc.size(), is(0));
}
Example 75
Project: mage-android-sdk-master  File: GeometryDeserializer.java View source code
public Geometry parseGeometry(JsonParser parser) throws IOException {
    if (parser.getCurrentToken() != JsonToken.START_OBJECT)
        return null;
    String typeName = null;
    ArrayNode coordinates = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        if ("type".equals(name)) {
            parser.nextToken();
            typeName = parser.getText();
        } else if ("coordinates".equals(name)) {
            parser.nextToken();
            coordinates = parser.readValueAsTree();
        } else {
            parser.nextToken();
            parser.skipChildren();
        }
    }
    if (typeName == null) {
        throw new IOException("'type' not present");
    }
    Geometry geometry = null;
    if (typeName.equals("Point")) {
        geometry = geometryFactory.createPoint(new Coordinate(coordinates.get(0).asDouble(), coordinates.get(1).asDouble()));
    } else if (typeName.equals("MultiPoint")) {
        geometry = geometryFactory.createMultiPoint(parseLineString(coordinates));
    } else if (typeName.equals("LineString")) {
        geometry = geometryFactory.createLineString(parseLineString(coordinates));
    } else if (typeName.equals("MultiLineString")) {
        geometry = geometryFactory.createMultiLineString(parseLineStrings(coordinates));
    } else if (typeName.equals("Polygon")) {
        geometry = parsePolygonCoordinates(coordinates);
    } else if (typeName.equals("MultiPolygon")) {
        geometry = geometryFactory.createMultiPolygon(parsePolygons(coordinates));
    } else if (typeName.equals("GeometryCollection")) {
        geometry = geometryFactory.createGeometryCollection(parseGeometries(coordinates));
    }
    return geometry;
}
Example 76
Project: myfda-master  File: EventController.java View source code
@RequestMapping("/event")
public String search(@RequestParam(value = "unii", defaultValue = "") String unii, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "skip", defaultValue = "0") int skip) throws IOException {
    if (unii == null) {
        unii = "";
    }
    Map<String, Long> terms = this.getEventTerms(unii);
    ObjectMapper mapper = new ObjectMapper();
    long max = 0L;
    for (String k : terms.keySet()) {
        if (terms.get(k) > max) {
            max = terms.get(k);
        }
    }
    Set<AdverseEffect> effects = new TreeSet<AdverseEffect>();
    for (String k : terms.keySet()) {
        AdverseEffect ef = new AdverseEffect();
        ef.setEffect(k);
        ef.setCount(terms.get(k));
        ef.setTotal(max);
        ef.setDescription(adverseEffectService.findEffectDescription(k));
        // TODO set description
        effects.add(ef);
    }
    ObjectNode top = mapper.createObjectNode();
    top.put("UNII", unii);
    ArrayNode array = mapper.createArrayNode();
    int count = 0;
    for (AdverseEffect ef : effects) {
        if (count >= skip) {
            if (count == limit + skip) {
                break;
            }
            array.add((JsonNode) mapper.valueToTree(ef));
        }
        count++;
    }
    top.put("effect", array);
    return mapper.writeValueAsString(top);
}
Example 77
Project: prospecter-master  File: HttpApiRequestHandler.java View source code
protected FullHttpResponse matchDocument(Schema schema) throws MalformedDocumentException, JsonProcessingException {
    ByteBuf content = request.content();
    int matchCount = 0;
    ObjectNode node = mapper.getNodeFactory().objectNode();
    if (content.isReadable()) {
        LOGGER.debug("start matching");
        Document doc = schema.getDocumentBuilder().build(content.toString(CharsetUtil.UTF_8));
        Matcher matcher = schema.matchDocument(doc);
        ArrayNode results = node.putArray("matches");
        for (Integer queryId : matcher.getMatchedQueries()) {
            matchCount++;
            ObjectNode queryNode = results.addObject();
            queryNode.put("id", queryId);
        }
        LOGGER.debug("finished matching");
    }
    node.put("count", matchCount);
    return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(mapper.writeValueAsString(node), CharsetUtil.UTF_8));
}
Example 78
Project: ratpack-master  File: AbstractPropertiesConfigSource.java View source code
private void populate(ObjectNode node, String key, String value) {
    int nextDot = key.indexOf('.');
    int nextOpenBracket = key.indexOf('[');
    boolean hasDelimiter = nextDot != -1;
    boolean hasIndexing = nextOpenBracket != -1;
    if (hasDelimiter && (!hasIndexing || (nextDot < nextOpenBracket))) {
        String fieldName = key.substring(0, nextDot);
        String remainingKey = key.substring(nextDot + 1);
        ObjectNode childNode = (ObjectNode) node.get(fieldName);
        if (childNode == null) {
            childNode = node.putObject(fieldName);
        }
        populate(childNode, remainingKey, value);
    } else if (hasIndexing) {
        int nextCloseBracket = key.indexOf(']', nextOpenBracket + 1);
        if (nextCloseBracket == -1) {
            throw new IllegalArgumentException("Invalid remaining key: " + key);
        }
        String fieldName = key.substring(0, nextOpenBracket);
        int index = Integer.valueOf(key.substring(nextOpenBracket + 1, nextCloseBracket));
        String remainingKey = key.substring(nextCloseBracket + 1);
        ArrayNode arrayNode = (ArrayNode) node.get(fieldName);
        if (arrayNode == null) {
            arrayNode = node.putArray(fieldName);
        }
        padToLength(arrayNode, index + 1);
        if (remainingKey.isEmpty()) {
            arrayNode.set(index, TextNode.valueOf(value));
        } else if (remainingKey.startsWith(".")) {
            remainingKey = remainingKey.substring(1);
            ObjectNode childNode;
            if (arrayNode.hasNonNull(index)) {
                childNode = (ObjectNode) arrayNode.get(index);
            } else {
                childNode = arrayNode.objectNode();
                arrayNode.set(index, childNode);
            }
            populate(childNode, remainingKey, value);
        } else {
            throw new IllegalArgumentException("Unknown key format: " + key);
        }
    } else {
        node.set(key, TextNode.valueOf(value));
    }
}
Example 79
Project: shapeshifter-master  File: AutoParserTest.java View source code
@Test
public void testParseWithEmptyRepeated() throws Exception {
    Actor actor = Actor.newBuilder().setName("James Dean").build();
    ObjectNode json = (ObjectNode) new AutoSerializer(Actor.getDescriptor()).serialize(actor, ReadableSchemaRegistry.EMPTY);
    json.put("quotes", new ArrayNode(JsonNodeFactory.instance));
    Message parsedMessage = new AutoParser(Actor.getDescriptor()).parse(json, ReadableSchemaRegistry.EMPTY);
    Actor parsedActor = Actor.newBuilder().mergeFrom(parsedMessage).build();
    Assert.assertEquals("James Dean", parsedActor.getName());
    Assert.assertEquals(0, parsedActor.getQuotesCount());
}
Example 80
Project: SmallMind-master  File: WireContextXmlAdapter.java View source code
@Override
public JsonNode marshal(WireContext[] wireContexts) throws JsonProcessingException {
    if (wireContexts == null) {
        return null;
    }
    ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(wireContexts.length);
    for (WireContext wireContext : wireContexts) {
        if (wireContext instanceof ProtoWireContext) {
            ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
            objectNode.set(((ProtoWireContext) wireContext).getSkin(), JsonCodec.writeAsJsonNode(((ProtoWireContext) wireContext).getGuts()));
            arrayNode.add(objectNode);
        } else {
            ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
            XmlRootElement xmlRootElementAnnotation = wireContext.getClass().getAnnotation(XmlRootElement.class);
            objectNode.set((xmlRootElementAnnotation == null) ? wireContext.getClass().getSimpleName() : xmlRootElementAnnotation.name(), JsonCodec.writeAsJsonNode(wireContext));
            arrayNode.add(objectNode);
        }
    }
    return arrayNode;
}
Example 81
Project: spimedb-master  File: Solr.java View source code
public static JsonNode nobject2solrUpdate(NObject... xx) {
    ObjectMapper j = JSON.json;
    ObjectNode a = j.createObjectNode();
    ArrayNode da = a.withArray("delete");
    for (NObject x : xx) {
        da.add(x.id());
    }
    a.with("commit");
    for (NObject x : xx) {
        ObjectNode y = j.createObjectNode();
        y.put("id", x.id());
        y.put("name", x.name());
        x.forEach(( k,  v) -> {
            if ((k.equals("I")) || (k.equals("N")) || k.equals("inh") || (k.equals(">") || (k.equals("url_in"))))
                return;
            if (v instanceof String)
                y.put(k, (String) v);
            else if (v instanceof Integer)
                y.put(k, (Integer) v);
            else if (v instanceof String[]) {
                String[] vv = (String[]) v;
                ArrayNode va = y.putArray(k);
                for (String s : vv) {
                    va.add(s);
                }
            } else {
                logger.error("{} has unhandled field type: {}, value={}", k, v.getClass(), v);
            }
        });
        a.with("add").put("overwrite", true).put("doc", y);
    }
    a.with("commit");
    System.out.println(JSON.toJSONString(a, true));
    return a;
}
Example 82
Project: steve-master  File: Serializer.java View source code
@Override
public void process(CommunicationContext context) {
    OcppJsonMessage message = context.getOutgoingMessage();
    ArrayNode str;
    MessageType messageType = message.getMessageType();
    switch(messageType) {
        case CALL:
            str = handleCall((OcppJsonCall) message);
            break;
        case CALL_RESULT:
            str = handleResult((OcppJsonResult) message);
            break;
        case CALL_ERROR:
            str = handleError((OcppJsonError) message);
            break;
        default:
            throw new SteveException("Unknown enum type");
    }
    try {
        String result = mapper.writeValueAsString(str);
        context.setOutgoingString(result);
    } catch (IOException e) {
        throw new SteveException("The outgoing message could not be serialized", e);
    }
}
Example 83
Project: Toga-master  File: ObjectDimension.java View source code
/**
     * Generate a json representation of this object.
     * @return a String containing a json array with all possible permutations of the given object.
     */
public String generateJson() {
    JsonFactory factory = new JsonFactory();
    StringWriter stringWriter = new StringWriter();
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        JsonGenerator generator = factory.createGenerator(stringWriter);
        ArrayNode arrayNode = objectMapper.createArrayNode();
        getValueDimensions().stream().forEach(arrayNode::add);
        objectMapper.writeTree(generator, arrayNode);
        return toPrettyString(stringWriter.toString());
    } catch (IOException e) {
        throw new RuntimeException("Error writing node json nodes.", e);
    }
}
Example 84
Project: unikitty-master  File: EventController.java View source code
@RequestMapping("/event")
public String search(@RequestParam(value = "unii", defaultValue = "") String unii, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "skip", defaultValue = "0") int skip) throws IOException {
    if (unii == null) {
        unii = "";
    }
    Map<String, Long> terms = this.getEventTerms(unii);
    ObjectMapper mapper = new ObjectMapper();
    long max = 0L;
    for (String k : terms.keySet()) {
        if (terms.get(k) > max) {
            max = terms.get(k);
        }
    }
    Set<AdverseEffect> effects = new TreeSet<AdverseEffect>();
    for (String k : terms.keySet()) {
        AdverseEffect ef = new AdverseEffect();
        ef.setEffect(k);
        ef.setCount(terms.get(k));
        ef.setTotal(max);
        ef.setDescription(adverseEffectService.findEffectDescription(k));
        // TODO set description
        effects.add(ef);
    }
    ObjectNode top = mapper.createObjectNode();
    top.put("UNII", unii);
    ArrayNode array = mapper.createArrayNode();
    int count = 0;
    for (AdverseEffect ef : effects) {
        if (count >= skip) {
            if (count == limit + skip) {
                break;
            }
            array.add((JsonNode) mapper.valueToTree(ef));
        }
        count++;
    }
    top.put("effect", array);
    return mapper.writeValueAsString(top);
}
Example 85
Project: vitam-master  File: UnsetAction.java View source code
/**
     * Add other UnSet sub actions to UnSet Query
     *
     * @param variableNames list of key name
     * @return the UnSetAction
     * @throws InvalidCreateOperationException when query is invalid
     */
public final UnsetAction add(final String... variableNames) throws InvalidCreateOperationException {
    if (currentUPDATEACTION != UPDATEACTION.UNSET) {
        throw new InvalidCreateOperationException("Cannot add an unset element since this is not a UnSet Action: " + currentUPDATEACTION);
    }
    for (final String name : variableNames) {
        if (name != null && !name.trim().isEmpty()) {
            try {
                GlobalDatas.sanityParameterCheck(name);
            } catch (final InvalidParseOperationException e) {
                throw new InvalidCreateOperationException(e);
            }
            ((ArrayNode) currentObject).add(name);
        }
    }
    return this;
}
Example 86
Project: wisdom-master  File: ControllerExtension.java View source code
/**
     * @return the JSON structure read by the HTML page.
     */
@Route(method = HttpMethod.GET, uri = "/monitor/controllers/controllers")
public Result getControllers() {
    ObjectNode node = json.newObject();
    ArrayNode array = json.newArray();
    for (org.wisdom.api.Controller controller : controllers) {
        array.add(ControllerModel.from(controller, router, json));
    }
    for (InstanceDescription description : getInvalidControllers()) {
        array.add(ControllerModel.from(description, json));
    }
    node.put("controllers", array);
    node.put("invalid", getInvalidControllers().size());
    return ok(node);
}
Example 87
Project: XMLTestFramework-master  File: UserStoryHandler.java View source code
public static void getTests(ArrayNode arrayNode, String userStoryUUID) {
    System.out.println("UUID :" + userStoryUUID);
    // String Userstory=getTotalFile(new
    // File(baseUrl+arrayNode+"/userStory.html"));
    // UserStory userStory=new UserStory(arrayNode, Userstory);
    // System.out.println(userStoryUUID);
    final File folder = new File(baseUrl + userStoryUUID);
    for (// looping the folder
    final File fileEntry : // looping the folder
    folder.listFiles()) {
        if (// tests
        fileEntry.isDirectory()) {
            ObjectNode objectNode = arrayNode.addObject();
            objectNode.put("run", getTotalFile(new File(baseUrl + userStoryUUID + "/" + fileEntry.getName() + "/run.js")));
            objectNode.put("runFile", userStoryUUID + "/" + fileEntry.getName() + "/run.js");
            objectNode.put("name", fileEntry.getName());
            ArrayNode inputArr = objectNode.putArray("input");
            File input = new File(baseUrl + userStoryUUID + "/" + fileEntry.getName() + "/input");
            System.out.println(baseUrl + userStoryUUID + "/" + fileEntry.getName() + "/input");
            FilenameFilter removeTilde = new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    String lowercaseName = name.toLowerCase();
                    if (!lowercaseName.endsWith("~")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            };
            if (input.exists()) {
                File[] files = input.listFiles(removeTilde);
                Arrays.sort(files);
                for (File inputFile : files) {
                    System.out.println(inputFile.getName());
                    inputArr.add(inputFile.getName());
                }
            }
            ArrayNode outputArr = objectNode.putArray("output");
            File output = new File(baseUrl + userStoryUUID + "/" + fileEntry.getName() + "/output");
            if (output.exists()) {
                File[] files = output.listFiles(removeTilde);
                Arrays.sort(files);
                for (File inputFile : files) {
                    outputArr.add(inputFile.getName());
                }
            }
        }
    }
}
Example 88
Project: zjsonpatch-master  File: TestDataGenerator.java View source code
public static JsonNode generate(int count) {
    ArrayNode jsonNode = JsonNodeFactory.instance.arrayNode();
    for (int i = 0; i < count; i++) {
        ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
        objectNode.put("name", name.get(random.nextInt(name.size())));
        objectNode.put("age", age.get(random.nextInt(age.size())));
        objectNode.put("gender", gender.get(random.nextInt(gender.size())));
        ArrayNode countryNode = getArrayNode(country.subList(random.nextInt(country.size() / 2), (country.size() / 2) + random.nextInt(country.size() / 2)));
        objectNode.put("country", countryNode);
        ArrayNode friendNode = getArrayNode(friends.subList(random.nextInt(friends.size() / 2), (friends.size() / 2) + random.nextInt(friends.size() / 2)));
        objectNode.put("friends", friendNode);
        jsonNode.add(objectNode);
    }
    return jsonNode;
}
Example 89
Project: accumulo-recipes-master  File: JsonEventStoreIT.java View source code
@Test
public void testTwitterJson() throws Exception {
    List<Event> eventList = new ArrayList<Event>();
    /**
         * First, we'll load a json object representing tweets
         */
    String tweetJson = Resources.toString(getResource("twitter_tweets.json"), defaultCharset());
    /**
         * Create tweet event with a random UUID and timestamp of current time
         * (both of these can be set manually in the constructor)
         */
    Event tweetEvent = EventBuilder.create("tweet", UUID.randomUUID().toString(), System.currentTimeMillis()).attrs(fromJson(tweetJson, objectMapper)).build();
    eventList.add(tweetEvent);
    /**
         * Next, we'll load a json array containing user timeline data
         */
    String timelineJson = Resources.toString(getResource("twitter_timeline.json"), defaultCharset());
    /**
         * Since we need to persist objects, we'll loop through the array and create
         * events out of the objects
         */
    ArrayNode node = (ArrayNode) objectMapper.readTree(timelineJson);
    for (JsonNode node1 : node) {
        // create an event from the current json object
        Event timelineEvent = EventBuilder.create("tweet", UUID.randomUUID().toString(), System.currentTimeMillis()).attrs(fromJson((ObjectNode) node1)).build();
        eventList.add(timelineEvent);
    }
    /**
         * Save events in the event store and flush
         */
    store.save(eventList);
    store.flush();
    AccumuloTestUtils.dumpTable(getConnector(), "eventStore_shard");
    /**
         * Build our query to retrieve stored events by their flattened json
         * representation.
         */
    Node query = QueryBuilder.create().and().eq("statuses_$entities_$hashtags_$indices", // the json tree has been flattened
    29).eq("statuses_$user_$name", // into key/value objects
    "Sean Cummings").end().build();
    CloseableIterable<Event> results = store.query(new Date(0), new Date(currentTimeMillis()), Sets.newHashSet("tweet"), query, Auths.EMPTY);
    assertEquals(1, size(results));
    List<Attribute> expectedAttributes = new ArrayList(tweetEvent.getAttributes());
    List<Attribute> actualAttributes = new ArrayList<Attribute>(get(results, 0).getAttributes());
    sort(expectedAttributes, comparator);
    sort(actualAttributes, comparator);
    assertEquals(expectedAttributes, actualAttributes);
}
Example 90
Project: alfresco-apache-storm-demo-master  File: RegexURLFilterBase.java View source code
@Override
public void configure(Map stormConf, JsonNode paramNode) {
    JsonNode node = paramNode.get("urlFilters");
    if (node != null && node.isArray()) {
        rules = readRules((ArrayNode) node);
    } else {
        JsonNode filenameNode = paramNode.get("regexFilterFile");
        String rulesFileName;
        if (filenameNode != null) {
            rulesFileName = filenameNode.textValue();
        } else {
            rulesFileName = "default-regex-filters.txt";
        }
        rules = readRules(rulesFileName);
    }
}
Example 91
Project: ame-master  File: ElasticTranscoderTasks.java View source code
protected void handleMessage(final Message message) {
    try {
        LOG.info("Handling message received from checkStatus");
        ObjectNode snsMessage = (ObjectNode) mapper.readTree(message.getBody());
        ObjectNode notification = (ObjectNode) mapper.readTree(snsMessage.get("Message").asText());
        String state = notification.get("state").asText();
        String jobId = notification.get("jobId").asText();
        String pipelineId = notification.get("pipelineId").asText();
        Video video = videoService.findByTranscodeJobId(jobId);
        if (video == null) {
            LOG.warn("Unable to process result for job {} because it does not exist.", jobId);
            Instant msgTime = Instant.parse(snsMessage.get("Timestamp").asText());
            if (Minutes.minutesBetween(msgTime, new Instant()).getMinutes() > 20) {
                LOG.error("Job {} has not been found for over 20 minutes, deleting message from queue", jobId);
                deleteMessage(message);
            }
            // Leave it on the queue for now.
            return;
        }
        if ("ERROR".equals(state)) {
            LOG.warn("Job {} for pipeline {} failed to complete. Body: \n{}", jobId, pipelineId, notification.get("messageDetails").asText());
            video.setThumbnailKey(videoService.getDefaultVideoPosterKey());
            videoService.save(video);
        } else {
            // Construct our url prefix: https://bucketname.s3.amazonaws.com/output/key/
            String prefix = notification.get("outputKeyPrefix").asText();
            if (!prefix.endsWith("/")) {
                prefix += "/";
            }
            ObjectNode output = ((ObjectNode) ((ArrayNode) notification.get("outputs")).get(0));
            String previewFilename = prefix + output.get("key").asText();
            String thumbnailFilename = prefix + output.get("thumbnailPattern").asText().replaceAll("\\{count\\}", "00002") + ".png";
            video.setPreviewKey(previewFilename);
            video.setThumbnailKey(thumbnailFilename);
            videoService.save(video);
        }
        deleteMessage(message);
    } catch (JsonProcessingException e) {
        LOG.error("JSON exception handling notification: {}", message.getBody(), e);
    } catch (IOException e) {
        LOG.error("IOException handling notification: {}", message.getBody(), e);
    }
}
Example 92
Project: amediamanager-master  File: ElasticTranscoderTasks.java View source code
protected void handleMessage(final Message message) {
    try {
        LOG.info("Handling message received from checkStatus");
        ObjectNode snsMessage = (ObjectNode) mapper.readTree(message.getBody());
        ObjectNode notification = (ObjectNode) mapper.readTree(snsMessage.get("Message").asText());
        String state = notification.get("state").asText();
        String jobId = notification.get("jobId").asText();
        String pipelineId = notification.get("pipelineId").asText();
        Video video = videoService.findByTranscodeJobId(jobId);
        if (video == null) {
            LOG.warn("Unable to process result for job {} because it does not exist.", jobId);
            Instant msgTime = Instant.parse(snsMessage.get("Timestamp").asText());
            if (Minutes.minutesBetween(msgTime, new Instant()).getMinutes() > 20) {
                LOG.error("Job {} has not been found for over 20 minutes, deleting message from queue", jobId);
                deleteMessage(message);
            }
            // Leave it on the queue for now.
            return;
        }
        if ("ERROR".equals(state)) {
            LOG.warn("Job {} for pipeline {} failed to complete. Body: \n{}", jobId, pipelineId, notification.get("messageDetails").asText());
            video.setThumbnailKey(videoService.getDefaultVideoPosterKey());
            videoService.save(video);
        } else {
            // Construct our url prefix: https://bucketname.s3.amazonaws.com/output/key/
            String prefix = notification.get("outputKeyPrefix").asText();
            if (!prefix.endsWith("/")) {
                prefix += "/";
            }
            ObjectNode output = ((ObjectNode) ((ArrayNode) notification.get("outputs")).get(0));
            String previewFilename = prefix + output.get("key").asText();
            String thumbnailFilename = prefix + output.get("thumbnailPattern").asText().replaceAll("\\{count\\}", "00002") + ".png";
            video.setPreviewKey(previewFilename);
            video.setThumbnailKey(thumbnailFilename);
            videoService.save(video);
        }
        deleteMessage(message);
    } catch (JsonProcessingException e) {
        LOG.error("JSON exception handling notification: {}", message.getBody(), e);
    } catch (IOException e) {
        LOG.error("IOException handling notification: {}", message.getBody(), e);
    }
}
Example 93
Project: amza-master  File: AmzaGetStress.java View source code
private static void get(org.apache.http.client.HttpClient httpClient, String hostName, int port, String partitionName, int firstDocId, int count, int batchSize) throws IOException, InterruptedException {
    long start = System.currentTimeMillis();
    for (int key = firstDocId; key < count; key++) {
        StringBuilder url = new StringBuilder();
        url.append("http://");
        url.append(hostName).append(":").append(port);
        url.append("/amza/get");
        url.append("?partition=").append(partitionName);
        url.append("&key=");
        Set<String> expectedValues = Sets.newHashSet();
        for (int b = 0; b < batchSize; b++) {
            if (b > 0) {
                url.append(',');
            }
            url.append(b).append('k').append(key);
            expectedValues.add(b + "v" + key);
        }
        while (true) {
            HttpGet method = new HttpGet(url.toString());
            StatusLine statusLine;
            try {
                try {
                    HttpResponse response = httpClient.execute(method);
                    statusLine = response.getStatusLine();
                    if (statusLine.getStatusCode() == 200) {
                        //System.out.println("Got:" + new String(method.getResponseBody()));
                        ArrayNode node = mapper.readValue(EntityUtils.toString(response.getEntity()), ArrayNode.class);
                        for (JsonNode value : node) {
                            if (!value.isNull()) {
                                expectedValues.remove(new String(BaseEncoding.base64().decode(value.textValue()), Charsets.UTF_8));
                            }
                        }
                        if (!expectedValues.isEmpty()) {
                            System.out.println("Missing values in " + partitionName + " for key " + key + ": " + expectedValues);
                        }
                        break;
                    }
                } catch (Exception x) {
                    x.printStackTrace();
                }
                Thread.sleep(1000);
            } finally {
                method.releaseConnection();
            }
        }
        if (key % 100 == 0) {
            long elapse = System.currentTimeMillis() - start;
            double millisPerAdd = ((double) elapse / (double) key);
            System.out.println(partitionName + " millisPerGet:" + millisPerAdd + " getsPerSec:" + (1000d / millisPerAdd) + " key:" + key);
        }
    }
}
Example 94
Project: Android-wamp-client-master  File: WampDeserializationHandler.java View source code
@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    if (readState != ReadState.Reading)
        return;
    if (frame instanceof TextWebSocketFrame) {
        // Only want Text when JSON subprotocol
        if (serialization != Serialization.Json)
            throw new IllegalStateException("Received unexpected TextFrame");
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        if (logger.isDebugEnabled()) {
            logger.debug("Deserialized Wamp Message: {}", textFrame.text());
        }
        try {
            // If we receive an invalid frame on of the following functions will throw
            // This will lead Netty to closing the connection
            ArrayNode arr = objectMapper.readValue(new ByteBufInputStream(textFrame.content()), ArrayNode.class);
            WampMessage recvdMessage = WampMessage.fromObjectArray(arr);
            out.add(recvdMessage);
        } finally {
        }
    } else if (frame instanceof BinaryWebSocketFrame) {
        // Only want Binary when MessagePack subprotocol
        if (serialization != Serialization.MessagePack)
            throw new IllegalStateException("Received unexpected BinaryFrame");
    // TODO: Support MessagePack
    } else if (frame instanceof PongWebSocketFrame) {
    // System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        // System.out.println("WebSocket Client received closing");
        readState = ReadState.Closed;
    }
}
Example 95
Project: aorra-master  File: UserController.java View source code
@Override
public final Result apply(Session session) throws RepositoryException {
    final JsonBuilder jb = new JsonBuilder();
    final ArrayNode json = JsonNodeFactory.instance.arrayNode();
    final UserDAO dao = new UserDAO(session, jcrom);
    for (final User user : dao.list()) {
        json.add(jb.toJson(user, isAdmin(session, dao, user)));
    }
    return ok(json).as("application/json; charset=utf-8");
}
Example 96
Project: arpnet-standard-master  File: Counter.java View source code
private ObjectNode buildDoubleValuesNode(final HashMap<String, ArrayList<Double>> map) {
    ObjectNode countersNode = JsonNodeFactory.instance.objectNode();
    for (Map.Entry<String, ArrayList<Double>> counterSet : map.entrySet()) {
        ArrayNode counterEntries = JsonNodeFactory.instance.arrayNode();
        for (Double timerEntry : counterSet.getValue()) {
            counterEntries.add(timerEntry);
        }
        countersNode.put(counterSet.getKey(), counterEntries);
    }
    return countersNode;
}
Example 97
Project: Blueprint-master  File: GraphSONWriterTest.java View source code
@Test
public void outputGraphNoEmbeddedTypes() throws JSONException, IOException {
    Graph g = TinkerGraphFactory.createTinkerGraph();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    GraphSONWriter writer = new GraphSONWriter(g);
    writer.outputGraph(stream, null, null, GraphSONMode.NORMAL);
    stream.flush();
    stream.close();
    String jsonString = new String(stream.toByteArray());
    ObjectMapper m = new ObjectMapper();
    JsonNode rootNode = m.readValue(jsonString, JsonNode.class);
    // ensure that the JSON conforms to basic structure and that the right
    // number of graph elements are present.  other tests already cover element formatting
    Assert.assertNotNull(rootNode);
    Assert.assertTrue(rootNode.has(GraphSONTokens.MODE));
    Assert.assertEquals("NORMAL", rootNode.get(GraphSONTokens.MODE).asText());
    Assert.assertTrue(rootNode.has(GraphSONTokens.VERTICES));
    ArrayNode vertices = (ArrayNode) rootNode.get(GraphSONTokens.VERTICES);
    Assert.assertEquals(6, vertices.size());
    Assert.assertTrue(rootNode.has(GraphSONTokens.EDGES));
    ArrayNode edges = (ArrayNode) rootNode.get(GraphSONTokens.EDGES);
    Assert.assertEquals(6, edges.size());
}
Example 98
Project: blueprints-master  File: GraphSONWriterTest.java View source code
@Test
public void outputGraphNoEmbeddedTypes() throws JSONException, IOException {
    Graph g = TinkerGraphFactory.createTinkerGraph();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    GraphSONWriter writer = new GraphSONWriter(g);
    writer.outputGraph(stream, null, null, GraphSONMode.NORMAL);
    stream.flush();
    stream.close();
    String jsonString = new String(stream.toByteArray());
    ObjectMapper m = new ObjectMapper();
    JsonNode rootNode = m.readValue(jsonString, JsonNode.class);
    // ensure that the JSON conforms to basic structure and that the right
    // number of graph elements are present.  other tests already cover element formatting
    Assert.assertNotNull(rootNode);
    Assert.assertTrue(rootNode.has(GraphSONTokens.MODE));
    Assert.assertEquals("NORMAL", rootNode.get(GraphSONTokens.MODE).asText());
    Assert.assertTrue(rootNode.has(GraphSONTokens.VERTICES));
    ArrayNode vertices = (ArrayNode) rootNode.get(GraphSONTokens.VERTICES);
    Assert.assertEquals(6, vertices.size());
    Assert.assertTrue(rootNode.has(GraphSONTokens.EDGES));
    ArrayNode edges = (ArrayNode) rootNode.get(GraphSONTokens.EDGES);
    Assert.assertEquals(6, edges.size());
}
Example 99
Project: bonita-ui-designer-master  File: ContractDeserializer.java View source code
private void parseNodeContractInput(ArrayNode inputArray, ContractInputContainer rootNodeInput) throws IOException {
    for (int i = 0; i < inputArray.size(); i++) {
        JsonNode childNode = inputArray.get(i);
        Class<?> inputType = inputType(childNode);
        if (inputType.equals(NodeContractInput.class)) {
            NodeContractInput nodeContractInput = newNodeContractInput(childNode);
            rootNodeInput.addInput(nodeContractInput);
            parseNodeContractInput(childInput(childNode), nodeContractInput);
        } else {
            rootNodeInput.addInput(newLeafContractInput(childNode, inputType));
        }
    }
}
Example 100
Project: codeq-invest-master  File: InvestmentOpportunitiesJsonGeneratorTest.java View source code
@Test
public void analysisWithOneArtefact() throws IOException {
    Artefact artefact = new Artefact("org.project.MyClass", "DUMMY");
    artefact.setChangeProbability(0.6);
    QualityViolation violation = new QualityViolation(artefact, null, 5, 10, 0, "");
    QualityAnalysis analysis = QualityAnalysis.success(project, Arrays.asList(violation));
    when(weightedProfitCalculator.calculateWeightedProfit(violation)).thenReturn(1234.0);
    JsonNode generatedJson = generate(analysis);
    ArrayNode rootPackagNode = (ArrayNode) generatedJson.get("children");
    assertThat(rootPackagNode.get(0).get("changeProbability").asInt()).isEqualTo(60);
    assertThat(rootPackagNode.get(0).get("children").get(0).get("children").get(0).get("value").asDouble()).isEqualTo(1234.0);
}
Example 101
Project: EMB-master  File: DataSourceImpl.java View source code
private static void mergeJsonObject(ObjectNode src, ObjectNode other) {
    Iterator<Map.Entry<String, JsonNode>> ite = other.fields();
    while (ite.hasNext()) {
        Map.Entry<String, JsonNode> pair = ite.next();
        JsonNode s = src.get(pair.getKey());
        JsonNode v = pair.getValue();
        if (v.isObject() && s != null && s.isObject()) {
            mergeJsonObject((ObjectNode) s, (ObjectNode) v);
        } else if (v.isArray() && s != null && s.isArray()) {
            mergeJsonArray((ArrayNode) s, (ArrayNode) v);
        } else {
            src.replace(pair.getKey(), v);
        }
    }
}