Java Examples for org.codehaus.jackson.node.ArrayNode

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

Example 1
Project: indie-master  File: ProjectPresenter.java View source code
public String toJson(List projects) {
    StringWriter out = new StringWriter();
    try {
        JsonGenerator g = factory.createJsonGenerator(out);
        JsonNode root = mapper.createObjectNode();
        ArrayNode projectArray = ((ObjectNode) root).putArray("projects");
        for (Object project : projects) {
            projectArray.add(project.toString());
        }
        mapper.writeValue(g, root);
        g.close();
    } catch (IOException e) {
        throw new RuntimeException("Json parsing failed! : " + e.getMessage());
    }
    return out.toString();
}
Example 2
Project: EasySOA-Incubation-master  File: DiscoveryRequest.java View source code
public void send() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode notificationsArray = mapper.createArrayNode();
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    for (SoaNode notification : notifications) {
        POJONode pojoNode = mapper.getNodeFactory().POJONode(notification);
        notificationsArray.add(pojoNode);
    }
    writer.writeValue(outputStream, notificationsArray);
}
Example 3
Project: org.handwerkszeug.riak-master  File: RiakOperationsTest.java View source code
void testMapReduce(final String bucket) throws Exception {
    final boolean[] is = { false };
    final int[] actual = new int[1];
    MapReduceQueryBuilder<RiakFuture> builder = this.target.mapReduce(new TestingHandler<MapReduceResponse>() {

        @Override
        public void handle(RiakContentsResponse<MapReduceResponse> response) throws RiakException {
            if (response.getContents().getDone()) {
                is[0] = true;
            } else {
                ArrayNode an = response.getContents().getResponse();
                JsonNode jn = an.get(0);
                actual[0] = jn.getIntValue();
            }
        }
    });
    RiakFuture waiter = builder.inputs(bucket).keyFilters(stringToInt, lessThanEq(10)).map(Erlang.map_object_value).reduce(Erlang.reduce_string_to_integer).reduce(Erlang.reduce_sum).execute();
    waitFor(waiter);
    assertEquals(165, actual[0]);
    assertTrue(is[0]);
}
Example 4
Project: pinot-master  File: JsonResponseUtil.java View source code
public static ObjectNode buildResponseJSON(List<? extends Object> list) {
    ObjectNode rootNode = MAPPER.getNodeFactory().objectNode();
    ArrayNode resultArrayNode = MAPPER.createArrayNode();
    rootNode.put("Result", "OK");
    for (Object obj : list) {
        JsonNode node = MAPPER.convertValue(obj, JsonNode.class);
        resultArrayNode.add(node);
    }
    rootNode.put("Records", resultArrayNode);
    return rootNode;
}
Example 5
Project: prototype-20150626-master  File: OpenFdaUrlTransportService.java View source code
/**
	 * The public method invoked by the DigitalEdge pipeline to start the transport process of openFDA data
	 * into DigitalEdge.  Calls the openFDA REST API to retrieve enforcement/recall data and sends it into
	 * DigitalEdge for processing.
	 */
@Override
public void execute() {
    int count = 0, skip = 0;
    int total = getTotal();
    while (count < total) {
        JsonNode jsonNode = getData(baseURL, batchLimit, skip);
        if (jsonNode != null) {
            ArrayNode results = (ArrayNode) jsonNode.get("results");
            if (results != null) {
                for (JsonNode result : results) {
                    JsonNode openFDA = result.get("openfda").get("substance_name");
                    if (openFDA != null || nonOpenFDA) {
                        String record = result.toString();
                        logger.debug(record);
                        SendJMSMessage(record);
                    }
                    count++;
                    skip++;
                }
            }
        }
        logger.info("Current record count: " + count);
    }
    logger.info("Total records retrieved: " + count);
}
Example 6
Project: spring-security-javaconfig-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").getTextValue());
    }
    model.addAttribute("friends", friends);
    return "facebook";
}
Example 7
Project: spring-security-oauth-javaconfig-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").getTextValue());
    }
    model.addAttribute("friends", friends);
    return "facebook";
}
Example 8
Project: weiboclient4j-master  File: StatusService.java View source code
public Map<Long, String> queryMidList(Collection<Id> idList, MidType midType) throws WeiboClientException {
    // [{"3436240135184587":"yfcLPlKKn"},{"3436255091659029":"yfd9X6XAx"}]
    ArrayNode arrayNode = doGet("statuses/querymid", withParams(Id.idParam(idList), midType, IsBatch.Yes), ArrayNode.class);
    Map<Long, String> map = new HashMap<Long, String>();
    for (int i = 0; i < arrayNode.size(); i++) {
        JsonNode node = arrayNode.get(i);
        Iterator<String> fieldNames = node.getFieldNames();
        while (fieldNames.hasNext()) {
            String idString = fieldNames.next();
            map.put(new Long(idString), node.get(idString).asText());
        }
    }
    return map;
}
Example 9
Project: android-xbmcremote-master  File: EnumSerializer.java View source code
@Override
public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
    ObjectNode objectNode = createSchemaNode("string", true);
    if (typeHint != null) {
        JavaType type = TypeFactory.type(typeHint);
        if (type.isEnumType()) {
            ArrayNode enumNode = objectNode.putArray("enum");
            for (String value : _values.values()) {
                enumNode.add(value);
            }
        }
    }
    return objectNode;
}
Example 10
Project: FiWare-Template-Handler-master  File: ProcessInstanceResource.java View source code
private void addTaskList(String processInstanceId, ObjectNode responseJSON) {
    List<HistoricTaskInstance> taskList = ActivitiUtil.getHistoryService().createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().asc().list();
    if (taskList != null && taskList.size() > 0) {
        ArrayNode tasksJSON = new ObjectMapper().createArrayNode();
        responseJSON.put("tasks", tasksJSON);
        for (HistoricTaskInstance historicTaskInstance : taskList) {
            ObjectNode taskJSON = new ObjectMapper().createObjectNode();
            taskJSON.put("taskId", historicTaskInstance.getId());
            taskJSON.put("taskName", historicTaskInstance.getName() != null ? historicTaskInstance.getName() : "null");
            taskJSON.put("owner", historicTaskInstance.getOwner() != null ? historicTaskInstance.getOwner() : "null");
            taskJSON.put("assignee", historicTaskInstance.getAssignee() != null ? historicTaskInstance.getAssignee() : "null");
            taskJSON.put("startTime", RequestUtil.dateToString(historicTaskInstance.getStartTime()));
            if (historicTaskInstance.getEndTime() == null) {
                taskJSON.put("completed", false);
            } else {
                taskJSON.put("completed", true);
                taskJSON.put("endTime", RequestUtil.dateToString(historicTaskInstance.getEndTime()));
                taskJSON.put("duration", historicTaskInstance.getDurationInMillis());
            }
            tasksJSON.add(taskJSON);
        }
    }
}
Example 11
Project: jenkow-plugin-master  File: BpmnJsonConverter.java View source code
public ObjectNode convertToJson(BpmnModel model) {
    ObjectNode modelNode = objectMapper.createObjectNode();
    modelNode.put("bounds", BpmnJsonConverterUtil.createBoundsNode(1485, 1050, 0, 0));
    modelNode.put("resourceId", "canvas");
    ObjectNode stencilNode = objectMapper.createObjectNode();
    stencilNode.put("id", "BPMNDiagram");
    modelNode.put("stencil", stencilNode);
    ObjectNode stencilsetNode = objectMapper.createObjectNode();
    stencilsetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
    stencilsetNode.put("url", "../editor/stencilsets/bpmn2.0/bpmn2.0.json");
    modelNode.put("stencilset", stencilsetNode);
    ArrayNode shapesArrayNode = objectMapper.createArrayNode();
    Process process = model.getMainProcess();
    ObjectNode propertiesNode = objectMapper.createObjectNode();
    if (StringUtils.isNotEmpty(process.getId())) {
        propertiesNode.put(PROPERTY_PROCESS_ID, process.getId());
    }
    if (StringUtils.isNotEmpty(process.getName())) {
        propertiesNode.put(PROPERTY_NAME, process.getName());
    }
    if (StringUtils.isNotEmpty(process.getDocumentation())) {
        propertiesNode.put(PROPERTY_DOCUMENTATION, process.getDocumentation());
    }
    modelNode.put(EDITOR_SHAPE_PROPERTIES, propertiesNode);
    processFlowElements(process.getFlowElements(), model, shapesArrayNode, 0.0, 0.0);
    modelNode.put(EDITOR_CHILD_SHAPES, shapesArrayNode);
    return modelNode;
}
Example 12
Project: partake-master  File: Event.java View source code
/** JSON string for external clients.
     * TODO: All Date should be long instead of Formatted date. However, maybe some clients uses this values... What should we do?
     * Maybe we should take a version number in request query. The version 2 format should obey the rule.
     */
public ObjectNode toSafeJSON() {
    ObjectNode obj = new ObjectNode(JsonNodeFactory.instance);
    obj.put("id", id);
    obj.put("title", title);
    obj.put("summary", summary);
    obj.put("category", category);
    // TODO Locale�外部ファイル���設定�能��る
    DateFormat format = new SimpleDateFormat(Constants.READABLE_DATE_FORMAT, Locale.getDefault());
    if (beginDate != null) {
        // TODO: beginDate should be deprecated.
        obj.put("beginDate", format.format(beginDate.toDate()));
        obj.put("beginDateText", format.format(beginDate.toDate()));
        obj.put("beginDateTime", beginDate.getTime());
    }
    if (endDate != null) {
        // TODO: endDate should be deprecated.
        obj.put("endDate", format.format(endDate.toDate()));
        obj.put("endDateText", format.format(endDate.toDate()));
        obj.put("endDateTime", endDate.getTime());
    }
    obj.put("eventDuration", Helper.readableDuration(beginDate, endDate));
    obj.put("url", url);
    obj.put("place", place);
    obj.put("address", address);
    obj.put("description", description);
    obj.put("hashTag", hashTag);
    obj.put("ownerId", ownerId);
    obj.put("foreImageId", foreImageId);
    obj.put("backImageId", backImageId);
    obj.put("passcode", passcode);
    obj.put("draft", draft);
    if (editorIds != null) {
        ArrayNode editorIdArray = obj.putArray("editorIds");
        for (String editorId : editorIds) {
            editorIdArray.add(editorId);
        }
    }
    if (relatedEventIds != null) {
        ArrayNode relatedEventIdArray = obj.putArray("relatedEventIds");
        for (String relatedEventId : relatedEventIds) {
            relatedEventIdArray.add(relatedEventId);
        }
    }
    if (enquetes != null)
        obj.put("enquetes", Util.toJSONArray(enquetes));
    if (createdAt != null) {
        obj.put("createdAt", format.format(createdAt.toDate()));
        obj.put("createdAtTime", createdAt.getTime());
    }
    if (modifiedAt != null) {
        obj.put("modifiedAt", format.format(modifiedAt.toDate()));
        obj.put("modifiedAtTime", modifiedAt.getTime());
    }
    obj.put("revision", revision);
    return obj;
}
Example 13
Project: rexster-master  File: JsonConverter.java View source code
/**
     * Recursively converts objects to json nodes
     * @param obj
     * @return
     */
public static JsonNode toJsonNode(Object obj) {
    if (obj == null) {
        return NullNode.getInstance();
    } else if (obj instanceof Map) {
        ObjectNode map = new ObjectNode(JsonNodeFactory.instance);
        for (Map.Entry entry : ((Map<Object, Object>) obj).entrySet()) {
            map.put(entry.getKey().toString(), toJsonNode(entry.getValue()));
        }
        return map;
    } else if (obj instanceof Iterable) {
        ArrayNode array = new ArrayNode(JsonNodeFactory.instance);
        for (Object o : (Iterable) obj) {
            array.add(toJsonNode(o));
        }
        return array;
    } else if (obj instanceof Object[]) {
        ArrayNode array = new ArrayNode(JsonNodeFactory.instance);
        for (Object o : (Object[]) obj) {
            array.add(toJsonNode(o));
        }
        return array;
    } else if (obj instanceof Integer) {
        return new IntNode((Integer) obj);
    } else if (obj instanceof Long) {
        return new LongNode((Long) obj);
    } else if (obj instanceof Double) {
        return new DoubleNode((Double) obj);
    } else if (obj instanceof Float) {
        return new DoubleNode((Float) obj);
    } else if (obj instanceof Boolean) {
        return BooleanNode.valueOf((Boolean) obj);
    } else {
        return new TextNode(obj.toString());
    }
}
Example 14
Project: RHome-master  File: MediaPlayer.java View source code
public void run() {
    mojManager m = new mojManager();
    ObjectMapper mapper = new ObjectMapper();
    // will be of type ObjectNode
    JsonNode fileNode = mapper.createObjectNode();
    ((ObjectNode) fileNode).put("file", izbrano.file);
    ArrayNode request = mapper.createArrayNode();
    request.add(fileNode);
    JsonNode nowPlay = c.getJson(m, "Player.Open", request);
}
Example 15
Project: sequenceiq-samples-master  File: QueueInformation.java View source code
public void printQueueInfo(HttpClient client, ObjectMapper mapper, String schedulerResourceURL) {
    //http://sandbox.hortonworks.com:8088/ws/v1/cluster/scheduler in case of HDP
    GetMethod get = new GetMethod(schedulerResourceURL);
    get.setRequestHeader("Accept", "application/json");
    try {
        int statusCode = client.executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + get.getStatusLine());
        }
        InputStream in = get.getResponseBodyAsStream();
        JsonNode jsonNode = mapper.readValue(in, JsonNode.class);
        ArrayNode queues = (ArrayNode) jsonNode.path("scheduler").path("schedulerInfo").path("queues").get("queue");
        for (int i = 0; i < queues.size(); i++) {
            JsonNode queueNode = queues.get(i);
            LOGGER.info("queueName / usedCapacity / absoluteUsedCap / absoluteCapacity / absMaxCapacity: " + queueNode.findValue("queueName") + " / " + queueNode.findValue("usedCapacity") + " / " + queueNode.findValue("absoluteUsedCapacity") + " / " + queueNode.findValue("absoluteCapacity") + " / " + queueNode.findValue("absoluteMaxCapacity"));
        }
    } catch (IOException e) {
        LOGGER.error("Exception occured", e);
    } finally {
        get.releaseConnection();
    }
}
Example 16
Project: torrenttunes-server-master  File: Transformations.java View source code
public static ObjectNode artistViewJson(String artistMbid) {
    Artist artist = ARTIST.findFirst("mbid = ?", artistMbid);
    List<ArtistTagView> tags = ARTIST_TAG_VIEW.find("mbid = ?", artistMbid);
    List<Model> relatedArtists = RELATED_ARTIST_VIEW.findBySQL(RELATED_ARTIST_VIEW_SQL, artistMbid, artistMbid);
    //		RELATED_ARTIST_VIEW.find
    //		log.info(RELATED_ARTIST_VIEW.find(
    //				"mbid like ? and `mbid:1` not like ?", 
    //				artistMbid,artistMbid).toSql());
    ObjectNode a = Tools.MAPPER.createObjectNode();
    JsonNode c = Tools.jsonToNode(artist.toJson(false));
    ObjectNode on = Tools.MAPPER.valueToTree(c);
    a.putAll(on);
    ArrayNode an = a.putArray("related_artists");
    for (Model relatedArtist : relatedArtists) {
        an.add(Tools.jsonToNode(relatedArtist.toJson(false)));
    }
    ArrayNode ab = a.putArray("tags");
    for (ArtistTagView tag : tags) {
        ab.add(Tools.jsonToNode(tag.toJson(false)));
    }
    return a;
}
Example 17
Project: vocidex-master  File: JSONHelper.java View source code
public void putURIArrayWithLabels(ObjectNode json, String key, Collection<Resource> uris, LabelDescriber labeller, DatatypeIdentifier datatypeIdentifier) {
    ArrayNode array = mapper.createArrayNode();
    for (Resource uri : uris) {
        ObjectNode o = mapper.createObjectNode();
        o.put("uri", uri.getURI());
        labeller.describe(uri, o);
        if (datatypeIdentifier != null) {
            if (datatypeIdentifier.isDatatype(uri)) {
                o.put("isDatatype", true);
            } else {
                o.put("isClass", true);
            }
        }
        array.add(o);
    }
    if (array.size() > 0) {
        json.put(key, array);
    }
}
Example 18
Project: YiDB-master  File: CMSClientServiceTest.java View source code
/**
     * TODO: Can't support a case when client library doens't conform to the
     * server metadata When the client library is out of date, says user add a
     * field
     * 
     * @throws Exception
     */
@Test
public void getJsonTypeField() throws Exception {
    // add a json-type field to the ApplicationService, add a entity
    // containing a such value
    // then get it through apis..
    Client c = Client.create();
    // update to add a field to application seervice
    WebResource wr = c.resource(LOCAL_ENDPOINT + "/repositories/raptor-paas/metadata/ApplicationService");
    String json = CMSResourceTest.loadJson("/ApplicationServiceAddJsonField.json");
    ClientResponse resp = wr.entity(json, MediaType.APPLICATION_JSON).post(ClientResponse.class);
    Assert.assertEquals(200, resp.getStatus());
    System.out.println(resp.getEntity(String.class));
    // Update a entity to add values to the json type field
    WebResource entityWr = c.resource(LOCAL_ENDPOINT + "/repositories/raptor-paas/branches/main/ApplicationService/4fbb314fc681caf13e283a76");
    String entityJson = CMSResourceTest.loadJson("/ApplicationServiceUpdateJsonField.json");
    ClientResponse entityCr = entityWr.entity(entityJson, MediaType.APPLICATION_JSON).post(ClientResponse.class);
    //        Assert.assertEquals(200, entityCr.getStatus());
    String entityRespStr = entityCr.getEntity(String.class);
    System.out.println(entityRespStr);
    // case 0: get entities with json fields fetched
    ApplicationService getAppService = raptorService.get("4fbb314fc681caf13e283a76", ApplicationService.class);
    Assert.assertNotNull(getAppService);
    Object jsonField = getAppService.getFieldValue("jsonField");
    Object multiJsonField = getAppService.getFieldValue("multiJsonField");
    Assert.assertNotNull(jsonField);
    Assert.assertTrue(jsonField instanceof ObjectNode);
    Assert.assertNotNull(multiJsonField);
    Assert.assertTrue(multiJsonField instanceof ArrayNode);
    // case 1: create entities with json fields given
    ApplicationService as = new ApplicationService();
    as.setName(generateRandomName("appName-newWithJson"));
    ObjectNode jo = JsonNodeFactory.instance.objectNode();
    jo.put("title", "S/W Eng");
    ObjectNode embedJson = JsonNodeFactory.instance.objectNode();
    embedJson.put("embedField-Contact", "DL-CLOUD-CMS-SHA@ebay.com");
    jo.put("embedJsonObject", embedJson);
    as.setFieldValue("jsonField", jo);
    ArrayNode jos = JsonNodeFactory.instance.arrayNode();
    jos.add(jo);
    as.setFieldValue("multiJsonField", jos);
    ApplicationService createdAs = raptorService.create(as);
    Assert.assertNotNull(createdAs.get_id());
    ApplicationService getAs = raptorService.get(createdAs.get_id(), ApplicationService.class);
    Assert.assertNotNull(getAs);
    Assert.assertEquals(as.getName(), getAs.getName());
    Assert.assertNotNull(getAs.getFieldValue("jsonField"));
    Assert.assertTrue(getAs.getFieldValue("jsonField") instanceof JsonNode);
    Assert.assertNotNull(getAs.getFieldValue("multiJsonField"));
    Assert.assertNotNull(getAs.getFieldValue("multiJsonField") instanceof ArrayNode);
    CMSEntityMapper mapper = new CMSEntityMapper(null, config, JsonCMSEntity.class, CMSEntityMapper.ProcessModeEnum.TYPE_SAFE, ApplicationService.class);
    getAs.traverse(mapper);
    System.out.println(((JsonCMSEntity) mapper.getTargetEntity()).getNode());
}
Example 19
Project: activityinfo-master  File: SitesResourcesTest.java View source code
@Test
public void indicatorsArePresent() throws IOException {
    QueryParameters parameters = new QueryParameters();
    parameters.databaseIds.add(2);
    String json = query(parameters);
    System.out.println(json);
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getJsonFactory();
    JsonParser jp = factory.createJsonParser(json);
    ArrayNode array = (ArrayNode) mapper.readTree(jp);
    assertThat(array.size(), equalTo(3));
    JsonNode site6 = getSiteById(array, 6);
    assertThat(site6.path("id").asInt(), equalTo(6));
    assertThat(site6.path("activity").asInt(), equalTo(4));
    double indicatorValue = site6.path("indicatorValues").path("6").asDouble();
    assertThat(indicatorValue, equalTo(70d));
}
Example 20
Project: aurora-master  File: PendingTasksTest.java View source code
/**
   * Create a {@link JsonNode} object to mimic the response.
   *
   * @param penaltyMs
   * @param taskIds
   * @param name
   * @param reasons
   * @return Json node for pending tasks whose values are initialized to the provided values.
   * @throws IOException
   */
private JsonNode getMimicResponseJson(long penaltyMs, String[] taskIds, String name, List<String> reasons) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode mutablePendingTaskJson = mapper.createObjectNode();
    // Adding the key=value pairs to mutablePendingTaskJson.
    mutablePendingTaskJson.put("penaltyMs", penaltyMs);
    mutablePendingTaskJson.putArray("taskIds");
    for (String taskId : taskIds) {
        ((ArrayNode) mutablePendingTaskJson.get("taskIds")).add(taskId);
    }
    mutablePendingTaskJson.put("name", name);
    mutablePendingTaskJson.put("reason", reasons.toString());
    return mutablePendingTaskJson;
}
Example 21
Project: cypher-dsl-master  File: JSONSerializer.java View source code
public ArrayNode toJSON(Iterable<Map<String, Object>> result) {
    ArrayNode root = mapper.createArrayNode();
    for (Map<String, Object> stringObjectMap : result) {
        ObjectNode entry = root.objectNode();
        for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
            if (stringObjectEntry.getValue() instanceof Path) {
                entry.put(stringObjectEntry.getKey(), stringObjectEntry.getValue().toString());
            } else if (stringObjectEntry.getValue() instanceof Node) {
                Node node = (Node) stringObjectEntry.getValue();
                ObjectNode nodeNode = entry.objectNode();
                nodeNode.put("_id", node.getId());
                for (String propertyName : node.getPropertyKeys()) {
                    addProperty(nodeNode, propertyName, node.getProperty(propertyName));
                }
                entry.put(stringObjectEntry.getKey(), nodeNode);
            } else {
                addProperty(entry, stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
        }
        root.add(entry);
    }
    return root;
}
Example 22
Project: fixflow-master  File: BpmnJsonConverter.java View source code
/**
   * 将模型转��json数�
   * @param model
   * @return
   */
public ObjectNode convertToJson(Definitions model) {
    ObjectNode modelNode = objectMapper.createObjectNode();
    modelNode.put("bounds", BpmnJsonConverterUtil.createBoundsNode(1485, 1050, 0, 0));
    modelNode.put("resourceId", "canvas");
    ObjectNode stencilNode = objectMapper.createObjectNode();
    stencilNode.put("id", "BPMNDiagram");
    modelNode.put("stencil", stencilNode);
    ObjectNode stencilsetNode = objectMapper.createObjectNode();
    stencilsetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
    stencilsetNode.put("url", "../editor/stencilsets/bpmn2.0/bpmn2.0.json");
    modelNode.put("stencilset", stencilsetNode);
    ArrayNode shapesArrayNode = objectMapper.createArrayNode();
    ProcessDefinitionBehavior mainProcess = null;
    mainProcess = (ProcessDefinitionBehavior) BpmnModelUtil.getProcess(model);
    EMFExtensionUtil.getDataVariables(mainProcess);
    ObjectNode propertiesNode = objectMapper.createObjectNode();
    if (StringUtils.isNotEmpty(mainProcess.getId())) {
        propertiesNode.put(PROPERTY_OVERRIDE_ID, mainProcess.getId());
    }
    if (StringUtils.isNotEmpty(mainProcess.getName())) {
        propertiesNode.put(PROPERTY_NAME, mainProcess.getName());
    }
    //fixflow扩展�程属性
    String category = mainProcess.getCategory();
    if (category != null) {
        propertiesNode.put(PROPERTY_PROCESS_CATEGORY, mainProcess.getCategory());
    }
    TaskSubjectBehavior taskSubject = mainProcess.getTaskSubject();
    if (taskSubject != null) {
        propertiesNode.put(PROPERTY_PROCESS_SUBJECT, mainProcess.getTaskSubject().getExpressionValue());
    }
    FormUri formObj = mainProcess.getFormUriObj();
    if (formObj != null) {
        propertiesNode.put(PROPERTY_PROCESS_DEFAULT_FORMURI, formObj.getExpression().getValue());
    }
    boolean isVerify = mainProcess.isVerification();
    propertiesNode.put(PROPERTY_PROCESS_IS_VERIFY, isVerify);
    //由于获��程模型的时候没有loadvariable,所以此处先用emf原始加载的方�加载数���,�期�能需�改掉
    List<DataVariable> dataVariables = EMFExtensionUtil.getDataVariables(mainProcess);
    if (dataVariables != null) {
        ObjectNode datavariableNode = objectMapper.createObjectNode();
        ArrayNode itemsNode = objectMapper.createArrayNode();
        for (DataVariable dataVariable : dataVariables) {
            ObjectNode datavariableItemNode = objectMapper.createObjectNode();
            datavariableItemNode.put(PROPERTY_DATAVARIABLE_ID, dataVariable.getId());
            datavariableItemNode.put(PROPERTY_DATAVARIABLE_TYPE, dataVariable.getDataType());
            datavariableItemNode.put(PROPERTY_DATAVARIABLE_BIZTYPE, dataVariable.getBizType());
            datavariableItemNode.put(PROPERTY_DATAVARIABLE_IS_PERSISTENCE, dataVariable.isIsPersistence());
            Expression expression = dataVariable.getExpression();
            if (expression != null) {
                datavariableItemNode.put(PROPERTY_DATAVARIABLE_DEFAULT_VALUE, expression.getValue());
            }
            itemsNode.add(datavariableItemNode);
        }
        datavariableNode.put("totalCount", itemsNode.size());
        datavariableNode.put(EDITOR_PROPERTIES_GENERAL_ITEMS, itemsNode);
        propertiesNode.put(PROPERTY_PROCESS_DATAVARIABLE, datavariableNode);
    }
    ConnectorInstanceElm cie = new ConnectorInstanceElm();
    propertiesNode.put(PROPERTY_CONNECTORINSTANCE, cie.convertElementToJson(mainProcess));
    propertiesNode.put(PROPERTY_PROCESS_NAMESPACE, model.getTargetNamespace());
    if (StringUtils.isNotEmpty(BpmnModelUtil.getDocumentation(mainProcess))) {
        propertiesNode.put(PROPERTY_DOCUMENTATION, BpmnModelUtil.getDocumentation(mainProcess));
    }
    modelNode.put(EDITOR_SHAPE_PROPERTIES, propertiesNode);
    /*****lane的处�******/
    List<Lane> lanes = new ArrayList<Lane>();
    List<FlowElement> laneFlowElements = new ArrayList<FlowElement>();
    fillAllLanes(lanes, mainProcess);
    if (lanes.size() > 0) {
        for (Lane lane : lanes) {
            addLaneElements(lane, mainProcess, laneFlowElements, model, shapesArrayNode, 0.0, 0.0);
        }
    }
    //处��包�在lane中的元素
    processFlowElements(BpmnModelUtil.getProcess(model).getFlowElements(), model, shapesArrayNode, 0.0, 0.0, laneFlowElements);
    modelNode.put(EDITOR_CHILD_SHAPES, shapesArrayNode);
    return modelNode;
}
Example 23
Project: jconfig-master  File: ConfigLoaderJmx.java View source code
/**
     * Given and attributeInfo and a configuration node, create and return a set
     * attribute object
     * 
     * @param attrib
     *            MBean attribute
     * @param node
     *            configuration node
     * 
     * @return a populated attribute
     * @throws ConfigException
     *             if configuration entry is missing in the JsonNode<br>
     *             Or type mismatch between entry in JsonNode and attribute
     *             type.
     */
private static Attribute createConfigAttribute(final MBeanAttributeInfo attrib, final JsonNode node) throws ConfigException {
    String attribName = attrib.getName();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();
    ArrayNode newSets = mapper.createArrayNode();
    if (null != node.get(attribName)) {
        rootNode.put(attribName, node.get(attribName));
    }
    if (null != node.get(SETS_TYPE)) {
        rootNode.put(SETS_TYPE, node.get(SETS_TYPE));
        JsonNode origSets = node.get(SETS);
        if ((origSets != null) && origSets.isArray()) {
            Iterator<JsonNode> itr = origSets.iterator();
            while (itr.hasNext()) {
                JsonNode setElement = itr.next();
                JsonNode key = setElement.get(SETS_KEY_NODE);
                JsonNode keyList = setElement.get(SETS_KEYLIST_NODE);
                // bad element; skip it
                if ((key == null) || (keyList == null)) {
                    continue;
                }
                Iterator<String> keyListItr = keyList.getFieldNames();
                while (keyListItr.hasNext()) {
                    String keyListAttribName = keyListItr.next();
                    // Is this the attribute name we are interested in
                    if (keyListAttribName.equals(attribName)) {
                        // Build a new node with just the keyList attribute
                        // we
                        // are interested in
                        ObjectNode newNode = mapper.createObjectNode();
                        ObjectNode attributeNode = mapper.createObjectNode();
                        attributeNode.put(attribName, keyList.path(attribName));
                        newNode.put(SETS_KEY_NODE, key);
                        newNode.put(SETS_KEYLIST_NODE, attributeNode);
                        newSets.add(newNode);
                    }
                }
            }
        }
        rootNode.put(SETS, newSets);
    }
    return new Attribute(attrib.getName(), rootNode.toString());
}
Example 24
Project: lilyproject-master  File: RecordRestTest.java View source code
@Test
public void testMultiValueHierarchicalBlobs() throws Exception {
    // Create a blob field type
    String body = json("{action: 'create', fieldType: {name: 'b$blob2', valueType: 'LIST<PATH<BLOB>>', " + "scope: 'versioned', namespaces: { 'org.lilyproject.resttest': 'b' } } }");
    ResponseAndContent response = post("/schema/fieldTypeById", body);
    assertStatus(HttpStatus.SC_CREATED, response);
    // Create a record type holding the blob field
    body = json("{action: 'create', recordType: {name: 'b$blobRT2', fields: [ {name: 'b$blob2'} ]," + "namespaces: { 'org.lilyproject.resttest': 'b' } } }");
    response = post("/schema/recordTypeById", body);
    assertStatus(HttpStatus.SC_CREATED, response);
    // Upload some blobs
    ObjectNode blob1Value = (ObjectNode) readJson(postText("/blob", "My blob 1"));
    ObjectNode blob2Value = (ObjectNode) readJson(postText("/blob", "My blob 2"));
    ObjectNode blob3Value = (ObjectNode) readJson(postText("/blob", "My blob 3"));
    ObjectNode blob4Value = (ObjectNode) readJson(postText("/blob", "My blob 4"));
    // Create a record with these blobs
    ObjectNode recordNode = JsonNodeFactory.instance.objectNode();
    recordNode.put("type", "b$blobRT2");
    ObjectNode fieldsNode = recordNode.putObject("fields");
    ArrayNode blobNode = fieldsNode.putArray("b$blob2");
    ArrayNode hierarchicalBlob1 = blobNode.addArray();
    hierarchicalBlob1.add(blob1Value);
    hierarchicalBlob1.add(blob2Value);
    ArrayNode hierarchicalBlob2 = blobNode.addArray();
    hierarchicalBlob2.add(blob3Value);
    hierarchicalBlob2.add(blob4Value);
    ObjectNode nsNode = recordNode.putObject("namespaces");
    nsNode.put("org.lilyproject.resttest", "b");
    response = put("/record/USER.blob2", recordNode.toString());
    assertStatus(HttpStatus.SC_CREATED, response);
    // Read the record
    response = get("/record/USER.blob2");
    assertStatus(HttpStatus.SC_OK, response);
    JsonNode jsonNode = readJson(response);
    String prefix = jsonNode.get("namespaces").get("org.lilyproject.resttest").getValueAsText();
    blobNode = (ArrayNode) jsonNode.get("fields").get(prefix + "$blob2");
    assertEquals(2, blobNode.size());
    // Read the blobs
    for (int mvIndex = 0; mvIndex < 2; mvIndex++) {
        for (int hIndex = 0; hIndex < 2; hIndex++) {
            response = get("/record/USER.blob2/field/b$blob2/data?ns.b=org.lilyproject.resttest" + "&indexes=" + mvIndex + "," + hIndex);
            assertStatus(HttpStatus.SC_OK, response);
        }
    }
    // Read a blob at non-existing indexes
    response = get("/record/USER.blob2/field/b$blob2/data?ns.b=org.lilyproject.resttest&mvIndex=5&hIndex=3");
    assertStatus(HttpStatus.SC_NOT_FOUND, response);
}
Example 25
Project: rce-master  File: WorkflowDescriptionPersistenceHandler.java View source code
private WorkflowDescription parseWorkflow(InputStream inputStream, ParsingFailedFlagHolder parsingFailedFlag) throws IOException, WorkflowFileException {
    ObjectNode wfRootJsonNode = workflowFileStreamToJsonNode(inputStream);
    if (!wfRootJsonNode.has(IDENTIFIER)) {
        throw new WorkflowFileException("Workflow identifier not found: " + wfRootJsonNode.toString());
    }
    WorkflowDescription wd = new WorkflowDescription(wfRootJsonNode.get(IDENTIFIER).asText());
    wd.setWorkflowVersion(WorkflowConstants.INITIAL_WORKFLOW_VERSION_NUMBER);
    wd.setWorkflowVersion(readWorkflowVersionNumber(wfRootJsonNode));
    if (wfRootJsonNode.has(NAME)) {
        wd.setName(wfRootJsonNode.get(NAME).asText());
    }
    if (wfRootJsonNode.has(ADDITIONAL_INFORMATION)) {
        wd.setAdditionalInformation(wfRootJsonNode.get(ADDITIONAL_INFORMATION).asText());
    }
    String wfControllerNodeId = readWorkflowControllerNodeId(wfRootJsonNode);
    wd.setControllerNode(NodeIdentifierUtils.parseArbitraryIdStringToLogicalNodeIdWithExceptionWrapping(wfControllerNodeId));
    Map<String, WorkflowNode> nodes = null;
    if (wfRootJsonNode.has(NODES) && wfRootJsonNode.get(NODES) instanceof ArrayNode) {
        nodes = parseNodesEntry((ArrayNode) wfRootJsonNode.get(NODES), wd, parsingFailedFlag);
    }
    List<Connection> connections = null;
    if (wfRootJsonNode.has(CONNECTIONS) && wfRootJsonNode.get(CONNECTIONS) instanceof ArrayNode) {
        connections = parseConnectionsEntry((ArrayNode) wfRootJsonNode.get(CONNECTIONS), nodes, wd, parsingFailedFlag);
    }
    if (wfRootJsonNode.has(BENDPOINTS)) {
        parseBendpointsEntry(wfRootJsonNode.get(BENDPOINTS), nodes, connections, parsingFailedFlag);
    }
    if (wfRootJsonNode.has(LABELS)) {
        parseLabelsEntry(wfRootJsonNode.get(LABELS), wd, parsingFailedFlag);
    }
    return wd;
}
Example 26
Project: stanbol-master  File: MorphoFeaturesSupport.java View source code
@Override
public ObjectNode serialize(ObjectMapper mapper, MorphoFeatures morpho) {
    ObjectNode jMorpho = mapper.createObjectNode();
    jMorpho.put("lemma", morpho.getLemma());
    List<CaseTag> caseList = morpho.getCaseList();
    if (!caseList.isEmpty()) {
        ArrayNode jCases = mapper.createArrayNode();
        for (CaseTag caseTag : caseList) {
            ObjectNode jCase = mapper.createObjectNode();
            jCase.put("tag", caseTag.getTag());
            if (caseTag.getCase() != null) {
                jCase.put("type", caseTag.getCase().name());
            }
            jCases.add(jCase);
        }
        jMorpho.put("case", jCases);
    }
    List<Definitness> definitnesses = morpho.getDefinitnessList();
    if (!definitnesses.isEmpty()) {
        if (definitnesses.size() == 1) {
            jMorpho.put("definitness", definitnesses.get(0).name());
        } else {
            ArrayNode jDefinitnesses = mapper.createArrayNode();
            for (Definitness d : definitnesses) {
                jDefinitnesses.add(d.name());
            }
            jMorpho.put("definitness", jDefinitnesses);
        }
    }
    List<GenderTag> genderList = morpho.getGenderList();
    if (!genderList.isEmpty()) {
        ArrayNode jGenders = mapper.createArrayNode();
        for (GenderTag genderTag : genderList) {
            ObjectNode jGender = mapper.createObjectNode();
            jGender.put("tag", genderTag.getTag());
            if (genderTag.getGender() != null) {
                jGender.put("type", genderTag.getGender().name());
            }
            jGenders.add(jGender);
        }
        jMorpho.put("gender", jGenders);
    }
    List<NumberTag> numberList = morpho.getNumberList();
    if (!numberList.isEmpty()) {
        ArrayNode jNumbers = mapper.createArrayNode();
        for (NumberTag numberTag : numberList) {
            ObjectNode jNumber = mapper.createObjectNode();
            jNumber.put("tag", numberTag.getTag());
            if (numberTag.getNumber() != null) {
                jNumber.put("type", numberTag.getNumber().name());
            }
            jNumbers.add(jNumber);
        }
        jMorpho.put("number", jNumbers);
    }
    List<Person> persons = morpho.getPersonList();
    if (!persons.isEmpty()) {
        if (persons.size() == 1) {
            jMorpho.put("person", persons.get(0).name());
        } else {
            ArrayNode jPersons = mapper.createArrayNode();
            for (Person d : persons) {
                jPersons.add(d.name());
            }
            jMorpho.put("person", jPersons);
        }
    }
    List<PosTag> posList = morpho.getPosList();
    if (!posList.isEmpty()) {
        ArrayNode jPosTags = mapper.createArrayNode();
        for (PosTag posTag : posList) {
            jPosTags.add(getPosTagSerializer().serialize(mapper, posTag));
        }
        jMorpho.put("pos", jPosTags);
    }
    List<TenseTag> tenseList = morpho.getTenseList();
    if (!tenseList.isEmpty()) {
        ArrayNode jTenses = mapper.createArrayNode();
        for (TenseTag tenseTag : tenseList) {
            ObjectNode jTense = mapper.createObjectNode();
            jTense.put("tag", tenseTag.getTag());
            if (tenseTag.getTense() != null) {
                jTense.put("type", tenseTag.getTense().name());
            }
            jTenses.add(jTense);
        }
        jMorpho.put("tense", jTenses);
    }
    List<VerbMoodTag> verbMoodList = morpho.getVerbMoodList();
    if (!verbMoodList.isEmpty()) {
        ArrayNode jMoods = mapper.createArrayNode();
        for (VerbMoodTag verbMoodTag : verbMoodList) {
            ObjectNode jMood = mapper.createObjectNode();
            jMood.put("tag", verbMoodTag.getTag());
            if (verbMoodTag.getVerbForm() != null) {
                jMood.put("type", verbMoodTag.getVerbForm().name());
            }
            jMoods.add(jMood);
        }
        jMorpho.put("verb-mood", jMoods);
    }
    return jMorpho;
}
Example 27
Project: android-xbmcremote-sandbox-master  File: MovieDetailsHandler.java View source code
@Override
protected ContentValues[] parse(JsonNode response, ContentResolver resolver) {
    /* SETUP CACHE VARIABLES
		 */
    if (PEOPLE_CACHE == null) {
        PEOPLE_CACHE = new HashMap<String, Integer>();
        THUMB_CACHE = new HashSet<Integer>();
        final String[] model = { BaseColumns._ID, VideoContract.People.NAME, VideoContract.People.THUMBNAIL };
        final Cursor cursor = resolver.query(VideoContract.People.CONTENT_URI, model, null, null, null);
        while (cursor.moveToNext()) {
            final int id = cursor.getInt(0);
            PEOPLE_CACHE.put(cursor.getString(1), id);
            if (cursor.getString(2) != null) {
                THUMB_CACHE.add(id);
            }
        }
    }
    // put genres into cache
    if (GENRE_CACHE == null) {
        GENRE_CACHE = new HashMap<String, Integer>();
        final String[] model = { BaseColumns._ID, VideoContract.Genres.NAME };
        final Cursor cursor = resolver.query(VideoContract.Genres.CONTENT_URI, model, null, null, null);
        while (cursor.moveToNext()) {
            GENRE_CACHE.put(cursor.getString(1), cursor.getInt(0));
        }
    }
    // retrieve object
    final ObjectNode movie = (ObjectNode) response.get(AbstractCall.RESULT).get(VideoLibrary.GetMovieDetails.RESULT);
    /* CAST
		 */
    final ArrayNode cast = (ArrayNode) movie.get(MovieDetail.CAST);
    final ContentValues[] batch = new ContentValues[cast.size()];
    int i = 0;
    for (JsonNode actor : cast) {
        final String name = actor.get(VideoModel.Cast.NAME).getTextValue();
        if (name.isEmpty()) {
            continue;
        }
        batch[i] = new ContentValues();
        batch[i].put(VideoContract.MovieCast.MOVIE_REF, id);
        batch[i].put(VideoContract.MovieCast.PERSON_REF, getPerson(resolver, name, actor));
        batch[i].put(VideoContract.MovieCast.ROLE, DBUtils.getStringValue(actor, VideoModel.Cast.ROLE));
        batch[i].put(VideoContract.MovieCast.SORT, DBUtils.getIntValue(actor, VideoModel.Cast.ORDER));
        i++;
    }
    /* DIRECTORS
		 */
    final ArrayNode directors = (ArrayNode) movie.get(MovieDetail.DIRECTOR);
    if (directors != null) {
        for (JsonNode director : directors) {
            final ContentValues row = new ContentValues();
            row.put(VideoContract.MovieDirector.MOVIE_REF, id);
            row.put(VideoContract.MovieDirector.PERSON_REF, getPerson(resolver, director.getTextValue()));
            resolver.insert(VideoContract.MovieDirector.CONTENT_URI, row);
        }
    }
    /* WRITERS
		 */
    final ArrayNode writers = (ArrayNode) movie.get(MovieDetail.WRITER);
    if (writers != null) {
        for (JsonNode writer : writers) {
            final ContentValues row = new ContentValues();
            row.put(VideoContract.MovieWriter.MOVIE_REF, id);
            row.put(VideoContract.MovieWriter.PERSON_REF, getPerson(resolver, writer.getTextValue()));
            resolver.insert(VideoContract.MovieWriter.CONTENT_URI, row);
        }
    }
    /* GENRES
		 */
    final ArrayNode genres = (ArrayNode) movie.get(MovieDetail.GENRE);
    for (JsonNode genre : genres) {
        final String name = genre.getTextValue();
        final int genreRef;
        if (GENRE_CACHE.containsKey(name)) {
            genreRef = GENRE_CACHE.get(name);
        } else {
            final ContentValues row = new ContentValues();
            row.put(VideoContract.Genres.NAME, name);
            final Uri newGenreUri = resolver.insert(VideoContract.Genres.CONTENT_URI, row);
            genreRef = VideoContract.Genres.getGenreId(newGenreUri);
            GENRE_CACHE.put(name, genreRef);
        }
        // insert reference
        final ContentValues row = new ContentValues();
        row.put(VideoContract.MovieGenres.GENRE_REF, genreRef);
        row.put(VideoContract.MovieGenres.MOVIE_REF, id);
        resolver.insert(VideoContract.MovieGenres.CONTENT_URI, row);
    }
    return batch;
}
Example 28
Project: baiji4j-master  File: Schema.java View source code
/**
     * Static method to return new instance of schema object
     *
     * @param node     JSON object
     * @param names    list of named schemas already read
     * @param encSpace enclosing namespace of the schema
     * @return
     */
static Schema parseJson(JsonNode node, SchemaNames names, String encSpace) {
    if (node == null) {
        throw new IllegalArgumentException("node cannot be null.");
    }
    if (node.isTextual()) {
        String value = node.getTextValue();
        PrimitiveSchema ps = PrimitiveSchema.newInstance(value);
        if (ps != null) {
            return ps;
        }
        NamedSchema schema = names.getSchema(value, null, encSpace);
        if (schema != null) {
            return schema;
        }
        throw new SchemaParseException("Undefined name: " + value);
    } else if (node.isArray()) {
        return UnionSchema.newInstance((ArrayNode) node, null, names, encSpace);
    } else if (node.isObject()) {
        JsonNode typeNode = node.get("type");
        if (typeNode == null) {
            throw new SchemaParseException("Property type is required");
        }
        PropertyMap props = JsonHelper.getProperties(node);
        if (typeNode.isTextual()) {
            String type = typeNode.getTextValue();
            if ("array".equals(type)) {
                return ArraySchema.newInstance(node, props, names, encSpace);
            } else if ("map".equals(type)) {
                return MapSchema.newInstance(node, props, names, encSpace);
            }
            PrimitiveSchema ps = PrimitiveSchema.newInstance(type);
            if (ps != null) {
                return ps;
            }
            return NamedSchema.newInstance(node, props, names, encSpace);
        } else if (typeNode.isArray()) {
            return UnionSchema.newInstance((ArrayNode) typeNode, props, names, encSpace);
        }
    }
    throw new BaijiTypeException("Invalid JSON for schema: " + node);
}
Example 29
Project: blueflood-master  File: HttpMetricsIndexHandler.java View source code
public static String getSerializedJSON(List<SearchResult> searchResults) {
    ArrayNode resultArray = JsonNodeFactory.instance.arrayNode();
    for (SearchResult result : searchResults) {
        ObjectNode resultNode = JsonNodeFactory.instance.objectNode();
        resultNode.put("metric", result.getMetricName());
        String unit = result.getUnit();
        if (unit != null) {
            //Preaggreated metrics do not have units. Do not want to return null units in query results.
            resultNode.put("unit", unit);
        }
        resultArray.add(resultNode);
    }
    return resultArray.toString();
}
Example 30
Project: Cubert-master  File: PhysicalParser.java View source code
@Override
public void exitInputCommand(@NotNull InputCommandContext ctx) {
    ObjectNode inputNode = objMapper.createObjectNode();
    addLine(ctx, inputNode);
    inputNode.put("name", ctx.ID().get(0).getText());
    if (ctx.format != null)
        inputNode.put("type", ctx.format.getText().toUpperCase());
    else
        inputNode.put("type", ctx.classname.getText());
    ObjectNode paramsNode = objMapper.createObjectNode();
    if (ctx.params() != null) {
        for (int i = 0; i < ctx.params().keyval().size(); i++) {
            List<TerminalNode> kv = ctx.params().keyval(i).STRING();
            paramsNode.put(CommonUtils.stripQuotes(kv.get(0).getText()), CommonUtils.stripQuotes(kv.get(1).getText()));
        }
    }
    inputNode.put("params", paramsNode);
    ArrayNode inputPathArray = createInputPathsNode(ctx.inputPaths());
    inputNode.put("path", inputPathArray);
    this.mapCommandsNode.put("input", inputNode);
}
Example 31
Project: emf4sw-master  File: RDFGraph2Json.java View source code
public static ObjectNode createJsonTree(DocumentGraph graph) {
    final ObjectMapper mapper = new ObjectMapper();
    final RDF2JsonSwitch switcher = new RDF2JsonSwitch();
    final ObjectNode root = mapper.createObjectNode();
    for (Namespace ns : graph.getNamespaces()) {
        final ObjectNode node = mapper.createObjectNode();
        final ObjectNode nodeP = mapper.createObjectNode();
        nodeP.put(ns.getPrefix(), ns.getURI());
        node.put("@prefix", nodeP);
        root.putAll(node);
    }
    for (SubjectNode n : graph.listSubjects()) {
        final ObjectNode node = mapper.createObjectNode();
        final ObjectNode a = mapper.createObjectNode();
        final Map<Property, List<Node>> valuesByProperty = new HashMap<Property, List<Node>>();
        for (Triple tr : n.getSubjectOf()) {
            if (valuesByProperty.containsKey(tr.getPredicate())) {
                valuesByProperty.get(tr.getPredicate()).add(tr.getObject());
            } else {
                final List<Node> list = new ArrayList<Node>();
                list.add(tr.getObject());
                valuesByProperty.put(tr.getPredicate(), list);
            }
        }
        for (Property p : valuesByProperty.keySet()) {
            ObjectNode n2 = mapper.createObjectNode();
            if (valuesByProperty.get(p).size() > 1) {
                ArrayNode an = mapper.createArrayNode();
                for (Node nn : valuesByProperty.get(p)) {
                    an.add(switcher.doSwitch(nn));
                }
                n2.put(p.getLocalName(), an);
            } else {
                n2.put(p.getLocalName(), switcher.doSwitch(valuesByProperty.get(p).get(0)));
            }
            a.putAll(n2);
        }
        node.put(((URIElement) n).getURI(), a);
        root.putAll(node);
    }
    return root;
}
Example 32
Project: FoxBPM-master  File: LocationUtil.java View source code
public static String parseProcessLocation(String processLocationJson) {
    ObjectMapper objectMapper = new ObjectMapper();
    String processStatus = "";
    JsonNode jsonNode = null;
    if (StringUtil.isEmpty(processLocationJson)) {
        return "";
    }
    try {
        jsonNode = objectMapper.readTree(processLocationJson);
    } catch (Exception e) {
        throw ExceptionUtil.getException("10806001", e, processLocationJson);
    }
    processStatus = jsonNode.get("processStatus").getTextValue();
    if (ProcessInstanceStatus.RUNNING.equals(processStatus)) {
        ArrayNode nodes = (ArrayNode) jsonNode.get("nodes");
        if (nodes != null) {
            StringBuilder sb = new StringBuilder();
            Iterator<JsonNode> nodeIterator = nodes.iterator();
            sb.append("<div>");
            while (nodeIterator.hasNext()) {
                JsonNode tmpNode = nodeIterator.next();
                sb.append("<span title='");
                sb.append("处�者:[");
                if (tmpNode.get("users") != null) {
                    JsonNode users = tmpNode.get("users");
                    if (users instanceof ArrayNode) {
                        sb.append("用户:");
                        Iterator<JsonNode> userIterator = users.iterator();
                        while (userIterator.hasNext()) {
                            JsonNode userNode = userIterator.next();
                            sb.append(userNode.get("userName").getTextValue());
                            sb.append(",");
                        }
                        sb.deleteCharAt(sb.length() - 1);
                    }
                }
                if (tmpNode.get("groups") != null) {
                    JsonNode group = tmpNode.get("groups");
                    if (group instanceof ArrayNode) {
                        if (group != null) {
                            sb.append("部门:");
                            Iterator<JsonNode> userIterator = group.iterator();
                            while (userIterator.hasNext()) {
                                JsonNode userNode = userIterator.next();
                                sb.append(userNode.get("groupName").getTextValue());
                                sb.append(",");
                            }
                            sb.deleteCharAt(sb.length() - 1);
                        }
                    }
                }
                sb.append("]'>");
                sb.append(tmpNode.get("nodeName").getTextValue());
                sb.append("</span>");
            }
            sb.append("</div>");
            return sb.toString();
        }
    }
    if (ProcessInstanceStatus.COMPLETE.equals(processStatus)) {
        return "已完�";
    } else if (ProcessInstanceStatus.ABORT.equals(processStatus)) {
        return "已终止";
    }
    return "未知状�";
}
Example 33
Project: geckoboard-java-api-master  File: BulletGraphTest.java View source code
@Test
public void testJson() throws JsonProcessingException, IOException {
    BulletGraph widget = new BulletGraph("1234", false);
    widget.setAxisPoints(Arrays.asList(new String[] { "1", "2", "3", "4", "8", "0" }));
    widget.setComparative("10");
    widget.setLabel("test-label");
    widget.setProjected(10, 100);
    widget.setSubLabel("sub-test-label");
    widget.setCurrent(1, 10);
    widget.addRange(0, 10, RAGColor.RED);
    widget.addRange(10, 20, RAGColor.AMBER);
    widget.addRange(20, 30, RAGColor.GREEN);
    widget.validate();
    JsonNode data = JsonTestHelper.getJsonFromWidget(widget);
    Assert.assertNotNull(data.get("data"));
    JsonNode node = data.get("data");
    Assert.assertNull(node.get("widgetKey"));
    JsonNode item = node.get("item");
    Assert.assertEquals("test-label", item.get("label").asText());
    Assert.assertEquals("sub-test-label", item.get("sublabel").asText());
    Assert.assertTrue(item.get("axis").get("point").isArray());
    ArrayNode points = (ArrayNode) item.get("axis").get("point");
    Assert.assertEquals(6, points.size());
    Assert.assertEquals(4, points.get(3).asInt());
    Assert.assertEquals(8, points.get(4).asInt());
    Assert.assertEquals(0, points.get(5).asInt());
    Assert.assertTrue(item.get("range").isArray());
    ArrayNode ranges = (ArrayNode) item.get("range");
    Assert.assertEquals(3, ranges.size());
    Assert.assertEquals("red", ranges.get(0).get("color").asText());
    Assert.assertEquals(0, ranges.get(0).get("start").asInt());
    Assert.assertEquals(10, ranges.get(0).get("end").asInt());
    Assert.assertEquals(1, item.get("measure").get("current").get("start").asInt());
    Assert.assertEquals(10, item.get("measure").get("current").get("end").asInt());
    Assert.assertEquals(10, item.get("measure").get("projected").get("start").asInt());
    Assert.assertEquals(100, item.get("measure").get("projected").get("end").asInt());
    Assert.assertEquals(10, item.get("comparative").get("point").asInt());
    Assert.assertEquals("horizontal", node.get("orientation").asText());
}
Example 34
Project: iql-master  File: QueryServlet.java View source code
private void handleDescribeField(HttpServletRequest req, HttpServletResponse resp, DescribeStatement parsedQuery) throws IOException {
    final ServletOutputStream outputStream = resp.getOutputStream();
    final String dataset = parsedQuery.dataset;
    final String fieldName = parsedQuery.field;
    final List<String> topTerms = topTermsCache.getTopTerms(dataset, fieldName);
    FieldMetadata field = metadata.getDataset(dataset).getField(fieldName);
    if (field == null) {
        field = new FieldMetadata("notfound", FieldType.String);
        field.setDescription("Field not found");
    }
    final boolean json = req.getParameter("json") != null;
    if (json) {
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        final ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        final ObjectNode jsonRoot = mapper.createObjectNode();
        field.toJSON(jsonRoot);
        final ArrayNode termsArray = mapper.createArrayNode();
        jsonRoot.put("topTerms", termsArray);
        for (String term : topTerms) {
            termsArray.add(term);
        }
        mapper.writeValue(outputStream, jsonRoot);
    } else {
        for (String term : topTerms) {
            outputStream.println(term);
        }
    }
    outputStream.close();
}
Example 35
Project: javabin-play-public-master  File: Twitter.java View source code
private static JsonNode mapSearchResult(final JsonNode jsonNode) {
    final JsonNode statuses = jsonNode.findPath("statuses");
    final Iterator<JsonNode> elementsIterator = statuses.getElements();
    ArrayNode resultArray = JsonNodeFactory.instance.arrayNode();
    while (elementsIterator.hasNext()) {
        final JsonNode status = elementsIterator.next();
        final ObjectNode resultNode = mapTweet(status);
        resultArray.add(resultNode);
    }
    return resultArray;
}
Example 36
Project: lodes-processor-master  File: GeometryDeserializer.java View source code
private Geometry parseGeometry(JsonNode root) {
    String typeName = root.get("type").asText();
    if (typeName.equals("Point")) {
        return gf.createPoint(parseCoordinate((ArrayNode) root.get("coordinates")));
    } else if (typeName.equals("MultiPoint")) {
        return gf.createMultiPoint(parseLineString(root.get("coordinates")));
    } else if (typeName.equals("LineString")) {
        return gf.createLineString(parseLineString(root.get("coordinates")));
    } else if (typeName.equals("MultiLineString")) {
        return gf.createMultiLineString(parseLineStrings(root.get("coordinates")));
    } else if (typeName.equals("Polygon")) {
        JsonNode arrayOfRings = root.get("coordinates");
        return parsePolygonCoordinates(arrayOfRings);
    } else if (typeName.equals("MultiPolygon")) {
        JsonNode arrayOfPolygons = root.get("coordinates");
        return gf.createMultiPolygon(parsePolygons(arrayOfPolygons));
    } else if (typeName.equals("GeometryCollection")) {
        return gf.createGeometryCollection(parseGeometries(root.get("geometries")));
    } else {
        throw new UnsupportedOperationException();
    }
}
Example 37
Project: mongo-hadoop-master  File: TestStandalone.java View source code
private JsonNode collectionSettings() {
    ArrayNode settings = new ArrayNode(JsonNodeFactory.instance);
    ObjectNode node = new ObjectNode(JsonNodeFactory.instance);
    node.put(INPUT_URI, getInputUri().toString());
    ObjectNode dow = new ObjectNode(JsonNodeFactory.instance);
    dow.put("dayOfWeek", "FRIDAY");
    node.put("query", dow);
    node.put(MONGO_SPLITTER_CLASS, SingleMongoSplitter.class.getName());
    node.put(SPLITS_USE_RANGEQUERY, true);
    node.put(INPUT_NOTIMEOUT, true);
    settings.add(node);
    MongoClientURI inputUri3 = authCheck(new MongoClientURIBuilder().collection("mongo_hadoop", "yield_historical.in3")).build();
    node = new ObjectNode(JsonNodeFactory.instance);
    node.put(INPUT_URI, inputUri3.toString());
    node.put(SPLITS_USE_RANGEQUERY, true);
    node.put(INPUT_NOTIMEOUT, true);
    settings.add(node);
    return settings;
}
Example 38
Project: ovirt-engine-master  File: WebAdminHostPageServletTest.java View source code
@Test
public void testGetPluginDefinitionsArray() {
    int mockDataCount = 10;
    List<PluginData> pluginData = new ArrayList<>();
    for (int i = 0; i < mockDataCount; i++) {
        PluginData mockData = mock(PluginData.class);
        //$NON-NLS-1$
        when(mockData.getName()).thenReturn("name" + i);
        //$NON-NLS-1$
        when(mockData.getUrl()).thenReturn("url" + i);
        when(mockData.mergeConfiguration()).thenReturn(mock(ObjectNode.class));
        when(mockData.isEnabled()).thenReturn(true);
        pluginData.add(mockData);
    }
    ArrayNode result = testServlet.getPluginDefinitionsArray(pluginData);
    assertEquals(mockDataCount, result.size());
    for (int i = 0; i < mockDataCount; i++) {
        JsonNode item = result.get(i);
        //$NON-NLS-1$ //$NON-NLS-2$
        assertEquals(item.get("name").asText(), "name" + i);
        //$NON-NLS-1$ //$NON-NLS-2$
        assertEquals(item.get("url").asText(), "url" + i);
        //$NON-NLS-1$
        assertTrue(item.get("config") instanceof ObjectNode);
        //$NON-NLS-1$
        assertTrue(item.get("enabled").asBoolean());
    }
}
Example 39
Project: siren-master  File: TwigQuery.java View source code
@Override
ObjectNode toJson() {
    final ObjectNode obj = mapper.createObjectNode();
    final ObjectNode twig = obj.putObject(TwigPropertyParser.TWIG_PROPERTY);
    if (hasRoot) {
        twig.put(RootPropertyParser.ROOT_PROPERTY, rootBooleanExpression);
    }
    if (this.hasLevel()) {
        twig.put(LevelPropertyParser.LEVEL_PROPERTY, this.getLevel());
    }
    if (this.hasRange()) {
        final ArrayNode array = twig.putArray(RangePropertyParser.RANGE_PROPERTY);
        array.add(this.getLowerBound());
        array.add(this.getUpperBound());
    }
    if (this.hasBoost()) {
        twig.put(BoostPropertyParser.BOOST_PROPERTY, this.getBoost());
    }
    ArrayNode childArray = null;
    ArrayNode descendantArray = null;
    for (final QueryClause clause : clauses) {
        if (clause instanceof BasicQueryClause) {
            if (!twig.has(ChildPropertyParser.CHILD_PROPERTY)) {
                // avoid to create an empty array in the JSON
                childArray = twig.putArray(ChildPropertyParser.CHILD_PROPERTY);
            }
            final ObjectNode e = childArray.addObject();
            e.put(OccurPropertyParser.OCCUR_PROPERTY, clause.getOccur().toString());
            e.putAll(clause.getQuery().toJson());
        } else {
            if (!twig.has(DescendantPropertyParser.DESCENDANT_PROPERTY)) {
                // avoid to create an empty array in the JSON
                descendantArray = twig.putArray(DescendantPropertyParser.DESCENDANT_PROPERTY);
            }
            final ObjectNode e = descendantArray.addObject();
            e.put(OccurPropertyParser.OCCUR_PROPERTY, clause.getOccur().toString());
            e.put(LevelPropertyParser.LEVEL_PROPERTY, ((DescendantQueryClause) clause).getLevel());
            e.putAll(clause.getQuery().toJson());
        }
    }
    return obj;
}
Example 40
Project: smart-cms-master  File: ContentLoaderImpl.java View source code
@Override
public FieldValue getValueFor(String value, DataType dataType) {
    final FieldValue result;
    final FieldValueType type = dataType.getType();
    if (logger.isDebugEnabled()) {
        logger.debug("Getting field value as " + type.name() + " from " + value);
    }
    switch(type) {
        case COMPOSITE:
            logger.debug("Getting as composite");
            MutableCompositeFieldValue compositeFieldValue = createCompositeFieldValue();
            try {
                JsonNode node = CollectionFieldValueImpl.MAPPER.readTree(value);
                if (node instanceof ObjectNode) {
                    ObjectNode objectNode = (ObjectNode) node;
                    CompositeDataType compositeDataType = (CompositeDataType) dataType;
                    Map<String, FieldDef> defs = compositeDataType.getComposedFieldDefs();
                    Collection<Field> compositeValues = new ArrayList<Field>(defs.size());
                    for (Entry<String, FieldDef> def : defs.entrySet()) {
                        final JsonNode fNode = objectNode.get(def.getKey());
                        final DataType itemDataType = def.getValue().getValueDef();
                        final String textValue;
                        if (fNode != null) {
                            if (itemDataType.getType().equals(FieldValueType.COLLECTION) || itemDataType.getType().equals(FieldValueType.COMPOSITE)) {
                                textValue = fNode.toString();
                            } else {
                                textValue = fNode.getTextValue();
                            }
                        } else {
                            textValue = "";
                        }
                        final FieldValue valueFor = org.apache.commons.lang.StringUtils.isNotBlank(textValue) ? getValueFor(textValue, itemDataType) : null;
                        final MutableField mutableField = createMutableField(null, def.getValue());
                        mutableField.setValue(valueFor);
                        compositeValues.add(mutableField);
                    }
                    compositeFieldValue.setValue(compositeValues);
                } else {
                    throw new IllegalStateException("Collection must be of array of strings!");
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            result = compositeFieldValue;
            break;
        case COLLECTION:
            logger.debug("Getting as collection");
            MutableCollectionFieldValue collectionFieldValue = createCollectionFieldValue();
            try {
                JsonNode node = CollectionFieldValueImpl.MAPPER.readTree(value);
                if (node instanceof ArrayNode) {
                    ArrayNode arrayNode = (ArrayNode) node;
                    int size = arrayNode.size();
                    ArrayList<FieldValue> values = new ArrayList<FieldValue>(size);
                    for (int i = 0; i < size; ++i) {
                        final DataType itemDataType = ((CollectionDataType) dataType).getItemDataType();
                        if (itemDataType.getType().equals(FieldValueType.COMPOSITE)) {
                            final String stringValue = arrayNode.get(i).toString();
                            values.add(getValueFor(stringValue, itemDataType));
                        } else {
                            final String stringValue = arrayNode.get(i).getTextValue();
                            values.add(getValueFor(stringValue, itemDataType));
                        }
                    }
                    collectionFieldValue.setValue(values);
                } else {
                    throw new IllegalStateException("Collection must be of array of strings!");
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            result = collectionFieldValue;
            break;
        default:
            logger.debug("Getting as all other than collection");
            result = getSimpleValueFor(value, type);
    }
    return result;
}
Example 41
Project: xbmc-jsonrpclib-android-legacy-master  File: VideoModel.java View source code
/**
		 * Extracts a list of {@link Cast} objects from a JSON array.
		 * @param node ObjectNode containing the list of objects.
		 * @param key Key pointing to the node where the list is stored.
		 */
static List<Cast> getVideoModelCastList(JsonNode node, String key) {
    if (node.has(key)) {
        final ArrayNode a = (ArrayNode) node.get(key);
        final List<Cast> l = new ArrayList<Cast>(a.size());
        for (int i = 0; i < a.size(); i++) {
            l.add(new Cast((JsonNode) a.get(i)));
        }
        return l;
    }
    return new ArrayList<Cast>(0);
}
Example 42
Project: xbmcremote-android-nx111-master  File: VideoModel.java View source code
/**
		 * Extracts a list of {@link Cast} objects from a JSON array.
		 * @param obj ObjectNode containing the list of objects.
		 * @param key Key pointing to the node where the list is stored.
		 */
static List<Cast> getVideoModelCastList(JsonNode node, String key) {
    if (node.has(key)) {
        final ArrayNode a = (ArrayNode) node.get(key);
        final List<Cast> l = new ArrayList<Cast>(a.size());
        for (int i = 0; i < a.size(); i++) {
            l.add(new Cast((JsonNode) a.get(i)));
        }
        return l;
    }
    return new ArrayList<Cast>(0);
}
Example 43
Project: amazon-ansible-play-article-master  File: Application.java View source code
@Restrict(@Group(Application.USER_ROLE))
public static Result getImagesForTag() {
    String tagId = request().getQueryString("tag");
    Logger.info(String.format("Requested images for tag [%s]", tagId));
    DynamoDbService db = DynamoDbService.INSTANCE;
    List<Photo> photos = db.getPhotosForTag(tagId);
    ObjectNode json = Json.newObject();
    ArrayNode array = json.putArray("images");
    for (Photo p : photos) {
        ObjectNode node = array.addObject();
        node.put("image", p.getImageUrl());
        node.put("thumbnail", p.getThumbnailUrl());
        node.put("text", p.getText());
    }
    return ok(json);
}
Example 44
Project: avro-master  File: Json.java View source code
/**
   * Read Json data from Avro data.
   * @deprecated internal method
   */
@Deprecated
public static JsonNode read(Decoder in) throws IOException {
    switch(JsonType.values()[in.readIndex()]) {
        case LONG:
            return new LongNode(in.readLong());
        case DOUBLE:
            return new DoubleNode(in.readDouble());
        case STRING:
            return new TextNode(in.readString());
        case BOOLEAN:
            return in.readBoolean() ? BooleanNode.TRUE : BooleanNode.FALSE;
        case NULL:
            in.readNull();
            return NullNode.getInstance();
        case ARRAY:
            ArrayNode array = JsonNodeFactory.instance.arrayNode();
            for (long l = in.readArrayStart(); l > 0; l = in.arrayNext()) for (long i = 0; i < l; i++) array.add(read(in));
            return array;
        case OBJECT:
            ObjectNode object = JsonNodeFactory.instance.objectNode();
            for (long l = in.readMapStart(); l > 0; l = in.mapNext()) for (long i = 0; i < l; i++) object.put(in.readString(), read(in));
            return object;
        default:
            throw new AvroRuntimeException("Unexpected Json node type");
    }
}
Example 45
Project: CrowdTransEval-master  File: JSONParams.java View source code
/**
	 * Gets the JSON formatted as a Hashmap of properties
	 * 
	 * @return the Hashmap containing all tht properties
	 */
public HashMap<String, String> formatAsHash() {
    HashMap<String, String> ret = new HashMap<String, String>();
    Iterator<Map.Entry<String, JsonNode>> it = this.rootNode.getFields();
    while (it.hasNext()) {
        Map.Entry<String, JsonNode> element = it.next();
        if (!(element.getValue() instanceof ObjectNode || element.getValue() instanceof ArrayNode)) {
            ret.put(element.getKey(), element.getValue().asText());
        }
    }
    return ret;
}
Example 46
Project: extended-objects-master  File: JsonEntityManager.java View source code
@Override
public ObjectNode createEntity(TypeMetadataSet<EntityTypeMetadata<JsonNodeMetadata>> types, Set<String> discriminators, Map<PrimitivePropertyMethodMetadata<JsonPropertyMetadata>, Object> exampleEntity) {
    ObjectNode rootNode = mapper.createObjectNode();
    ArrayNode typesNode = mapper.createArrayNode();
    for (String typeName : discriminators) {
        typesNode.add(typeName);
    }
    rootNode.put(TYPES_PROPERTY, typesNode);
    UUID uuid = UUID.randomUUID();
    rootNode.put(ID_PROPERTY, uuid.toString());
    for (Map.Entry<PrimitivePropertyMethodMetadata<JsonPropertyMetadata>, Object> entry : exampleEntity.entrySet()) {
        setProperty(rootNode, entry.getKey(), entry.getValue());
    }
    return rootNode;
}
Example 47
Project: gravel-master  File: StringExtensions.java View source code
private static Object jsonNodeAsSimpleObject(JsonNode value) {
    Object o = null;
    if (value.isTextual()) {
        o = value.asText();
    } else if (value.isArray()) {
        ArrayList<Object> arrayList = new ArrayList<>();
        for (Iterator<JsonNode> iter = ((ArrayNode) value).getElements(); iter.hasNext(); ) {
            arrayList.add(jsonNodeAsSimpleObject(iter.next()));
        }
        o = arrayList.toArray();
    } else if (value.isNull()) {
        o = null;
    } else if (value.isObject()) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        final Iterator<Entry<String, JsonNode>> fields = value.getFields();
        while (fields.hasNext()) {
            final Entry<String, JsonNode> next = fields.next();
            map.put(next.getKey(), jsonNodeAsSimpleObject(next.getValue()));
        }
        o = map;
    } else
        throw new RuntimeException("Unknown type: " + value);
    return o;
}
Example 48
Project: grefine-rdf-extension-master  File: GRefineJsonUtilitiesImpl.java View source code
@Override
public ObjectNode jsonizeSearchResult(ImmutableList<SearchResultItem> results, String prefix) throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode resultObj = mapper.createObjectNode();
    resultObj.put("code", "/api/status/ok");
    resultObj.put("status", "200 OK");
    resultObj.put("prefix", prefix);
    ArrayNode resultArr = mapper.createArrayNode();
    for (SearchResultItem item : results) {
        ObjectNode resultItemObj = mapper.createObjectNode();
        resultItemObj.put("id", item.getId());
        resultItemObj.put("name", item.getName());
        //FIXME id is used instead of type to enable the suggest autocomplete to function as it doesn't work when no type is given
        ObjectNode tmpObj = mapper.createObjectNode();
        tmpObj.put("id", item.getId());
        tmpObj.put("name", item.getId());
        resultItemObj.put("type", tmpObj);
        resultArr.add(resultItemObj);
    }
    resultObj.put("result", resultArr);
    return resultObj;
}
Example 49
Project: kaa-master  File: AbstractTestControlServer.java View source code
protected CTLSchemaDto createCTLSchema(String name, String namespace, int version, String tenantId, String applicationToken, Set<FqnVersion> dependencies, Map<String, String> fields) throws Exception {
    LOG.debug("Generating CTL schema...");
    JsonNodeFactory factory = JsonNodeFactory.instance;
    ObjectNode body = factory.objectNode();
    body.put("type", "record");
    body.put("name", name);
    body.put("namespace", namespace);
    body.put("version", version);
    if (dependencies != null && !dependencies.isEmpty()) {
        ArrayNode array = factory.arrayNode();
        for (FqnVersion dependency : dependencies) {
            ObjectNode object = factory.objectNode();
            object.put("fqn", dependency.getFqnString());
            object.put("version", dependency.getVersion());
            array.add(object);
        }
        body.put("dependencies", array);
    }
    ArrayNode array = factory.arrayNode();
    if (fields != null) {
        for (Map.Entry<String, String> field : fields.entrySet()) {
            ObjectNode object = factory.objectNode();
            object.put("name", field.getKey());
            object.put("type", field.getValue());
            array.add(object);
        }
    }
    body.put("fields", array);
    LOG.debug("CTL schema generated: " + body);
    return client.saveCTLSchemaWithAppToken(body.toString(), tenantId, applicationToken);
}
Example 50
Project: kiji-schema-master  File: FormattedEntityIdRowFilter.java View source code
@Override
protected JsonNode toJsonNode() {
    final ObjectNode root = JsonNodeFactory.instance.objectNode();
    try {
        root.put(ROW_KEY_FORMAT_NODE, ToJson.toAvroJsonString(mRowKeyFormat, mRowKeyFormat.getSchema()));
        final ArrayNode components = root.putArray(COMPONENTS_NODE);
        for (int i = 0; i < mComponents.length; i++) {
            final Object component = mComponents[i];
            if (null == component) {
                components.add(components.nullNode());
            } else {
                switch(mRowKeyFormat.getComponents().get(i).getType()) {
                    case INTEGER:
                        components.add((Integer) component);
                        break;
                    case LONG:
                        components.add((Long) component);
                        break;
                    case STRING:
                        components.add((String) component);
                        break;
                    default:
                        throw new IllegalStateException("Unknown component type: " + mRowKeyFormat.getComponents().get(i).getType());
                }
            }
        }
    } catch (IOException ioe) {
        throw new KijiIOException(ioe);
    }
    return root;
}
Example 51
Project: nuxeo-master  File: DocumentBrowsingTest.java View source code
/**
     * @since 8.3
     */
@Test
public void iCanGetTheCollectionsOfADocument() throws Exception {
    Map<String, String> headers = new HashMap<>();
    headers.put(MarshallingConstants.EMBED_ENRICHERS + ".document", CollectionsJsonEnricher.NAME);
    DocumentModel note = RestServerInit.getNote(0, session);
    ClientResponse response = getResponse(RequestType.GET, "repo/" + note.getRepositoryName() + "/path" + note.getPathAsString(), headers);
    // The above GET will force the creation of the user workspace if it did not exist yet.
    // Force to refresh current transaction context.
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    assertEquals(0, ((ArrayNode) node.get(RestConstants.CONTRIBUTOR_CTX_PARAMETERS).get(CollectionsJsonEnricher.NAME)).size());
    CollectionManager collectionManager = Framework.getService(CollectionManager.class);
    collectionManager.addToNewCollection("dummyCollection", null, note, session);
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    response = getResponse(RequestType.GET, "repo/" + note.getRepositoryName() + "/path" + note.getPathAsString(), headers);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    ArrayNode collections = (ArrayNode) node.get(RestConstants.CONTRIBUTOR_CTX_PARAMETERS).get(CollectionsJsonEnricher.NAME);
    assertEquals(1, collections.size());
    assertEquals("dummyCollection", collections.get(0).get("title").getTextValue());
}
Example 52
Project: semantictools-master  File: LdContextReaderImpl.java View source code
@Override
public LdContext parseContext(JsonNode node) throws LdContextParseException, IOException {
    LdContext context = null;
    boolean external = false;
    if (node.isTextual()) {
        context = loadExternalContext(node.asText());
        external = true;
    } else if (node instanceof ObjectNode) {
        context = new LdContext();
        parseContextObject((ObjectNode) node, context);
    } else if (node instanceof ArrayNode) {
        context = new LdContext();
        parseContextArray((ArrayNode) node, context);
    }
    if (context != null) {
        context.close();
        prepareOwlClasses(context);
        //
        if (!external && context.isEnhanced()) {
            resolveRefereces(context);
        }
    }
    return context;
}
Example 53
Project: xbmc-jsonrpclib-android-master  File: JsonAccesClassModule.java View source code
@Override
public Set<String> getImports(JavaClass klass) {
    final Set<String> imports = new HashSet<String>();
    imports.add("org.codehaus.jackson.JsonNode");
    imports.add("org.codehaus.jackson.node.ObjectNode");
    if (klass.isUsedAsResult()) {
        imports.add("org.codehaus.jackson.node.ArrayNode");
        imports.add("java.util.List");
        imports.add("java.util.ArrayList");
    }
    if (klass.isMultiType()) {
        for (JavaAttribute member : klass.getMembers()) {
            if (!member.isEnum()) {
                if ("boolean".equals(member.getType().getName())) {
                    imports.add("org.codehaus.jackson.node.BooleanNode");
                }
                if ("string".equals(member.getType().getName())) {
                    imports.add("org.codehaus.jackson.node.TextNode");
                }
                if ("integer".equals(member.getType().getName())) {
                    imports.add("org.codehaus.jackson.node.IntNode");
                }
                if ("number".equals(member.getType().getName())) {
                    imports.add("org.codehaus.jackson.node.DoubleNode");
                }
            } else {
                imports.add("org.codehaus.jackson.node.TextNode");
            }
        }
    }
    return imports;
}
Example 54
Project: ApAM-master  File: RemoteDependencyDeclaration.java View source code
public ObjectNode toJson() {
    ObjectMapper om = new ObjectMapper();
    ObjectNode root = om.createObjectNode();
    root.put(JSON_ID, getIdentifier());
    root.put(JSON_IS_MULTIPLE, isMultiple());
    root.put(JSON_COMP_REF_NAME, getComponent().getName());
    root.put(JSON_PROVIDER_URL, providerURL);
    ObjectNode json_rr = om.createObjectNode();
    json_rr.put(JSON_RESOLVABLE_REF_NAME, getTarget().getName());
    // Set RRTYPE
    if (getTarget() instanceof InterfaceReference) {
        json_rr.put(JSON_RESOLVABLE_REF_TYPE, RRTYPE.itf.toString());
    } else if (getTarget() instanceof MessageReference) {
        json_rr.put(JSON_RESOLVABLE_REF_TYPE, RRTYPE.message.toString());
    } else if (getTarget() instanceof InstanceReference) {
        json_rr.put(JSON_RESOLVABLE_REF_TYPE, RRTYPE.instance.toString());
    }
    // Set the ResolvableReference
    root.put(JSON_RESOLVABLE_REF, json_rr);
    ArrayNode instanceconstraints = om.createArrayNode();
    ArrayNode implementationconstraints = om.createArrayNode();
    for (String filter : this.getInstanceConstraints()) {
        instanceconstraints.add(filter);
    }
    for (String filter : this.getImplementationConstraints()) {
        implementationconstraints.add(filter);
    }
    root.put(JSON_INSTANCE_CONSTRAINT, instanceconstraints);
    root.put(JSON_IMPLEMENTATION_CONSTRAINT, implementationconstraints);
    return root;
}
Example 55
Project: DSMAPICAT-master  File: FacadeRestUtil.java View source code
private static ObjectNode createNodeViewWithFields(ObjectMapper mapper, Object bean, Set<String> fieldNames) {
    // split fieldNames in 2 categories : 
    // simpleFields for simple property names with no '.'
    // nestedFields for nested property names with a '.'
    Set<String> simpleFields = new HashSet<String>();
    MultivaluedMapImpl nestedFields = new MultivaluedMapImpl();
    for (String fieldName : fieldNames) {
        int index = fieldName.indexOf('.');
        boolean isNestedField = index > 0 && index < fieldName.length();
        if (isNestedField) {
            String rootFieldName = fieldName.substring(0, index);
            String subFieldName = fieldName.substring(index + 1);
            nestedFields.add(rootFieldName, subFieldName);
        } else {
            simpleFields.add(fieldName);
        }
    }
    // create a simple node with only one level containing all simples properties
    ObjectNode rootNode = createNodeWithSimpleFields(mapper, bean, simpleFields);
    // create nested nodes with deeper levels
    Set<Map.Entry<String, List<String>>> entrySet = nestedFields.entrySet();
    // for each nested property, create recursively a node        
    for (Map.Entry<String, List<String>> entry : entrySet) {
        String rootFieldName = entry.getKey();
        // add in current node only if full property is not already present in 1st level
        if (!simpleFields.contains(rootFieldName)) {
            Object nestedBean = getField(bean, rootFieldName);
            // add only non null fields
            if (nestedBean == null) {
                break;
            }
            Set<String> nestedFieldNames = new HashSet<String>(entry.getValue());
            // current node is an array or a list
            if ((nestedBean.getClass().isArray()) || (Collection.class.isAssignableFrom(nestedBean.getClass()))) {
                Object[] array = null;
                if ((nestedBean.getClass().isArray())) {
                    array = (Object[]) nestedBean;
                } else {
                    Collection collection = (Collection) nestedBean;
                    array = collection.toArray();
                }
                if (array.length > 0) {
                    // create a node for each element in array 
                    // and add created node in an arrayNode
                    Collection<JsonNode> nodes = new LinkedList<JsonNode>();
                    for (Object object : array) {
                        ObjectNode nestedNode = createNodeViewWithFields(mapper, object, nestedFieldNames);
                        if (nestedNode != null && nestedNode.size() > 0) {
                            nodes.add(nestedNode);
                        }
                    }
                    ArrayNode arrayNode = mapper.createArrayNode();
                    arrayNode.addAll(nodes);
                    if (arrayNode.size() > 0) {
                        rootNode.put(rootFieldName, arrayNode);
                    }
                }
            } else {
                // create recursively a node and add it in current root node
                ObjectNode nestedNode = createNodeViewWithFields(mapper, nestedBean, nestedFieldNames);
                if (nestedNode != null && nestedNode.size() > 0) {
                    rootNode.put(rootFieldName, nestedNode);
                }
            }
        }
    }
    return rootNode;
}
Example 56
Project: elasticsearch-suggest-plugin-master  File: RestSuggestActionTest.java View source code
@Override
public FstStats getStatistics() throws Exception {
    List<FstStats.FstIndexShardStats> stats = Lists.newArrayList();
    Response r = httpClient.prepareGet("http://localhost:" + port + "/__suggestStatistics").execute().get();
    assertThat(r.getStatusCode(), is(200));
    System.out.println(r.getResponseBody());
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootObj = objectMapper.readTree(r.getResponseBody());
    FstStats fstStats = new FstStats();
    ArrayNode jsonFstStats = (ArrayNode) rootObj.get("fstStats");
    Iterator<JsonNode> nodesIterator = jsonFstStats.iterator();
    while (nodesIterator.hasNext()) {
        JsonNode fstStatsNodeEntry = nodesIterator.next();
        if (fstStatsNodeEntry.isObject()) {
            ShardId shardId = new ShardId(fstStatsNodeEntry.get("index").asText(), fstStatsNodeEntry.get("id").asInt());
            FstStats.FstIndexShardStats fstIndexShardStats = new FstStats.FstIndexShardStats(shardId, null, null, fstStatsNodeEntry.get("sizeInBytes").getLongValue());
            stats.add(fstIndexShardStats);
        }
        fstStats.getStats().addAll(stats);
    }
    return fstStats;
}
Example 57
Project: exhibitor-master  File: IndexResource.java View source code
@Path("dataTable/{index-name}/{search-handle}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getDataTableData(@PathParam("index-name") String indexName, @PathParam("search-handle") String searchHandle, @QueryParam("iDisplayStart") int iDisplayStart, @QueryParam("iDisplayLength") int iDisplayLength, @QueryParam("sEcho") String sEcho) throws Exception {
    LogSearch logSearch = getLogSearch(indexName);
    if (logSearch == null) {
        return "{}";
    }
    ObjectNode node;
    try {
        CachedSearch cachedSearch = logSearch.getCachedSearch(searchHandle);
        DateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT_STR);
        ArrayNode dataTab = JsonNodeFactory.instance.arrayNode();
        for (int i = iDisplayStart; i < (iDisplayStart + iDisplayLength); ++i) {
            if (i < cachedSearch.getTotalHits()) {
                ObjectNode data = JsonNodeFactory.instance.objectNode();
                int docId = cachedSearch.getNthDocId(i);
                SearchItem item = logSearch.toResult(docId);
                data.put("DT_RowId", "index-query-result-" + docId);
                data.put("0", getTypeName(EntryTypes.getFromId(item.getType())));
                data.put("1", dateFormatter.format(item.getDate()));
                data.put("2", trimPath(item.getPath()));
                dataTab.add(data);
            }
        }
        node = JsonNodeFactory.instance.objectNode();
        node.put("sEcho", sEcho);
        node.put("iTotalRecords", logSearch.getDocQty());
        node.put("iTotalDisplayRecords", cachedSearch.getTotalHits());
        node.put("aaData", dataTab);
    } finally {
        context.getExhibitor().getIndexCache().releaseLogSearch(logSearch.getFile());
    }
    return node.toString();
}
Example 58
Project: kaleido-repository-master  File: JsonConfiguration.java View source code
/*
    * (non-Javadoc)
    * @see org.kaleidofoundry.core.config.AbstractConfiguration#storeProperties(org.kaleidofoundry.core.store.ResourceHandler,
    * org.kaleidofoundry.core.cache.Cache)
    */
@Override
protected Cache<String, Serializable> storeProperties(final ResourceHandler resourceHandler, final Cache<String, Serializable> properties) throws ResourceException, ConfigurationException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();
    Map<String, ObjectNode> currentNodes = new HashMap<String, ObjectNode>();
    for (String key : keySet()) {
        StringTokenizer strToken = new StringTokenizer(key.substring(KeyRoot.length()), KeySeparator);
        String subKey = "";
        ObjectNode node = rootNode;
        while (strToken.hasMoreTokens()) {
            String nodeName = strToken.nextToken();
            subKey = subKey + KeySeparator + nodeName;
            ObjectNode newNode;
            if (!currentNodes.containsKey(subKey)) {
                newNode = mapper.createObjectNode();
                currentNodes.put(subKey, newNode);
            } else {
                newNode = currentNodes.get(subKey);
            }
            if (strToken.hasMoreElements()) {
                node.put(nodeName, newNode);
                node = newNode;
            } else {
                List<String> values = getStringList(key);
                if (values == null || values.size() == 1) {
                    node.put(nodeName, getString(key));
                } else {
                    ArrayNode arrayNode = mapper.createArrayNode();
                    for (String value : values) {
                        arrayNode.add(value);
                    }
                    node.put(nodeName, arrayNode);
                }
                node = newNode;
            }
        }
    }
    ByteArrayOutputStream jsonOutput = null;
    JsonGenerator jsonGenerator = null;
    try {
        // create output stream and json serializer
        jsonOutput = new ByteArrayOutputStream();
        jsonGenerator = JSON_FACTORY.createJsonGenerator(jsonOutput);
        jsonGenerator.useDefaultPrettyPrinter();
        // jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
        // write json content
        mapper.writeTree(jsonGenerator, rootNode);
        // flush output stream writes
        jsonGenerator.close();
        // Store the document content
        singleFileStore.store(singleFileStore.createResourceHandler(resourceHandler.getUri(), new ByteArrayInputStream(jsonOutput.toByteArray())));
        return properties;
    } catch (IOException ioe) {
        if (ioe instanceof ResourceException) {
            throw (ResourceException) ioe;
        } else {
            throw new ResourceException(ioe, resourceHandler.getUri());
        }
    } finally {
        if (jsonGenerator != null && !jsonGenerator.isClosed()) {
            try {
                jsonGenerator.close();
            } catch (IOException ioe) {
                throw new ResourceException(ioe, resourceHandler.getUri());
            }
        }
    }
}
Example 59
Project: LeanEngine-Server-master  File: JsonUtils.java View source code
public static Object propertyFromJson(JsonNode node) throws LeanException {
    if (node.isObject()) {
        return typedObjectFromJson((ObjectNode) node);
    } else if (node.isArray()) {
        return typedArrayFromJson((ArrayNode) node);
    } else if (node.isLong()) {
        return node.getLongValue();
    } else if (node.isInt()) {
        return node.getIntValue();
    } else if (node.isDouble()) {
        return node.getDoubleValue();
    } else if (node.isBoolean()) {
        return node.getBooleanValue();
    } else if (node.isTextual()) {
        return node.getTextValue();
    } else {
        throw new LeanException(LeanException.Error.ValueToJSON, " Unknown value node type.");
    }
}
Example 60
Project: nifi-master  File: ConvertJSONToSQL.java View source code
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    final boolean translateFieldNames = context.getProperty(TRANSLATE_FIELD_NAMES).asBoolean();
    final boolean ignoreUnmappedFields = IGNORE_UNMATCHED_FIELD.getValue().equalsIgnoreCase(context.getProperty(UNMATCHED_FIELD_BEHAVIOR).getValue());
    final String statementType = context.getProperty(STATEMENT_TYPE).getValue();
    final String updateKeys = context.getProperty(UPDATE_KEY).evaluateAttributeExpressions(flowFile).getValue();
    final String catalog = context.getProperty(CATALOG_NAME).evaluateAttributeExpressions(flowFile).getValue();
    final String schemaName = context.getProperty(SCHEMA_NAME).evaluateAttributeExpressions(flowFile).getValue();
    final String tableName = context.getProperty(TABLE_NAME).evaluateAttributeExpressions(flowFile).getValue();
    final SchemaKey schemaKey = new SchemaKey(catalog, tableName);
    final boolean includePrimaryKeys = UPDATE_TYPE.equals(statementType) && updateKeys == null;
    // Is the unmatched column behaviour fail or warning?
    final boolean failUnmappedColumns = FAIL_UNMATCHED_COLUMN.getValue().equalsIgnoreCase(context.getProperty(UNMATCHED_COLUMN_BEHAVIOR).getValue());
    final boolean warningUnmappedColumns = WARNING_UNMATCHED_COLUMN.getValue().equalsIgnoreCase(context.getProperty(UNMATCHED_COLUMN_BEHAVIOR).getValue());
    //Escape column names?
    final boolean escapeColumnNames = context.getProperty(QUOTED_IDENTIFIERS).asBoolean();
    // Quote table name?
    final boolean quoteTableName = context.getProperty(QUOTED_TABLE_IDENTIFIER).asBoolean();
    // get the database schema from the cache, if one exists. We do this in a synchronized block, rather than
    // using a ConcurrentMap because the Map that we are using is a LinkedHashMap with a capacity such that if
    // the Map grows beyond this capacity, old elements are evicted. We do this in order to avoid filling the
    // Java Heap if there are a lot of different SQL statements being generated that reference different tables.
    TableSchema schema;
    synchronized (this) {
        schema = schemaCache.get(schemaKey);
        if (schema == null) {
            // No schema exists for this table yet. Query the database to determine the schema and put it into the cache.
            final DBCPService dbcpService = context.getProperty(CONNECTION_POOL).asControllerService(DBCPService.class);
            try (final Connection conn = dbcpService.getConnection()) {
                schema = TableSchema.from(conn, catalog, schemaName, tableName, translateFieldNames, includePrimaryKeys);
                schemaCache.put(schemaKey, schema);
            } catch (final SQLException e) {
                getLogger().error("Failed to convert {} into a SQL statement due to {}; routing to failure", new Object[] { flowFile, e.toString() }, e);
                session.transfer(flowFile, REL_FAILURE);
                return;
            }
        }
    }
    // Parse the JSON document
    final ObjectMapper mapper = new ObjectMapper();
    final AtomicReference<JsonNode> rootNodeRef = new AtomicReference<>(null);
    try {
        session.read(flowFile, new InputStreamCallback() {

            @Override
            public void process(final InputStream in) throws IOException {
                try (final InputStream bufferedIn = new BufferedInputStream(in)) {
                    rootNodeRef.set(mapper.readTree(bufferedIn));
                }
            }
        });
    } catch (final ProcessException pe) {
        getLogger().error("Failed to parse {} as JSON due to {}; routing to failure", new Object[] { flowFile, pe.toString() }, pe);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }
    final JsonNode rootNode = rootNodeRef.get();
    // The node may or may not be a Json Array. If it isn't, we will create an
    // ArrayNode and add just the root node to it. We do this so that we can easily iterate
    // over the array node, rather than duplicating the logic or creating another function that takes many variables
    // in order to implement the logic.
    final ArrayNode arrayNode;
    if (rootNode.isArray()) {
        arrayNode = (ArrayNode) rootNode;
    } else {
        final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
        arrayNode = new ArrayNode(nodeFactory);
        arrayNode.add(rootNode);
    }
    final String fragmentIdentifier = UUID.randomUUID().toString();
    final Set<FlowFile> created = new HashSet<>();
    for (int i = 0; i < arrayNode.size(); i++) {
        final JsonNode jsonNode = arrayNode.get(i);
        final String sql;
        final Map<String, String> attributes = new HashMap<>();
        try {
            // build the fully qualified table name
            final StringBuilder tableNameBuilder = new StringBuilder();
            if (catalog != null) {
                tableNameBuilder.append(catalog).append(".");
            }
            if (schemaName != null) {
                tableNameBuilder.append(schemaName).append(".");
            }
            tableNameBuilder.append(tableName);
            final String fqTableName = tableNameBuilder.toString();
            if (INSERT_TYPE.equals(statementType)) {
                sql = generateInsert(jsonNode, attributes, fqTableName, schema, translateFieldNames, ignoreUnmappedFields, failUnmappedColumns, warningUnmappedColumns, escapeColumnNames, quoteTableName);
            } else if (UPDATE_TYPE.equals(statementType)) {
                sql = generateUpdate(jsonNode, attributes, fqTableName, updateKeys, schema, translateFieldNames, ignoreUnmappedFields, failUnmappedColumns, warningUnmappedColumns, escapeColumnNames, quoteTableName);
            } else {
                sql = generateDelete(jsonNode, attributes, fqTableName, schema, translateFieldNames, ignoreUnmappedFields, failUnmappedColumns, warningUnmappedColumns, escapeColumnNames, quoteTableName);
            }
        } catch (final ProcessException pe) {
            getLogger().error("Failed to convert {} to a SQL {} statement due to {}; routing to failure", new Object[] { flowFile, statementType, pe.toString() }, pe);
            session.remove(created);
            session.transfer(flowFile, REL_FAILURE);
            return;
        }
        FlowFile sqlFlowFile = session.create(flowFile);
        created.add(sqlFlowFile);
        sqlFlowFile = session.write(sqlFlowFile, new OutputStreamCallback() {

            @Override
            public void process(final OutputStream out) throws IOException {
                out.write(sql.getBytes(StandardCharsets.UTF_8));
            }
        });
        attributes.put(CoreAttributes.MIME_TYPE.key(), "text/plain");
        attributes.put("sql.table", tableName);
        attributes.put(FRAGMENT_ID.key(), fragmentIdentifier);
        attributes.put(FRAGMENT_COUNT.key(), String.valueOf(arrayNode.size()));
        attributes.put(FRAGMENT_INDEX.key(), String.valueOf(i));
        if (catalog != null) {
            attributes.put("sql.catalog", catalog);
        }
        sqlFlowFile = session.putAllAttributes(sqlFlowFile, attributes);
        session.transfer(sqlFlowFile, REL_SQL);
    }
    flowFile = copyAttributesToOriginal(session, flowFile, fragmentIdentifier, arrayNode.size());
    session.transfer(flowFile, REL_ORIGINAL);
}
Example 61
Project: qi4j-sdk-master  File: JacksonValueDeserializer.java View source code
@Override
protected <T> void putArrayNodeInCollection(JsonNode inputNode, Function<JsonNode, T> deserializer, Collection<T> collection) throws Exception {
    if (isNullOrMissing(inputNode)) {
        return;
    }
    if (!inputNode.isArray()) {
        throw new ValueSerializationException("Expected an array but got " + inputNode);
    }
    ArrayNode array = (ArrayNode) inputNode;
    for (JsonNode item : array) {
        T value = deserializer.map(item);
        collection.add(value);
    }
}
Example 62
Project: sensim-master  File: JsonLoader.java View source code
private void flatten_value(JsonNode node, Map<String, Object> values) {
    Iterator<String> keys = node.getFieldNames();
    Iterator<JsonNode> nodes = node.getElements();
    while (keys.hasNext()) {
        String key = keys.next();
        JsonNode value = nodes.next();
        System.out.println(key + ":" + value.toString());
        if (value.isArray()) {
            ArrayNode array = (ArrayNode) value;
            DataBag bag = DefaultBagFactory.getInstance().newDefaultBag();
            for (JsonNode innervalue : array) {
                flatten_array(innervalue, bag);
            }
            values.put(key, bag);
        } else if (value.isObject()) {
            Map<String, Object> values2 = new HashMap<String, Object>();
            flatten_value((ObjectNode) value, values2);
            values.put(key, tupleFactory.newTuple(values2));
        } else {
            values.put(key, value != null ? value.toString().replaceAll("[\"]", "") : null);
        }
    }
}
Example 63
Project: addis-master  File: SMAASerializer.java View source code
public JsonNode getRootNode() {
    ObjectNode rootNode = (ObjectNode) d_mapper.createObjectNode();
    rootNode.put("title", d_analysis.getName());
    insertCriteria(d_mapper, rootNode);
    insertAlternatives(d_mapper, rootNode);
    // Add PerfomanceTable
    FullJointMeasurements m = d_model.getMeasurements();
    ArrayNode performancesNode = (ArrayNode) d_mapper.createArrayNode();
    if (m instanceof ImpactMatrix) {
        insertMeasurements(d_mapper, m, performancesNode);
    }
    if (m instanceof PerCriterionMeasurements) {
        insertPerCriterionMeasurement(d_mapper, m, performancesNode);
    }
    rootNode.put("performanceTable", performancesNode);
    rootNode.put("preferences", d_mapper.createObjectNode());
    return rootNode;
}
Example 64
Project: ambari-master  File: VersionDefinitionResourceProvider.java View source code
/**
   * Provide the dry-run entity with fake sub-resources.  These are not queryable by normal API.
   */
private void addSubresources(Resource res, RepositoryVersionEntity entity) {
    JsonNodeFactory factory = JsonNodeFactory.instance;
    ArrayNode subs = factory.arrayNode();
    for (OperatingSystemEntity os : entity.getOperatingSystems()) {
        ObjectNode osBase = factory.objectNode();
        ObjectNode osElement = factory.objectNode();
        osElement.put(PropertyHelper.getPropertyName(OperatingSystemResourceProvider.OPERATING_SYSTEM_AMBARI_MANAGED_REPOS), os.isAmbariManagedRepos());
        osElement.put(PropertyHelper.getPropertyName(OperatingSystemResourceProvider.OPERATING_SYSTEM_OS_TYPE_PROPERTY_ID), os.getOsType());
        osElement.put(PropertyHelper.getPropertyName(OperatingSystemResourceProvider.OPERATING_SYSTEM_STACK_NAME_PROPERTY_ID), entity.getStackName());
        osElement.put(PropertyHelper.getPropertyName(OperatingSystemResourceProvider.OPERATING_SYSTEM_STACK_VERSION_PROPERTY_ID), entity.getStackVersion());
        osBase.put(PropertyHelper.getPropertyCategory(OperatingSystemResourceProvider.OPERATING_SYSTEM_AMBARI_MANAGED_REPOS), osElement);
        ArrayNode reposArray = factory.arrayNode();
        for (RepositoryEntity repo : os.getRepositories()) {
            ObjectNode repoBase = factory.objectNode();
            ObjectNode repoElement = factory.objectNode();
            repoElement.put(PropertyHelper.getPropertyName(RepositoryResourceProvider.REPOSITORY_BASE_URL_PROPERTY_ID), repo.getBaseUrl());
            repoElement.put(PropertyHelper.getPropertyName(RepositoryResourceProvider.REPOSITORY_OS_TYPE_PROPERTY_ID), os.getOsType());
            repoElement.put(PropertyHelper.getPropertyName(RepositoryResourceProvider.REPOSITORY_REPO_ID_PROPERTY_ID), repo.getRepositoryId());
            repoElement.put(PropertyHelper.getPropertyName(RepositoryResourceProvider.REPOSITORY_REPO_NAME_PROPERTY_ID), repo.getName());
            repoElement.put(PropertyHelper.getPropertyName(RepositoryResourceProvider.REPOSITORY_STACK_NAME_PROPERTY_ID), entity.getStackName());
            repoElement.put(PropertyHelper.getPropertyName(RepositoryResourceProvider.REPOSITORY_STACK_VERSION_PROPERTY_ID), entity.getStackVersion());
            repoBase.put(PropertyHelper.getPropertyCategory(RepositoryResourceProvider.REPOSITORY_BASE_URL_PROPERTY_ID), repoElement);
            reposArray.add(repoBase);
        }
        osBase.put(new RepositoryResourceDefinition().getPluralName(), reposArray);
        subs.add(osBase);
    }
    res.setProperty(new OperatingSystemResourceDefinition().getPluralName(), subs);
}
Example 65
Project: AndroidIntelliJStarter-master  File: JsonEditor.java View source code
private JsonEditor insertAtArrayIndex(int index, JsonNode newNode) {
    if (index < 0) {
        throw new ArrayIndexOutOfBoundsException("negative index: " + index);
    }
    if (index > 0) {
        assertNodeIsArrayNodeAndHasIndex(index);
    } else {
        assertNodeIsArrayNode();
    }
    ((ArrayNode) focusedNode).insert(index, newNode);
    return this;
}
Example 66
Project: cassa-master  File: CompactionLogger.java View source code
private JsonNode formatSSTables(AbstractCompactionStrategy strategy) {
    ArrayNode node = json.arrayNode();
    CompactionStrategyManager csm = csmRef.get();
    ColumnFamilyStore cfs = cfsRef.get();
    if (csm == null || cfs == null)
        return node;
    for (SSTableReader sstable : cfs.getLiveSSTables()) {
        if (csm.getCompactionStrategyFor(sstable) == strategy)
            node.add(formatSSTable(strategy, sstable));
    }
    return node;
}
Example 67
Project: cassandra-master  File: CompactionLogger.java View source code
private JsonNode formatSSTables(AbstractCompactionStrategy strategy) {
    ArrayNode node = json.arrayNode();
    CompactionStrategyManager csm = csmRef.get();
    ColumnFamilyStore cfs = cfsRef.get();
    if (csm == null || cfs == null)
        return node;
    for (SSTableReader sstable : cfs.getLiveSSTables()) {
        if (csm.getCompactionStrategyFor(sstable) == strategy)
            node.add(formatSSTable(strategy, sstable));
    }
    return node;
}
Example 68
Project: enunciate-master  File: DataTypeExampleImpl.java View source code
@Override
public String getBody() {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    Context context = new Context();
    context.stack = new LinkedList<String>();
    build(node, this.type, context);
    if (this.type.getContext().isWrapRootValue()) {
        ObjectNode wrappedNode = JsonNodeFactory.instance.objectNode();
        wrappedNode.put(this.type.getJsonRootName(), node);
        node = wrappedNode;
    }
    JsonNode outer = node;
    for (DataTypeReference.ContainerType container : this.containers) {
        switch(container) {
            case array:
            case collection:
            case list:
                ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
                arrayNode.add(outer);
                outer = arrayNode;
                break;
            case map:
                ObjectNode mapNode = JsonNodeFactory.instance.objectNode();
                mapNode.put("...", outer);
                outer = mapNode;
                break;
        }
    }
    ObjectMapper mapper = new ObjectMapper().enable(SerializationConfig.Feature.INDENT_OUTPUT);
    try {
        return mapper.writeValueAsString(outer);
    } catch (JsonProcessingException e) {
        throw new EnunciateException(e);
    } catch (IOException e) {
        throw new EnunciateException(e);
    }
}
Example 69
Project: GNDMS-master  File: ConfigEditor.java View source code
/**
         * Ask visitor to verify the update corresponding to this record and if the visitor doesn't veto, apply it.
         *
         * @param records record stack used by current update call
         * @param visitor the visitor used to verify updates
         *
         * @throws UpdateRejectedException if the visitor vetos
         * @throws IOException on parsing problems
         */
void visit(Stack<Record> records, Visitor visitor) throws UpdateRejectedException, IOException {
    final Update updater = this.updater();
    visitor.updateNode(updater);
    if (updater.isAccepted()) {
        if (parent == null)
            // toplevel neeeds special handling to create null node or replace
            snapshot = Update.Mode.DELETE.equals(updater.getMode()) ? ConfigHolder.newNullNode(visitor.getObjectMapper()) : updater.getUpdate();
        else {
            if (parent.snapshot.isArray())
                ((ArrayNode) parent.snapshot).set((Integer) cursor, (Update.Mode.DELETE.equals(updater.getMode()) ? ConfigHolder.newNullNode(visitor.getObjectMapper()) : updater.getUpdate()));
            else {
                if (parent.snapshot.isObject()) {
                    switch(updater.getMode()) {
                        case OVERWRITE:
                            ((ObjectNode) parent.snapshot).put((String) cursor, updater.getUpdate());
                            break;
                        case APPEND:
                            for (final Iterator<String> iter = update.getFieldNames(); iter.hasNext(); ) {
                                String fieldName = iter.next();
                                ObjectNode objSnapshot = ((ObjectNode) snapshot);
                                records.push(new Record(objSnapshot.get(fieldName), update.get(fieldName), this, fieldName, Update.Mode.OVERWRITE));
                            }
                            break;
                        case DELETE:
                            ((ObjectNode) parent.snapshot).remove((String) cursor);
                            break;
                        default:
                            throw new IllegalStateException("Should never have been reached");
                    }
                } else
                    throw new IllegalStateException("Update of non-container node");
            }
        }
    } else
        throw new UpdateRejectedException();
}
Example 70
Project: hadoop-monitoring-extension-master  File: ResourceMgrMetricsFetcherTask.java View source code
protected void printJobTypeMonitoring() {
    Map<String, ?> config = configuration.getConfigYml();
    int monitoringTimePeriod = YmlUtils.getInt(config.get("monitoringTimePeriod"), 15);
    long monitoringPeriod = System.currentTimeMillis() - monitoringTimePeriod * 60 * 1000;
    List<Map<String, ?>> applications = (List<Map<String, ?>>) config.get("applications");
    if (applications != null) {
        for (Map<String, ?> application : applications) {
            String applicationType = (String) application.get("type");
            String prefix = StringUtils.concatMetricPath(getMetricPrefix(), "Current Apps", applicationType);
            JsonNode response = getAppsOfTypeResponse(monitoringPeriod, application);
            JsonNode apps = JsonUtils.getNestedObject(response, "apps", "app");
            List<String> names = (List<String>) application.get("names");
            if (apps instanceof ArrayNode) {
                ArrayNode jsonNodes = (ArrayNode) apps;
                GroupCounter<String> stateCounter = new GroupCounter<String>();
                GroupCounter<String> statusCounter = new GroupCounter<String>();
                for (JsonNode jsonNode : jsonNodes) {
                    String name = JsonUtils.getTextValue(jsonNode, "name");
                    if (matches(name, names)) {
                        String state = JsonUtils.getTextValue(jsonNode, "state");
                        stateCounter.increment(state);
                        String status = JsonUtils.getTextValue(jsonNode, "finalStatus");
                        statusCounter.increment(status);
                    } else {
                        logger.debug("The application name [{}] didnt match with the filter {}", name, names);
                    }
                }
                printAppTypeStates(StringUtils.concatMetricPath(prefix, "Final Status"), statusCounter, KNOWN_STATUS);
                printAppTypeStates(StringUtils.concatMetricPath(prefix, "State"), stateCounter, KNOWN_STATES);
            } else {
                logger.warn("There are no jobs of type {} found between [{}] and now", applicationType, new Date(monitoringPeriod));
            }
        }
    }
}
Example 71
Project: singly-android-master  File: JSON.java View source code
public static List<JsonNode> getJsonNodes(JsonNode parent, String field) {
    JsonNode node = getJsonNode(parent, field);
    List<JsonNode> values = new ArrayList<JsonNode>();
    if (node != null && !node.isNull() && node instanceof ArrayNode) {
        for (JsonNode curNode : (ArrayNode) node) {
            values.add(curNode);
        }
    }
    return values;
}
Example 72
Project: CoreLib-master  File: Neo4jServerImpl.java View source code
@Override
public long getChildrenCount(Node node) {
    // start n = node(id) match (n)-[:HAS_PART]->(part) RETURN COUNT(part)
    // as children
    ObjectNode obj = JsonNodeFactory.instance.objectNode();
    ArrayNode statements = JsonNodeFactory.instance.arrayNode();
    obj.put("statements", statements);
    ObjectNode statement = JsonNodeFactory.instance.objectNode();
    statement.put("statement", "start n = node:edmsearch2(rdf_about={from}) match (n)-[:`dcterms:hasPart`]->(part)" + " WHERE NOT ID(n)=ID(part) RETURN COUNT(part) as children");
    //								" RETURN COUNT(part) as children");
    ObjectNode parameters = statement.with("parameters");
    statements.add(statement);
    parameters.put("from", (String) node.getProperty("rdf:about"));
    HttpPost httpMethod = new HttpPost(fixTrailingSlash(serverPath) + "transaction/commit");
    try {
        String str = new ObjectMapper().writeValueAsString(obj);
        httpMethod.setEntity(new StringEntity(str));
        httpMethod.setHeader("content-type", "application/json");
        HttpResponse resp = client.execute(httpMethod);
        CustomResponse cr = new ObjectMapper().readValue(resp.getEntity().getContent(), CustomResponse.class);
        if (cr.getResults() != null && !cr.getResults().isEmpty() && cr.getResults().get(0) != null && cr.getResults().get(0).getData() != null && !cr.getResults().get(0).getData().isEmpty() && cr.getResults().get(0).getData().get(0).get("row") != null && !cr.getResults().get(0).getData().get(0).get("row").isEmpty()) {
            return Long.parseLong(cr.getResults().get(0).getData().get(0).get("row").get(0));
        }
    } catch (IllegalStateExceptionIOException |  e) {
        LOG.error(e.getMessage());
    } finally {
        httpMethod.releaseConnection();
    }
    return 0;
}
Example 73
Project: DiabloMiner-master  File: JSONRPCNetworkState.java View source code
boolean doSendWorkMessage(WorkState workState) throws IOException {
    StringBuilder dataOutput = new StringBuilder(8 * 32 + 1);
    Formatter dataFormatter = new Formatter(dataOutput);
    int[] data = workState.getData();
    dataFormatter.format("%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x" + "%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x", Integer.reverseBytes(data[0]), Integer.reverseBytes(data[1]), Integer.reverseBytes(data[2]), Integer.reverseBytes(data[3]), Integer.reverseBytes(data[4]), Integer.reverseBytes(data[5]), Integer.reverseBytes(data[6]), Integer.reverseBytes(data[7]), Integer.reverseBytes(data[8]), Integer.reverseBytes(data[9]), Integer.reverseBytes(data[10]), Integer.reverseBytes(data[11]), Integer.reverseBytes(data[12]), Integer.reverseBytes(data[13]), Integer.reverseBytes(data[14]), Integer.reverseBytes(data[15]), Integer.reverseBytes(data[16]), Integer.reverseBytes(data[17]), Integer.reverseBytes(data[18]), Integer.reverseBytes(data[19]), Integer.reverseBytes(data[20]), Integer.reverseBytes(data[21]), Integer.reverseBytes(data[22]), Integer.reverseBytes(data[23]), Integer.reverseBytes(data[24]), Integer.reverseBytes(data[25]), Integer.reverseBytes(data[26]), Integer.reverseBytes(data[27]), Integer.reverseBytes(data[28]), Integer.reverseBytes(data[29]), Integer.reverseBytes(data[30]), Integer.reverseBytes(data[31]));
    ObjectNode sendWorkMessage = mapper.createObjectNode();
    sendWorkMessage.put("method", "getwork");
    ArrayNode params = sendWorkMessage.putArray("params");
    params.add(dataOutput.toString());
    sendWorkMessage.put("id", 1);
    JsonNode responseMessage = doJSONRPCCall(false, sendWorkMessage);
    boolean accepted;
    dataFormatter.close();
    try {
        accepted = responseMessage.getBooleanValue();
    } catch (Exception e) {
        throw new IOException("Bitcoin returned unparsable JSON");
    }
    return accepted;
}
Example 74
Project: IRISv2-master  File: VKConnectorImpl.java View source code
public List<Group> searchGroups(String query, int count, String token) throws IOException {
    String request = String.format(groupsSearchUrl, URLEncoder.encode(query, "UTF-8"), 0, count, token);
    log.debug(request);
    HttpGet httpGet = new HttpGet(request);
    HttpResponse response = client.execute(httpGet);
    String responseBody = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    log.debug(responseBody);
    JsonNode resultTree = objectMapper.readTree(responseBody);
    ArrayNode arrayNode = (ArrayNode) resultTree.get("response");
    List<Group> groups = new ArrayList<>();
    for (int i = 1; i < arrayNode.size(); i++) {
        Group group = objectMapper.readValue(arrayNode.get(i).toString(), Group.class);
        groups.add(group);
    }
    return groups;
}
Example 75
Project: VKOpenRobot-master  File: VKConnectorImpl.java View source code
public List<Group> searchGroups(String query, int count, String token) throws IOException {
    String request = String.format(groupsSearchUrl, URLEncoder.encode(query, "UTF-8"), 0, count, token);
    log.debug(request);
    HttpGet httpGet = new HttpGet(request);
    HttpResponse response = client.execute(httpGet);
    String responseBody = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    log.debug(responseBody);
    JsonNode resultTree = objectMapper.readTree(responseBody);
    ArrayNode arrayNode = (ArrayNode) resultTree.get("response");
    List<Group> groups = new ArrayList<Group>();
    for (int i = 1; i < arrayNode.size(); i++) {
        Group group = objectMapper.readValue(arrayNode.get(i).toString(), Group.class);
        groups.add(group);
    }
    return groups;
}
Example 76
Project: incubator-brooklyn-master  File: ApplicationResource.java View source code
private ArrayNode entitiesIdAndNameAsArray(Collection<? extends Entity> entities) {
    ArrayNode node = mapper().createArrayNode();
    for (Entity entity : entities) {
        if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
            ObjectNode holder = mapper().createObjectNode();
            holder.put("id", entity.getId());
            holder.put("name", entity.getDisplayName());
            node.add(holder);
        }
    }
    return node;
}
Example 77
Project: nuxeo-chemistry-master  File: TestCmisBindingComplexProperties.java View source code
private ArrayList<ObjectNode> createComplexNodeList(int listSize, DateTimeFormat dateTimeFormat) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayList<ObjectNode> jsonObjects = new ArrayList<ObjectNode>();
    for (int i = 1; i <= listSize; i++) {
        ObjectNode jsonObj = mapper.createObjectNode();
        jsonObj.put("stringProp", "testString" + i);
        if (dateTimeFormat.equals(DateTimeFormat.TIME_IN_MILLIS)) {
            jsonObj.put("dateProp", 1234500000000L);
        } else {
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(1234500000000L);
            String dateStr = DateParser.formatW3CDateTime(cal.getTime());
            jsonObj.put("dateProp", dateStr);
        }
        jsonObj.put("enumProp", "ValueA");
        ArrayNode jsonArray = mapper.createArrayNode();
        jsonObj.put("arrayProp", jsonArray);
        for (int j = 1; j <= i; j++) {
            jsonArray.add(Integer.toString(j));
        }
        jsonObj.put("intProp", 123);
        jsonObj.put("boolProp", true);
        jsonObj.put("floatProp", 123.45d);
        jsonObjects.add(jsonObj);
    }
    return jsonObjects;
}
Example 78
Project: reddit-is-fun-master  File: Common.java View source code
public static String getSubredditId(String mSubreddit) {
    String subreddit_id = null;
    JsonNode subredditInfo = RestJsonClient.connect(Constants.REDDIT_BASE_URL + "/r/" + mSubreddit + "/.json?count=1");
    if (subredditInfo != null) {
        ArrayNode children = (ArrayNode) subredditInfo.path("data").path("children");
        subreddit_id = children.get(0).get("data").get("subreddit_id").getTextValue();
    }
    return subreddit_id;
}
Example 79
Project: xml-to-avro-master  File: AvroSchemaGenerator.java View source code
private void addXmlSchemasListToRoot(QName rootTagQName) {
    if (((schemaUrls == null) || schemaUrls.isEmpty()) && ((schemaFiles == null) || schemaFiles.isEmpty()) && ((baseUri == null) || !baseUri.isEmpty())) {
        return;
    }
    final ObjectNode schemasNode = JsonNodeFactory.instance.objectNode();
    if ((schemaUrls != null) && !schemaUrls.isEmpty()) {
        final ArrayNode urlArrayNode = JsonNodeFactory.instance.arrayNode();
        for (URL schemaUrl : schemaUrls) {
            urlArrayNode.add(schemaUrl.toString());
        }
        schemasNode.put("urls", urlArrayNode);
    }
    if ((schemaFiles != null) && !schemaFiles.isEmpty()) {
        final ArrayNode fileArrayNode = JsonNodeFactory.instance.arrayNode();
        for (File schemaFile : schemaFiles) {
            fileArrayNode.add(schemaFile.getAbsolutePath());
        }
        schemasNode.put("files", fileArrayNode);
    }
    if ((baseUri != null) && !baseUri.isEmpty()) {
        schemasNode.put("baseUri", baseUri);
    }
    final ObjectNode rootTagNode = JsonNodeFactory.instance.objectNode();
    rootTagNode.put("namespace", rootTagQName.getNamespaceURI());
    rootTagNode.put("localPart", rootTagQName.getLocalPart());
    schemasNode.put("rootTag", rootTagNode);
    if (root.getType().equals(Schema.Type.RECORD)) {
        root.addProp("xmlSchemas", schemasNode);
    } else if (root.getType().equals(Schema.Type.UNION)) {
        if ((root.getTypes() == null) || root.getTypes().isEmpty()) {
            throw new IllegalStateException("Root is a substitution group with no children!");
        }
        final Schema firstElem = root.getTypes().get(0);
        if (!firstElem.getType().equals(Schema.Type.RECORD)) {
            throw new IllegalStateException("Root is a substitution group with a first element of type " + firstElem.getType());
        }
        firstElem.addProp("xmlSchemas", schemasNode);
    } else {
        throw new IllegalStateException("Document root is neither a RECORD nor a UNION.");
    }
}
Example 80
Project: zenoss-protocols-master  File: QueueConfig.java View source code
/**
     * Converts an <code>array</code> argument type to a Java List suitable for passing as one
     * of the argument values to exchange.declare, queue.bind, queue.declare.
     *
     * @param arrayNode The array node pointing to the value of the array argument.
     * @return A list with all members converted to the appropriate types.
     * @throws IOException If an exception occurs parsing the nodes.
     */
private static List<Object> convertArrayNodeToList(ArrayNode arrayNode) throws IOException {
    final List<Object> list = new ArrayList<Object>(arrayNode.size());
    for (Iterator<JsonNode> it = arrayNode.getElements(); it.hasNext(); ) {
        final JsonNode node = it.next();
        if (!node.isObject()) {
            throw new IllegalArgumentException("Invalid node: " + node);
        }
        list.add(convertObjectNode((ObjectNode) node));
    }
    return list;
}
Example 81
Project: avro-ui-master  File: SchemaFormAvroConverter.java View source code
/**
     * Creates the schema string.
     *
     * @param schema the schema
     * @param pretty the pretty
     * @return the string
     * @throws IOException Signals that an I/O exception has occurred.
     */
public static String createSchemaString(Schema schema, boolean pretty) throws IOException {
    Schema holderSchema = Schema.createRecord(SchemaFormAvroConverter.class.getSimpleName(), null, SchemaFormAvroConverter.class.getPackage().getName(), false);
    List<Field> fields = new ArrayList<Field>();
    JsonNode dependenciesNode = schema.getJsonProp(DEPENDENCIES);
    if (dependenciesNode != null && dependenciesNode.isArray()) {
        for (int i = 0; i < dependenciesNode.size(); i++) {
            JsonNode dependencyNode = dependenciesNode.get(i);
            String fqn = dependencyNode.get(FQN).asText();
            Schema fieldType = findType(schema, fqn, null);
            if (fieldType != null) {
                Field tempField = new Field(fqn.replaceAll("\\.", "_"), fieldType, null, null);
                fields.add(tempField);
            }
        }
    }
    Field holdedField = new Field(HOLDED_SCHEMA_FIELD, schema, null, null);
    fields.add(holdedField);
    holderSchema.setFields(fields);
    String schemaString = holderSchema.toString();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(schemaString);
    ArrayNode fieldsNode = (ArrayNode) node.get(FIELDS);
    JsonNode fieldNode = fieldsNode.get(fields.size() - 1);
    JsonNode typeNode = fieldNode.get(TYPE);
    if (pretty) {
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(typeNode);
    } else {
        return mapper.writeValueAsString(typeNode);
    }
}
Example 82
Project: hadoop-master  File: JobHistoryEventHandler.java View source code
@Private
public JsonNode countersToJSON(Counters counters) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode nodes = mapper.createArrayNode();
    if (counters != null) {
        for (CounterGroup counterGroup : counters) {
            ObjectNode groupNode = nodes.addObject();
            groupNode.put("NAME", counterGroup.getName());
            groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
            ArrayNode countersNode = groupNode.putArray("COUNTERS");
            for (Counter counter : counterGroup) {
                ObjectNode counterNode = countersNode.addObject();
                counterNode.put("NAME", counter.getName());
                counterNode.put("DISPLAY_NAME", counter.getDisplayName());
                counterNode.put("VALUE", counter.getValue());
            }
        }
    }
    return nodes;
}
Example 83
Project: hadoop-release-2.6.0-master  File: JobHistoryEventHandler.java View source code
@Private
public JsonNode countersToJSON(Counters counters) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode nodes = mapper.createArrayNode();
    if (counters != null) {
        for (CounterGroup counterGroup : counters) {
            ObjectNode groupNode = nodes.addObject();
            groupNode.put("NAME", counterGroup.getName());
            groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
            ArrayNode countersNode = groupNode.putArray("COUNTERS");
            for (Counter counter : counterGroup) {
                ObjectNode counterNode = countersNode.addObject();
                counterNode.put("NAME", counter.getName());
                counterNode.put("DISPLAY_NAME", counter.getDisplayName());
                counterNode.put("VALUE", counter.getValue());
            }
        }
    }
    return nodes;
}
Example 84
Project: hops-master  File: JobHistoryEventHandler.java View source code
@Private
public JsonNode countersToJSON(Counters counters) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode nodes = mapper.createArrayNode();
    if (counters != null) {
        for (CounterGroup counterGroup : counters) {
            ObjectNode groupNode = nodes.addObject();
            groupNode.put("NAME", counterGroup.getName());
            groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName());
            ArrayNode countersNode = groupNode.putArray("COUNTERS");
            for (Counter counter : counterGroup) {
                ObjectNode counterNode = countersNode.addObject();
                counterNode.put("NAME", counter.getName());
                counterNode.put("DISPLAY_NAME", counter.getDisplayName());
                counterNode.put("VALUE", counter.getValue());
            }
        }
    }
    return nodes;
}
Example 85
Project: schema-registry-master  File: AvroData.java View source code
// Convert default values from Connect data format to Avro's format, which is an
// org.codehaus.jackson.JsonNode. The default value is provided as an argument because even
// though you can get a default value from the schema, default values for complex structures need
// to perform the same translation but those defaults will be part of the original top-level
// (complex type) default value, not part of the child schema.
private static JsonNode defaultValueFromConnect(Schema schema, Object defaultVal) {
    try {
        switch(schema.type()) {
            case INT8:
                return JsonNodeFactory.instance.numberNode((Byte) defaultVal);
            case INT16:
                return JsonNodeFactory.instance.numberNode((Short) defaultVal);
            case INT32:
                return JsonNodeFactory.instance.numberNode((Integer) defaultVal);
            case INT64:
                return JsonNodeFactory.instance.numberNode((Long) defaultVal);
            case FLOAT32:
                return JsonNodeFactory.instance.numberNode((Float) defaultVal);
            case FLOAT64:
                return JsonNodeFactory.instance.numberNode((Double) defaultVal);
            case BOOLEAN:
                return JsonNodeFactory.instance.booleanNode((Boolean) defaultVal);
            case STRING:
                return JsonNodeFactory.instance.textNode((String) defaultVal);
            case BYTES:
                if (defaultVal instanceof byte[]) {
                    return JsonNodeFactory.instance.binaryNode((byte[]) defaultVal);
                } else {
                    return JsonNodeFactory.instance.binaryNode(((ByteBuffer) defaultVal).array());
                }
            case ARRAY:
                {
                    ArrayNode array = JsonNodeFactory.instance.arrayNode();
                    for (Object elem : (List<Object>) defaultVal) {
                        array.add(defaultValueFromConnect(schema.valueSchema(), elem));
                    }
                    return array;
                }
            case MAP:
                if (schema.keySchema().type() == Schema.Type.STRING && !schema.keySchema().isOptional()) {
                    ObjectNode node = JsonNodeFactory.instance.objectNode();
                    for (Map.Entry<String, Object> entry : ((Map<String, Object>) defaultVal).entrySet()) {
                        JsonNode entryDef = defaultValueFromConnect(schema.valueSchema(), entry.getValue());
                        node.put(entry.getKey(), entryDef);
                    }
                    return node;
                } else {
                    ArrayNode array = JsonNodeFactory.instance.arrayNode();
                    for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) defaultVal).entrySet()) {
                        JsonNode keyDefault = defaultValueFromConnect(schema.keySchema(), entry.getKey());
                        JsonNode valDefault = defaultValueFromConnect(schema.valueSchema(), entry.getValue());
                        ArrayNode jsonEntry = JsonNodeFactory.instance.arrayNode();
                        jsonEntry.add(keyDefault);
                        jsonEntry.add(valDefault);
                        array.add(jsonEntry);
                    }
                    return array;
                }
            case STRUCT:
                {
                    ObjectNode node = JsonNodeFactory.instance.objectNode();
                    Struct struct = ((Struct) defaultVal);
                    for (Field field : (schema.fields())) {
                        JsonNode fieldDef = defaultValueFromConnect(field.schema(), struct.get(field));
                        node.put(field.name(), fieldDef);
                    }
                    return node;
                }
            default:
                throw new DataException("Unknown schema type:" + schema.type());
        }
    } catch (ClassCastException e) {
        throw new DataException("Invalid type used for default value of " + schema.type() + " field: " + schema.defaultValue().getClass());
    }
}