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.apache.openaz.xacml.admin.util.RESTfulPAPEngine.java

/**
 * Send a request to the PAP Servlet and get the response.
 * /*www .  ja  va2 s .c om*/
 * The content is either an InputStream to be copied to the Request OutputStream
 *    OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
 * 
 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
 * 
 * @param method
 * @param content   - EITHER an InputStream OR an Object to be encoded in JSON
 * @param collectionTypeClass
 * @param responseContentClass
 * @param parameters
 * @return
 * @throws Exception
 */
private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
        String... parameters) throws PAPException {
    HttpURLConnection connection = null;
    try {
        String fullURL = papServletURLString;
        if (parameters != null && parameters.length > 0) {
            String queryString = "";
            for (String p : parameters) {
                queryString += "&" + p;
            }
            fullURL += "?" + queryString.substring(1);
        }

        // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
        if (method.equals("GET") && content instanceof PDP && responseContentClass == StdPDPStatus.class) {
            // Adjust the url and properties appropriately
            fullURL = ((PDP) content).getId() + "?type=Status";
            content = null;
        }

        URL url = new URL(fullURL);

        //
        // Open up the connection
        //
        connection = (HttpURLConnection) url.openConnection();
        //
        // Setup our method and headers
        //
        connection.setRequestMethod(method);
        //            connection.setRequestProperty("Accept", "text/x-java-properties");
        //               connection.setRequestProperty("Content-Type", "text/x-java-properties");
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        if (content != null) {
            if (content instanceof InputStream) {
                try {
                    //
                    // Send our current policy configuration
                    //
                    try (OutputStream os = connection.getOutputStream()) {
                        int count = IOUtils.copy((InputStream) content, os);
                        if (logger.isDebugEnabled()) {
                            logger.debug("copied to output, bytes=" + count);
                        }
                    }
                } catch (Exception e) {
                    logger.error("Failed to write content in '" + method + "'", e);
                    throw e;
                }
            } else {
                // The content is an object to be encoded in JSON
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(connection.getOutputStream(), content);
            }
        }
        //
        // Do the connect
        //
        connection.connect();
        if (connection.getResponseCode() == 204) {
            logger.info("Success - no content.");
            return null;
        } else if (connection.getResponseCode() == 200) {
            logger.info("Success. We have a return object.");

            // get the response content into a String
            String json = null;
            // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
            java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
            scanner.useDelimiter("\\A");
            json = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
            logger.info("JSON response from PAP: " + json);

            // convert Object sent as JSON into local object
            ObjectMapper mapper = new ObjectMapper();

            if (collectionTypeClass != null) {
                // collection of objects expected
                final CollectionType javaType = mapper.getTypeFactory()
                        .constructCollectionType(collectionTypeClass, responseContentClass);

                Object objectFromJSON = mapper.readValue(json, javaType);
                return objectFromJSON;
            } else {
                // single value object expected
                Object objectFromJSON = mapper.readValue(json, responseContentClass);
                return objectFromJSON;
            }

        } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
            // redirection
            String newURL = connection.getHeaderField("Location");
            if (newURL == null) {
                logger.error(
                        "No Location header to redirect to when response code=" + connection.getResponseCode());
                throw new IOException(
                        "No redirect Location header when response code=" + connection.getResponseCode());
            }
            int qIndex = newURL.indexOf("?");
            if (qIndex > 0) {
                newURL = newURL.substring(0, qIndex);
            }
            logger.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
            return newURL;
        } else {
            logger.warn("Unexpected response code: " + connection.getResponseCode() + "  message: "
                    + connection.getResponseMessage());
            throw new IOException("Server Response: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage());
        }

    } catch (Exception e) {
        logger.error("HTTP Request/Response to PAP: " + e, e);
        throw new PAPException("Request/Response threw :" + e);
    } finally {
        // cleanup the connection
        if (connection != null) {
            try {
                // For some reason trying to get the inputStream from the connection
                // throws an exception rather than returning null when the InputStream does not exist.
                InputStream is = null;
                try {
                    is = connection.getInputStream();
                } catch (Exception e1) { //NOPMD
                    // ignore this
                }
                if (is != null) {
                    is.close();
                }

            } catch (IOException ex) {
                logger.error("Failed to close connection: " + ex, ex);
            }
            connection.disconnect();
        }
    }
}

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//  w  ww.  j a  v a 2s  .  co 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:cn.powerdash.libsystem.common.exception.ExceptionResolver.java

@Override
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) {
    if (WebUtil.isAjaxRequest(request)) {
        try {//from  w w w.  ja  v a  2 s. c  o m
            String formId = request.getHeader(ApplicationConstant.X_FORM_ID);
            Locale locale = request.getLocale();
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=UTF-8");
            ResultDto<?> error = getErrorDto(ex, handler, formId, locale);
            if (error.isNonBizError()) {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            } else {
                response.setStatus(HttpStatus.OK.value());
            }
            PrintWriter writer = response.getWriter();
            objectMapper.writeValue(response.getWriter(), error);
            writer.flush();
        } catch (IOException ie) {
            LOGGER.error("Failed to serialize the object to json for exception handling.", ie);
        }
        return new ModelAndView();
    } else {
        response.setContentType("text/html;charset=UTF-8");
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMessage", ExceptionUtils.getStackTrace(ex));
        if (ex instanceof AuthorizationException) {
            LOGGER.warn("AuthorizationException handled (non-ajax style):", ex);
            mav.setViewName("error/access_denied");
        } else {
            LOGGER.error("Unknown exception handled (non-ajax style):", ex);
            mav.setViewName("error/404");
        }
        return mav;
    }
}

From source file:com.ning.metrics.action.endpoint.HdfsBrowser.java

@GET
@Produces(MediaType.APPLICATION_JSON)//  ww  w  .j  a v a2 s .co  m
@Path("/viewer")
@Timed
public Response prettyPrintOneLine(@QueryParam("object") final String object) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    final String objectURIDecoded = URLDecoder.decode(object, "UTF-8");
    final byte[] objectBase64Decoded = Base64.decodeBase64(objectURIDecoded.getBytes());

    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    final LinkedHashMap map = mapper.readValue(new String(objectBase64Decoded), LinkedHashMap.class);

    // We need to re-serialize the json (pretty print works only on serialization)
    mapper.writeValue(out, map);

    return Response.ok().entity(new String(out.toByteArray())).build();
}

From source file:org.apache.nifi.toolkit.tls.service.server.TlsCertificateAuthorityServiceHandler.java

private void writeResponse(ObjectMapper objectMapper, HttpServletRequest request, HttpServletResponse response,
        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse, int responseCode) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info(new StringBuilder("Returning code:").append(responseCode).append(" payload ")
                .append(objectMapper.writeValueAsString(tlsCertificateAuthorityResponse)).append(" to ")
                .append(request.getRemoteHost()).toString());
    }//from  ww  w .j a  v a  2s  .c  o m
    if (responseCode == Response.SC_OK) {
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
        response.setStatus(responseCode);
    } else {
        response.setStatus(responseCode);
        response.setContentType("application/json");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
    }
}

From source file:es.tid.fiware.rss.oauth.test.OauthManagerTest.java

/**
 * Parse request object to JSON./*from   w ww.jav a  2  s  . co m*/
 * 
 * @param request
 * @return JSON String
 * @throws GRETAException
 */
private String parseRequest2JSON(Object request) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ByteArrayOutputStream baosRequest = new ByteArrayOutputStream();
    try {
        mapper.writeValue(baosRequest, request);
        return baosRequest.toString();
    } catch (Exception e) {
        OauthManagerTest.log.error("Error:" + e.toString());
        throw new Exception("Wrong request " + request + ".Error: " + e.getMessage());
    } finally {
        if (baosRequest != null) {
            try {
                baosRequest.close();
            } catch (IOException e) {
                OauthManagerTest.log.error("Error closing ByteOutputStream.Message:" + e.getMessage());
            }
        }
    }
}

From source file:jp.or.openid.eiwg.filter.InitFilter.java

/**
 * ?//from ww w.java 2s  .  co m
 *
 * @param code HTTP
 * @param type 
 * @param message 
 */
private void errorResponse(HttpServletResponse response, int code, String type, String message)
        throws IOException {
    try {
        // ??
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode rootNode = mapper.createObjectNode();
        ArrayNode schemasArray = rootNode.putArray("schemas");
        schemasArray.add("urn:ietf:params:scim:api:messages:2.0:Error");
        if (type != null && !type.isEmpty()) {
            rootNode.put("scimType", type);
        }
        rootNode.put("detail", message);
        rootNode.put("status", code);

        response.setStatus(code);
        response.setContentType("application/scim+json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        mapper.writeValue(out, rootNode);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * Parameters: type=hb|config|Status 1. HeartBeat Status HeartBeat OK - All Policies are Loaded, All PIPs
 * are Loaded LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration
 * LAST_UPDATE_FAILED - Need to track the items that failed during last update LOAD_FAILURE - ??? Need to
 * determine what information is sent and how 2. Configuration 3. Status return the StdPDPStatus object in
 * the Response content//  ww w  . j a  va2 s  . c o  m
 *
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    XACMLRest.dumpRequest(request);
    //
    // What are they requesting?
    //
    boolean returnHB = false;
    response.setHeader("Cache-Control", "no-cache");
    String type = request.getParameter("type");
    // type might be null, so use equals on string constants
    if ("config".equals(type)) {
        response.setContentType("text/x-java-properties");
        try {
            String lists = XACMLProperties.PROP_ROOTPOLICIES + "="
                    + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, "");
            lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "="
                    + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n";
            try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes());
                    InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig());
                    OutputStream os = response.getOutputStream()) {
                IOUtils.copy(listInputStream, os);
                IOUtils.copy(pipInputStream, os);
            }
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            logger.error("Failed to copy property file", e);
            response.sendError(400, "Failed to copy Property file");
        }

    } else if ("hb".equals(type)) {
        returnHB = true;
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);

    } else if ("Status".equals(type)) {
        // convert response object to JSON and include in the response
        synchronized (pdpStatusLock) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), status);
        }
        response.setStatus(HttpServletResponse.SC_OK);

    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'");
    }
    if (returnHB) {
        synchronized (pdpStatusLock) {
            response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
        }
    }
}

From source file:org.mule.tools.rhinodo.rhino.NodeRequireTest.java

/**
 * Require of a directory that contains a package.json file.
 *//*from   ww w . j  a  va  2  s.c  o m*/
@Test
public void testRequirePackageJsonDirectory() throws Exception {
    final File module = folder.newFolder("my_module");
    final File packageJSON = new File(module, "package.json");
    final File otherModule = folder.newFolder("my_module", "node_modules", "other_module");
    final File mainJs = new File(module, "main.js");
    final File otherModulePackageJSON = new File(otherModule, "package.json");
    final File otherModuleMain = new File(otherModule, "main.js");
    final ObjectMapper objectMapper = new ObjectMapper();

    HashMap<String, Object> packageJSONMap = new HashMap<String, Object>();
    packageJSONMap.put("main", "./main.js");

    HashMap<String, String> dependencies = new HashMap<String, String>();
    dependencies.put("other_module", "*");
    packageJSONMap.put("dependencies", dependencies);

    objectMapper.writeValue(packageJSON, packageJSONMap);

    HashMap<String, Object> otherModulePackageJSONMap = new HashMap<String, Object>();
    otherModulePackageJSONMap.put("main", "./main");
    otherModulePackageJSONMap.put("name", "other_module");

    objectMapper.writeValue(otherModulePackageJSON, otherModulePackageJSONMap);

    FileUtils.write(mainJs, "exports.hello = 'bye';" + "exports.other = require('other_module');");

    FileUtils.write(otherModuleMain, "exports.text = 'second';");

    final Queue asyncCallback = mock(Queue.class);
    final NodeJsGlobal globalScope = new NodeJsGlobal();
    final ExitCallbackExecutor exitCallbackExecutor = mock(ExitCallbackExecutor.class);

    ContextFactory contextFactory = new ContextFactory();
    contextFactory.call(new ContextAction() {
        @Override
        public Object run(Context cx) {
            cx.initStandardObjects(globalScope);
            NodeRequireBuilder rb = new NodeRequireBuilder(asyncCallback, exitCallbackExecutor);
            globalScope.installNodeJsRequire(cx, cx.newObject(globalScope),
                    new NodeModuleProviderImpl(new ArrayList<NodeModule>()), rb, false);
            Function nodeRequire = ScriptableObject.getTypedProperty(globalScope, "require", Function.class);
            NativeObject main = (NativeObject) nodeRequire.call(cx, globalScope, globalScope,
                    new Object[] { module.getAbsolutePath() });

            assertNotNull(main);

            assertEquals("bye", ScriptableObject.getTypedProperty(main, "hello", String.class));

            assertFalse(ScriptableObject.NOT_FOUND.equals(main));
            NativeObject other = ScriptableObject.getTypedProperty(main, "other", NativeObject.class);

            assertNotNull(other);
            assertEquals("second", ScriptableObject.getProperty(other, "text"));

            return null;
        }
    });
}

From source file:fll.web.api.TournamentTeamsServlet.java

@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    final ServletContext application = getServletContext();

    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {//from w w  w .  j  a v  a2  s .  c o  m
        connection = datasource.getConnection();

        final Map<Integer, TournamentTeam> teamMap = Queries.getTournamentTeams(connection);
        final ObjectMapper jsonMapper = new ObjectMapper();

        response.reset();
        response.setContentType("application/json");
        final PrintWriter writer = response.getWriter();

        final String pathInfo = request.getPathInfo();
        if (null != pathInfo && pathInfo.length() > 1) {
            final String teamNumberStr = pathInfo.substring(1);
            try {
                final int teamNumber = Integer.parseInt(teamNumberStr);
                LOGGER.info("Found team number: " + teamNumber);
                final TournamentTeam team = teamMap.get(teamNumber);
                if (null != team) {
                    jsonMapper.writeValue(writer, team);
                    return;
                } else {
                    throw new RuntimeException("No team found with number " + teamNumber);
                }
            } catch (final NumberFormatException e) {
                throw new RuntimeException("Error parsing team number " + teamNumberStr, e);
            }
        }

        final Collection<TournamentTeam> teams = teamMap.values();

        jsonMapper.writeValue(writer, teams);
    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }

}