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

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

Introduction

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

Prototype

public ObjectWriter writer() 

Source Link

Document

Convenience method for constructing ObjectWriter with default settings.

Usage

From source file:capital.scalable.restdocs.payload.AbstractJacksonFieldSnippet.java

protected Collection<FieldDescriptor> createFieldDescriptors(Operation operation, HandlerMethod handlerMethod) {
    ObjectMapper objectMapper = getObjectMapper(operation);
    ObjectWriter writer = objectMapper.writer();
    TypeFactory typeFactory = objectMapper.getTypeFactory();

    JavadocReader javadocReader = getJavadocReader(operation);
    ConstraintReader constraintReader = getConstraintReader(operation);

    Map<String, FieldDescriptor> fieldDescriptors = new LinkedHashMap<>();

    Type signatureType = getType(handlerMethod);
    if (signatureType != null) {
        try {//  w  w  w  .j a  v a2  s.  c  o m
            for (Type type : resolveActualTypes(signatureType)) {
                resolveFieldDescriptors(fieldDescriptors, type, writer, typeFactory, javadocReader,
                        constraintReader);
            }
        } catch (JsonMappingException e) {
            throw new JacksonFieldProcessingException("Error while parsing fields", e);
        }
    }

    return fieldDescriptors.values();
}

From source file:com.auth0.api.internal.SimpleRequest.java

public SimpleRequest(Handler handler, HttpUrl url, OkHttpClient client, ObjectMapper mapper,
        String httpMethod) {/*  w  ww.  j  a  va 2  s  .  c o m*/
    super(handler, url, client, mapper.reader(new TypeReference<Map<String, Object>>() {
    }), mapper.writer());
    this.errorReader = mapper.reader(new TypeReference<Map<String, Object>>() {
    });
    this.method = httpMethod;
}

From source file:org.usd.edu.btl.cli.ConvertBld.java

public void toBets(String inputS, String output) {
    ObjectMapper bldMapper = new ObjectMapper(); //create new Jackson Mapper
    File input = new File(inputS);

    BLDV1 bldTool; //create new seqTool
    ObjectWriter oW = bldMapper.writer().withDefaultPrettyPrinter();
    try {//  www .j  a  v a2 s  .  co  m
        //map input json files to iplant class
        bldTool = bldMapper.readValue(input, BLDV1.class);
        //            String seqInputJson = oW.writeValueAsString(bldTool); //write Json as String
        //            System.out.println("=====BLD INPUT FILE =====");
        //            System.out.println(seqInputJson);

        BETSV1 betsOutput = BLDConverter.toBETS(bldTool);
        String betsOutputJson = oW.writeValueAsString(betsOutput); //write Json as String
        if (output == null) {
            /*===============PRINT JSON TO CONSOLE AND FILES =================== */
            System.err.println("************************************************\n"
                    + "*********PRINTING OUT FIRST CONVERSION************\n"
                    + "--------------Seq --> BETS--------------\n"
                    + "************************************************\n");
            //print objects as Json using jackson

            System.err.println("=== BLD TO BETS JSON - OUTPUT === \n");
            System.out.println(betsOutputJson);
        } else {
            System.err.println("Writing to file...");
            //write to files
            oW.writeValue(new File(output), betsOutput);
            System.err.println(output + " has been created successfully");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.streamsets.datacollector.websockets.LogMessageWebSocket.java

@Override
public void onWebSocketConnect(final Session session) {
    super.onWebSocketConnect(session);

    synchronized (LogMessageWebSocket.class) {
        int maxClients = config.get(MAX_LOGTAIL_CONCURRENT_REQUESTS_KEY,
                MAX_LOGTAIL_CONCURRENT_REQUESTS_DEFAULT);
        if (logTailClients < maxClients) {
            logTailClients++;/*from   w w w .j  a  v a2s. c  om*/
        } else {
            session.close(StatusCode.NORMAL, "Maximum concurrent connections reached");
            return;
        }
    }

    TailerListener listener = new TailerListenerAdapter() {
        @Override
        public void handle(String line) {
            try {
                Map<String, String> namedGroupToValuesMap = logFileGrok.extractNamedGroups(line);

                if (namedGroupToValuesMap == null) {
                    namedGroupToValuesMap = new HashMap<>();
                    namedGroupToValuesMap.put("exceptionMessagePart", line);
                }

                ObjectMapper objectMapper = ObjectMapperFactory.get();
                String logDataJson = objectMapper.writer().writeValueAsString(namedGroupToValuesMap);
                session.getRemote().sendString(logDataJson);

            } catch (IOException ex) {
                LOG.warn("Error while sending log line through WebSocket message, {}", ex.toString(), ex);
            }
        }

        @Override
        public void fileNotFound() {
            LOG.warn("Log file '{}' does not exist", logFile);
        }

        @Override
        public void handle(Exception ex) {
            LOG.warn("Error while trying to read log file '{}': {}", logFile, ex.toString(), ex);
        }
    };

    //TODO send -20K of logFile to session, separator line, then tailer

    tailer = new Tailer(new File(logFile), listener, 100, true, true);
    Thread thread = new Thread(tailer, "LogMessageWebSocket-tailLog");
    thread.setDaemon(true);
    thread.start();
}

From source file:org.geppetto.simulator.jlems.test.JLEMSSimulatorServiceTest.java

/**
 * Test method for {@link org.geppetto.simulator.jlems.JLEMSSimulatorService#getWatchableVariables()}.
 * @throws Exception /*from w w  w  . j a v  a  2s  .  c  o m*/
 */
@Test
public void testGetWatchableVariables() throws Exception {
    setup();
    JLEMSSimulatorService simulator = new JLEMSSimulatorService();
    simulator.setRunConfig(_runConfig);
    simulator.setWatchableVariables();

    SimpleType ft = DataModelFactory.getSimpleType(SimpleType.Type.FLOAT);

    SimpleVariable mq = DataModelFactory.getSimpleVariable("q", ft);
    SimpleVariable hq = DataModelFactory.getSimpleVariable("q", ft);
    StructuredType m = DataModelFactory.getStructuredType("mT");
    m.getVariables().add(mq);
    StructuredType h = DataModelFactory.getStructuredType("hT");
    h.getVariables().add(hq);
    SimpleVariable nq = DataModelFactory.getSimpleVariable("q", ft);
    StructuredType n = DataModelFactory.getStructuredType("nT");
    n.getVariables().add(nq);

    StructuredType na = DataModelFactory.getStructuredType("naT");
    na.getVariables().add(DataModelFactory.getSimpleVariable("m", m));
    na.getVariables().add(DataModelFactory.getSimpleVariable("h", h));

    StructuredType k = DataModelFactory.getStructuredType("kT");
    k.getVariables().add(DataModelFactory.getSimpleVariable("n", n));

    StructuredType naChans = DataModelFactory.getStructuredType("naChansT");
    naChans.getVariables().add(DataModelFactory.getSimpleVariable("na", na));

    StructuredType kChans = DataModelFactory.getStructuredType("kChansT");
    kChans.getVariables().add(DataModelFactory.getSimpleVariable("k", k));

    StructuredType membraneProperties = DataModelFactory.getStructuredType("membranePropertiesT");
    membraneProperties.getVariables().add(DataModelFactory.getSimpleVariable("naChans", naChans));
    membraneProperties.getVariables().add(DataModelFactory.getSimpleVariable("kChans", kChans));

    StructuredType bioPhys1 = DataModelFactory.getStructuredType("bioPhys1T");
    bioPhys1.getVariables().add(DataModelFactory.getSimpleVariable("membraneProperties", membraneProperties));

    StructuredType hhpop = DataModelFactory.getStructuredType("hhpopT");
    hhpop.getVariables().add(DataModelFactory.getSimpleVariable("bioPhys1", bioPhys1));
    hhpop.getVariables().add(DataModelFactory.getSimpleVariable("v", ft));

    VariableList expectedList = new VariableList();
    expectedList.getVariables().add(DataModelFactory.getArrayVariable("hhpop", hhpop, 1));

    ObjectMapper mapper = new ObjectMapper();

    Assert.assertEquals(mapper.writer().writeValueAsString(expectedList),
            mapper.writer().writeValueAsString(simulator.getWatchableVariables()));
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdJob.java

/**
 * Serialize the template to a JSON string
 * @return//  w  w  w  .  jav a2  s.  c  o m
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */

String getTemplateAsString() throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    return writer.writeValueAsString(template);
}

From source file:tachyon.master.InodeFolderTest.java

@Test
public void writeImageTest() throws IOException {
    // create the InodeFolder and the output streams
    long creationTime = System.currentTimeMillis();
    InodeFolder inode1 = new InodeFolder("test1", 1, 0, creationTime);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    ObjectMapper mapper = JsonObject.createObjectMapper();
    ObjectWriter writer = mapper.writer();

    // write the image
    inode1.writeImage(writer, dos);/*from ww  w  . j a v a2  s.  c  o  m*/

    // decode the written bytes
    ImageElement decoded = mapper.readValue(os.toByteArray(), ImageElement.class);

    // test the decoded ImageElement
    Assert.assertEquals(creationTime, decoded.getLong("creationTimeMs").longValue());
    Assert.assertEquals(1, decoded.getInt("id").intValue());
    Assert.assertEquals("test1", decoded.getString("name"));
    Assert.assertEquals(0, decoded.getInt("parentId").intValue());
    Assert.assertEquals(new ArrayList<Integer>(),
            decoded.get("childrenIds", new TypeReference<List<Integer>>() {
            }));
    Assert.assertEquals(creationTime, decoded.getLong("lastModificationTimeMs").longValue());
}

From source file:net.riezebos.thoth.renderers.RendererBase.java

protected void executeJson(Map<String, Object> variables, OutputStream outputStream) throws ServletException {
    try {//from  www. ja va 2 s.c  om
        boolean prettyPrintJson = getConfiguration().isPrettyPrintJson();
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = prettyPrintJson ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer();
        writer.writeValue(outputStream, variables);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:jenkins.metrics.api.MetricsRootAction.java

/**
 * Utility wrapper to construct the writer to use for a {@link HttpServletResponse} based on the
 * {@link HttpServletRequest}.//from  www  . j  a  va2 s.c o m
 *
 * @param mapper  the {@link ObjectMapper} to use.
 * @param request the {@link HttpServletRequest} to respond to.
 * @return the {@link ObjectWriter} to use for the response.
 */
private static ObjectWriter getWriter(ObjectMapper mapper, HttpServletRequest request) {
    final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty"));
    if (prettyPrint) {
        return mapper.writerWithDefaultPrettyPrinter();
    }
    return mapper.writer();
}

From source file:cn.org.once.cstack.volumes.VolumeControllerTestIT.java

private String getString(VolumeResource volumeResource, ObjectMapper mapper) throws JsonProcessingException {
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    return ow.writeValueAsString(volumeResource);
}