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

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

Example 1
Project: apiman-master  File: DataMigrator.java View source code
/**
     * @see io.apiman.manager.api.migrator.IReaderHandler#onMetaData(com.fasterxml.jackson.databind.node.ObjectNode)
     */
@Override
public void onMetaData(ObjectNode node) throws IOException {
    //$NON-NLS-1$
    String fromVersion = node.get("apimanVersion").asText();
    String toVersion = this.getVersion().getVersionString();
    chain = VersionMigrators.chain(fromVersion, toVersion);
    if (chain.hasMigrators()) {
        //$NON-NLS-1$
        logger.info(Messages.i18n.format("DataMigrator.MigratingNow", fromVersion));
        chain.migrateMetaData(node);
        //$NON-NLS-1$
        node.put("apimanVersion", toVersion);
    }
    writer.writeMetaData(node);
}
Example 2
Project: droidtowers-master  File: Migration_GameSave_UnhappyrobotToDroidTowers.java View source code
@Override
protected void process(ObjectNode node, String fileName) {
    ObjectNode gameSaveNode = getGameSaveUnlessFileFormatIsNewer(node, "com.unhappyrobot.gamestate.GameSave", 1);
    if (gameSaveNode == null) {
        return;
    }
    ArrayNode gridObjects = gameSaveNode.withArray("gridObjects");
    for (JsonNode gridObjectNode : gridObjects) {
        ObjectNode gridObject = (ObjectNode) gridObjectNode;
        if (gridObject == null) {
            throw new RuntimeException("Error converting: " + gridObject);
        } else if (!gridObject.has("typeId")) {
            String typeName = gridObject.get("typeName").asText();
            String typeId = transformTypeNameToTypeId(typeName);
            gridObject.put("typeId", typeId);
            gridObject.remove("typeClass");
            gridObject.remove("typeName");
        }
    }
    gameSaveNode.remove("objectCounts");
    gameSaveNode.put("gridObjects", gridObjects);
    node.removeAll();
    if (!gameSaveNode.has("baseFilename")) {
        gameSaveNode.put("baseFilename", fileName);
    }
    if (!gameSaveNode.has("towerName")) {
        gameSaveNode.put("towerName", "Untitled Tower");
    }
    gameSaveNode.put("fileFormat", 2);
    node.put("GameSave", gameSaveNode);
}
Example 3
Project: playconf-master  File: RandomlySelectedTalkEvent.java View source code
@Override
public JsonNode json() {
    ObjectNode result = Json.newObject();
    result.put("messageType", "proposalSubmission");
    result.put("title", proposal.title);
    result.put("proposal", proposal.proposal);
    result.put("name", proposal.speaker.name);
    result.put("pictureUrl", proposal.speaker.pictureUrl);
    result.put("twitterId", proposal.speaker.twitterId);
    return result;
}
Example 4
Project: cloudbreak-master  File: AmbariClustersHostsResponse.java View source code
@Override
public Object handle(Request request, Response response) throws Exception {
    response.type("text/plain");
    ObjectNode rootNode = JsonNodeFactory.instance.objectNode();
    ArrayNode items = rootNode.putArray("items");
    for (String instanceId : instanceMap.keySet()) {
        CloudVmMetaDataStatus status = instanceMap.get(instanceId);
        if (InstanceStatus.STARTED == status.getCloudVmInstanceStatus().getStatus()) {
            ObjectNode item = items.addObject();
            item.putObject("Hosts").put("host_name", HostNameUtil.generateHostNameByIp(status.getMetaData().getPrivateIp()));
            ArrayNode components = item.putArray("host_components");
            components.addObject().putObject("HostRoles").put("component_name", "DATANODE").put("state", state);
            components.addObject().putObject("HostRoles").put("component_name", "NODEMANAGER").put("state", state);
        }
    }
    return rootNode;
}
Example 5
Project: Leads-QueryProcessorM-master  File: ObjectNodeTest.java View source code
public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        SQLQuery query = new SQLQuery("user", "location", "select * from atable", "SELECT");
        String val = mapper.writeValueAsString(query);
        JsonNode root = mapper.readTree(val);
        ((ObjectNode) root).put("state", String.valueOf(QueryState.COMPLETED));
        System.out.println("node: " + root.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 6
Project: open-data-service-master  File: IntToStringKeyFilterTest.java View source code
@Test
public void testObjectParentNode() throws Exception {
    DataSource source = createDataSource("/parent/id");
    ObjectNode baseNode = new ObjectNode(JsonNodeFactory.instance);
    ObjectNode parentNode = baseNode.putObject("parent");
    parentNode.put("id", 10);
    ObjectNode resultNode = new IntToStringKeyFilter(source, registry).doFilter(baseNode);
    Assert.assertTrue(resultNode.path("parent").path("id").isTextual());
}
Example 7
Project: storm-data-contracts-master  File: ObjectConverterTest.java View source code
@Test
public void testJsonNodeToObjectMissingOptionalValue() throws IOException {
    ObjectNode node = (ObjectNode) mapper.readTree("{\"x\":\"-1\"}");
    ContractFactory<MockInput> factory = new ContractFactory(MockInput.class);
    MockInput input = ContractConverter.instance().convertObjectNodeToContract(node, factory);
    assertThat(input.x).isEqualTo(-1);
    assertThat(input.y.isPresent()).isFalse();
}
Example 8
Project: 101simplejava-master  File: Cut.java View source code
/**
	 * Divide all double-properties of the JsonNode node with the name "salary"
	 * by 2
	 * 
	 * @param node
	 */
public static void cut(JsonNode node) {
    if (node.has("departments")) {
        Iterator<JsonNode> iterator = node.get("departments").elements();
        while (iterator.hasNext()) {
            cut(iterator.next());
        }
    }
    if (node.has("employees")) {
        Iterator<JsonNode> iterator = node.get("employees").elements();
        while (iterator.hasNext()) {
            cutEmployee((ObjectNode) iterator.next());
        }
    }
    if (node.has("manager")) {
        cutEmployee((ObjectNode) node.get("manager"));
    }
}
Example 9
Project: amos-ss15-proj2-master  File: PlacesManager.java View source code
public List<Place> getNearbyPlaces(Map<String, String> queryMap, int maxResults) {
    ObjectNode jsonResult = placesApi.getNearybyPlaces(queryMap);
    JsonNode jsonPlaces = jsonResult.path("results");
    int count = 0;
    List<Place> places = new ArrayList<>();
    for (JsonNode jsonPlace : jsonPlaces) {
        if (count >= maxResults)
            break;
        ++count;
        JsonNode jsonLocation = jsonPlace.path("geometry").path("location");
        Place place = new Place(jsonPlace.path("name").asText(), new RouteLocation(jsonLocation.path("lat").asDouble(), jsonLocation.path("lng").asDouble()));
        places.add(place);
    }
    return places;
}
Example 10
Project: bootique-master  File: PathSegment.java View source code
void fillMissingNodes(String field, JsonNode child, JsonNodeFactory nodeFactory) {
    if (node == null) {
        node = new ObjectNode(nodeFactory);
        parent.fillMissingNodes(incomingPath, node, nodeFactory);
    }
    if (child != null) {
        if (node instanceof ObjectNode) {
            ((ObjectNode) node).set(field, child);
        } else {
            throw new IllegalArgumentException("Node '" + incomingPath + "' is unexpected in the middle of the path");
        }
    }
}
Example 11
Project: docker-java-master  File: AbstrDockerCmdExec.java View source code
protected String registryConfigs(AuthConfigurations authConfigs) {
    try {
        final String json;
        final ObjectMapper objectMapper = new ObjectMapper();
        final RemoteApiVersion apiVersion = dockerClientConfig.getApiVersion();
        if (apiVersion.equals(UNKNOWN_VERSION)) {
            // all registries
            ObjectNode rootNode = objectMapper.valueToTree(authConfigs.getConfigs());
            // wrapped in "configs":{}
            final ObjectNode authNodes = objectMapper.valueToTree(authConfigs);
            // merge 2 variants
            rootNode.setAll(authNodes);
            json = rootNode.toString();
        } else if (apiVersion.isGreaterOrEqual(VERSION_1_19)) {
            json = objectMapper.writeValueAsString(authConfigs.getConfigs());
        } else {
            json = objectMapper.writeValueAsString(authConfigs);
        }
        return Base64.encodeBase64String(json.getBytes());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 12
Project: eve-java-master  File: ZmqTransportBuilder.java View source code
/**
		 * Gets the ZMQ transport.
		 * 
		 * @param <T>
		 *            the generic type
		 * @param <V>
		 *            the value type
		 * @param params
		 *            the params
		 * @param handle
		 *            the handle
		 * @return the zmq transport
		 */
public <T extends Capability, V> ZmqTransport get(final ObjectNode params, final Handler<V> handle) {
    final Handler<Receiver> newHandle = Transport.TYPEUTIL.inject(handle);
    final ZmqTransportConfig config = ZmqTransportConfig.decorate(params);
    final URI address = config.getAddress();
    ZmqTransport result = instances.get(address);
    if (result == null) {
        result = new ZmqTransport(config, newHandle, this);
        instances.put(address, result);
    } else {
        result.getHandle().update(newHandle);
    }
    return result;
}
Example 13
Project: json-schema-validator-demo-master  File: AvroProcessing.java View source code
@Override
protected JsonNode buildResult(final String input) throws IOException, ProcessingException {
    final ObjectNode ret = FACTORY.objectNode();
    final boolean invalidSchema = fillWithData(ret, INPUT, INVALID_INPUT, input);
    final JsonNode schemaNode = ret.remove(INPUT);
    if (invalidSchema)
        return ret;
    final JsonTree tree = new SimpleJsonTree(schemaNode);
    final ValueHolder<JsonTree> holder = ValueHolder.hold(tree);
    final ProcessingReport report = new ListProcessingReport();
    final ProcessingResult<ValueHolder<SchemaTree>> result = ProcessingResult.uncheckedResult(PROCESSOR, report, holder);
    final boolean success = result.isSuccess();
    final JsonNode content = success ? result.getResult().getValue().getBaseNode() : buildReport(result.getReport());
    ret.put(VALID, success);
    ret.put(RESULTS, JacksonUtils.prettyPrint(content));
    return ret;
}
Example 14
Project: oj_web-master  File: AuthAction.java View source code
public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    String username = session("user");
    if (username == null) {
        if (configuration.json()) {
            ObjectNode out = Json.newObject();
            out.put("status", 1234);
            out.put("message", "Not log in");
            return F.Promise.pure(ok(out));
        } else {
            return F.Promise.promise(() -> redirect(routes.UserController.loginPage()));
        }
    } else {
        User user = User.find.where().eq("name", username).findUnique();
        if (user == null || user.adminLevel < configuration.admin()) {
            if (configuration.json()) {
                ObjectNode out = Json.newObject();
                out.put("status", 2345);
                out.put("message", "Member not found");
                return F.Promise.pure(ok(out));
            } else {
                return F.Promise.promise(() -> redirect(routes.UserController.logoutRedirect()));
            }
        }
        Logger.debug("Setting user in ctx.");
        ctx.args.put("user", user);
        return delegate.call(ctx);
    }
}
Example 15
Project: sphere-snowflake-master  File: ListAddress.java View source code
public static ObjectNode getJson(Address address) {
    ObjectNode json = Json.newObject();
    if (address == null)
        return json;
    json.put("addressId", address.getId());
    json.put("company", address.getCompany());
    json.put("firstName", address.getFirstName());
    json.put("lastName", address.getLastName());
    json.put("email", address.getEmail());
    json.put("phone", address.getPhone());
    json.put("mobile", address.getMobile());
    json.put("street", address.getStreetName());
    json.put("street2", address.getStreetNumber());
    json.put("postalCode", address.getPostalCode());
    json.put("city", address.getCity());
    json.put("country", address.getCountry().getAlpha2());
    json.put("countryName", address.getCountry().getName());
    return json;
}
Example 16
Project: spring-security-oauth-master  File: FacebookController.java View source code
@RequestMapping("/facebook/info")
public String photos(Model model) throws Exception {
    ObjectNode result = facebookRestTemplate.getForObject("https://graph.facebook.com/me/friends", ObjectNode.class);
    ArrayNode data = (ArrayNode) result.get("data");
    ArrayList<String> friends = new ArrayList<String>();
    for (JsonNode dataNode : data) {
        friends.add(dataNode.get("name").asText());
    }
    model.addAttribute("friends", friends);
    return "facebook";
}
Example 17
Project: threatconnect-java-master  File: CustomIndicatorListResponseDataDeserializer.java View source code
@Override
public CustomIndicatorListResponseData deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    CustomIndicatorListResponseData result = new CustomIndicatorListResponseData();
    ObjectCodec oc = p.getCodec();
    ObjectNode rootNode = oc.readTree(p);
    Iterator<String> keys = rootNode.fieldNames();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        //ignore "resultCount"
        if ("resultCount".compareTo(key) != 0) {
            JsonNode value = rootNode.get(key);
            List<CustomIndicator> indicators = mapper.reader(collectionType).readValue(value);
            for (CustomIndicator indicator : indicators) {
                //indicator.setType(key);
                indicator.setIndicatorType(key);
            }
            result.setCustomIndicator(indicators);
        }
    }
    return result;
}
Example 18
Project: verjson-master  File: Example2Transformation.java View source code
@Override
protected void transform(JsonNode node) {
    ObjectNode obj = obj(node);
    // remove first
    remove(obj, "first");
    // rename second
    rename(obj, "second", "segundo");
    // keep third and fourth
    // convert fifth
    ArrayNode fifth = getArrayAndRemove(obj, "fifth");
    if (fifth != null) {
        StringBuilder builder = new StringBuilder();
        for (JsonNode elem : fifth) {
            builder.append(elem.asText());
        }
        obj.put("fifth", builder.toString());
    }
    // convert sixth
    ObjectNode sixth = getObjAndRemove(obj, "sixth");
    rename(sixth, "one", "uno");
    remove(sixth, "two");
    // rename SubB
    rename(obj(obj.get("subB")), "bbb", "ccc");
    obj.set("sixth", createArray(sixth));
}
Example 19
Project: Activiti-master  File: SecureJavascriptTaskActivityBehavior.java View source code
@Override
public void execute(ActivityExecution execution) throws Exception {
    ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl) execution.getEngineServices().getProcessEngineConfiguration();
    if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
        ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(scriptTaskId, execution.getProcessDefinitionId());
        if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT)) {
            String overrideScript = taskElementProperties.get(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT).asText();
            if (StringUtils.isNotEmpty(overrideScript) && overrideScript.equals(script) == false) {
                script = overrideScript;
            }
        }
    }
    boolean noErrors = true;
    try {
        Object result = SecureJavascriptUtil.evaluateScript(execution, script, config.getBeans());
        if (resultVariable != null) {
            execution.setVariable(resultVariable, result);
        }
    } catch (ActivitiException e) {
        LOGGER.warn("Exception while executing " + execution.getActivity().getId() + " : " + e.getMessage());
        noErrors = false;
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof BpmnError) {
            ErrorPropagation.propagateError((BpmnError) rootCause, execution);
        } else {
            throw e;
        }
    }
    if (noErrors) {
        leave(execution);
    }
}
Example 20
Project: alien4cloud-master  File: TaskDeserializer.java View source code
@Override
protected AbstractTask deserializeAfterRead(JsonParser jp, DeserializationContext ctxt, ObjectMapper mapper, ObjectNode root) throws JsonProcessingException {
    AbstractTask result = super.deserializeAfterRead(jp, ctxt, mapper, root);
    if (result == null) {
        Map data = mapper.treeToValue(root, Map.class);
        if (data.containsKey("nodeTemplateName")) {
            result = mapper.treeToValue(root, TopologyTask.class);
        } else {
            failedToFindImplementation(jp, root);
        }
    }
    return result;
}
Example 21
Project: baasbox-master  File: JsonTree.java View source code
public static JsonNode write(JsonNode json, PartsParser pp, JsonNode data) throws MissingNodeException {
    JsonNode root = json;
    for (Part p : pp.parts()) {
        if (p.equals(pp.last())) {
            break;
        }
        if (p instanceof PartsLexer.ArrayField) {
            int index = ((PartsLexer.ArrayField) p).arrayIndex;
            root = root.path(p.getName()).path(index);
        } else if (p instanceof PartsLexer.Field) {
            root = root.path(p.getName());
        }
    }
    if (root.isMissingNode()) {
        throw new MissingNodeException(pp.treeFields());
    }
    Part last = pp.last();
    if (last instanceof PartsLexer.ArrayField) {
        PartsLexer.ArrayField arr = (PartsLexer.ArrayField) last;
        int index = arr.arrayIndex;
        root = root.path(last.getName());
        ArrayNode arrNode = (ArrayNode) root;
        if (arrNode.size() <= index) {
            arrNode.add(data);
        } else {
            arrNode.set(index, data);
        }
        return root;
    } else {
        try {
            ((ObjectNode) root).put(last.getName(), data);
        } catch (Exception e) {
            throw new MissingNodeException(pp.treeFields());
        }
        return root.get(last.getName());
    }
}
Example 22
Project: Baragon-master  File: MergingConfigProvider.java View source code
@Override
public InputStream open(String path) throws IOException {
    JsonNode originalNode = readFromPath(defaultConfigPath);
    JsonNode overrideNode = readFromPath(path);
    if (originalNode.isObject() && overrideNode.isObject()) {
        ObjectNode original = (ObjectNode) originalNode;
        ObjectNode override = (ObjectNode) overrideNode;
        merge(original, override);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        objectMapper.writeTree(yamlFactory.createGenerator(outputStream), original);
        return new ByteArrayInputStream(outputStream.toByteArray());
    } else {
        throw new IllegalArgumentException("Both configuration files must be objects");
    }
}
Example 23
Project: celos-master  File: OozieExternalServiceTest.java View source code
@Test
public void runPropertiesAreCorrectlySetup() {
    ScheduledTime t = new ScheduledTime("2013-11-26T17:23Z");
    SlotID id = new SlotID(new WorkflowID("test"), t);
    ObjectNode defaults = Util.newObjectNode();
    defaults.put("foo", "bar");
    defaults.put("uses-variables", "${year}-${month}-${day}-${hour}-${year}");
    defaults.put("another-one", "${year}-${month}-${day}T${hour}:${minute}:${second}.${millisecond}Z");
    Properties runProperties = makeOozieExternalService().setupRunProperties(defaults, id);
    Assert.assertEquals("bar", runProperties.getProperty("foo"));
    Assert.assertEquals("2013-11-26-17-2013", runProperties.getProperty("uses-variables"));
    Assert.assertEquals("2013-11-26T17:23:00.000Z", runProperties.getProperty("another-one"));
    Assert.assertEquals("2013", runProperties.getProperty(OozieExternalService.YEAR_PROP));
    Assert.assertEquals("11", runProperties.getProperty(OozieExternalService.MONTH_PROP));
    Assert.assertEquals("26", runProperties.getProperty(OozieExternalService.DAY_PROP));
    Assert.assertEquals("17", runProperties.getProperty(OozieExternalService.HOUR_PROP));
    Assert.assertEquals("23", runProperties.getProperty(OozieExternalService.MINUTE_PROP));
    Assert.assertEquals("00", runProperties.getProperty(OozieExternalService.SECOND_PROP));
    Assert.assertEquals("test@2013-11-26T17:23Z", runProperties.getProperty(OozieExternalService.WORKFLOW_NAME_PROP));
}
Example 24
Project: cf-java-component-master  File: VarzHandlerMapping.java View source code
@Override
public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
        if (authenticator.authenticate(httpServletRequest, httpServletResponse)) {
            httpServletResponse.setContentType("application/json;charset=utf-8");
            final ObjectNode varz = aggregator.aggregateVarz();
            mapper.writeValue(httpServletResponse.getOutputStream(), varz);
        }
    } else {
        httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }
}
Example 25
Project: degraphmalizer-master  File: DegraphmalizeResultEncoder.java View source code
@Override
protected final Object encode(ChannelHandlerContext ctx, Channel channel, Object o) {
    final Class oc = o.getClass();
    for (Class c : acceptedMessages) if (c.isAssignableFrom(oc)) {
        //                    final JsonNode n = objectMapper.valueToTree(o);
        //                    final HttpResponse r = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK);
        //                    r.setContent(ChannelBuffers.copiedBuffer(n.toString(), Charsets.UTF_8));
        //                    return r;
        final ObjectNode n = objectMapper.createObjectNode();
        n.put("type", c.getSimpleName());
        final HttpResponse r = new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK);
        r.setContent(ChannelBuffers.copiedBuffer(n.toString(), Charsets.UTF_8));
        return r;
    }
    // otherwise pass it on
    return o;
}
Example 26
Project: demoapps-master  File: ManagementAgent.java View source code
/**
	 * Inits the Conference Cloud Agent.
	 */
public void init() {
    final String id = "management";
    final AgentConfig config = new AgentConfig(id);
    final WebsocketTransportConfig serverConfig = new WebsocketTransportConfig();
    serverConfig.setServer(true);
    serverConfig.setAddress("ws://10.10.1.180:8082/ws/" + id);
    serverConfig.setServletLauncher("JettyLauncher");
    final ObjectNode jettyParms = JOM.createObjectNode();
    jettyParms.put("port", 8082);
    serverConfig.set("jetty", jettyParms);
    config.setTransport(serverConfig);
    setConfig(config);
}
Example 27
Project: emfjson-mongo-master  File: MongoOutputStream.java View source code
private String toJson(Resource resource) throws JsonProcessingException {
    final ObjectMapper mapper = new ObjectMapper();
    final JacksonOptions jacksonOptions = JacksonOptions.from(options);
    mapper.registerModule(new EMFModule(resource.getResourceSet(), jacksonOptions));
    final JsonNode contents = mapper.valueToTree(resource);
    final ObjectNode resourceNode = mapper.createObjectNode();
    final String id = uri.segment(2);
    resourceNode.put(MongoHandler.ID_FIELD, id);
    resourceNode.put(MongoHandler.TYPE_FIELD, "resource");
    resourceNode.set(MongoHandler.CONTENTS_FIELD, contents);
    return mapper.writeValueAsString(resourceNode);
}
Example 28
Project: emfjson-samples-master  File: Example2.java View source code
public static void main(String[] args) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    // Register EMFModule to handle EObject and Resource types.
    // Set as option the type of the object we want to read
    JacksonOptions options = new JacksonOptions.Builder().withRoot(ModelPackage.Literals.USER).build();
    mapper.registerModule(new EMFModule(new ResourceSetImpl(), options));
    // First we create a JSON object using Jackson API
    final ObjectNode objectNode = mapper.createObjectNode();
    objectNode.put("name", "John Doe");
    String stringNode = mapper.writeValueAsString(objectNode);
    System.out.println(stringNode);
    // Convert object node to an EObject.
    User user = (User) mapper.readValue(stringNode, EObject.class);
    // We add more information about the user
    user.setBirthDate(new DateTime(1975, 10, 5, 12, 0, 0, 0).toDate());
    Address address = ModelFactory.eINSTANCE.createAddress();
    address.setCity("Paris");
    address.setCountry("France");
    address.setNumber(12);
    address.setStreet("Montmartre");
    user.getAddresses().add(address);
    // Write it back into a JSON Object
    System.out.println(mapper.writeValueAsString(user));
}
Example 29
Project: evrythng-java-sdk-master  File: TypeMapDeserializer.java View source code
@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    ObjectCodec codec = jp.getCodec();
    ObjectMapper mapper = (ObjectMapper) codec;
    ObjectNode root = mapper.readTree(jp);
    JsonNode type = root.get(typeFieldName);
    final String sType = type == null ? null : type.textValue();
    Class<? extends T> clazz = resolveClass(sType);
    return codec.treeToValue(root, clazz);
}
Example 30
Project: flink-master  File: JSONKeyValueDeserializationSchemaTest.java View source code
@Test
public void testDeserializeWithoutMetadata() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode initialKey = mapper.createObjectNode();
    initialKey.put("index", 4);
    byte[] serializedKey = mapper.writeValueAsBytes(initialKey);
    ObjectNode initialValue = mapper.createObjectNode();
    initialValue.put("word", "world");
    byte[] serializedValue = mapper.writeValueAsBytes(initialValue);
    JSONKeyValueDeserializationSchema schema = new JSONKeyValueDeserializationSchema(false);
    ObjectNode deserializedValue = schema.deserialize(serializedKey, serializedValue, "", 0, 0);
    Assert.assertTrue(deserializedValue.get("metadata") == null);
    Assert.assertEquals(4, deserializedValue.get("key").get("index").asInt());
    Assert.assertEquals("world", deserializedValue.get("value").get("word").asText());
}
Example 31
Project: htwplus-master  File: JsonService.java View source code
/**
     * Returns an ObjectNode instance from a map.
     *
     * @param map Map instance
     * @return ObjectNode instance
     */
public ObjectNode getObjectNodeFromMap(Map<String, Object> map) {
    ObjectNode node = Json.newObject();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        Object value = entry.getValue();
        if (value.getClass().equals(String.class)) {
            node.put(entry.getKey(), (String) value);
        } else if (value.getClass().equals(Integer.class)) {
            node.put(entry.getKey(), (Integer) value);
        } else if (value.getClass().equals(Long.class)) {
            node.put(entry.getKey(), (Long) value);
        } else if (value.getClass().equals(Date.class)) {
            node.put(entry.getKey(), ((Date) value).getTime());
        } else {
            node.put(entry.getKey(), value.toString());
        }
    }
    return node;
}
Example 32
Project: iiif-presentation-api-master  File: PropertyValueDeserializer.java View source code
@Override
public PropertyValue deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    TreeNode node = mapper.readTree(jp);
    if (TextNode.class.isAssignableFrom(node.getClass())) {
        return new PropertyValueSimpleImpl(((TextNode) node).textValue());
    } else if (ObjectNode.class.isAssignableFrom(node.getClass())) {
        ObjectNode obj = (ObjectNode) node;
        String language = ((TextNode) node.get("@language")).textValue();
        String value = ((TextNode) node.get("@value")).textValue();
        return new PropertyValueLocalizedImpl(Locale.forLanguageTag(language), value);
    } else if (ArrayNode.class.isAssignableFrom(node.getClass())) {
        ArrayNode arr = (ArrayNode) node;
        ObjectNode curObj;
        PropertyValueLocalizedImpl propVal = new PropertyValueLocalizedImpl();
        for (int i = 0; i < arr.size(); i++) {
            if (ObjectNode.class.isAssignableFrom(arr.get(i).getClass())) {
                curObj = (ObjectNode) arr.get(i);
                propVal.addValue(((TextNode) curObj.get("@language")).textValue(), ((TextNode) curObj.get("@value")).textValue());
            } else if (TextNode.class.isAssignableFrom(arr.get(i).getClass())) {
                propVal.addValue("", ((TextNode) arr.get(i)).asText());
            }
        }
        return propVal;
    }
    return null;
}
Example 33
Project: incubator-streams-master  File: SchemaUtil.java View source code
/**
   * merge parent and child properties maps.
   * @param content ObjectNode
   * @param parent ObjectNode
   * @return merged ObjectNode
   */
public static ObjectNode mergeProperties(ObjectNode content, ObjectNode parent) {
    ObjectNode merged = parent.deepCopy();
    Iterator<Map.Entry<String, JsonNode>> fields = content.fields();
    for (; fields.hasNext(); ) {
        Map.Entry<String, JsonNode> field = fields.next();
        String fieldId = field.getKey();
        merged.put(fieldId, field.getValue().deepCopy());
    }
    return merged;
}
Example 34
Project: jackson-databind-master  File: NullSerializationTest.java View source code
// #281
public void testCustomNullForTrees() throws Exception {
    ObjectNode root = MAPPER.createObjectNode();
    root.putNull("a");
    // by default, null is... well, null
    assertEquals("{\"a\":null}", MAPPER.writeValueAsString(root));
    // but then we can customize it:
    DefaultSerializerProvider prov = new MyNullProvider();
    prov.setNullValueSerializer(new NullSerializer());
    ObjectMapper m = new ObjectMapper();
    m.setSerializerProvider(prov);
    assertEquals("{\"a\":\"foobar\"}", m.writeValueAsString(root));
}
Example 35
Project: jackson-datatype-protobuf-master  File: FailOnUnknownPropertiesTest.java View source code
@Test
public void testAdvancesParser() throws JsonProcessingException {
    AllFields message = ProtobufCreator.create(AllFields.class);
    ObjectNode tree = (ObjectNode) toTree(camelCase(), message);
    addObject(tree);
    addArray(tree);
    AllFields parsed = objectMapper(false).treeToValue(tree, AllFields.class);
    assertThat(parsed).isEqualTo(message);
}
Example 36
Project: json-data-generator-master  File: JsonUtils.java View source code
public void flattenJsonIntoMap(String currentPath, JsonNode jsonNode, Map<String, Object> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            flattenJsonIntoMap(pathPrefix + entry.getKey(), entry.getValue(), map);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            flattenJsonIntoMap(currentPath + "[" + i + "]", arrayNode.get(i), map);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        Object value = null;
        if (valueNode.isNumber()) {
            value = valueNode.numberValue();
        } else if (valueNode.isBoolean()) {
            value = valueNode.asBoolean();
        } else if (valueNode.isTextual()) {
            value = valueNode.asText();
        }
        map.put(currentPath, value);
    }
}
Example 37
Project: json-schema-avro-master  File: TypeUnionWriter.java View source code
private static List<ValueHolder<SchemaTree>> expand(final JsonNode node) {
    final ObjectNode common = node.deepCopy();
    final ArrayNode typeNode = (ArrayNode) common.remove("type");
    final List<ValueHolder<SchemaTree>> ret = Lists.newArrayList();
    ObjectNode schema;
    SchemaTree tree;
    for (final JsonNode element : typeNode) {
        schema = common.deepCopy();
        schema.put("type", element);
        tree = new CanonicalSchemaTree(schema);
        ret.add(ValueHolder.hold("schema", tree));
    }
    return ret;
}
Example 38
Project: json-schema-validation-master  File: AnyOfValidatorTest.java View source code
@Override
protected void checkKoKo(final ProcessingReport report) throws ProcessingException {
    final ArgumentCaptor<ProcessingMessage> captor = ArgumentCaptor.forClass(ProcessingMessage.class);
    verify(report).error(captor.capture());
    final ProcessingMessage message = captor.getValue();
    final ObjectNode reports = FACTORY.objectNode();
    final ArrayNode oneReport = FACTORY.arrayNode();
    oneReport.add(MSG.asJson());
    reports.put(ptr1.toString(), oneReport);
    reports.put(ptr2.toString(), oneReport);
    assertMessage(message).isValidationError(keyword, BUNDLE.printf("err.common.schema.noMatch", 2)).hasField("reports", reports);
}
Example 39
Project: json-schema-validator-master  File: AnyOfValidatorTest.java View source code
@Override
protected void checkKoKo(final ProcessingReport report) throws ProcessingException {
    final ArgumentCaptor<ProcessingMessage> captor = ArgumentCaptor.forClass(ProcessingMessage.class);
    verify(report).error(captor.capture());
    final ProcessingMessage message = captor.getValue();
    final ObjectNode reports = FACTORY.objectNode();
    final ArrayNode oneReport = FACTORY.arrayNode();
    oneReport.add(MSG.asJson());
    reports.put(ptr1.toString(), oneReport);
    reports.put(ptr2.toString(), oneReport);
    assertMessage(message).isValidationError(keyword, BUNDLE.printf("err.common.schema.noMatch", 2)).hasField("reports", reports);
}
Example 40
Project: juzu-master  File: JacksonRequestTreeTestCase.java View source code
@Override
public void testRequest() throws Exception {
    super.testRequest();
    ObjectNode node = assertInstanceOf(ObjectNode.class, payload);
    Iterator<String> fields = node.fieldNames();
    assertEquals("foo", fields.next());
    assertFalse(fields.hasNext());
    TextNode text = assertInstanceOf(TextNode.class, node.get("foo"));
    assertEquals("bar", text.textValue());
}
Example 41
Project: keycloak-master  File: RPTIntrospectionProvider.java View source code
@Override
public Response introspect(String token) {
    LOGGER.debug("Introspecting requesting party token");
    try {
        AccessToken requestingPartyToken = toAccessToken(token);
        boolean active = isActive(requestingPartyToken);
        ObjectNode tokenMetadata;
        if (active) {
            LOGGER.debug("Token is active");
            AccessToken introspect = new AccessToken();
            introspect.type(requestingPartyToken.getType());
            introspect.expiration(requestingPartyToken.getExpiration());
            introspect.issuedAt(requestingPartyToken.getIssuedAt());
            introspect.audience(requestingPartyToken.getAudience());
            introspect.notBefore(requestingPartyToken.getNotBefore());
            introspect.setRealmAccess(null);
            introspect.setResourceAccess(null);
            tokenMetadata = JsonSerialization.createObjectNode(introspect);
            tokenMetadata.putPOJO("permissions", requestingPartyToken.getAuthorization().getPermissions());
        } else {
            LOGGER.debug("Token is not active");
            tokenMetadata = JsonSerialization.createObjectNode();
        }
        tokenMetadata.put("active", active);
        return Response.ok(JsonSerialization.writeValueAsBytes(tokenMetadata)).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (Exception e) {
        throw new RuntimeException("Error creating token introspection response.", e);
    }
}
Example 42
Project: lightblue-client-master  File: DataUpdateRequest.java View source code
@Override
public JsonNode getBodyJson() {
    ObjectNode node = (ObjectNode) super.getBodyJson();
    if (projection != null) {
        node.set("projection", projection.toJson());
    }
    if (query != null) {
        node.set("query", query.toJson());
    }
    if (update != null) {
        node.set("update", update.toJson());
    }
    appendRangeToJson(node, begin, maxResults);
    appendUpdateIfCurrentToJson(node);
    return node;
}
Example 43
Project: lightblue-core-master  File: JsonNodeCursor.java View source code
@Override
protected KeyValueCursor<String, JsonNode> getCursor(JsonNode node) {
    if (node instanceof ArrayNode) {
        return new ArrayElementCursor(((ArrayNode) node).elements());
    } else if (node instanceof ObjectNode) {
        return new KeyValueCursorIteratorAdapter<>(((ObjectNode) node).fields());
    } else {
        throw new IllegalArgumentException(node.getClass().getName());
    }
}
Example 44
Project: lightblue-migrator-master  File: AbstractMigratorController.java View source code
/**
     * Work around method until a way to pass in security access level is found.
     */
protected ObjectNode grantAnyoneAccess(ObjectNode node) {
    ObjectNode schema = (ObjectNode) node.get("schema");
    ObjectNode access = (ObjectNode) schema.get("access");
    Iterator<JsonNode> children = access.iterator();
    while (children.hasNext()) {
        ArrayNode child = (ArrayNode) children.next();
        child.removeAll();
        child.add("anyone");
    }
    return node;
}
Example 45
Project: mdk-master  File: JsonPatchFunction.java View source code
private static void preProcess(JsonNode client, JsonNode server) {
    if (!(client instanceof ObjectNode) || !(server instanceof ObjectNode)) {
        return;
    }
    ObjectNode sourceObjectNode = (ObjectNode) client;
    ObjectNode targetObjectNode = (ObjectNode) server;
    Iterator<String> targetKeyIterator = targetObjectNode.fieldNames();
    while (targetKeyIterator.hasNext()) {
        String targetKey = targetKeyIterator.next();
        if (targetKey.startsWith(MDKConstants.DERIVED_KEY_PREFIX) && !sourceObjectNode.has(targetKey)) {
            targetKeyIterator.remove();
        }
    }
}
Example 46
Project: NemakiWare-master  File: Util.java View source code
public static ObjectNode convertToJackson(JsonObject gson) {
    String json = gson.toString();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jackson;
    try {
        jackson = mapper.readTree(json);
        return (ObjectNode) jackson;
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 47
Project: onos-master  File: InvalidConfigExceptionMapper.java View source code
@Override
protected Response.ResponseBuilder response(Response.Status status, Throwable exception) {
    error = exception;
    InvalidConfigException ex = (InvalidConfigException) exception;
    ObjectMapper mapper = new ObjectMapper();
    String message = messageFrom(exception);
    ObjectNode result = mapper.createObjectNode().put("code", status.getStatusCode()).put("message", message).put("subjectKey", ex.subjectKey()).put("subject", ex.subject()).put("configKey", ex.configKey());
    if (ex.getCause() instanceof InvalidFieldException) {
        InvalidFieldException fieldException = (InvalidFieldException) ex.getCause();
        result.put("field", fieldException.field()).put("reason", fieldException.reason());
    }
    return Response.status(status).entity(result.toString());
}
Example 48
Project: ratpack-master  File: ObjectConfigSource.java View source code
@Override
public ObjectNode loadConfigData(ObjectMapper mapper, FileSystemBinding fileSystemBinding) throws Exception {
    JsonNode value = mapper.valueToTree(object);
    ObjectNode root = mapper.createObjectNode();
    String[] keys = path.split("\\.");
    Iterator<String> iterator = Arrays.asList(keys).iterator();
    ObjectNode node = root;
    while (true) {
        String key = iterator.next();
        if (iterator.hasNext()) {
            node = node.putObject(key);
        } else {
            node.set(key, value);
            break;
        }
    }
    return root;
}
Example 49
Project: seldon-server-master  File: FeatureFilter.java View source code
@Override
public JsonNode transform(String client, JsonNode input, FeatureTransformerStrategy strategy) {
    String type = "inclusive";
    if (strategy.config.containsKey(featureFilterType))
        type = strategy.config.get(featureFilterType);
    switch(type) {
        case "inclusive":
            {
                Iterator<String> it = input.fieldNames();
                for (String fieldName; it.hasNext(); ) {
                    fieldName = it.next();
                    if (!strategy.inputCols.contains(fieldName)) {
                        it.remove();
                    }
                }
                return input;
            }
        case "exclusive":
            {
                Iterator<String> it = input.fieldNames();
                for (String fieldName; it.hasNext(); ) {
                    fieldName = it.next();
                    if (strategy.inputCols.contains(fieldName))
                        ((ObjectNode) input).remove(fieldName);
                }
                return input;
            }
        default:
            logger.warn("Unknown feature filter type " + type + " doing nothing");
            return input;
    }
}
Example 50
Project: Singularity-master  File: MergingSourceProvider.java View source code
@Override
public InputStream open(String path) throws IOException {
    final JsonNode originalNode = objectMapper.readTree(yamlFactory.createParser(delegate.open(defaultConfigurationPath)));
    final JsonNode overrideNode = objectMapper.readTree(yamlFactory.createParser(delegate.open(path)));
    if (!(originalNode instanceof ObjectNode && overrideNode instanceof ObjectNode)) {
        throw new SingularityConfigurationMergeException(String.format("Both %s and %s need to be YAML objects", defaultConfigurationPath, path));
    }
    merge((ObjectNode) originalNode, (ObjectNode) overrideNode);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    objectMapper.writeTree(yamlFactory.createGenerator(baos), originalNode);
    return new ByteArrayInputStream(baos.toByteArray());
}
Example 51
Project: Slipstream-Mod-Manager-master  File: JacksonCatalogWriter.java View source code
/**
	 * Writes collated catalog entries to a file, as condensed json.
	 */
public static void write(List<ModsInfo> modsInfoList, File dstFile) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();
    ObjectNode catalogsNode = rootNode.objectNode();
    rootNode.put("catalog_versions", catalogsNode);
    ArrayNode catalogNode = rootNode.arrayNode();
    catalogsNode.put("1", catalogNode);
    for (ModsInfo modsInfo : modsInfoList) {
        ObjectNode infoNode = rootNode.objectNode();
        catalogNode.add(infoNode);
        infoNode.put("title", modsInfo.getTitle());
        infoNode.put("author", modsInfo.getAuthor());
        infoNode.put("desc", modsInfo.getDescription());
        infoNode.put("url", modsInfo.getThreadURL());
        infoNode.put("thread_hash", modsInfo.threadHash);
        ArrayNode versionsNode = rootNode.arrayNode();
        infoNode.put("versions", versionsNode);
        for (Map.Entry<String, String> entry : modsInfo.getVersionsMap().entrySet()) {
            String versionFileHash = entry.getKey();
            String versionString = entry.getValue();
            ObjectNode versionNode = rootNode.objectNode();
            versionNode.put("hash", versionFileHash);
            versionNode.put("version", versionString);
            versionsNode.add(versionNode);
        }
    }
    OutputStream os = null;
    try {
        os = new FileOutputStream(dstFile);
        OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("US-ASCII"));
        mapper.writeValue(writer, rootNode);
    } finally {
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }
    }
}
Example 52
Project: Stage-master  File: SpanJsonModuleTest.java View source code
@Test
public void testNestDottedTagKeys() {
    final ReadbackSpan span = createTestSpan(1);
    span.setTag("a.b.c.d1", "1");
    span.setTag("a.b.c.d2", "2");
    final ObjectNode jsonSpan = JsonUtils.toObjectNode(span);
    System.out.println(jsonSpan);
    assertEquals("1", jsonSpan.get("a").get("b").get("c").get("d1").asText());
    assertEquals("2", jsonSpan.get("a").get("b").get("c").get("d2").asText());
}
Example 53
Project: stagemonitor-master  File: SpanJsonModuleTest.java View source code
@Test
public void testNestDottedTagKeys() {
    final ReadbackSpan span = createTestSpan(1);
    span.setTag("a.b.c.d1", "1");
    span.setTag("a.b.c.d2", "2");
    final ObjectNode jsonSpan = JsonUtils.toObjectNode(span);
    System.out.println(jsonSpan);
    assertEquals("1", jsonSpan.get("a").get("b").get("c").get("d1").asText());
    assertEquals("2", jsonSpan.get("a").get("b").get("c").get("d2").asText());
}
Example 54
Project: stork-master  File: JacksonUtil.java View source code
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {
    Iterator<String> fieldNames = updateNode.fieldNames();
    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        JsonNode jsonNode = mainNode.get(fieldName);
        // if field exists and is an embedded object
        if (jsonNode != null && jsonNode.isObject()) {
            merge(jsonNode, updateNode.get(fieldName));
        } else {
            if (mainNode instanceof ObjectNode) {
                // Overwrite field
                JsonNode value = updateNode.get(fieldName);
                ((ObjectNode) mainNode).put(fieldName, value);
            }
        }
    }
    return mainNode;
}
Example 55
Project: stormpath-sdk-java-master  File: JSONPropertiesSource.java View source code
private void getFlattenedMap(String currentPath, JsonNode jsonNode, Map<String, String> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            getFlattenedMap(pathPrefix + entry.getKey(), entry.getValue(), map);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            getFlattenedMap(currentPath + "[" + i + "]", arrayNode.get(i), map);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        map.put(currentPath, valueNode.asText());
    }
}
Example 56
Project: swagger-core-master  File: SerializationMatchers.java View source code
private static void apply(Object objectToSerialize, String str, ObjectMapper mapper) {
    final ObjectNode lhs = mapper.convertValue(objectToSerialize, ObjectNode.class);
    ObjectNode rhs = null;
    try {
        rhs = mapper.readValue(str, ObjectNode.class);
    } catch (IOException e) {
        LOGGER.error("Failed to read value", e);
    }
    if (!lhs.equals(new ObjectNodeComparator(), rhs)) {
        fail(String.format("Serialized object:\n%s\ndoes not equal to expected serialized string:\n%s", lhs, rhs));
    }
}
Example 57
Project: swagger-parser-master  File: PathAppenderMigrator.java View source code
@Nonnull
@Override
public JsonNode migrate(@Nonnull final JsonNode input) throws SwaggerMigrationException {
    try {
        Preconditions.checkArgument(input.isObject(), "expected JSON to be a JSON object but it isn't");
        Preconditions.checkArgument(input.path("path").isTextual(), "\"path\" member of API object is not a JSON string");
    } catch (IllegalArgumentException e) {
        throw new SwaggerMigrationException(e.getMessage());
    }
    // We have to do that... JsonNode is not immutable
    final ObjectNode node = input.deepCopy();
    final String oldPath = node.get("path").textValue();
    node.put("path", basePath + oldPath);
    return node;
}
Example 58
Project: sync-android-master  File: OpenRevisionDeserializer.java View source code
@Override
public OpenRevision deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectNode node = jp.readValueAsTree();
    if (node.has("ok")) {
        return jp.getCodec().treeToValue(node, OkOpenRevision.class);
    } else if (node.has("missing")) {
        return jp.getCodec().treeToValue(node, MissingOpenRevision.class);
    } else {
        // Should never happen
        throw new IllegalStateException("Unexpected object in open revisions response.");
    }
}
Example 59
Project: syncope-master  File: SyncTokenDeserializer.java View source code
@Override
public SyncToken deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {
    ObjectNode tree = jp.readValueAsTree();
    Object value = null;
    if (tree.has("value")) {
        JsonNode node = tree.get("value");
        value = node.isNull() ? null : node.isBoolean() ? node.asBoolean() : node.isDouble() ? node.asDouble() : node.isLong() ? node.asLong() : node.isInt() ? node.asInt() : node.asText();
        if (value instanceof String) {
            String base64 = (String) value;
            try {
                value = Base64.decode(base64);
            } catch (RuntimeException e) {
                value = base64;
            }
        }
    }
    return new SyncToken(value);
}
Example 60
Project: telegraph-master  File: NodeDeserializer.java View source code
@Override
public Node deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    JsonNode node = mapper.readTree(jsonParser);
    if (node instanceof TextNode) {
        return new NodeText(node.asText());
    } else {
        JsonNode childrenNode = node.get(NodeElement.CHILDREN_FIELD);
        JsonNode tagNode = node.get(NodeElement.TAG_FIELD);
        JsonNode attrsNode = node.get(NodeElement.ATTRS_FIELD);
        NodeElement element = new NodeElement();
        element.setTag(tagNode.asText());
        if (attrsNode != null && attrsNode instanceof ObjectNode) {
            Map<String, String> attributes = new HashMap<>();
            for (Iterator<String> it = attrsNode.fieldNames(); it.hasNext(); ) {
                String field = it.next();
                attributes.put(field, attrsNode.get(field).asText());
            }
            element.setAttrs(attributes);
        }
        if (childrenNode != null && childrenNode instanceof ArrayNode) {
            List<Node> childNodes = new ArrayList<>();
            for (Iterator<JsonNode> it = childrenNode.elements(); it.hasNext(); ) {
                childNodes.add(mapper.treeToValue(it.next(), Node.class));
            }
            element.setChildren(childNodes);
        }
        return element;
    }
}
Example 61
Project: TinCanJava-master  File: Score.java View source code
@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectNode node = Mapper.getInstance().createObjectNode();
    if (this.scaled != null) {
        node.put("scaled", this.getScaled());
    }
    if (this.raw != null) {
        node.put("raw", this.getRaw());
    }
    if (this.min != null) {
        node.put("min", this.getMin());
    }
    if (this.max != null) {
        node.put("max", this.getMax());
    }
    return node;
}
Example 62
Project: Unified-Log-Processing-master  File: FullProducer.java View source code
public void process(String message) {
    try {
        JsonNode root = MAPPER.readTree(message);
        // b
        JsonNode ipAddressNode = root.path("shopper").path("ipAddress");
        if (ipAddressNode.isMissingNode()) {
            IProducer.write(this.producer, this.badTopic, // c
            "{\"error\": \"shopper.ipAddress missing\"}");
        } else {
            String ipAddress = ipAddressNode.textValue();
            // d
            Location location = maxmind.getLocation(ipAddress);
            ((ObjectNode) root).with("shopper").put("country", // e
            location.countryName);
            ((ObjectNode) root).with("shopper").put("city", // e
            location.city);
            IProducer.write(this.producer, this.goodTopic, // f
            MAPPER.writeValueAsString(root));
        }
    } catch (Exception e) {
        IProducer.write(this.producer, this.badTopic, "{\"error\": \"" + e.getClass().getSimpleName() + ": " + e.getMessage() + "\"}");
    }
}
Example 63
Project: unravl-master  File: TextExtractor.java View source code
@Override
public void extract(UnRAVL current, ObjectNode extractor, ApiCall call) throws UnRAVLException {
    super.extract(current, extractor, call);
    JsonNode target = Json.firstFieldValue(extractor);
    if (!target.isTextual())
        throw new UnRAVLException("json binding value must be a var name or a @file-name string");
    String to = target.textValue();
    String text = Text.utf8ToString(call.getResponseBody().toByteArray());
    current.bind("responseBody", text);
    if (to.startsWith(UnRAVL.REDIRECT_PREFIX)) {
        String where = to.substring(UnRAVL.REDIRECT_PREFIX.length());
        where = getScript().expand(where);
        try {
            boolean stdout = where.equals("-");
            Writer f = stdout ? new PrintWriter(System.out) : new OutputStreamWriter(new FileOutputStream(where), Text.UTF_8);
            f.write(text);
            if (stdout)
                System.out.println();
            else
                f.close();
        } catch (IOException e) {
            throw new UnRAVLException(e.getMessage(), e);
        }
        if (!where.equals("-"))
            logger.info("Wrote text to file " + where);
    } else {
        current.bind(to, text);
    }
}
Example 64
Project: useful-java-links-master  File: TreeModel.java View source code
/**
     * Example to writeJson using TreeModel
     */
private static void writeJson() throws IOException {
    OutputStream outputStream = new ByteArrayOutputStream();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();
    rootNode.put("message", "Hi");
    ObjectNode childNode = rootNode.putObject("place");
    childNode.put("name", "World!");
    mapper.writeValue(outputStream, childNode);
    // print "{"message":"Hi","place":{"name":"World!"}}"
    System.out.println(outputStream.toString());
}
Example 65
Project: vitam-master  File: UnitInheritedRuleTest.java View source code
@Test
public void testUnitRuleResult() throws Exception {
    UnitInheritedRule au1RulesResult = new UnitInheritedRule((ObjectNode) JsonHandler.getFromString(AU1_MGT), "AU1");
    UnitInheritedRule au2RulesResult = au1RulesResult.createNewInheritedRule((ObjectNode) JsonHandler.getFromString(AU2_MGT), "AU2");
    UnitInheritedRule au3RulesResult = new UnitInheritedRule((ObjectNode) JsonHandler.getFromString(AU1_MGT), "AU3");
    assertEquals(EXPECTED_RESULT, JsonHandler.unprettyPrint(au2RulesResult));
    UnitInheritedRule au5RulesResult = new UnitInheritedRule((ObjectNode) JsonHandler.getFromString(AU5_MGT), "AU5");
    assertNotNull(au5RulesResult);
    au1RulesResult.concatRule(au3RulesResult);
    assertEquals(EXPECTED_CONCAT_RESULT, JsonHandler.unprettyPrint(au1RulesResult));
    au1RulesResult.concatRule(au1RulesResult);
    assertEquals(EXPECTED_CONCAT_RESULT, JsonHandler.unprettyPrint(au1RulesResult));
}
Example 66
Project: WebAPI-master  File: GenericRowMapper.java View source code
@Override
public JsonNode mapRow(ResultSet rs, int rowNum) throws SQLException {
    ObjectNode objectNode = mapper.createObjectNode();
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        Object value = rs.getObject(column);
        if (value == null) {
            objectNode.putNull(column);
        } else if (value instanceof Integer) {
            objectNode.put(column, (Integer) value);
        } else if (value instanceof String) {
            objectNode.put(column, (String) value);
        } else if (value instanceof Boolean) {
            objectNode.put(column, (Boolean) value);
        } else if (value instanceof Date) {
            objectNode.put(column, ((Date) value).getTime());
        } else if (value instanceof Long) {
            objectNode.put(column, (Long) value);
        } else if (value instanceof Double) {
            objectNode.put(column, (Double) value);
        } else if (value instanceof Float) {
            objectNode.put(column, (Float) value);
        } else if (value instanceof BigDecimal) {
            objectNode.put(column, (BigDecimal) value);
        } else if (value instanceof Byte) {
            objectNode.put(column, (Byte) value);
        } else if (value instanceof byte[]) {
            objectNode.put(column, (byte[]) value);
        } else {
            throw new IllegalArgumentException("Unmappable object type: " + value.getClass());
        }
    }
    return objectNode;
}
Example 67
Project: winlet-master  File: CORSResponseStream.java View source code
@Override
public void close() throws IOException {
    ObjectNode node = JsonNodeFactory.instance.objectNode();
    for (String header : new String[] { HEADER_UPDATE, HEADER_TITLE, HEADER_DIALOG, HEADER_REDIRECT, HEADER_CACHE, HEADER_MSG }) {
        String value = response.getHeader(header);
        if (value != null && !value.trim().equals("")) {
            node.put(header, value);
        }
    }
    try {
        Matcher m = P_COOKIE.matcher(response.getHeader("Set-Cookie"));
        if (m.find()) {
            node.put("X-Winlet-Session-ID", m.group(1));
        }
    } catch (Exception e) {
    }
    output.write(("<div id=\"winlet_header\" style=\"display:none\">" + node.toString() + "</div>").getBytes());
    output.flush();
    output.close();
}
Example 68
Project: wisdom-master  File: RouteModelTest.java View source code
@Test
public void testFrom() throws Exception {
    Route route = new Route(HttpMethod.DELETE, "/", new MyController(), MyController.class.getMethod("foo"));
    final JacksonSingleton json = new JacksonSingleton();
    json.validate();
    ObjectNode node = RouteModel.from(route, json);
    assertThat(node.get("http_method").textValue()).isEqualTo("DELETE");
    assertThat(node.get("method").textValue()).isEqualTo("foo");
}
Example 69
Project: XChange-master  File: VircurexOpenOrdersDeserializer.java View source code
@Override
public VircurexOpenOrdersReturn deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
    List<VircurexOpenOrder> openOrdersList = new ArrayList<VircurexOpenOrder>();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode jsonNodes = mapper.readTree(jsonParser);
    Iterator<Map.Entry<String, JsonNode>> jsonNodeIterator = jsonNodes.fields();
    while (jsonNodeIterator.hasNext()) {
        Map.Entry<String, JsonNode> jsonNodeField = jsonNodeIterator.next();
        if (jsonNodeField.getKey().contains("order-")) {
            VircurexOpenOrder openOrder = mapper.readValue(jsonNodeField.getValue().toString(), VircurexOpenOrder.class);
            openOrdersList.add(openOrder);
        } else {
            // found the last of the order objects
            break;
        }
    }
    VircurexOpenOrdersReturn openOrdersReturn = new VircurexOpenOrdersReturn(jsonNodes.get("numberorders").asInt(), jsonNodes.get("account").asText(), jsonNodes.get("timestamp").asText(), jsonNodes.get("token").asText(), jsonNodes.get("status").asInt(), jsonNodes.get("function").asText());
    if (openOrdersList.size() > 0) {
        openOrdersReturn.setOpenOrders(openOrdersList);
    }
    return openOrdersReturn;
}
Example 70
Project: xmlsh-master  File: object.java View source code
@Override
public XValue run(Shell shell, List<XValue> args) throws InvalidArgumentException {
    StringBuffer sb = new StringBuffer();
    ObjectMapper mapper = JSONUtils.getJsonObjectMapper();
    ObjectNode obj = mapper.createObjectNode();
    String name = null;
    boolean bOdd = true;
    for (XValue arg : args) {
        if (bOdd)
            name = arg.toString();
        else
            obj.set(name, JSONUtils.toJsonType(arg));
        bOdd = !bOdd;
    }
    return XValue.newXValue(TypeFamily.JSON, obj);
}
Example 71
Project: XMLVersioningFramework-master  File: RepositoryRevision.java View source code
/**
	 * Writes the content of repository Head to JSON
	 * 
	 * @param head
	 * @return
	 */
public ObjectNode toJSON() {
    ObjectNode headJSON = Json.newObject();
    for (RepositoryFile repoFile : this.getRepositoryFiles()) {
        ObjectNode fileObjectNode = headJSON.putArray(JSONConstants.FILES).addObject();
        fileObjectNode.put(JSONConstants.FILE_URL, repoFile.getFileURL());
        fileObjectNode.put(JSONConstants.FILE_CONTENT, repoFile.getFileContent());
    }
    headJSON.put(JSONConstants.ELAPSED_TIME, this.getElapsedTime());
    headJSON.put(JSONConstants.LAST_COMMIT, this.getLastCommit());
    headJSON.put(JSONConstants.LAST_COMMIT_MESSAGE, this.getLastCommitMessage());
    headJSON.put(JSONConstants.LAST_COMMIT_AUTHOR, this.getLastCommitAuthor());
    return headJSON;
}
Example 72
Project: aerogear-sync-server-master  File: JsonPatchClientIntegrationTest.java View source code
@Test
public void connect() throws InterruptedException {
    final ObjectMapper objectMapper = new ObjectMapper();
    final ObjectNode originalVersion = objectMapper.createObjectNode().put("name", "fletch");
    final String documentId = "1234";
    final String clientId = "client2";
    final JsonPatchClientSynchronizer synchronizer = new JsonPatchClientSynchronizer();
    final ClientInMemoryDataStore<JsonNode, JsonPatchEdit> dataStore = new ClientInMemoryDataStore<JsonNode, JsonPatchEdit>();
    final ClientSyncEngine<JsonNode, JsonPatchEdit> clientSyncEngine = new ClientSyncEngine<JsonNode, JsonPatchEdit>(synchronizer, dataStore, new DefaultPatchObservable<JsonNode>());
    final NettySyncClient<JsonNode, JsonPatchEdit> client = NettySyncClient.<JsonNode, JsonPatchEdit>forHost("localhost").syncEngine(clientSyncEngine).port(7777).path("/sync").build();
    client.connect();
    client.addDocument(clientDoc(documentId, clientId, originalVersion));
    Thread.sleep(1000);
    client.disconnect();
}
Example 73
Project: alchemy-rest-client-generator-master  File: ExceptionPayloadDeserializer.java View source code
/*
     * (non-Javadoc)
     * @see
     * com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml
     * .jackson.core.JsonParser,
     * com.fasterxml.jackson.databind.DeserializationContext)
     */
@SuppressWarnings("unchecked")
@Override
public ExceptionPayload deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    final ObjectMapper sourceObjectMapper = ((ObjectMapper) jp.getCodec());
    final ObjectNode tree = jp.readValueAsTree();
    String message = null;
    if (tree.has("exceptionMessage")) {
        message = tree.get("exceptionMessage").asText();
    }
    Throwable exception = null;
    try {
        final String className = tree.get("exceptionClassFQN").asText();
        final Class<? extends Throwable> clazz = (Class<? extends Throwable>) ReflectionUtils.forName(className);
        exception = sourceObjectMapper.treeToValue(tree.get("exception"), clazz);
    } catch (final Throwable t) {
        log.warn("Error deserializing exception class", t);
        exception = new InternalServerErrorException(message);
    }
    return new ExceptionPayload(exception.getClass().getName(), message, exception);
}
Example 74
Project: android-viewer-for-khan-academy-master  File: UserVideoDeserializerModule.java View source code
@Override
public UserVideo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    TreeNode tree = defaultMapper.readTree(jp);
    ObjectNode root = (ObjectNode) tree;
    Iterator<String> keys = root.fieldNames();
    while (keys.hasNext()) {
        String key = keys.next();
        if ("video".equals(key)) {
            JsonNode value = root.get(key);
            if (value.isObject()) {
                root.set(key, value.get("readable_id"));
            }
        }
    }
    UserVideo video = defaultMapper.treeToValue(tree, UserVideo.class);
    return video;
}
Example 75
Project: astrix-master  File: ServiceRegistryV1ApiMigration.java View source code
@Override
public void upgrade(ObjectNode json) {
    // ApplicationInstanceId concept was introduced to uniquely identify a service.
    // Old clients will not set the property, but it was expected that a service (api + qualifier)
    // was only provided by a single application instance, hence we use it as id.
    String qualifier = json.get("serviceProperties").get("_qualifier").asText();
    String api = json.get("serviceProperties").get("_api").asText();
    String applicationInstanceId = api + "_" + qualifier;
    ObjectNode.class.cast(json.get("serviceProperties")).put(ServiceProperties.APPLICATION_INSTANCE_ID, applicationInstanceId);
// ServiceState was introduced to allow multiple servers providing same service. 
// We assume old servers are not run concurrently and hence alwasy assume them to be active
//			ObjectNode.class.cast(json.get("serviceProperties")).put(ServiceProperties., ServiceState.ACTIVE);
}
Example 76
Project: aws-dynamodb-examples-master  File: MoviesLoadData.java View source code
public static void main(String[] args) throws Exception {
    AmazonDynamoDBClient client = new AmazonDynamoDBClient();
    client.setEndpoint("http://localhost:8000");
    DynamoDB dynamoDB = new DynamoDB(client);
    Table table = dynamoDB.getTable("Movies");
    JsonParser parser = new JsonFactory().createParser(new File("moviedata.json"));
    Iterator<JsonNode> iter = getRootNode(parser).iterator();
    ObjectNode currentNode;
    while (iter.hasNext()) {
        currentNode = (ObjectNode) iter.next();
        int year = getYear(currentNode);
        String title = getTitle(currentNode);
        System.out.println("Adding movie: " + year + " " + title);
        table.putItem(new Item().withPrimaryKey("year", year, "title", title).withJSON("info", getInfo(currentNode)));
    }
    parser.close();
}
Example 77
Project: bard-master  File: ProjectListJsonConverter.java View source code
@Override
public JsonNode convert(BardLinkedEntity o) throws Exception {
    DBUtils db = new DBUtils();
    ObjectMapper mapper = new ObjectMapper();
    if (!(o.getCollection() instanceof Collection))
        throw new IllegalArgumentException("Must supply an object of type BardLinkedEntity");
    Collection coll = (Collection) o.getCollection();
    JsonNode list = mapper.valueToTree(o);
    ArrayNode items = mapper.createArrayNode();
    for (Object item : coll) {
        if (!(item instanceof Project))
            throw new IllegalArgumentException("The BardLinkedEntity must contain Project objects as elements");
        Project p = (Project) item;
        List<Assay> assays = new ArrayList<Assay>();
        for (Long aid : p.getAids()) assays.add(db.getAssayByAid(aid));
        List<Experiment> expts = new ArrayList<Experiment>();
        for (Long eid : p.getEids()) expts.add(db.getExperimentByExptId(eid));
        List<Publication> pubs = new ArrayList<Publication>();
        for (Long pmid : p.getPublications()) pubs.add(db.getPublicationByPmid(pmid));
        ArrayNode an = mapper.createArrayNode();
        for (Assay assay : assays) {
            an.add(mapper.valueToTree(assay));
        }
        ArrayNode en = mapper.createArrayNode();
        for (Experiment expt : expts) {
            en.add(mapper.valueToTree(expt));
        }
        ArrayNode pn = mapper.createArrayNode();
        for (Publication pub : pubs) {
            pn.add(mapper.valueToTree(pub));
        }
        JsonNode tree = mapper.valueToTree(p);
        ((ObjectNode) tree).put("eids", en);
        ((ObjectNode) tree).put("aids", an);
        ((ObjectNode) tree).put("publications", pn);
        items.add(tree);
    }
    ((ObjectNode) list).put("collection", items);
    db.closeConnection();
    return list;
}
Example 78
Project: beam-master  File: ValueProviders.java View source code
/**
   * Given {@code serializedOptions} as a JSON-serialized {@link PipelineOptions}, updates
   * the values according to the provided values in {@code runtimeValues}.
   */
public static String updateSerializedOptions(String serializedOptions, Map<String, String> runtimeValues) {
    ObjectMapper mapper = new ObjectMapper().registerModules(ObjectMapper.findModules(ReflectHelpers.findClassLoader()));
    ObjectNode root, options;
    try {
        root = mapper.readValue(serializedOptions, ObjectNode.class);
        options = (ObjectNode) root.get("options");
        checkNotNull(options, "Unable to locate 'options' in %s", serializedOptions);
    } catch (IOException e) {
        throw new RuntimeException(String.format("Unable to parse %s", serializedOptions), e);
    }
    for (Map.Entry<String, String> entry : runtimeValues.entrySet()) {
        options.put(entry.getKey(), entry.getValue());
    }
    try {
        return mapper.writeValueAsString(root);
    } catch (IOException e) {
        throw new RuntimeException("Unable to parse re-serialize options", e);
    }
}
Example 79
Project: belladati-sdk-java-master  File: FormDataPostBuilderImpl.java View source code
@Override
public JsonNode toJson() {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode object = mapper.createObjectNode();
    for (Entry<String, String> entry : textValues.entrySet()) {
        object.put(entry.getKey(), entry.getValue());
    }
    for (Entry<String, BigDecimal> entry : numberValues.entrySet()) {
        object.put(entry.getKey(), entry.getValue());
    }
    for (Entry<String, Boolean> entry : booleanValues.entrySet()) {
        object.put(entry.getKey(), entry.getValue().booleanValue());
    }
    return object;
}
Example 80
Project: bson4jackson-master  File: BsonJavaScriptDeserializer.java View source code
@Override
@SuppressWarnings("deprecation")
public JavaScript deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (jp instanceof BsonParser) {
        BsonParser bsonParser = (BsonParser) jp;
        if (bsonParser.getCurrentToken() != JsonToken.VALUE_EMBEDDED_OBJECT || (bsonParser.getCurrentBsonType() != BsonConstants.TYPE_JAVASCRIPT && bsonParser.getCurrentBsonType() != BsonConstants.TYPE_JAVASCRIPT_WITH_SCOPE)) {
            throw ctxt.mappingException(JavaScript.class);
        }
        return (JavaScript) bsonParser.getEmbeddedObject();
    } else {
        TreeNode tree = jp.getCodec().readTree(jp);
        String code = null;
        TreeNode codeNode = tree.get("$code");
        if (codeNode instanceof ValueNode) {
            code = ((ValueNode) codeNode).asText();
        }
        Map<String, Object> scope = null;
        TreeNode scopeNode = tree.get("$scope");
        if (scopeNode instanceof ObjectNode) {
            @SuppressWarnings("unchecked") Map<String, Object> scope2 = jp.getCodec().treeToValue(scopeNode, Map.class);
            scope = scope2;
        }
        return new JavaScript(code, scope);
    }
}
Example 81
Project: bw-calendar-engine-master  File: JsonMapper.java View source code
@Override
public BwPrincipal deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode root = mapper.readTree(jp);
    final JsonNode node = root.get("kind");
    if (node == null) {
        return null;
    }
    final Number kind = node.numberValue();
    Class<? extends BwPrincipal> cl = registry.get(kind.intValue());
    if (cl == null) {
        return null;
    }
    System.out.println("Got class " + cl + " kind " + kind.intValue());
    if (kind.intValue() == WhoDefs.whoTypeGroup) {
        final JsonNode gonode = root.get("groupOwnerHref");
        if (gonode != null) {
            System.out.println("Class now " + cl);
            cl = BwAdminGroup.class;
        }
    }
    return mapper.treeToValue(root, cl);
}
Example 82
Project: cf-java-client-master  File: _Member.java View source code
@Override
public Member deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    Member.Builder builder = Member.builder();
    ObjectCodec codec = p.getCodec();
    ObjectNode tree = p.readValueAsTree();
    if (tree.has("entity")) {
        JsonNode entity = tree.get("entity");
        String type = tree.get("type").asText();
        if (MemberType.GROUP.getValue().equalsIgnoreCase(type)) {
            builder.entity(codec.treeToValue(entity, GroupEntity.class));
        } else if (MemberType.USER.getValue().equalsIgnoreCase(type)) {
            builder.entity(codec.treeToValue(entity, UserEntity.class));
        } else {
            throw new IllegalArgumentException(String.format("Unknown member type: %s", type));
        }
    }
    builder.memberId(tree.get("value").asText());
    if (tree.has("origin")) {
        builder.origin(tree.get("origin").asText());
    }
    if (tree.has("type")) {
        builder.type(codec.treeToValue(tree.get("type"), MemberType.class));
    }
    return builder.build();
}
Example 83
Project: emchat-server-examples-master  File: ClientSecretCredential.java View source code
@Override
public Token getToken() {
    if (null == token || token.isExpired()) {
        try {
            ObjectNode objectNode = factory.objectNode();
            objectNode.put("grant_type", GRANT_TYPE);
            objectNode.put("client_id", tokenKey1);
            objectNode.put("client_secret", tokenKey2);
            List<NameValuePair> headers = new ArrayList<NameValuePair>();
            headers.add(new BasicNameValuePair("Content-Type", "application/json"));
            ObjectNode tokenRequest = JerseyUtils.sendRequest(getTokenRequestTarget(), objectNode, null, HTTPMethod.METHOD_POST, headers);
            if (null != tokenRequest.get("error")) {
                throw new RuntimeException("Some errors occurred while fetching a token by " + "grant_type[" + GRANT_TYPE + "] client_id[" + tokenKey1 + "]" + " and client_secret[" + tokenKey2 + "] .");
            }
            String accessToken = tokenRequest.get("access_token").asText();
            Long expiredAt = System.currentTimeMillis() + tokenRequest.get("expires_in").asLong() * 1000;
            token = new Token(accessToken, expiredAt);
        } catch (Exception e) {
            throw new RuntimeException("Some errors occurred while fetching a token by " + "grant_type[" + GRANT_TYPE + "] client_id[" + tokenKey1 + "]" + " and client_secret[" + tokenKey2 + "] .");
        }
    }
    return token;
}
Example 84
Project: emfjson-couchdb-master  File: CouchOutputStream.java View source code
private JsonNode toJson(Resource resource) {
    ResourceSet resourceSet = resource.getResourceSet();
    if (resourceSet == null) {
        resourceSet = new ResourceSetImpl();
    }
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new EMFModule(resourceSet, JacksonOptions.from(options)));
    final JsonNode contents = mapper.valueToTree(resource);
    final ObjectNode resourceNode = mapper.createObjectNode();
    final String id = uri.segment(1);
    resourceNode.put("_id", id);
    resourceNode.set("contents", contents);
    return resourceNode;
}
Example 85
Project: eucalyptus-master  File: ResourceInfoHelper.java View source code
public static String getResourceAttributesJson(ResourceInfo resourceInfo) throws CloudFormationException {
    Collection<String> attributeNames = resourceInfo.getAttributeNames();
    ObjectNode attributesNode = JsonHelper.createObjectNode();
    if (attributeNames != null) {
        for (String attributeName : attributeNames) {
            String resourceAttributeJson = resourceInfo.getResourceAttributeJson(attributeName);
            if (resourceAttributeJson == null) {
                // no real point in setting a value to null (which is default)
                continue;
            }
            attributesNode.put(attributeName, resourceAttributeJson);
        }
    }
    return JsonHelper.getStringFromJsonNode(attributesNode);
}
Example 86
Project: fabric8-devops-master  File: JsonNodes.java View source code
/**
     * Creates nested objects if they don't exist on the given paths.
     *
     * @returns the last object or null if it could not be created
     */
public static ObjectNode setObjects(JsonNode node, String... paths) {
    JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    JsonNode iter = node;
    for (String path : paths) {
        if (!iter.isObject()) {
            return null;
        }
        ObjectNode object = (ObjectNode) iter;
        iter = object.get(path);
        if (iter == null || !iter.isObject()) {
            iter = nodeFactory.objectNode();
            object.set(path, iter);
        }
    }
    return (ObjectNode) iter;
}
Example 87
Project: funktion-connectors-master  File: FunktionDeserializer.java View source code
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectNode node = jp.readValueAsTree();
    JsonNode kind = node.get("kind");
    if (kind == null) {
        throw new JsonParseException(jp, "No `kind` property!");
    }
    Class kindClass = kinds.get(kind.asText());
    if (kindClass == null) {
        throw ctxt.mappingException("Unknown kind: " + kind);
    } else {
        return (Step) jp.getCodec().treeToValue(node, kindClass);
    }
}
Example 88
Project: gennai-master  File: ShowViewsTask.java View source code
@Override
public String execute() throws TaskExecuteException {
    List<Schema> schemas = null;
    try {
        schemas = GungnirManager.getManager().getMetaStore().findSchemas(owner);
    } catch (MetaStoreException e) {
        throw new TaskExecuteException(e);
    }
    ArrayNode schemasNode = mapper.createArrayNode();
    for (Schema schema : schemas) {
        if (schema instanceof ViewSchema) {
            ViewSchema viewSchema = (ViewSchema) schema;
            ObjectNode schemaNode = mapper.createObjectNode();
            schemaNode.put("name", viewSchema.getSchemaName());
            ArrayNode topologiesNode = mapper.createArrayNode();
            for (String topologyId : viewSchema.getTopologies()) {
                topologiesNode.add(topologyId);
            }
            schemaNode.set("topologies", topologiesNode);
            schemaNode.put("owner", viewSchema.getOwner().getName());
            schemaNode.putPOJO("createTime", viewSchema.getCreateTime());
            if (viewSchema.getComment() != null) {
                schemaNode.put("comment", viewSchema.getComment());
            }
            schemasNode.add(schemaNode);
        }
    }
    try {
        return mapper.writeValueAsString(schemasNode);
    } catch (Exception e) {
        throw new TaskExecuteException("Failed to convert json format", e);
    }
}
Example 89
Project: geode-master  File: PulseVersionService.java View source code
public ObjectNode execute(final HttpServletRequest request) throws Exception {
    // json object to be sent as response
    ObjectNode responseJSON = mapper.createObjectNode();
    // Response
    responseJSON.put("pulseVersion", PulseController.pulseVersion.getPulseVersion());
    responseJSON.put("buildId", PulseController.pulseVersion.getPulseBuildId());
    responseJSON.put("buildDate", PulseController.pulseVersion.getPulseBuildDate());
    responseJSON.put("sourceDate", PulseController.pulseVersion.getPulseSourceDate());
    responseJSON.put("sourceRevision", PulseController.pulseVersion.getPulseSourceRevision());
    responseJSON.put("sourceRepository", PulseController.pulseVersion.getPulseSourceRepository());
    // Send json response
    return responseJSON;
}
Example 90
Project: glowroot-master  File: PluginDescriptor.java View source code
// this is only for use by glowroot-agent-dist-maven-plugin, which needs to perform
// serialization of shaded immutables objects using shaded jackson
public static String writeValue(List<PluginDescriptor> pluginDescriptors) throws IOException {
    ObjectMapper mapper = ObjectMappers.create();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)).setPrettyPrinter(ObjectMappers.getPrettyPrinter());
    jg.writeStartArray();
    for (PluginDescriptor pluginDescriptor : pluginDescriptors) {
        ObjectNode objectNode = mapper.valueToTree(pluginDescriptor);
        ObjectMappers.stripEmptyContainerNodes(objectNode);
        jg.writeTree(objectNode);
    }
    jg.writeEndArray();
    jg.close();
    // newline is not required, just a personal preference
    sb.append(ObjectMappers.NEWLINE);
    return sb.toString();
}
Example 91
Project: graphhopper-master  File: I18NServlet.java View source code
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String locale = "";
    String path = req.getPathInfo();
    if (!Helper.isEmpty(path) && path.startsWith("/"))
        locale = path.substring(1);
    if (Helper.isEmpty(locale)) {
        // fall back to language specified in header e.g. via browser settings
        String acceptLang = req.getHeader("Accept-Language");
        if (!Helper.isEmpty(acceptLang))
            locale = acceptLang.split(",")[0];
    }
    Translation tr = map.get(locale);
    ObjectNode json = objectMapper.createObjectNode();
    if (tr != null && !Locale.US.equals(tr.getLocale()))
        json.putPOJO("default", tr.asMap());
    json.put("locale", locale);
    json.putPOJO("en", map.get("en").asMap());
    writeJson(req, res, json);
}
Example 92
Project: gwt-rest-master  File: GreetingServlet.java View source code
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Creating custom greeting.");
    try {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode nameObject = mapper.readValue(req.getInputStream(), ObjectNode.class);
        String name = nameObject.get("name").asText();
        String greeting = "Hello " + name;
        ObjectNode resultObject = new ObjectNode(JsonNodeFactory.instance);
        resultObject.put("greeting", greeting);
        mapper.writeValue(resp.getOutputStream(), resultObject);
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        System.out.flush();
        System.err.flush();
    }
}
Example 93
Project: hamcrest-jackson-master  File: HasJsonFieldTest.java View source code
@Before
public void setup() {
    jsonNodeFactory = JsonNodeFactory.instance;
    book = jsonNodeFactory.objectNode();
    book.put("title", "Romeo and Juliette");
    ObjectNode author = jsonNodeFactory.objectNode();
    author.put("name", "William Shakespeare");
    author.put("dateOfBirth", "1564-04-23");
    book.put("author", author);
    book.put("publicationYear", 1960);
    book.put("paperback", true);
}
Example 94
Project: helios-master  File: RolloutOptionsTest.java View source code
/**
   * Test that a JSON representing a RolloutOptions instance prior to the addition of the
   * ignoreFailures field can be deserialized properly.
   */
@Test
public void testCanDeserializeWithoutIgnoreFailuresField() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode node = mapper.createObjectNode().put("migrate", false).put("parallalism", 2).put("timeout", 1000).put("overlap", true).put("token", "blah");
    final RolloutOptions options = Json.read(node.toString(), RolloutOptions.class);
    assertThat("RolloutOptions.ignoreFailures should default to false", options.getIgnoreFailures(), is(false));
}
Example 95
Project: incubator-taverna-language-master  File: BiomartActivityParser.java View source code
@Override
public Configuration parseConfiguration(T2FlowParser t2FlowParser, ConfigBean configBean, ParserState parserState) throws ReaderException {
    Configuration configuration = new Configuration();
    configuration.setParent(parserState.getCurrentProfile());
    ObjectNode json = (ObjectNode) configuration.getJson();
    configuration.setType(ACTIVITY_URI.resolve("#Config"));
    json.put("martQuery", T2FlowParser.elementToXML((Element) configBean.getAny()));
    return configuration;
}
Example 96
Project: Ingestion-master  File: EventParserTest.java View source code
private Event createEvent(String index) {
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    jsonBody.put("field1" + index, "foo");
    jsonBody.put("field2" + index, 32);
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("header1" + index, "bar");
    headers.put("header2" + index, "64");
    headers.put("header3" + index, "true");
    headers.put("header4" + index, "1.0");
    headers.put("header5" + index, null);
    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}
Example 97
Project: isis-master  File: JsonNodeUtils.java View source code
/**
     * Walks the path, ensuring keys exist and are maps, or creating required
     * maps as it goes.
     * 
     * <p>
     * For example, if given a list ("a", "b", "c") and starting with an empty
     * map, then will create:
     * 
     * <pre>
     * {
     *   "a": {
     *     "b: {
     *       "c": {
     *       }       
     *     }
     *   }
     * }
     */
public static ObjectNode walkNodeUpTo(ObjectNode node, final List<String> keys) {
    for (final String key : keys) {
        JsonNode jsonNode = node.get(key);
        if (jsonNode == null) {
            jsonNode = new ObjectNode(JsonNodeFactory.instance);
            node.put(key, jsonNode);
        } else {
            if (!jsonNode.isObject()) {
                throw new IllegalArgumentException(String.format("walking path: '%s', existing key '%s' is not a map", keys, key));
            }
        }
        node = (ObjectNode) jsonNode;
    }
    return node;
}
Example 98
Project: jackson-jaxrs-propertyfiltering-master  File: PropertyFilter.java View source code
private void filter(ObjectNode object) {
    if (!includedProperties.isEmpty()) {
        object.retain(includedProperties);
    }
    object.remove(excludedProperties);
    for (Entry<String, NestedPropertyFilter> entry : nestedProperties.entrySet()) {
        JsonNode node = object.get(entry.getKey());
        if (node != null) {
            entry.getValue().filter(node);
        }
    }
}
Example 99
Project: jlibs-master  File: ResultMessage.java View source code
@Override
public WAMPMessage decode(ArrayNode array) throws InvalidMessageException {
    if (array.size() < 3 || array.size() > 5)
        throw new InvalidMessageException();
    assert id(array) == ID;
    long requestID = longValue(array, 1);
    ObjectNode details = objectValue(array, 2);
    ArrayNode arguments = array.size() >= 4 ? arrayValue(array, 3) : null;
    ObjectNode argumentsKw = array.size() == 5 ? objectValue(array, 4) : null;
    return new ResultMessage(requestID, details, arguments, argumentsKw);
}
Example 100
Project: Kore-master  File: AddonsHandler.java View source code
@Override
public ArrayList<JsonResponse> getResponse(String method, ObjectNode jsonRequest) {
    ArrayList<JsonResponse> jsonResponses = new ArrayList<>();
    int methodId = jsonRequest.get(ID_NODE).asInt(-1);
    switch(method) {
        case Addons.GetAddons.METHOD_NAME:
            try {
                String result = FileUtils.readFile(context, "Addons.GetAddons.json");
                Addons.GetAddons getAddons = new Addons.GetAddons(methodId, result);
                jsonResponses.add(getAddons);
            } catch (IOException e) {
                LogUtils.LOGW(TAG, "Error creating GetAddons response: " + e.getMessage());
            }
            break;
        default:
            LogUtils.LOGD(TAG, "method: " + method + ", not implemented");
    }
    return jsonResponses;
}
Example 101
Project: listaCAP-master  File: ComuneDeserializer.java View source code
@Override
public Comune deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
    ObjectNode root = (ObjectNode) mapper.readTree(jsonParser);
    JsonNode codiceIstatNode = root.get("codiceIstat");
    String codiceIstat = codiceIstatNode.asText();
    JsonNode codiceCatastaleNode = root.get("codiceCatastale");
    String codiceCatastale = codiceCatastaleNode.asText();
    JsonNode nomeNode = root.get("nome");
    String nome = nomeNode.asText();
    JsonNode provinciaNode = root.get("provincia");
    String provincia = provinciaNode.asText();
    JsonNode codiciCapNode = root.get("codiciCap");
    Collection<String> codiciCap = new ArrayList<>();
    Iterator<JsonNode> capNodes = codiciCapNode.elements();
    while (capNodes.hasNext()) {
        JsonNode codiceCapNode = capNodes.next();
        String codiceCap = codiceCapNode.asText();
        codiciCap.add(codiceCap);
    }
    Comune comune = new Comune(codiceIstat, codiceCatastale, nome, provincia);
    comune.setCodiciCap(codiciCap);
    logger.trace("comune =" + comune + " deserializzato from json");
    return comune;
}