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

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

Introduction

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

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:org.mayocat.shop.front.views.WebViewMessageBodyWriter.java

@Override
public void writeTo(WebView webView, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    try {//ww  w  .ja va2  s  .  c  o m

        if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE) && webContext.getTheme() != null
                && !webContext.getTheme().isValidDefinition()) {
            // Fail fast with invalid theme error page, so that the developer knows ASAP and can correct it.
            writeHttpError("Invalid theme definition", entityStream);
            return;
        }

        Template masterTemplate = null;
        try {
            masterTemplate = themeFileResolver.getIndexTemplate(webContext.getRequest().getBreakpoint());
        } catch (TemplateNotFoundException e) {
            if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
                // For JSON API calls, we don't care if the template is found or not.
                // For other calls, raise the exception
                throw e;
            }
        }

        Template template = null;
        String jsonContext = null;

        if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
            if (webView.model().isPresent()) {
                // Check for a model

                Optional<String> path = themeFileResolver.resolveModelPath(webView.model().get());
                if (path.isPresent()) {
                    try {
                        template = themeFileResolver.getTemplate(path.get(),
                                webContext.getRequest().getBreakpoint());
                    } catch (TemplateNotFoundException e) {
                        // Keep going
                    }
                }
                // else just fallback on the default model
            }

            if (template == null) {
                try {
                    template = themeFileResolver.getTemplate(webView.template().toString(),
                            webContext.getRequest().getBreakpoint());
                } catch (TemplateNotFoundException e) {
                    if (webView.hasOption(WebView.Option.FALLBACK_ON_DEFAULT_THEME)) {
                        try {
                            template = themeFileResolver.getTemplate(themeManager.getDefaultTheme(),
                                    webView.template().toString(), webContext.getRequest().getBreakpoint());
                        } catch (TemplateNotFoundException e1) {
                            // continue
                        }
                    }
                    if (template == null && webView.hasOption(WebView.Option.FALLBACK_ON_GLOBAL_TEMPLATES)) {
                        template = themeFileResolver.getGlobalTemplate(webView.template().toString(),
                                webContext.getRequest().getBreakpoint());
                    }
                }
            }
        }

        if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)
                || httpHeaders.containsKey("X-Mayocat-Full-Context")) {
            if (template != null) {
                webView.data().put("templateContent", template.getId());
                webView.data().put("template", FilenameUtils.getBaseName(webView.template().toString()));
            }

            for (WebDataSupplier supplier : dataSuppliers.values()) {
                supplier.supply(webView.data());
            }
        }

        try {
            ObjectMapper mapper = new ObjectMapper();

            if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
                mapper.writeValue(entityStream, webView.data());
                return;
            }

            if (template == null) {
                throw new TemplateNotFoundException();
            }

            jsonContext = mapper.writeValueAsString(webView.data());
            engine.get().register(template);
            engine.get().register(masterTemplate);
            String rendered = engine.get().render(masterTemplate.getId(), jsonContext);
            entityStream.write(rendered.getBytes());
        } catch (JsonMappingException e) {
            this.logger.warn("Failed to serialize JSON context", e);
            writeDeveloperError(webView, e, entityStream);
        } catch (TemplateEngineException e) {
            writeDeveloperError(webView, e, entityStream);
        }
    } catch (TemplateNotFoundException e) {
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("Template not found : " + webView.template().toString()).build());
    }
}

From source file:nl.ortecfinance.opal.jacksonweb.SimulationResponseTest.java

@Test
public void testJsonIgnore() throws IOException {

    SimulationResponse resp = new SimulationResponse();

    resp.setCapitalGoalProbabilities(Arrays.asList(new Double(10), null, new Double(33)));

    StringWriter sr = new StringWriter();
    ObjectMapper om = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    //      module.addSerializer(List<Double[]>.class, new ListOfDoubleArraySerializer());
    module.addSerializer(Double[].class, new MyDoubleArraySerializer());
    om.registerModule(module);/*from ww w. j  a v a2s .c  o m*/
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    om.writeValue(sr, resp);

    System.out.println("SimulationResponse=" + sr);

}

From source file:org.dice_research.topicmodeling.lang.DictionaryDictCC.java

@Override
public void saveAsObjectFile() {
    if (localDictionaryChanged) {
        FileOutputStream fout = null;
        try {/*w  w  w. j  av a2  s  . c  om*/
            String filename = DICTIONARY_FILE_NAME;
            if (System.getProperty(SYSTEM_PROPERTY_NAME_FILE_APPENDIX) != null) {
                filename = filename.replace("$APPENDIX$",
                        System.getProperty(SYSTEM_PROPERTY_NAME_FILE_APPENDIX));
            } else {
                filename = filename.replace("$APPENDIX$", "");
            }
            fout = new FileOutputStream(filename);
            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new HppcModule());
            mapper.writeValue(fout, dictionary);
            localDictionaryChanged = false;
        } catch (IOException e) {
            LOGGER.error("Error while writing the serialized dictionary to file.", e);
        } finally {
            try {
                fout.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:net.roboconf.dm.rest.commons.json.JSonBindingUtilsTest.java

@Test
public void testInstanceBinding_5() throws Exception {

    final String result = "{\"name\":\"instance\",\"path\":\"/instance\",\"status\":\"NOT_DEPLOYED\",\"data\":{\"ip\":\"127.0.0.1\",\"any field\":\"some value\"}}";
    ObjectMapper mapper = JSonBindingUtils.createObjectMapper();

    Instance inst = new Instance("instance");
    inst.data.put("ip", "127.0.0.1");
    inst.data.put("any field", "some value");

    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, inst);
    String s = writer.toString();

    Assert.assertEquals(result, s);//  w  w w.  j  a  v a2 s  .c  o  m
}

From source file:org.wildfly.swarm.plugin.fractionlist.FractionListMojo.java

protected void generateJavascript(Set<FractionMetadata> fractions) {
    ObjectMapper mapper = new ObjectMapper();

    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

    File outFile = new File(this.project.getBuild().getOutputDirectory(), "fraction-list.js");

    try (FileWriter writer = new FileWriter(outFile)) {

        writer.write("fractionList = ");
        writer.flush();//from ww  w.j a v a  2 s  .c om

        mapper.writeValue(writer, fractions);

        writer.write(";");
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    org.apache.maven.artifact.DefaultArtifact artifact = new org.apache.maven.artifact.DefaultArtifact(
            this.project.getGroupId(), this.project.getArtifactId(), this.project.getVersion(), "compile", "js",
            "", new DefaultArtifactHandler("js"));

    artifact.setFile(outFile);
    this.project.addAttachedArtifact(artifact);
}

From source file:com.kinglcc.spring.jms.core.converter.Jackson2JmsMessageConverter.java

/**
 * Map the given object to a {@link TextMessage}.
 * @param object the object to be mapped
 * @param session current JMS session/* w w w.  j a  va  2  s . co m*/
 * @param objectMapper the mapper to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @see Session#createBytesMessage
 */
protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper)
        throws JMSException, IOException {

    StringWriter writer = new StringWriter();
    objectMapper.writeValue(writer, object);
    return session.createTextMessage(writer.toString());
}

From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java

@Test
public void writeBinaryData() throws Exception {
    byte[] binary = new byte[] { (byte) 0x05, (byte) 0xff, (byte) 0xaf, (byte) 0x30, 'A', 'B', 'C', (byte) 0x13,
            (byte) 0x80, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };

    Map<String, Object> data = new LinkedHashMap<String, Object>();
    data.put("binary", binary);

    //binary data has to be converted to base64 with normal JSON
    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(data);
    assertEquals("{\"binary\":\"Bf+vMEFCQxOA/////w==\"}", jsonString);

    //with BSON we don't have to convert to base64
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    ObjectMapper om = new ObjectMapper(bsonFactory);
    om.writeValue(baos, data);

    //document header (4 bytes) + type (1 byte) + field_name ("binary", 6 bytes) +
    //end_of_string (1 byte) + binary_size (4 bytes) + subtype (1 byte) +
    //binary_data (13 bytes) + end_of_document (1 byte)
    int expectedLen = 4 + 1 + 6 + 1 + 4 + 1 + 13 + 1;

    assertEquals(expectedLen, baos.size());

    //BSON is smaller than JSON (at least in this case)
    assertTrue(baos.size() < jsonString.length());

    //test if binary data can be parsed
    BSONObject obj = generateAndParse(data);
    byte[] objbin = (byte[]) obj.get("binary");
    assertArrayEquals(binary, objbin);//from   w  w  w.j  a  v a  2  s.  c  om
}

From source file:com.github.jasonruckman.lz4.AbstractBenchmark.java

private void initializeJackson() {
    try {/*  w  w w  . ja  v  a2s  .c  om*/
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        LZ4BlockOutputStream gzos = new LZ4BlockOutputStream(baos);
        mapper.writeValue(gzos, sampleData);
        gzos.close();
        serializedJacksonData = baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:guru.nidi.raml.doc.servlet.MirrorServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final int delay = req.getParameter("delay") == null ? 0 : Integer.parseInt(req.getParameter("delay"));
    try {/*w w  w.  j  a v a  2 s .  c  o m*/
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        //ignore
    }
    final String q = req.getParameter("q") == null ? "" : req.getParameter("q");
    if (q.equals("png")) {
        final ServletOutputStream out = res.getOutputStream();
        res.setContentType("image/png");
        copy(getClass().getClassLoader().getResourceAsStream("data/google.png"), out);
    } else {
        final PrintWriter out = res.getWriter();
        switch (q) {
        case "html":
            res.setContentType("text/html");
            out.print("<html><body><ul>");
            for (int i = 0; i < 50; i++) {
                out.println("<li>" + i + "</li>");
            }
            out.print("</ul></body></html>");
            break;
        case "json":
            res.setContentType("application/json");
            final ObjectMapper mapper = new ObjectMapper();
            final Map<String, Object> map = new HashMap<>();
            map.put("method", req.getMethod());
            map.put("url", req.getRequestURL().toString());
            map.put("headers", headers(req));
            map.put("query", query(req));
            mapper.writeValue(out, map);
            break;
        case "error":
            res.sendError(500, "Dummy error message");
            break;
        default:
            out.println(req.getMethod() + " " + req.getRequestURL());
            headers(req, out);
            query(req, out);
            copy(req.getReader(), out);
        }
    }
    res.flushBuffer();
}

From source file:org.freeinternals.javaclassviewer.ui.JSplitPaneClassFile.java

/**
 * Creates a split panel from a Java class file byte array.
 * /*  www . j  a  v  a2 s  .c  o m*/
 * @param byteArray
 *            Java class file byte array
 */
public JSplitPaneClassFile(final byte[] byteArray, JFrame top) {
    try {
        this.classFile = new ClassFile(byteArray.clone());
    } catch (IOException | FileFormatException ex) {
        Logger.getLogger(JSplitPaneClassFile.class.getName()).log(Level.SEVERE, null, ex);
    }

    ObjectMapper mapper = new ObjectMapper();
    // or:
    //      byte[] jsonBytes = mapper.writeValueAsBytes(classFile);
    String jsonString;
    try {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(new File("f:\\result.json"), classFile);
        //jsonString = mapper.writeValueAsString(classFile);
        //System.out.println(jsonString);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    this.createAndShowGUI(top);
    this.generateClassReport();
}