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.mitre.secretsharing.server.SplitServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

    resp.setContentType("application/json");

    try {/*from ww  w. j  a v a2s  .com*/
        Request jreq = mapper.readValue(req.getParameter("q"), Request.class);

        byte[] secret;

        if (jreq.base64 != null && jreq.base64)
            secret = Base64Variants.MIME_NO_LINEFEEDS.decode(jreq.secret);
        else
            secret = jreq.secret.getBytes("UTF-8");

        if (jreq.secret == null || jreq.totalParts == null || jreq.requiredParts == null)
            throw new IllegalArgumentException();

        Part[] parts = Secrets.splitPerByte(secret, jreq.totalParts, jreq.requiredParts, rnd);

        Response jresp = new Response();
        jresp.parts = new ArrayList<String>();
        for (Part part : parts)
            jresp.parts.add(part.toString());
        jresp.status = "ok";

        mapper.writeValue(resp.getOutputStream(), jresp);
    } catch (Throwable t) {
        t.printStackTrace();

        Response jresp = new Response();
        jresp.status = "error";

        mapper.writeValue(resp.getOutputStream(), jresp);
    }
}

From source file:fll.web.api.TournamentsServlet.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 {/* w  w  w  .  j av a  2 s .  com*/
        connection = datasource.getConnection();

        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 tournamentStr = pathInfo.substring(1);

            int id;
            if ("current".equals(tournamentStr)) {
                id = Queries.getCurrentTournament(connection);
            } else {
                try {
                    id = Integer.parseInt(tournamentStr);
                } catch (final NumberFormatException e) {
                    throw new RuntimeException("Error parsing tournament id " + tournamentStr, e);
                }
            }

            final Tournament tournament = Tournament.findTournamentByID(connection, id);
            if (null != tournament) {
                jsonMapper.writeValue(writer, tournament);
                return;
            } else {
                throw new RuntimeException("No tournament found with id " + id);
            }

        }

        final Collection<Tournament> tournaments = Tournament.getTournaments(connection);

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

}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java

public String getAllLatencyInformations() throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();

    List<RunInformations> datas = new ArrayList<>();

    for (Run run : this.builds) {
        LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class);
        if (buildAction != null) {
            if (buildAction.getGlobalLatencyTimeInformations() != null) {
                RunInformations runInformations = new RunInformations(run.getId(),
                        buildAction.getGlobalLatencyTimeInformations());
                datas.add(runInformations);
            }/*w w w. j  a  va  2 s  .c om*/
        }
    }

    // order by buildId

    Collections.sort(datas, Comparator.comparing(RunInformations::getBuildId));

    StringWriter stringWriter = new StringWriter();

    objectMapper.writeValue(stringWriter, datas);

    return stringWriter.toString();

}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java

public String getAllResponseTimeInformations() throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();

    List<RunInformations> datas = new ArrayList<>();

    for (Run run : this.builds) {
        LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class);
        if (buildAction != null) {
            if (buildAction.getGlobalResponseTimeInformations() != null) {
                RunInformations runInformations = new RunInformations(run.getId(),
                        buildAction.getGlobalResponseTimeInformations());
                datas.add(runInformations);
            }/*from   w w  w  .  j  a  va 2  s. c om*/
        }
    }

    // order by buildId

    Collections.sort(datas, Comparator.comparing(RunInformations::getBuildId));

    StringWriter stringWriter = new StringWriter();

    objectMapper.writeValue(stringWriter, datas);

    return stringWriter.toString();

}

From source file:uniko.west.topology.bolts.DiscussionTreeBolt.java

/**
 * searches for locations in the message and computes related locations
 *
 * @param input/*ww  w  .  j  a  va2s .  c  o m*/
 *            standard Storm tuple input object (passed within Storm
 *            topology itself, not be a user)
 */
@Override
public void execute(Tuple input) {
    // Retrieve hash map tuple object from Tuple input at index 0, index 1
    // will be message delivery tag (not used here)
    Map<Object, Object> inputMap = (HashMap<Object, Object>) input.getValue(0);
    // Get JSON object from the HashMap from the Collections.singletonList
    Map<Object, Object> message = (Map<Object, Object>) inputMap.get("message");

    // Acknowledge the collector that we actually received the input
    this.collector.ack(input);

    if (!message.containsKey("created_at")) {
        return; // skip delete messages
    }
    // Print received message
    // this.logger.info("Received message: " + message.toJSONString());

    String timeStamp = (String) message.get("created_at");
    DateTime timestamp = DateTime.parse(timeStamp,
            DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy").withLocale(Locale.US));

    if (this.bufferStartTime == null) {
        this.bufferStartTime = timestamp;
        this.deadline = this.bufferStartTime.plusMinutes(this.intervalInMinutes);
    }

    String authorId = (String) ((Map<Object, Object>) message.get("user")).get("id_str");
    String authorScreenName = (String) ((Map<Object, Object>) message.get("user")).get("screen_name");
    String text = (String) message.get("text");
    String tweetId = (String) message.get("id_str");
    boolean retweet = false;

    String ancestorTweetId = (String) message.get("in_reply_to_status_id_str");
    String ancestorAuthorId = (String) message.get("in_reply_to_user_id_str");
    String ancestorAutorScreenName = (String) message.get("in_reply_to_screen_name");

    Map<Object, Object> retweeted_status = (Map<Object, Object>) message.get("retweeted_status");
    if (retweeted_status != null) {
        retweet = true;
        ancestorTweetId = (String) ((Map<Object, Object>) message.get("retweeted_status")).get("id_str");
    }

    Tweet tweet = new Tweet(authorId, authorScreenName, tweetId, timestamp, text, ancestorTweetId, true,
            retweet);

    if (ancestorTweetId != null) {
        if (this.rootTweetsMap.containsKey(tweet.getIn_reply_to())) {
            this.rootTweetsMap.get(tweet.getIn_reply_to()).getReplies().add(tweet);
        } else if (this.childrenTweetsMap.containsKey(tweet.getIn_reply_to())) {
            this.childrenTweetsMap.get(tweet.getIn_reply_to()).getReplies().add(tweet);
        } else {
            // tweet is a reply or retweet but its ancestor was'nt observed
            // by this bolt, therefore its ancestor is treated as a dummy
            // entry
            Tweet dummyTweet = new Tweet(ancestorAuthorId, ancestorAutorScreenName, ancestorTweetId, null, null,
                    null, false, false);
            dummyTweet.getReplies().add(tweet);
            this.rootTweetsMap.put(ancestorTweetId, dummyTweet);
        }
        this.childrenTweetsMap.put(tweetId, tweet);
    } else {
        // tweet is no reply or retweet
        this.rootTweetsMap.put(tweetId, tweet);
    }

    if (timestamp.isAfter(this.deadline) || timestamp.isEqual(this.deadline)) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonResultString;
            HashMap<String, Object> jsonResult = new HashMap<>();
            jsonResult.put("start", this.bufferStartTime.toString());
            jsonResult.put("end", timestamp.toString());
            jsonResult.put("result", this.rootTweetsMap.values());
            jsonResultString = mapper.writeValueAsString(jsonResult);
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.INFO,
                    "Deadline expired, Buffer size : " + this.rootTweetsMap.size());
            this.collector.emit(new Values(jsonResultString));
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            mapper.writeValue(
                    new File("/home/martin/test/discussionTreeBolt/discussionTree-" + this.bufferStartTime),
                    jsonResult);
            this.bufferStartTime = null;
            this.rootTweetsMap = new LinkedHashMap<>();
            this.childrenTweetsMap = new HashMap<>();
        } catch (JsonProcessingException ex) {
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:acmi.l2.clientmod.l2smr.Controller.java

@FXML
private void exportSM() {
    List<Actor> actors = this.table.getSelectionModel().getSelectedItems().stream().map(Actor::clone)
            .collect(Collectors.toList());

    if (actors.isEmpty())
        return;/*from  w  w  w .j a  v a  2 s  .  com*/

    int xy = 18 | (20 << 8);
    try {
        xy = getXY(getMapsDir(), this.unrChooser.getSelectionModel().getSelectedItem());
    } catch (IOException e) {
        showAlert(Alert.AlertType.WARNING, "Export", null, "Couldn't read map coords, using default 18_20");
    }
    ImportExportDialog dlg = new ImportExportDialog(xy & 0xff, (xy >> 8) & 0xff);
    ButtonType response = dlg.showAndWait().orElse(null);
    if (response != ButtonType.OK)
        return;

    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON", "*.json"));
    fileChooser.setTitle("Save");
    File file = fileChooser.showSaveDialog(getStage());
    if (file == null)
        return;

    longTask(progress -> {
        float x = dlg.getX(), y = dlg.getY(), z = dlg.getZ();
        double angle = dlg.getAngle();
        AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI * angle / 180, x, y);
        AffineTransform translate = AffineTransform.getTranslateInstance(-x, -y);

        for (int i = 0; i < actors.size(); i++) {
            progress.accept((double) i / actors.size());
            Actor o = actors.get(i);
            Point2D.Float point = new Point2D.Float(o.getX(), o.getY());
            rotate.transform(point, point);
            translate.transform(point, point);

            o.setX(point.x);
            o.setY(point.y);
            o.setZ(o.getZ() - z);
            if (o.getYaw() == null)
                o.setYaw(0);
            o.setYaw(((int) (o.getYaw() + angle * 0xFFFF / 360)) & 0xFFFF);
        }
        progress.accept(-1.0);

        L2Map map = new L2Map(x, y, z, actors);
        ObjectMapper objectMapper = new ObjectMapper();

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            objectMapper.writeValue(baos, map);

            try (OutputStream fos = new FileOutputStream(file)) {
                baos.writeTo(fos);
            }
        }
    }, e -> onException("Export failed", e));
}

From source file:com.amazon.feeds.SampleFeedGenerator.java

/**
 * The method for generating sample feeds.
 *
 * @param format The class containing the format specifications.
 * @param items The number of items to generate.
 * @param ext File extension./*from   ww w  .  j  a  v a2 s  .c  o m*/
 */
public void createSampleFeed(IFeedFormat format, int items, String ext) throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    mapper.getFactory().setCharacterEscapes(format.getEscapeRules());

    // create output file
    String out = format.getFeedFormat() + "-" + items + "." + ext;
    // TODO: add XML support

    File outFile = new File(SAMPLE_PATH, out);
    if (!outFile.exists()) {
        outFile.getParentFile().mkdirs();
    }

    // populate sample feed
    System.out.println("Generating " + items + (items == 1 ? " item" : " items") + " for "
            + format.getProvider() + " feed at " + outFile.getAbsolutePath());
    format.populate(items);

    // write JSON to file
    if (format.usePrettyPrint()) {

        DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter("   ", DefaultIndenter.SYS_LF);
        DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
        printer.indentObjectsWith(indenter);
        printer.indentArraysWith(indenter);
        mapper.writer(printer).writeValue(outFile, format);
    } else {
        mapper.writeValue(outFile, format);
    }
}

From source file:org.apache.olingo.fit.utils.AbstractJSONUtilities.java

@Override
public InputStream getProperty(final String entitySetName, final String entityId, final List<String> path,
        final String edmType) throws Exception {

    final InputStream src = fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId) + ENTITY,
            Accept.JSON_FULLMETA);//from   ww w. j a  v  a  2 s. c  om

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode srcNode = mapper.readTree(src);

    final ObjectNode propertyNode = new ObjectNode(JsonNodeFactory.instance);

    if (StringUtils.isNotBlank(edmType)) {
        propertyNode.put(JSON_ODATAMETADATA_NAME, ODATA_METADATA_PREFIX + edmType);
    }

    JsonNode jsonNode = getProperty(srcNode, path);

    if (jsonNode.isArray()) {
        propertyNode.put("value", (ArrayNode) jsonNode);
    } else if (jsonNode.isObject()) {
        propertyNode.putAll((ObjectNode) jsonNode);
    } else {
        propertyNode.put("value", jsonNode.asText());
    }

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    mapper.writeValue(bos, propertyNode);

    final InputStream res = new ByteArrayInputStream(bos.toByteArray());
    IOUtils.closeQuietly(bos);

    return res;
}

From source file:jonelo.jacksum.concurrent.Jacksum2Cli.java

public int printResults() {
    try {//from  w  w  w .  j ava2  s  . co  m

        if (this.isHelp()) {
            this.printHelp();
            return OK;
        }

        this.initOutput();

        if (this.isPrintMetainfo()) {

            final HashFormat simpleFormat = new SimpleHashFormat(this.getEncoding(), this.getHexaGroupSize(),
                    this.getHexaGroupSeparatorChar(), null);

            final ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

            final JacksumReport report = new JacksumReport();
            report.setAlgorithms(
                    this.algorithms.stream().map(algo -> algo.getCanonicalName()).collect(Collectors.toList()));
            report.setAlternative(this.alternative);
            report.setEncoding(this.getEncoding().getValue());
            report.setHexaGroupSeparatorChar(this.hexaGroupSeparatorChar);
            report.setHexaGroupSize(this.hexaGroupSize);
            report.setPathSeparator(this.separator);

            if (this.quickSequence != null) {

                this.buildQuickReport(report, simpleFormat);

                mapper.writeValue(this.out, report);

                return OK;
            }
            //process files
            this.buildFilesReport(report, simpleFormat);

            mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValue(this.out, report);

            return OK;

        }

        if (this.quickSequence != null) {
            this.out.println(this.getFormattedQuickHash());
            return OK;
        }

        for (String resultString : this.getFormattedFileHashes()) {
            this.out.println(resultString);
        }

        return OK;

    } catch (Throwable ex) {
        this.printError(ex.getMessage());
        return ERROR_STATUS;
    }
}

From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java

private void copyCurrentStructure(JsonParser parser, ObjectMapper mapper, int depth, JsonGenerator generator)
        throws IOException {
    // Avoid using the mapper to parse the entire input until we absolutely must.  This allows pretty
    // printing huge top-level arrays (that wouldn't fit in memory) containing smaller objects (that
    // individually do fit in memory) where the objects are printed with sorted keys.
    JsonToken t = parser.getCurrentToken();
    if (t == null) {
        generator.copyCurrentStructure(parser); // Will report the error of a null token.
        return;//  w  w  w .  j av  a2s. c  o m
    }
    int id = t.id();
    if (id == ID_FIELD_NAME) {
        if (depth > flatten) {
            generator.writeFieldName(parser.getCurrentName());
        }
        t = parser.nextToken();
        id = t.id();
    }
    switch (id) {
    case ID_START_OBJECT:
        if (sortKeys && depth >= flatten) {
            // Load the entire object in memory so we can sort its keys and serialize it back out.
            mapper.writeValue(generator, parser.readValueAs(Map.class));
        } else {
            // Don't load the whole object into memory.  Copy it in a memory-efficient streaming fashion.
            if (depth >= flatten) {
                generator.writeStartObject();
            }
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                copyCurrentStructure(parser, mapper, depth + 1, generator);
            }
            if (depth >= flatten) {
                generator.writeEndObject();
            }
        }
        break;
    case ID_START_ARRAY:
        // Don't load the whole array into memory.  Copy it in a memory-efficient streaming fashion.
        if (depth >= flatten) {
            generator.writeStartArray();
        }
        while (parser.nextToken() != JsonToken.END_ARRAY) {
            copyCurrentStructure(parser, mapper, depth + 1, generator);
        }
        if (depth >= flatten) {
            generator.writeEndArray();
        }
        break;
    default:
        generator.copyCurrentEvent(parser);
        break;
    }
}