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:com.zenesis.qx.remote.RequestHandler.java

/**
 * Called to handle exceptions during processRequest
 * @param response//  w  w  w  .ja va2  s  . com
 * @param objectMapper
 * @param e
 * @throws IOException
 */
protected void handleException(Writer response, ObjectMapper objectMapper, ProxyException e)
        throws IOException {
    tracker.getQueue().queueCommand(CommandType.EXCEPTION, e.getServerObject(), null,
            new ExceptionDetails(e.getClass().getName(), e.getMessage()));
    objectMapper.writeValue(response, tracker.getQueue());
}

From source file:com.ifeng.computing.service.impl.DataFactoryServiceTest.java

@Test
public void buildPushData() {

    File file = null;//ww  w  . j av a2  s.  c o m
    PrintWriter pw = null;
    OutputStream out = null;

    try {
        file = new File("F:BIG_EVENT_LOG2.txt");
        pw = new PrintWriter(new File("F:/HUGE_FILE.txt"));

        int start = 0;
        List<NewsItem> newsList = new ArrayList<NewsItem>();
        List<LogData> logList = new ArrayList<LogData>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("limit", LIMIT_SIZE);

        int steps = (MAX_USER_SIZE % LIMIT_SIZE == 0) ? (MAX_USER_SIZE / LIMIT_SIZE)
                : (MAX_USER_SIZE / LIMIT_SIZE + 1);

        Map<String, Object> newsMap = new HashMap<String, Object>();
        newsMap.put("start", 0);
        newsMap.put("limit", NEWS_ITEM_SIZE);

        pw.append("[");

        ObjectMapper mapper = new ObjectMapper();
        for (int i = 0; i < steps; i++) {
            start = i * LIMIT_SIZE;
            map.put("start", start);

            log.info("Step {} loading ... , Start index is [{}]", i, start);

            logList = dataFactoryService.readLogData(map);

            for (int j = 0, length = logList.size(); j < length; j++) {
                LogData data = logList.get(j);

                newsMap.put("pId", data.getpId());
                newsList = dataFactoryService.readNewsByUserId(newsMap);

                data.setNewsItem(newsList);

                if (i == 0 && j == 0) {
                    pw.append(mapper.writeValueAsString(data));
                } else {
                    pw.append(",");
                    pw.append(mapper.writeValueAsString(data));
                }

                if (j % 50 == 0)
                    pw.flush();

            }

            out = new BufferedOutputStream(new FileOutputStream(file, true), BUFFER_SIZE);
            mapper.writeValue(out, logList);

        }

        pw.append("]");

    } catch (JsonGenerationException e) {
        log.error(e.getMessage(), e);
    } catch (JsonMappingException e) {
        log.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (pw != null) {
            pw.flush();
            pw.close();
        }

    }
}

From source file:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java

/**
 * Saves all the data to JSON files except for the hostUrl, projectName,
 * and apiToken./*w  ww .  j a v  a  2 s. c o  m*/
 * @param filepath The filepath prefix
 * @return T=success, F=fail
 */
public boolean saveAllData(String filepath) {

    ObjectMapper mapper = new ObjectMapper();

    // Always the output pretty.
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    File w;
    String wname = "(none)";

    w = createFileForWriting(filepath, "_project");
    if (w == null) {
        return false;
    }

    // Project 
    try {
        mapper.writeValue(w, project);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to project to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote project (%s) to %s.\n", projectName, wname);

    // Users
    w = createFileForWriting(filepath, "_users");
    if (w == null) {
        return false;
    }
    try {
        mapper.writeValue(w, users);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to users to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote users to %s.\n", wname);

    // Milestones
    w = createFileForWriting(filepath, "_milestones");
    if (w == null) {
        return false;
    }
    try {
        // Set to List
        mapper.writeValue(w, new ArrayList<GitlabMilestone>(milestones));
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to milestones to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote milestones to %s.\n", wname);

    // Issues
    w = createFileForWriting(filepath, "_issues");
    if (w == null) {
        return false;
    }
    try {
        // Set to List
        mapper.writeValue(w, new ArrayList<GitlabIssue>(issues));
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to issues to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote issues to %s.\n", wname);

    // Issue Notes
    w = createFileForWriting(filepath, "_inotes");
    if (w == null) {
        return false;
    }
    try {
        // Map of Integer,Set to Integer,List
        Map<Integer, List<GitlabNote>> mapList = new TreeMap<Integer, List<GitlabNote>>();
        for (Integer k : issueNotes.keySet()) {
            mapList.put(k, new ArrayList<GitlabNote>(issueNotes.get(k)));
        }

        mapper.writeValue(w, mapList);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to issues to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote issue notes to %s.\n", wname);

    System.out.printf("Writing to files complete.\n");

    return true;
}

From source file:jeplus.JEPlusProject.java

/**
 * Save this project to an XML file/*  www  .ja v  a  2  s  .co m*/
 * @param file The File object associated with the file to which the contents will be saved
 * @return Successful or not
 */
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("Project saved to " + file.getAbsolutePath());
    } catch (Exception ex) {
        logger.error("Error saving project to JSON.", ex);
        success = false;
    }
    return success;
}

From source file:org.mongojack.internal.util.SerializationUtils.java

/**
 * Serialize the given field//w  w w . j ava  2s .  co m
 * 
 * @param objectMapper
 *            The object mapper to serialize it with
 * @param value
 *            The value to serialize
 * @return The serialized field. May return the same object if no
 *         serialization was necessary.
 */
public static Object serializeField(ObjectMapper objectMapper, Object value) {
    if (value == null || BASIC_TYPES.contains(value.getClass())) {
        // Return as is
        return value;
    } else if (value instanceof DBObject) {
        return serializeFields(objectMapper, (DBObject) value);
    } else if (value instanceof Collection) {
        Collection<?> coll = (Collection<?>) value;
        List<Object> copy = null;
        int position = 0;
        for (Object item : coll) {
            Object returned = serializeField(objectMapper, item);
            if (returned != item) {
                if (copy == null) {
                    copy = new ArrayList<Object>(coll);
                }
                copy.set(position, returned);
            }
            position++;
        }
        if (copy != null) {
            return copy;
        } else {
            return coll;
        }
    } else if (value.getClass().isArray()) {
        if (BASIC_TYPES.contains(value.getClass().getComponentType())) {
            return value;
        }
        Object[] array = (Object[]) value;
        Object[] copy = null;
        for (int i = 0; i < array.length; i++) {
            Object returned = serializeField(objectMapper, array[i]);
            if (returned != array[i]) {
                if (copy == null) {
                    copy = new Object[array.length];
                    System.arraycopy(array, 0, copy, 0, array.length);
                }
                copy[i] = returned;
            }
        }
        if (copy != null) {
            return copy;
        } else {
            return array;
        }
    } else {
        // We don't know what it is, serialise it
        BsonObjectGenerator generator = new BsonObjectGenerator();
        try {
            objectMapper.writeValue(generator, value);
        } catch (JsonMappingException e) {
            throw new MongoJsonMappingException(e);
        } catch (IOException e) {
            throw new RuntimeException("Somehow got an IOException writing to memory", e);
        }
        return generator.getValue();
    }
}

From source file:edu.usu.sdl.openstorefront.usecase.DataConvertUseCase.java

@Test
public void testConvert() throws JsonProcessingException, IOException {

    ObjectMapper objectMapper = StringProcessor.defaultObjectMapper();
    OldDataWrapper oldDataWrapper = objectMapper.readValue(
            new File("C:\\development\\storefront\\source\\old\\old_data\\new-data-all.json"),
            new TypeReference<OldDataWrapper>() {
            });/*from   w  w w.  j  a  v a2s. c  o  m*/

    List<OldAsset> assets = oldDataWrapper.getData();

    List<ComponentAll> newAssetMin = processData(assets, false);
    newAssetMin.forEach(asset -> {
        String filename = asset.getComponent().getName().replace(" ", "_");
        if (filename.length() > 15) {
            filename = filename.substring(0, 15);
        }
        filename = filename + "_" + asset.getComponent().getComponentId();
        try {
            objectMapper.writeValue(
                    new File("C:\\development\\storefront\\source\\master\\openstorefront\\server\\components\\"
                            + filename + ".json"),
                    asset);
        } catch (IOException ex) {
            Logger.getLogger(DataConvertUseCase.class.getName()).log(Level.SEVERE, null, ex);
        }

    });

    //      List<ComponentDetailView> newAssetComplete = processData(assets, true);
    //System.out.println(objectMapper.writeValueAsString(newAssetMin));
    //      objectMapper.writeValue(new File("c:/development/storefront/data/components-min.json"), newAssetMin);
    //      objectMapper.writeValue(new File("c:/development/storefront/data/components-full.json"), newAssetComplete);
    //      objectMapper.writeValue(new File("c:/development/storefront/data/searchResults.json"), mapSearchResults(newAssetComplete));
}

From source file:reactor.ipc.netty.tcp.TcpServerTests.java

@Test
public void tcpServerHandlesJsonPojosOverSsl() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);

    SslContext clientOptions = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();/*w  w w  . j ava 2  s .c om*/
    final TcpServer server = TcpServer.create(opts -> opts.listen("localhost").sslSelfSigned());

    ObjectMapper m = new ObjectMapper();

    NettyContext connectedServer = server.newHandler((in, out) -> {
        in.receive().asByteArray().map(bb -> {
            try {
                return m.readValue(bb, Pojo.class);
            } catch (IOException io) {
                throw Exceptions.propagate(io);
            }
        }).log("conn").subscribe(data -> {
            if ("John Doe".equals(data.getName())) {
                latch.countDown();
            }
        });

        return out.sendString(Mono.just("Hi")).neverComplete();
    }).block(Duration.ofSeconds(30));

    final TcpClient client = TcpClient.create(
            opts -> opts.connect("localhost", connectedServer.address().getPort()).sslContext(clientOptions));

    NettyContext connectedClient = client.newHandler((in, out) -> {
        //in
        in.receive().asString().log("receive").subscribe(data -> {
            if (data.equals("Hi")) {
                latch.countDown();
            }
        });

        //out
        return out.send(Flux.just(new Pojo("John" + " Doe")).map(s -> {
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                m.writeValue(os, s);
                return out.alloc().buffer().writeBytes(os.toByteArray());
            } catch (IOException ioe) {
                throw Exceptions.propagate(ioe);
            }
        })).neverComplete();
        //         return Mono.empty();
    }).block(Duration.ofSeconds(30));

    assertTrue("Latch was counted down", latch.await(5, TimeUnit.SECONDS));

    connectedClient.dispose();
    connectedServer.dispose();
}

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

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from w w  w .j  a v a  2  s  .  c  o  m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        XACMLRest.dumpRequest(request);

        // Is this from the Admin Console?
        String groupId = request.getParameter("groupId");
        if (groupId != null) {
            // this is from the Admin Console, so handle separately
            doACGet(request, response, groupId);
            return;
        }
        //
        // Get the PDP's ID
        //
        String id = this.getPDPID(request);
        logger.info("doGet from: " + id);
        //
        // Get the PDP Object
        //
        PDP pdp = this.papEngine.getPDP(id);
        //
        // Is it known?
        //
        if (pdp == null) {
            //
            // Check if request came from localhost
            //
            String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: "
                    + request.getLocalAddr();
            logger.info(message);
            if (request.getRemoteHost().equals("localhost") || request.getRemoteHost().equals("127.0.0.1") //NOPMD
                    || request.getRemoteHost().equals(request.getLocalAddr())) {
                //
                // Return status information - basically all the groups
                //
                Set<PDPGroup> groups = papEngine.getPDPGroups();

                // convert response object to JSON and include in the response
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), groups);
                response.setHeader("content-type", "application/json");
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
            return;
        }
        //
        // Get the PDP's Group
        //
        PDPGroup group = this.papEngine.getPDPGroup(pdp);
        if (group == null) {
            String message = "No group associated with pdp " + pdp.getId();
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
            return;
        }
        //
        // Which policy do they want?
        //
        String policyId = request.getParameter("id");
        if (policyId == null) {
            String message = "Did not specify an id for the policy";
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        PDPPolicy policy = group.getPolicy(policyId);
        if (policy == null) {
            String message = "Unknown policy: " + policyId;
            logger.warn(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
            return;
        }
        //
        // Get its stream
        //
        try (InputStream is = policy.getStream(); OutputStream os = response.getOutputStream()) {
            //
            // Send the policy back
            //
            IOUtils.copy(is, os);

            response.setStatus(HttpServletResponse.SC_OK);
        } catch (PAPException e) {
            String message = "Failed to open policy id " + policyId;
            logger.error(message);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
        }
    } catch (PAPException e) {
        logger.error("GET exception: " + e, e);
        response.sendError(500, e.getMessage());
        return;
    }
}

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

/**
 * Requests from the Admin Console to GET info about the Groups and PDPs
 *
 * @param request/*from  w  w w . j  a v  a 2  s.  c  o m*/
 * @param response
 * @param groupId
 * @throws ServletException
 * @throws java.io.IOException
 */
private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId)
        throws ServletException, IOException {
    try {
        String parameterDefault = request.getParameter("default");
        String pdpId = request.getParameter("pdpId");
        String pdpGroup = request.getParameter("getPDPGroup");
        if ("".equals(groupId)) {
            // request IS from AC but does not identify a group by name
            if (parameterDefault != null) {
                // Request is for the Default group (whatever its id)
                PDPGroup group = papEngine.getDefaultGroup();

                // convert response object to JSON and include in the response
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), group);

                if (logger.isDebugEnabled()) {
                    logger.debug("GET Default group req from '" + request.getRequestURL() + "'");
                }
                response.setStatus(HttpServletResponse.SC_OK);
                response.setHeader("content-type", "application/json");
                response.getOutputStream().close();
                return;

            } else if (pdpId != null) {
                // Request is related to a PDP
                if (pdpGroup == null) {
                    // Request is for the PDP itself
                    // Request is for the (unspecified) group containing a given PDP
                    PDP pdp = papEngine.getPDP(pdpId);

                    // convert response object to JSON and include in the response
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writeValue(response.getOutputStream(), pdp);

                    if (logger.isDebugEnabled()) {
                        logger.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
                    }
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.setHeader("content-type", "application/json");
                    response.getOutputStream().close();
                    return;

                } else {
                    // Request is for the (unspecified) group containing a given PDP
                    PDP pdp = papEngine.getPDP(pdpId);
                    PDPGroup group = papEngine.getPDPGroup(pdp);

                    // convert response object to JSON and include in the response
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writeValue(response.getOutputStream(), group);

                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
                    }
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.setHeader("content-type", "application/json");
                    response.getOutputStream().close();
                    return;
                }

            } else {
                // request is for top-level properties about all groups
                Set<PDPGroup> groups = papEngine.getPDPGroups();

                // convert response object to JSON and include in the response
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), groups);

                // TODO
                // In "notification" section, ALSO need to tell AC about other changes (made by other
                // ACs)?'
                // TODO add new PDP notification (or just "config changed" notification) in appropriate
                // place
                if (logger.isDebugEnabled()) {
                    logger.debug("GET All groups req");
                }
                response.setStatus(HttpServletResponse.SC_OK);
                response.setHeader("content-type", "application/json");
                response.getOutputStream().close();
                return;
            }
        }

        // for all other GET operations the group must exist before the operation can be done
        PDPGroup group = papEngine.getGroup(groupId);
        if (group == null) {
            logger.error("Unknown groupId '" + groupId + "'");
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'");
            return;
        }

        // Figure out which request this is based on the parameters
        String policyId = request.getParameter("policyId");

        if (policyId != null) {
            // // retrieve a policy
            // PDPPolicy policy = papEngine.getPDPPolicy(policyId);
            //
            // // convert response object to JSON and include in the response
            // ObjectMapper mapper = new ObjectMapper();
            // mapper.writeValue(response.getOutputStream(), pdp);
            //
            // logger.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() +
            // "'");
            // response.setStatus(HttpServletResponse.SC_OK);
            // response.setHeader("content-type", "application/json");
            // response.getOutputStream().close();
            // return;
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");

        } else {
            // No other parameters, so return the identified Group

            // convert response object to JSON and include in the response
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), group);

            if (logger.isDebugEnabled()) {
                logger.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
            }
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("content-type", "application/json");
            response.getOutputStream().close();
            return;
        }

        //
        // Currently there are no other GET calls from the AC.
        // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all
        // other GETs without calling the PAP.
        // Other GETs that could be called:
        // Specific Group (groupId=<groupId>)
        // A Policy (groupId=<groupId> policyId=<policyId>)
        // A PDP (groupId=<groupId> pdpId=<pdpId>)

        // TODO - implement other GET operations if needed

        logger.error("UNIMPLEMENTED ");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
    } catch (PAPException e) {
        logger.error("AC Get exception: " + e, e);
        response.sendError(500, e.getMessage());
        return;
    }

}

From source file:com.mastfrog.netty.http.client.CookieStore.java

public void store(OutputStream out) throws IOException {
    ObjectMapper om = new ObjectMapper();
    Lock readLock = lock.readLock();
    List<DateCookie> cks = new ArrayList<>();
    readLock.lock();//from w ww .  j  a  v a2  s  .  c  o  m
    try {
        cks.addAll(cookies);
    } finally {
        readLock.unlock();
    }
    List<Map<String, Object>> list = new LinkedList<>();
    for (DateCookie ck : cks) {
        Map<String, Object> m = new HashMap<>();
        m.put("domain", ck.getDomain());
        m.put("maxAge", ck.getMaxAge());
        m.put("timestamp", ck.getTimestamp().getMillis());
        m.put("path", ck.getPath());
        m.put("name", ck.getName());
        m.put("value", ck.getValue());
        m.put("httpOnly", ck.isHttpOnly());
        m.put("secure", ck.isSecure());
        if (ck.getComment() != null) {
            m.put("comment", ck.getComment());
        }
        if (ck.getCommentUrl() != null) {
            m.put("commentUrl", ck.getCommentUrl());
        }
        if (ck.getPorts() != null && !ck.getPorts().isEmpty()) {
            m.put("ports", ck.getPorts().toArray(new Integer[0]));
        }
        list.add(m);
    }
    om.writeValue(out, list);
}