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

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

Introduction

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

Prototype

public ObjectMapper enable(SerializationFeature f) 

Source Link

Document

Method for enabling specified DeserializationConfig feature.

Usage

From source file:it.uniroma2.sag.kelp.linearization.nystrom.NystromMethod.java

/**
 * Save a Nystrom-based projection function in a file. If the .gz suffix is
 * used a compressed file is obtained//from w  ww. ja va2  s. co  m
 * 
 * @param outputFilePath
 *            the output file path
 * @throws FileNotFoundException
 * @throws IOException
 */
public void save(String outputFilePath) throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    OutputStreamWriter out = new OutputStreamWriter(FileUtils.createOutputStream(outputFilePath), "utf8");
    mapper.writeValue(out, this);
    out.close();
}

From source file:org.eclipse.winery.bpmn2bpel.parser.Bpmn4JsonParser.java

@Override
public ManagementFlow parse(URI jsonFileUrl) throws ParseException {

    try {/*from w  ww . ja va  2 s .co m*/
        // general method, same as with data binding
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        // (note: can also use more specific type, like ArrayNode or
        // ObjectNode!)
        JsonNode rootNode = mapper.readValue(jsonFileUrl.toURL(), JsonNode.class);

        String prettyPrintedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
        log.debug("Creating management flow from following Json model:" + prettyPrintedJson);

        ManagementFlow managementFlow = new ManagementFlow();
        /* Contains the ids (values) of the target nodes of a certain node
         * (key is node id of this node) */
        Map<String, Set<String>> nodeWithTargetsMap = new HashMap<String, Set<String>>();

        /* Create model objects from Json nodes */
        log.debug("Creating node models...");
        Iterator<JsonNode> iter = rootNode.iterator();
        while (iter.hasNext()) {
            JsonNode jsonNode = (JsonNode) iter.next();

            /*
             * As top level elements just start events, end events and
             * management tasks expected which are transformed to tasks in
             * our management model
             */
            Task task = createTaskFromJson(jsonNode);
            /*
             * Task may be null if it could not be created due to missing or
             * incorrect fields/values in the Json node
             */
            if (task != null) {
                managementFlow.addVertex(task);

                // TODO GATEWAAAAYYYYSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
                // !!!!!!!!!!!!!!!!!!

                /*
                 * To create the links later, relate the id of the created
                 * node with its direct successor nodes
                 */
                nodeWithTargetsMap.put(task.getId(), extractNodeTargetIds(jsonNode));
            } else {
                String ignoredJsonNode = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
                log.warn(
                        "No model element could be created from following node due to missing or invalid keys/values :"
                                + ignoredJsonNode);
            }
        }

        /*
         * Now since all node models are created they can be linked with each other in the management flow
         */
        log.debug("Building management flow by relating node models...");
        Iterator<Map.Entry<String, Set<String>>> nodeWithTargetsMapIter = nodeWithTargetsMap.entrySet()
                .iterator();
        while (nodeWithTargetsMapIter.hasNext()) {
            Map.Entry<String, Set<String>> inputParamEntry = (Map.Entry<String, Set<String>>) nodeWithTargetsMapIter
                    .next();
            String srcNodeId = inputParamEntry.getKey();
            Node srcNode = managementFlow.getNode(srcNodeId);
            if (srcNode == null) {
                throw new Exception(
                        "Node with id '" + srcNodeId + "' could not be found in the management flow.");
            }

            /* Relate the source node with its link targets */
            Iterator<String> nodeTargetIdsIter = inputParamEntry.getValue().iterator();
            while (nodeTargetIdsIter.hasNext()) {
                String targetNodeId = (String) nodeTargetIdsIter.next();
                Node targetNode = managementFlow.getNode(targetNodeId);
                if (targetNode == null) {
                    throw new Exception(
                            "Node with id '" + targetNodeId + "' could not be found in the management flow.");
                }

                log.debug("Creating link between node with id '" + srcNodeId + "' and target node with id '"
                        + targetNodeId + "'");
                managementFlow.addEdge(srcNode, targetNode);
            }
        }

        return managementFlow;

    } catch (Exception e) {
        log.error("Error while creating management flow : " + e.getMessage());
        throw new ParseException(e);
    }

}

From source file:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java

public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException {

    request.request.technicalUser.username = this.user;
    request.request.technicalUser.password = this.password;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, request);/*from  www. j a  v  a  2s .c om*/

    String requestJson = sw.getBuffer().toString();

    logger.debug("callWebService(): jsonRequest:" + requestJson);

    URL url = new URL(this.endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(requestJson.getBytes("UTF-8"));
    out.flush();
    int responseCode = conn.getResponseCode();

    InputStream input = conn.getInputStream();

    ByteArrayOutputStream data = new ByteArrayOutputStream();
    int len;
    byte[] buf = new byte[50000];
    while ((len = input.read(buf)) > 0) {
        data.write(buf, 0, len);
    }
    conn.disconnect();
    String jsonResponse = new String(data.toByteArray(), "UTF-8");

    if (responseCode != 200) {
        throw new IOException(jsonResponse);
    }

    logger.debug("callWebService(): jsonResponse:" + jsonResponse);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    T response = mapper.readValue(new StringReader(jsonResponse), clazz);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    sw = new StringWriter();
    mapper.writeValue(sw, response);
    logger.debug(
            "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString());

    return response;
}

From source file:org.dswarm.graph.gdm.test.GDMResource3Test.java

private void readGDMFromDBThatWasWrittenAsGDM(final Optional<ObjectNode> optionalContentSchemaRequestJSON,
        final String resourcePathV1, final String resourcePathV2, final String dataModelURI,
        final String recordClassURI, final long statementCountCurrentVersion, final long statementCountV1,
        final boolean deprecateMissingRecords, final Optional<String> optionalRecordClassUri)
        throws IOException {

    LOG.debug("start read test for GDM resource at {} DB", dbType);

    writeGDMToDBInternal(dataModelURI, resourcePathV1);
    writeGDMToDBInternalWithContentSchema(resourcePathV2, dataModelURI, optionalContentSchemaRequestJSON,
            deprecateMissingRecords, optionalRecordClassUri);

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    requestJson.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    final String requestJsonString = objectMapper.writeValueAsString(requestJson);

    // POST the request
    final ClientResponse response = target().path("/get").type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, requestJsonString);

    Assert.assertEquals("expected 200", 200, response.getStatus());

    final InputStream actualResult = response.getEntity(InputStream.class);
    final BufferedInputStream bis = new BufferedInputStream(actualResult, 1024);
    final ModelParser modelParser = new ModelParser(bis);
    final org.dswarm.graph.json.Model model = new org.dswarm.graph.json.Model();

    final Observable<Void> parseObservable = modelParser.parse().map(resource1 -> {

        model.addResource(resource1);// w ww. j a  v a  2 s  .c  o  m

        return null;
    });

    final Iterator<Void> iterator = parseObservable.toBlocking().getIterator();

    Assert.assertTrue(iterator.hasNext());

    while (iterator.hasNext()) {

        iterator.next();
    }

    bis.close();
    actualResult.close();

    LOG.debug("read '{}' statements", model.size());

    Assert.assertEquals("the number of statements should be " + statementCountCurrentVersion,
            statementCountCurrentVersion, model.size());

    // read first version
    final ObjectNode requestJson2 = objectMapper.createObjectNode();

    requestJson2.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI);
    requestJson2.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);
    requestJson2.put(DMPStatics.VERSION_IDENTIFIER, 1);

    final String requestJsonString2 = objectMapper.writeValueAsString(requestJson2);

    // POST the request
    final ClientResponse response2 = target().path("/get").type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, requestJsonString2);

    Assert.assertEquals("expected 200", 200, response2.getStatus());

    final InputStream actualResult2 = response2.getEntity(InputStream.class);
    final BufferedInputStream bis2 = new BufferedInputStream(actualResult2, 1024);
    final ModelParser modelParser2 = new ModelParser(bis2);
    final org.dswarm.graph.json.Model model2 = new org.dswarm.graph.json.Model();

    final Observable<Void> parseObservable2 = modelParser2.parse().map(resource1 -> {

        model2.addResource(resource1);

        return null;
    });

    final Iterator<Void> iterator2 = parseObservable2.toBlocking().getIterator();

    Assert.assertTrue(iterator2.hasNext());

    while (iterator2.hasNext()) {

        iterator2.next();
    }

    bis2.close();
    actualResult2.close();

    LOG.debug("read '{}' statements", model2.size());

    Assert.assertEquals("the number of statements should be " + statementCountV1, statementCountV1,
            model2.size());

    LOG.debug("finished read test for GDM resource at {} DB", dbType);
}

From source file:com.hurence.logisland.serializer.JsonSerializer.java

@Override
public void serialize(OutputStream out, Record record) throws RecordSerializationException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(StandardRecord.class, new EventSerializer());
    mapper.registerModule(module);//from  ww w .j  a v  a  2 s.c  om

    //map json to student

    try {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        String jsonString = mapper.writeValueAsString(record);

        out.write(jsonString.getBytes());
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:jeplus.JEPlusConfig.java

/**
 * Save this configuration to a JSON file
 * @param file The File object associated with the file to which the contents will be saved
 * @return Successful or not//from   w  ww. j av a  2s  .  c  o m
 */
public boolean saveAsJSON(File file) {
    boolean success = true;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(format);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try (FileOutputStream fw = new FileOutputStream(file);) {
        mapper.writeValue(fw, this);
        logger.info("Configuration saved to " + file.getAbsolutePath());
    } catch (Exception ex) {
        logger.error("Error saving configuration to JSON.", ex);
        success = false;
    }
    return success;
}

From source file:org.dswarm.graph.gdm.test.GDMResource4Test.java

@Test
public void readGDMRecordByURIFromDBThatWasWrittenAsGDM() throws IOException {

    LOG.debug("start read GDM record by URI test for GDM resource at {} DB", dbType);

    writeGDMToDBInternal(DATA_MODEL_URI, MABXML_RESOURCE_GSON);

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    final String recordURI = "http://data.slub-dresden.de/records/e9e1fa5a-3350-43ec-bb21-6ccfa90a4497";

    requestJson.put(DMPStatics.RECORD_URI_IDENTIFIER, recordURI);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, DATA_MODEL_URI);

    final Resource actualResource = readGDMRecord(requestJson, 191);

    Assert.assertEquals(recordURI, actualResource.getUri());

    LOG.debug("finished read GDM record by URI test for GDM resource at {} DB", dbType);
}

From source file:org.dswarm.graph.gdm.test.GDMResource4Test.java

@Test
public void readGDMRecordByIDFromDBThatWasWrittenAsGDM() throws IOException {

    LOG.debug("start read GDM record by ID test for GDM resource at {} DB", dbType);

    final String dataModelURI = "http://data.slub-dresden.de/resources/11111";

    writeGDMToDBInternal(dataModelURI, "versioning/csv.gdm.v1.json");

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    final String recordID = "1234";
    final String recordURI = "http://data.slub-dresden.de/datamodels/DataModel-574990f5-4785-4020-b86a-9765bb084f16/records/5f7019a6-96e3-4aae-aaac-da743e2840b9";
    final String legacyRecordIdentifierAP = "http://data.slub-dresden.de/resources/1/schema#id";

    requestJson.put(DMPStatics.RECORD_ID_IDENTIFIER, recordID);
    requestJson.put(DMPStatics.LEGACY_RECORD_IDENTIFIER_ATTRIBUTE_PATH, legacyRecordIdentifierAP);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    final Resource actualResource = readGDMRecord(requestJson, 6);

    Assert.assertEquals(recordURI, actualResource.getUri());

    LOG.debug("finished read GDM record by ID test for GDM resource at {} DB", dbType);
}

From source file:org.dswarm.graph.gdm.test.GDMResource4Test.java

@Test
public void searchGDMRecordFromDBThatWasWrittenAsGDM1() throws IOException {

    LOG.debug("start search GDM records test 1 for GDM resource at {} DB", dbType);

    final String dataModelURI = "http://data.slub-dresden.de/resources/4444";

    writeGDMToDBInternal(dataModelURI, MABXML_RESOURCE_GSON);

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    final String recordURI = "http://data.slub-dresden.de/records/e9e1fa5a-3350-43ec-bb21-6ccfa90a4497";
    final String keyAP = "http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feld\u001Ehttp://www.w3.org/1999/02/22-rdf-syntax-ns#value";
    final String searchValue = "06978834";

    requestJson.put(DMPStatics.KEY_ATTRIBUTE_PATH_IDENTIFIER, keyAP);
    requestJson.put(DMPStatics.SEARCH_VALUE_IDENTIFIER, searchValue);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    final Model actualModel = searchGDMRecords(requestJson, 191);

    Assert.assertEquals(recordURI, actualModel.getResources().iterator().next().getUri());

    LOG.debug("finished search GDM records test 1 for GDM resource at {} DB", dbType);
}

From source file:org.dswarm.graph.gdm.test.GDMResource4Test.java

@Test
public void searchGDMRecordFromDBThatWasWrittenAsGDM2() throws IOException {

    LOG.debug("start search GDM records test 2 for GDM resource at {} DB", dbType);

    final String dataModelURI = "http://data.slub-dresden.de/resources/5555";

    writeGDMToDBInternal(dataModelURI, "versioning/csv.gdm.v1.json");

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    final String recordURI = "http://data.slub-dresden.de/datamodels/DataModel-574990f5-4785-4020-b86a-9765bb084f16/records/cb31b25a-7aff-4b1d-a308-91be2fa2cc37";
    final String keyAP = "http://data.slub-dresden.de/resources/1/schema#name";
    final String searchValue = "foo";

    requestJson.put(DMPStatics.KEY_ATTRIBUTE_PATH_IDENTIFIER, keyAP);
    requestJson.put(DMPStatics.SEARCH_VALUE_IDENTIFIER, searchValue);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    final Model actualModel = searchGDMRecords(requestJson, 6);

    Assert.assertEquals(recordURI, actualModel.getResources().iterator().next().getUri());

    LOG.debug("finished search GDM records test 2 for GDM resource at {} DB", dbType);
}