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

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

Introduction

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

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

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

Usage

From source file:org.bimserver.javamodelchecker.WriteToJson.java

public static void main(String[] args) {
    try {/* w ww  .  ja v a2  s . c om*/
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        ArrayNode array = objectMapper.createArrayNode();
        rootNode.set("modelcheckers", array);

        ObjectNode objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Check window widths");
        objectNode.put("description", "Check window widths");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code",
                changeClassName(
                        FileUtils.readFileToString(
                                new File("src/org/bimserver/javamodelchecker/WindowWidthChecker.java")),
                        "WindowWidthChecker"));

        objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Pass always");
        objectNode.put("description", "Pass always");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code", changeClassName(
                FileUtils.readFileToString(new File("src/org/bimserver/javamodelchecker/PassAlways.java")),
                "PassAlways"));

        objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Fail always");
        objectNode.put("description", "Fail always");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code", changeClassName(
                FileUtils.readFileToString(new File("src/org/bimserver/javamodelchecker/FailAlways.java")),
                "FailAlways"));

        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("modelcheckers.json"), rootNode);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.ikanow.aleph2.example.external_harvester.services.ExternalProcessLaunchService.java

public static void main(String[] args) throws InstantiationException, IllegalAccessException,
        ClassNotFoundException, JsonProcessingException, IOException, InterruptedException, ExecutionException {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    // Get the context (unused here)

    final IHarvestContext context = ContextUtils.getHarvestContext(args[0]);

    final DataBucketBean bucket = context.getBucket().get();

    _logger.info("Launched context, eg bucket status = : "
            + BeanTemplateUtils.toJson(context.getBucketStatus(Optional.empty()).get()));
    _logger.info("Retrieved bucket from CON: " + BeanTemplateUtils.toJson(bucket));

    // Get the bucket (unused here)

    _logger.info("Retrieved arg from CLI: " + args[1]);

    // Check that joins the cluster if I request the data bucket store
    //context.getService(IManagementDbService.class, Optional.of("core_management_db")).get().getDataBucketStore();
    //(But not if it's in read only mode)
    final IManagementCrudService<DataBucketBean> bucket_service = context.getServiceContext()
            .getCoreManagementDbService().readOnlyVersion().getDataBucketStore();
    _logger.info("Getting Management DB and reading number of buckets = "
            + bucket_service.countObjects().get().intValue());

    // Demonstration of accessing (read only) library state information:

    final Tuple2<SharedLibraryBean, Optional<GlobalConfigBean>> lib_config = ExternalProcessHarvestTechnology
            .getConfig(context);//w ww  .  j a v a 2  s.com
    _logger.info("Retrieved library configuration: "
            + lib_config._2().map(g -> BeanTemplateUtils.toJson(g).toString()).orElse("(no config)"));

    // 1) Preferred method of getting per library state: 
    final ICrudService<ProcessInfoBean> pid_crud = context
            .getGlobalHarvestTechnologyObjectStore(ProcessInfoBean.class, ProcessInfoBean.PID_COLLECTION_NAME);
    // 2) Lower level way:
    //final IManagementDbService core_db = context.getServiceContext().getCoreManagementDbService();
    //final ICrudService<ProcessInfoBean> pid_crud = core_db.getPerLibraryState(ProcessInfoBean.class, lib_config._1(), ProcessInfoBean.PID_COLLECTION_NAME);
    // 3) Alternatively (this construct is how you get per bucket state also):
    //final ICrudService<ProcessInfoBean> pid_crud = context.getBucketObjectStore(ProcessInfoBean.class, Optional.empty(), ProcessInfoBean.PID_COLLECTION_NAME, Optional.of(AssetStateDirectoryBean.StateDirectoryType.library));

    lib_config._2().ifPresent(gc -> {
        if (gc.store_pids_in_db())
            pid_crud.getObjectsBySpec(CrudUtils.allOf(ProcessInfoBean.class).when(ProcessInfoBean::bucket_name,
                    bucket.full_name())).thenAccept(cursor -> {
                        String pids = StreamSupport.stream(cursor.spliterator(), false).map(c -> c._id())
                                .collect(Collectors.joining(","));
                        _logger.info("Pids/hostnames for this bucket: " + pids);
                    }).exceptionally(err -> {
                        _logger.error("Failed to get bucket pids", err);
                        return null;
                    });
    });

    // Just run for 10 minutes as an experiment
    for (int i = 0; i < 60; ++i) {
        // Example of promoting data to next stage
        if ((MasterEnrichmentType.streaming == bucket.master_enrichment_type())
                || (MasterEnrichmentType.streaming_and_batch == bucket.master_enrichment_type())) {
            // Send an object to kafka
            final JsonNode json = mapper.createObjectNode().put("@timestamp", new Date().getTime())
                    .put("test_str", "test" + i).put("test_int", i);
            _logger.info("Sending object to kafka: " + json);
            context.sendObjectToStreamingPipeline(Optional.empty(), Either.left(json));
        }
        _logger.info("(sleeping: " + i + ")");
        try {
            Thread.sleep(10L * 1000L);
        } catch (Exception e) {
        }
    }
}

From source file:org.trustedanalytics.hadoop.admin.tools.HadoopClientParamsImporter.java

static String returnJSON(Map<String, String> props) {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.createObjectNode();
    props.forEach((k, v) -> ((ObjectNode) rootNode).with(ConfigConstants.HADOOP_CONFIG_KEY_VALUE).put(k, v));
    return escapeCharacters(rootNode.toString());
}

From source file:Main.java

public static String takeDumpJSON(ThreadMXBean threadMXBean) throws IOException {
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
    List<Map<String, Object>> threads = new ArrayList<>();

    for (ThreadInfo thread : threadInfos) {
        Map<String, Object> threadMap = new HashMap<>();
        threadMap.put("name", thread.getThreadName());
        threadMap.put("id", thread.getThreadId());
        threadMap.put("state", thread.getThreadState().name());
        List<String> stacktrace = new ArrayList<>();
        for (StackTraceElement element : thread.getStackTrace()) {
            stacktrace.add(element.toString());
        }/* ww  w. j  a v a  2 s  . co m*/
        threadMap.put("stack", stacktrace);

        if (thread.getLockName() != null) {
            threadMap.put("lock_name", thread.getLockName());
        }
        if (thread.getLockOwnerId() != -1) {
            threadMap.put("lock_owner_id", thread.getLockOwnerId());
        }
        if (thread.getBlockedTime() > 0) {
            threadMap.put("blocked_time", thread.getBlockedTime());
        }
        if (thread.getBlockedCount() > 0) {
            threadMap.put("blocked_count", thread.getBlockedCount());
        }
        if (thread.getLockedMonitors().length > 0) {
            threadMap.put("locked_monitors", thread.getLockedMonitors());
        }
        if (thread.getLockedSynchronizers().length > 0) {
            threadMap.put("locked_synchronizers", thread.getLockedSynchronizers());
        }
        threads.add(threadMap);
    }
    ObjectMapper om = new ObjectMapper();
    ObjectNode json = om.createObjectNode();
    json.put("date", new Date().toString());
    json.putPOJO("threads", threads);

    long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
    long[] monitorDeadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    if (deadlockedThreads != null && deadlockedThreads.length > 0) {
        json.putPOJO("deadlocked_thread_ids", deadlockedThreads);
    }
    if (monitorDeadlockedThreads != null && monitorDeadlockedThreads.length > 0) {
        json.putPOJO("monitor_deadlocked_thread_ids", monitorDeadlockedThreads);
    }
    om.enable(SerializationFeature.INDENT_OUTPUT);
    return om.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}

From source file:org.opendaylight.nic.bgp.service.parser.BgpDataflowParser.java

public static String fromBgpDataFlow(final BgpDataflow bgpDataflow) {
    final ObjectMapper objectMapper = createObjectMapper();
    final ObjectNode ipv4NextHopNode = objectMapper.createObjectNode();
    final ObjectNode originNode = objectMapper.createObjectNode();
    final ObjectNode localPrefNode = objectMapper.createObjectNode();
    final ObjectNode asPathNode = objectMapper.createObjectNode();

    final ObjectNode attributesNode = objectMapper.createObjectNode();

    ipv4NextHopNode.put(GLOBAL, bgpDataflow.getGlobalIp().getValue());
    attributesNode.put(IPV4_NEXT_HOP, ipv4NextHopNode);
    attributesNode.put(AS_PATH, asPathNode);
    originNode.put(VALUE, ORIGIN_IGP);/*from  w  w w .j a v a2  s  .c om*/
    attributesNode.put(ORIGIN, originNode);
    localPrefNode.put(PREF, FIXED_PREF);
    attributesNode.put(LOCAL_PREF, localPrefNode);

    final ObjectNode ipv4RouteAttributesNode = objectMapper.createObjectNode();
    ipv4RouteAttributesNode.put(PREFIX, bgpDataflow.getPrefix().getValue());
    ipv4RouteAttributesNode.put(PATH_ID, bgpDataflow.getPathId());
    ipv4RouteAttributesNode.put(ATTRIBUTES, attributesNode);

    final ArrayNode arrayNode = objectMapper.createArrayNode();
    arrayNode.add(ipv4RouteAttributesNode);

    final ObjectNode ipv4RouteNode = objectMapper.createObjectNode();
    ipv4RouteNode.put(IPV4_ROUTE, arrayNode);

    final ObjectNode bgpInetIpv4Routes = objectMapper.createObjectNode();
    bgpInetIpv4Routes.put(BGP_INET_IPV4_ROUTES, ipv4RouteNode);

    return bgpInetIpv4Routes.toString();
}

From source file:com.github.khazrak.jdocker.utils.Filters.java

public static String encodeFilters(Map<String, String> filters) {
    ObjectMapper mapper = new ObjectMapper();
    String result = null;//w  ww .j  av  a  2  s .c  o m
    ObjectNode objectNode = mapper.createObjectNode();
    if (!filters.keySet().isEmpty()) {
        for (Map.Entry<String, String> s : filters.entrySet()) {
            objectNode.putObject(s.getKey()).put(s.getValue(), true);
        }
    }

    try {
        result = URLEncoder.encode(objectNode.toString(), StandardCharsets.UTF_8.toString());
    } catch (UnsupportedEncodingException e) {
        logger.error("Error encoding filtersMap", e);
    }
    return result;
}

From source file:utils.ReflectionService.java

public static JsonNode createJsonNode(Class clazz, int maxDeep) {

    if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) {
        return null;
    }//  www .  j  av a  2  s  . c o  m

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode objectNode = objectMapper.createObjectNode();

    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String key = field.getName();
        try {
            // is array or collection
            if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0];
                ArrayNode arrayNode = objectMapper.createArrayNode();
                arrayNode.add(createJsonNode(type, maxDeep - 1));
                objectNode.put(key, arrayNode);
            } else {
                Class<?> type = field.getType();
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                } else if (type.isEnum()) {
                    objectNode.put(key, Enum.class.getName());
                } else if (!type.getName().startsWith("java") && !key.startsWith("_")) {
                    objectNode.put(key, createJsonNode(type, maxDeep - 1));
                } else {
                    objectNode.put(key, type.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return objectNode;
}

From source file:org.opendaylight.sfc.sbrest.json.ExporterUtil.java

protected static ObjectNode getSffSfDataPlaneLocatorObjectNode(SffSfDataPlaneLocator sffSfDpl) {
    if (sffSfDpl == null) {
        return null;
    }//from www .  jav a2s .  com

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode sffSfDplNode = mapper.createObjectNode();

    if (sffSfDpl.getSfDplName() != null) {
        sffSfDplNode.put(_SF_DPL_NAME, sffSfDpl.getSfDplName().getValue());
    }

    if (sffSfDpl.getSffDplName() != null) {
        sffSfDplNode.put(_SFF_DPL_NAME, sffSfDpl.getSffDplName().getValue());
    }

    return sffSfDplNode;
}

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

public static void createRESTUser(String usrName, String pass, String roleName) {
    try {// www  .j  a v a2s  . co m
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/users?format=json");
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode mainNode = mapper.createObjectNode();
        //         ObjectNode childNode = mapper.createObjectNode();
        ArrayNode childArray = mapper.createArrayNode();
        mainNode.put("name", usrName);
        mainNode.put("description", "user discription");
        mainNode.put("password", pass);
        childArray.add(roleName);
        mainNode.put("role", childArray);
        //System.out.println(type + mainNode.path("range-element-indexes").path("range-element-index").toString());
        //            System.out.println(mainNode.toString());
        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(mainNode.toString()));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 400) {
            System.out.println("User already exist or a bad create request");
        } else if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        } else {
            System.out.print("No Proper Response");
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

From source file:org.roda.core.common.ClassificationPlanUtils.java

public static ConsumesOutputStream retrieveClassificationPlan(User user, String filename)
        throws RequestNotValidException, NotFoundException, GenericException, AuthorizationDeniedException {
    try {/*from  w w  w  .j a  v  a2 s  .  c o  m*/
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        ObjectNode root = mapper.createObjectNode();

        ArrayNode array = mapper.createArrayNode();
        List<String> descriptionsLevels = RodaUtils.copyList(
                RodaCoreFactory.getRodaConfiguration().getList(RodaConstants.LEVELS_CLASSIFICATION_PLAN));

        Filter allButRepresentationsFilter = new Filter(
                new OneOfManyFilterParameter(RodaConstants.AIP_LEVEL, descriptionsLevels));

        IndexService index = RodaCoreFactory.getIndexService();
        boolean justActive = true;
        IterableIndexResult<IndexedAIP> res = index.findAll(IndexedAIP.class, allButRepresentationsFilter, null,
                Sublist.ALL, user, justActive, new ArrayList<>());
        Iterator<IndexedAIP> it = res.iterator();
        while (it.hasNext()) {
            array.add(aipToJSON(it.next()));
        }

        root.set("dos", array);
        return new ConsumesOutputStream() {

            @Override
            public void consumeOutputStream(OutputStream out) throws IOException {
                try {
                    mapper.writeValue(out, root);
                } catch (IOException e) {
                    throw e;
                } finally {
                    IOUtils.closeQuietly(out);
                }

            }

            @Override
            public String getFileName() {
                return filename;
            }

            @Override
            public String getMediaType() {
                return RodaConstants.MEDIA_TYPE_APPLICATION_JSON;
            }

        };
    } catch (IOException e) {
        throw new GenericException(e);
    }
}