Example usage for com.fasterxml.jackson.core JsonGenerator close

List of usage examples for com.fasterxml.jackson.core JsonGenerator close

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator close.

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Method called to close this generator, so that no more content can be written.

Usage

From source file:com.netflix.spectator.tdigest.TDigestWriter.java

/**
 * Write a list of measurements to some underlying storage.
 *//*from w w w. ja v a 2s  .c om*/
void write(List<TDigestMeasurement> measurements) throws IOException {
    JsonGenerator gen = json.newGenerator(out);
    gen.writeStartArray();
    gen.flush();
    int pos = buf.position();
    for (TDigestMeasurement m : measurements) {
        json.encode(commonTags, m, gen);
        gen.flush();

        if (out.overflow()) {
            // Ignore the last entry written to the buffer
            out.setPosition(pos);
            gen.writeEndArray();
            gen.close();
            write(buf);

            // Reuse the buffer and write the current entry
            out.reset();
            gen = json.newGenerator(out);
            gen.writeStartArray();
            json.encode(commonTags, m, gen);
            gen.flush();

            // If a single entry is too big, then drop it
            if (out.overflow()) {
                LOGGER.warn("dropping measurement {}, serialized size exceeds the buffer cap", m.id());
                out.reset();
                gen = json.newGenerator(out);
                gen.writeStartArray();
                gen.flush();
            }

            pos = buf.position();
        } else if (buf.remaining() < MIN_FREE) {
            // Not enough free-space, go ahead and write
            gen.writeEndArray();
            gen.close();
            write(buf);

            // Reuse the buffer
            out.reset();
            gen = json.newGenerator(out);
            gen.writeStartArray();
            gen.flush();
            pos = buf.position();
        } else {
            pos = buf.position();
        }
    }

    // Write any data that is still in the buffer
    if (buf.position() > 1) {
        gen.writeEndArray();
        gen.close();
        write(buf);
    }
}

From source file:test.com.azaptree.services.json.JsonUtilsTest.java

@Test
public void test_serialize() throws JsonGenerationException, IOException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final JsonGenerator generator = JsonUtils.createJsonGenerator(bos);
    generator.writeStartObject();//from  ww w. j  a  va2  s  . c o m
    generator.writeStringField("stringField", "stringFieldValue");
    generator.writeNumberField("numberField", 5);
    generator.writeEndObject();
    generator.close();

    final Map<String, Object> test = JsonUtils.parse(new ByteArrayInputStream(bos.toByteArray()));
    Assert.assertEquals(test.get("stringField"), "stringFieldValue");
    Assert.assertEquals(test.get("numberField"), 5);
}

From source file:javasnack.snacks.json.PojoEncodeJackson.java

@Override
public void run() {
    ObjectMapper objectMapper = new ObjectMapper();
    try {//w w  w  . j a v a  2s .com
        String jsonout = objectMapper.writeValueAsString(new EncodePojo());
        System.out.println("--- simple jackson encode ---");
        System.out.println(jsonout);
        String jsonout2 = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new EncodePojo());
        System.out.println("--- default pretty-print jackson encode ---");
        System.out.println(jsonout2);
        System.out.println("--- streaming jackson encode ---");
        JsonFactory jsonFactory = objectMapper.getFactory();
        Writer out = new OutputStreamWriter(System.out);
        JsonGenerator jg = jsonFactory.createGenerator(out);
        jg.setPrettyPrinter(new DefaultPrettyPrinter());
        jg.writeStartObject();
        jg.writeStringField("message", "success");
        jg.writeNumberField("count", 10);
        jg.writeArrayFieldStart("records");
        for (int i = 0; i < 10; i++) {
            jg.writeObject(new EncodePojo());
            Thread.sleep(100);
            jg.flush();
        }
        jg.writeEndArray();
        jg.writeEndObject();
        jg.close();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:piazza.services.ingest.test.SerializationTests.java

/**
 * Tests serialization and deserialization of GeoJSON Features
 *///from  w  w  w.  j a va 2  s . c om
@Test
public void testSerialization() throws Exception {
    List<String> geometries = new ArrayList<String>(Arrays.asList("Point", "Polygon", "LineString",
            "MultiPoint", "MultiPolygon", "MultiLineString", "GeometryCollection"));
    JsonGenerator generator = jsonFactory.createGenerator(System.out);
    File file;
    for (String geometryType : geometries) {
        // Load test file
        file = new File(String.format("%s%s.%s", resourceBasePath, geometryType, "geojson"));
        JsonParser parser = jsonFactory.createParser(file);
        // Read
        Geometry geometry = deserializer.deserialize(parser, null);
        // Write
        serializer.serialize(geometry, generator, null);
    }
    file = null;
    generator.close();
}

From source file:eu.mondo.driver.mongo.util.StatementSerializer.java

@Override
public void serialize(Statement st, JsonGenerator generator, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    generator.writeStartObject();//from   w  w  w .  ja va  2s.  c om
    generator.writeStringField("subject", st.getSubject().toString());
    generator.writeStringField("predicate", st.getPredicate().toString());
    generator.writeStringField("object", st.getObject().toString());
    generator.writeStringField("subjectBI", "");
    generator.writeStringField("predicateBI", "");
    generator.writeStringField("objectBI", "");
    generator.writeEndObject();

    generator.close();

}

From source file:org.openiot.security.oauth.OAuth20ProfileController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN);
    log.debug("accessToken : {}", accessToken);

    final JsonFactory jsonFactory = new JsonFactory();
    final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(response.getWriter());

    response.setContentType("application/json");

    // accessToken is required
    if (StringUtils.isBlank(accessToken)) {
        log.error("missing accessToken");
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.MISSING_ACCESS_TOKEN);
        jsonGenerator.writeEndObject();//from www. j a  v  a  2 s  .  co m
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // get ticket granting ticket
    final TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry
            .getTicket(accessToken);
    if (ticketGrantingTicket == null || ticketGrantingTicket.isExpired()) {
        log.error("expired accessToken : {}", accessToken);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN);
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        response.flushBuffer();
        return null;
    }

    // generate profile : identifier + attributes
    final Principal principal = ticketGrantingTicket.getAuthentication().getPrincipal();
    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField(CasWrapperProfile.ID, principal.getId());
    jsonGenerator.writeArrayFieldStart(CasWrapperProfile.ATTRIBUTES);
    final Map<String, Object> attributes = principal.getAttributes();
    for (final String key : attributes.keySet()) {
        jsonGenerator.writeStartObject();
        Object vals = attributes.get(key);
        if (vals instanceof Iterable<?>) {
            jsonGenerator.writeArrayFieldStart(key);
            for (final Object value : (Iterable<?>) vals)
                jsonGenerator.writeString(value.toString());
            jsonGenerator.writeEndArray();
        } else if ("role_name".equals(key)) {
            jsonGenerator.writeArrayFieldStart(key);
            if (!StringUtils.isBlank((String) vals))
                jsonGenerator.writeString(vals.toString());
            jsonGenerator.writeEndArray();
        } else
            jsonGenerator.writeObjectField(key, attributes.get(key));

        jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndArray();
    jsonGenerator.writeEndObject();
    jsonGenerator.close();
    response.flushBuffer();
    return null;
}

From source file:ratpack.codahale.metrics.internal.WebSocketReporter.java

@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {
    try {/* www . j av a2 s. com*/
        OutputStream out = new ByteArrayOutputStream();
        JsonGenerator json = factory.createGenerator(out);

        json.writeStartObject();
        json.writeNumberField("timestamp", clock.getTime());
        writeTimers(json, timers);
        writeGauges(json, gauges);
        writeMeters(json, meters);
        writeCounters(json, counters);
        writeHistograms(json, histograms);
        json.writeEndObject();

        json.flush();
        json.close();

        metricsBroadcaster.broadcast(out.toString());
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Exception encountered while reporting metrics: " + e.getLocalizedMessage());
    }
}

From source file:test.com.azaptree.services.json.JsonUtilsTest.java

@Test
public void test_serialize_JSONEncoding() throws JsonGenerationException, IOException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final JsonGenerator generator = JsonUtils.createJsonGenerator(bos, JsonEncoding.UTF8);
    generator.writeStartObject();/* w  w w  .ja v  a  2 s .c  om*/
    generator.writeStringField("stringField", "stringFieldValue");
    generator.writeNumberField("numberField", 5);
    generator.writeEndObject();
    generator.close();

    final Map<String, Object> test = JsonUtils.parse(new ByteArrayInputStream(bos.toByteArray()));
    Assert.assertEquals(test.get("stringField"), "stringFieldValue");
    Assert.assertEquals(test.get("numberField"), 5);
}

From source file:uk.ac.cam.cl.dtg.isaac.quiz.IsaacSymbolicValidator.java

@Override
public QuestionValidationResponse validateQuestionResponse(final Question question, final Choice answer)
        throws ValidatorUnavailableException {
    Validate.notNull(question);/*from  w ww  .j av  a2 s. c om*/
    Validate.notNull(answer);

    if (!(question instanceof IsaacSymbolicQuestion)) {
        throw new IllegalArgumentException(
                String.format("This validator only works with Isaac Symbolic Questions... (%s is not symbolic)",
                        question.getId()));
    }

    if (!(answer instanceof Formula)) {
        throw new IllegalArgumentException(
                String.format("Expected Formula for IsaacSymbolicQuestion: %s. Received (%s) ",
                        question.getId(), answer.getClass()));
    }

    IsaacSymbolicQuestion symbolicQuestion = (IsaacSymbolicQuestion) question;
    Formula submittedFormula = (Formula) answer;

    // These variables store the important features of the response we'll send.
    Content feedback = null; // The feedback we send the user
    MatchType responseMatchType = MatchType.NONE; // The match type we found
    boolean responseCorrect = false; // Whether we're right or wrong

    // There are several specific responses the user can receive. Each of them will set feedback content, so
    // use that to decide whether to proceed to the next check in each case.

    // STEP 0: Do we even have any answers for this question? Always do this check, because we know we
    //         won't have feedback yet.

    if (null == symbolicQuestion.getChoices() || symbolicQuestion.getChoices().isEmpty()) {
        log.error("Question does not have any answers. " + question.getId() + " src: "
                + question.getCanonicalSourceFile());

        feedback = new Content("This question does not have any correct answers");
    }

    // STEP 1: Did they provide an answer?

    if (null == feedback && (null == submittedFormula.getPythonExpression()
            || submittedFormula.getPythonExpression().isEmpty())) {
        feedback = new Content("You did not provide an answer");
    }

    // STEP 2: Otherwise, Does their answer match a choice exactly?

    if (null == feedback) {

        // For all the choices on this question...
        for (Choice c : symbolicQuestion.getChoices()) {

            // ... that are of the Formula type, ...
            if (!(c instanceof Formula)) {
                log.error("Isaac Symbolic Validator for questionId: " + symbolicQuestion.getId()
                        + " expected there to be a Formula. Instead it found a Choice.");
                continue;
            }

            Formula formulaChoice = (Formula) c;

            // ... and that have a python expression ...
            if (null == formulaChoice.getPythonExpression() || formulaChoice.getPythonExpression().isEmpty()) {
                log.error("Expected python expression, but none found in choice for question id: "
                        + symbolicQuestion.getId());
                continue;
            }

            // ... look for an exact string match to the submitted answer.
            if (formulaChoice.getPythonExpression().equals(submittedFormula.getPythonExpression())) {
                feedback = (Content) formulaChoice.getExplanation();
                responseMatchType = MatchType.EXACT;
                responseCorrect = formulaChoice.isCorrect();
            }
        }
    }

    // STEP 3: Otherwise, use the symbolic checker to analyse their answer

    if (null == feedback) {

        // Go through all choices, keeping track of the best match we've seen so far. A symbolic match terminates
        // this loop immediately. A numeric match may later be replaced with a symbolic match, but otherwise will suffice.

        Formula closestMatch = null;
        MatchType closestMatchType = MatchType.NONE;

        // Sort the choices so that we match incorrect choices last, taking precedence over correct ones.
        List<Choice> orderedChoices = Lists.newArrayList(symbolicQuestion.getChoices());

        Collections.sort(orderedChoices, new Comparator<Choice>() {
            @Override
            public int compare(Choice o1, Choice o2) {
                int o1Val = o1.isCorrect() ? 0 : 1;
                int o2Val = o2.isCorrect() ? 0 : 1;
                return o1Val - o2Val;
            }
        });

        // For all the choices on this question...
        for (Choice c : orderedChoices) {

            // ... that are of the Formula type, ...
            if (!(c instanceof Formula)) {
                // Don't need to log this - it will have been logged above.
                continue;
            }

            Formula formulaChoice = (Formula) c;

            // ... and that have a python expression ...
            if (null == formulaChoice.getPythonExpression() || formulaChoice.getPythonExpression().isEmpty()) {
                // Don't need to log this - it will have been logged above.
                continue;
            }

            // ... test their answer against this choice with the symbolic checker.

            // We don't do any sanitisation of user input here, we'll leave that to the python.

            MatchType matchType = MatchType.NONE;

            try {
                // This is ridiculous. All I want to do is pass some JSON to a REST endpoint and get some JSON back.

                ObjectMapper mapper = new ObjectMapper();

                HashMap<String, String> req = Maps.newHashMap();
                req.put("target", formulaChoice.getPythonExpression());
                req.put("test", submittedFormula.getPythonExpression());
                req.put("description", symbolicQuestion.getId());

                StringWriter sw = new StringWriter();
                JsonGenerator g = new JsonFactory().createGenerator(sw);
                mapper.writeValue(g, req);
                g.close();
                String requestString = sw.toString();

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + "/check");

                httpPost.setEntity(new StringEntity(requestString, "UTF-8"));
                httpPost.addHeader("Content-Type", "application/json");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity responseEntity = httpResponse.getEntity();
                String responseString = EntityUtils.toString(responseEntity);
                HashMap<String, Object> response = mapper.readValue(responseString, HashMap.class);

                if (response.containsKey("error")) {
                    if (response.containsKey("code")) {
                        log.error("Failed to check formula \"" + submittedFormula.getPythonExpression()
                                + "\" against \"" + formulaChoice.getPythonExpression() + "\": "
                                + response.get("error"));
                    } else {
                        // If it doesn't contain a code, it wasn't a fatal error in the checker; probably only a
                        // problem with the submitted answer.
                        log.warn("Problem checking formula \"" + submittedFormula.getPythonExpression()
                                + "\" for (" + symbolicQuestion.getId() + ") with symbolic checker: "
                                + response.get("error"));
                    }
                } else {
                    if (response.get("equal").equals("true")) {
                        matchType = MatchType.valueOf(((String) response.get("equality_type")).toUpperCase());
                    }
                }

            } catch (IOException e) {
                log.error(
                        "Failed to check formula with symbolic checker. Is the server running? Not trying again.");
                throw new ValidatorUnavailableException(
                        "We are having problems marking Symbolic Questions." + " Please try again later!");
            }

            if (matchType == MatchType.EXACT) {
                closestMatch = formulaChoice;
                closestMatchType = MatchType.EXACT;
                break;
            } else if (matchType.compareTo(closestMatchType) > 0) {
                if (formulaChoice.getRequiresExactMatch() && formulaChoice.isCorrect()) {
                    closestMatch = formulaChoice;
                    closestMatchType = matchType;
                } else {
                    if (closestMatch == null || !closestMatch.getRequiresExactMatch()) {
                        closestMatch = formulaChoice;
                        closestMatchType = matchType;
                    } else {
                        // This is not as good a match as the one we already have.
                    }
                }
            }
        }

        if (null != closestMatch) {
            // We found a decent match. Of course, it still might be wrong.

            if (closestMatchType != MatchType.EXACT && closestMatch.getRequiresExactMatch()) {
                if (closestMatch.isCorrect()) {
                    feedback = new Content(
                            "Your answer is not in the form we expected. Can you rearrange or simplify it?");
                    responseCorrect = false;
                    responseMatchType = closestMatchType;

                    log.info("User submitted an answer that was close to an exact match, but not exact "
                            + "for question " + symbolicQuestion.getId() + ". Choice: "
                            + closestMatch.getPythonExpression() + ", submitted: "
                            + submittedFormula.getPythonExpression());
                } else {
                    // This is weak match to a wrong answer; we can't use the feedback for the choice.
                }
            } else {
                feedback = (Content) closestMatch.getExplanation();
                responseCorrect = closestMatch.isCorrect();
                responseMatchType = closestMatchType;
            }

            if (closestMatchType == MatchType.NUMERIC) {
                log.info("User submitted an answer that was only numerically equivalent to one of our choices "
                        + "for question " + symbolicQuestion.getId() + ". Choice: "
                        + closestMatch.getPythonExpression() + ", submitted: "
                        + submittedFormula.getPythonExpression());

                // TODO: Decide whether we want to add something to the explanation along the lines of "you got it
                //       right, but only numerically.
            }

        }
    }

    // If we got this far and feedback is still null, they were wrong. There's no useful feedback we can give at this point.

    return new FormulaValidationResponse(symbolicQuestion.getId(), answer, feedback, responseCorrect,
            responseMatchType.toString(), new Date());
}

From source file:com.microsoft.azure.storage.blob.BlobEncryptionData.java

public String serialize() throws IOException {

    final StringWriter strWriter = new StringWriter();
    JsonGenerator generator = Utility.getJsonGenerator(strWriter);

    try {//from ww  w  .j  a  va  2 s  . c  o m
        // start object
        generator.writeStartObject();

        // write the encryption mode
        generator.writeStringField(Constants.EncryptionConstants.ENCRYPTION_MODE,
                Constants.EncryptionConstants.FULL_BLOB);

        // write the encryption data
        this.serialize(generator);

        // end object
        generator.writeEndObject();
    } finally {
        generator.close();
    }

    return strWriter.toString();
}