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:fll.web.developer.QueryHandler.java

@SuppressFBWarnings(value = {
        "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE" }, justification = "Executing query from user")
@Override/*  ww  w  . j  av a 2s .c  o m*/
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    final List<String> columnNames = new LinkedList<String>();
    final List<Map<String, String>> data = new LinkedList<Map<String, String>>();
    String error = null;

    DataSource datasource = ApplicationAttributes.getDataSource(application);
    Statement stmt = null;
    ResultSet rs = null;
    Connection connection = null;
    try {
        connection = datasource.getConnection();
        final String query = request.getParameter(QUERY_PARAMETER);
        stmt = connection.createStatement();
        rs = stmt.executeQuery(query);

        ResultSetMetaData meta = rs.getMetaData();
        for (int columnNum = 1; columnNum <= meta.getColumnCount(); ++columnNum) {
            columnNames.add(meta.getColumnName(columnNum).toLowerCase());
        }
        while (rs.next()) {
            final Map<String, String> row = new HashMap<String, String>();
            for (final String columnName : columnNames) {
                final String value = rs.getString(columnName);
                row.put(columnName, value);
            }
            data.add(row);
        }

    } catch (final SQLException e) {
        error = e.getMessage();
        LOGGER.error("Exception doing developer query", e);
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(stmt);
        SQLFunctions.close(connection);
    }

    response.setContentType("application/json");
    response.setCharacterEncoding(Utilities.DEFAULT_CHARSET.name());

    final ResultData result = new ResultData(columnNames, data, error);
    final ObjectMapper jsonMapper = new ObjectMapper();
    final Writer writer = response.getWriter();

    jsonMapper.writeValue(writer, result);
}

From source file:io.seldon.api.interceptor.GenericScopedInterceptor.java

protected void exceptionResponse(HttpServletRequest request, HttpServletResponse response, APIException e)
        throws IOException {
    ErrorBean bean = new ErrorBean(e);
    logger.error("GenericScopedInterceptor#exceptionResponse: " + e.getMessage(), e);
    final ObjectMapper objectMapper = new ObjectMapper();
    response.setContentType("application/json");
    objectMapper.writeValue(response.getOutputStream(), bean);
}

From source file:jp.or.openid.eiwg.scim.servlet.ServiceProviderConfigs.java

/**
 * GET?//from   w w  w  .j a  v a2s . c om
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // [draft-ietf-scim-api-13 3.2.2.1. Query Endpoints]
        //  Queries MAY be performed against a SCIM resource object, a resource
        //  type endpoint, or a SCIM server root.

        // ServiceProviderConfigs ??????????

        // location?URL?
        String location = request.getScheme() + "://" + request.getServerName();
        int serverPort = request.getServerPort();
        if (serverPort != 80 && serverPort != 443) {
            location += ":" + Integer.toString(serverPort);
        }
        location += request.getContextPath();

        // ??
        @SuppressWarnings("unchecked")
        Map<String, Object> serviceProviderConfigsObject = (Map<String, Object>) context
                .getAttribute("ServiceProviderConfigs");

        try {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, serviceProviderConfigsObject);
            String serviceProviderConfigs = writer.toString();
            serviceProviderConfigs = String.format(serviceProviderConfigs, location);

            response.setContentType("application/scim+json;charset=UTF-8");
            response.setHeader("Location", request.getRequestURL().toString());
            PrintWriter out = response.getWriter();
            out.println(serviceProviderConfigs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.datacleaner.monitor.server.media.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    clearSession(req);/*  w  w  w .ja  v a 2  s . c om*/

    File tempFolder = FileHelper.getTempDir();
    try {
        File subDirectory = new File(tempFolder, ".datacleaner_upload");
        if (subDirectory.mkdirs()) {
            tempFolder = subDirectory;
        }
    } catch (Exception e) {
        logger.warn("Could not create subdirectory in temp folder", e);
    }

    final FileItemFactory fileItemFactory = new DiskFileItemFactory(0, tempFolder);
    final ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    servletFileUpload.setFileSizeMax(FILE_SIZE_MAX);
    servletFileUpload.setSizeMax(REQUEST_SIZE_MAX);

    final List<Object> resultFileElements = new ArrayList<Object>();
    final HttpSession session = req.getSession();

    try {
        int index = 0;
        @SuppressWarnings("unchecked")
        final List<DiskFileItem> items = servletFileUpload.parseRequest(req);
        for (DiskFileItem item : items) {
            if (item.isFormField()) {
                logger.warn("Ignoring form field in request: {}", item);
            } else {
                final String sessionKey = "file_upload_" + index;
                final File file = item.getStoreLocation();

                String filename = toFilename(item.getName());
                logger.info("File '{}' uploaded to temporary location: {}", filename, file);

                session.setAttribute(sessionKey, file);

                final Map<String, String> resultItem = new LinkedHashMap<String, String>();
                resultItem.put("field_name", item.getFieldName());
                resultItem.put("file_name", filename);
                resultItem.put("content_type", item.getContentType());
                resultItem.put("size", Long.toString(item.getSize()));
                resultItem.put("session_key", sessionKey);

                resultFileElements.add(resultItem);

                index++;
            }
        }
    } catch (FileUploadException e) {
        logger.error("Unexpected file upload exception: " + e.getMessage(), e);
        throw new IOException(e);
    }

    final String contentType = req.getParameter("contentType");
    if (contentType == null) {
        resp.setContentType("application/json");
    } else {
        resp.setContentType(contentType);
    }

    final Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    resultMap.put("status", "success");
    resultMap.put("files", resultFileElements);

    // write result as JSON
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValue(resp.getOutputStream(), resultMap);
}

From source file:de.javagl.jgltf.model.io.GltfWriter.java

/**
 * Write the given {@link GlTF} to the given output stream. The caller
 * is responsible for closing the stream.
 * /*  w w  w  .j a  v  a2s . c o m*/
 * @param gltf The {@link GlTF}
 * @param outputStream The output stream
 * @throws IOException If an IO error occurred
 */
public void writeGltf(GlTF gltf, OutputStream outputStream) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    if (indenting) {
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    }
    objectMapper.writeValue(outputStream, gltf);
}

From source file:edu.usu.sdl.opencatalog.web.extension.OpenCatalogExceptionHandler.java

public Resolution handleAll(Throwable error, HttpServletRequest request, HttpServletResponse response) {
    ActionBean action = (ActionBean) request.getAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN);

    //TODO: Generate Error Ticket
    // Capture all request information, stacktraces, user info
    if (action != null) {

    }//  w w w  . j  a v a  2 s .c  om

    //Strip and senstive info (See Checklist Q: 410)

    systemErrorModel.setMessage(error.getLocalizedMessage());

    final ObjectMapper objectMapper = new ObjectMapper();
    return new StreamingResolution(MediaType.APPLICATION_JSON) {

        @Override
        protected void stream(HttpServletResponse response) throws Exception {
            objectMapper.writeValue(response.getOutputStream(), systemErrorModel);
        }
    };
}

From source file:ijfx.service.history.HistoryService.java

public boolean saveWorkflow(String path, Workflow workflow) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new WorkflowMapperModule());
    try {//from ww  w  .j a  v a2s  .c  om
        mapper.writeValue(new File(path), workflow);
        return true;
    } catch (IOException ex) {
        ImageJFX.getLogger().log(Level.SEVERE,
                "Error when saving worflow. It's possible you don't have the permission.", ex);
        ;
    }
    return false;
}

From source file:com.kylinolap.rest.service.UserService.java

private byte[] serialize(Collection<? extends GrantedAuthority> auths) {
    if (null == auths) {
        return null;
    }/* w  w  w .  ja v  a2s .  c  o m*/

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(buf);

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(dout, auths);
        dout.close();
        buf.close();
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
    }

    return buf.toByteArray();
}

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

@Test
public void testDoubleSerializer() throws IOException {
    IncomePlanningSimulationRequest req = new IncomePlanningSimulationRequest();

    req.setMyPrimitiveDouble(3.4);/*from   w ww.  j a va2 s . c o  m*/
    req.setMyObjectDouble(Double.parseDouble("3.9"));
    final double[] doubleArray = new double[] { 2.1, 2, 2 };

    req.setMyPrimitiveDoubleArray(doubleArray);

    double[][] my2DimArray = new double[2][2];
    my2DimArray[0] = new double[] { 2.333333, 2.2555555 };
    my2DimArray[1] = new double[] { 8.1, 8.3 };

    System.out.println("doubleArray:" + doubleArray);
    System.out.println("my2DimArray:" + my2DimArray);

    req.setMyPrimitiveDouble2DimArray(my2DimArray);

    Double[] myObjectDoubleArray = { Double.parseDouble("4.3"), Double.parseDouble("4.5") };
    req.setMyObjectDoubleArray(myObjectDoubleArray);

    SimpleModule module = new SimpleModule();
    module.addSerializer(Double.class, new MyDoubleSerializer());
    module.addSerializer(double.class, new MyDoubleSerializer());
    module.addSerializer(Double[].class, new MyDoubleArraySerializer());
    module.addSerializer(double[].class, new MyPrimitiveDoubleArraySerializer());
    module.addSerializer(double[][].class, new MyPrimitive2DimDoubleArraySerializer());
    module.addSerializer(double[][].class, new MyPrimitive2DimDoubleArraySerializer());

    ObjectMapper m = new ObjectMapper();
    m.registerModule(module);

    StringWriter sw = new StringWriter();
    m.writeValue(sw, req);
    String json = sw.toString();
    System.out.println("testSerializeDate:" + json);
}

From source file:org.fusesource.restygwt.examples.server.PizzaServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("Processing Pizza Order...");
    try {/*w w  w.jav  a2  s.c  om*/

        ObjectMapper mapper = new ObjectMapper();
        PizzaOrder order = mapper.readValue(req.getInputStream(), PizzaOrder.class);

        StringWriter sw = new StringWriter();
        mapper.writeValue(sw, order);
        System.out.println("Request: " + sw.toString());

        OrderConfirmation confirmation = new OrderConfirmation();
        confirmation.order_id = 123123;
        confirmation.order = order;
        confirmation.price = 27.54;
        confirmation.ready_time = System.currentTimeMillis() + 1000 * 60 * 30; // in
                                                                               // 30
                                                                               // min.

        sw = new StringWriter();
        mapper.writeValue(sw, confirmation);
        System.out.println("Response: " + sw.toString());

        resp.setContentType(Resource.CONTENT_TYPE_JSON);
        mapper.writeValue(resp.getOutputStream(), confirmation);
        System.out.println("Pizza Order Confirimed: " + confirmation.order_id);

    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        System.out.flush();
        System.err.flush();
    }

}