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.baidubce.services.bos.BosClient.java

/**
 * Completes a multipart upload by assembling previously uploaded parts.
 *
 * @param request The CompleteMultipartUploadRequest object that specifies all the parameters of this operation.
 * @return A CompleteMultipartUploadResponse from Bos containing the ETag for
 *     the new object composed of the individual parts.
 */// ww w .j a va2  s  . c  o  m
public CompleteMultipartUploadResponse completeMultipartUpload(CompleteMultipartUploadRequest request) {
    checkNotNull(request, "request should not be null.");

    InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST);
    internalRequest.addParameter("uploadId", request.getUploadId());

    ObjectMetadata metadata = request.getObjectMetadata();
    if (metadata != null) {
        populateRequestMetadata(internalRequest, metadata);
    }

    byte[] json = null;
    List<PartETag> partETags = request.getPartETags();
    StringWriter writer = new StringWriter();
    try {
        JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeArrayFieldStart("parts");
        for (PartETag partETag : partETags) {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeNumberField("partNumber", partETag.getPartNumber());
            jsonGenerator.writeStringField("eTag", partETag.getETag());
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
    } catch (IOException e) {
        throw new BceClientException("Fail to generate json", e);
    }
    try {
        json = writer.toString().getBytes(DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new BceClientException("Fail to get UTF-8 bytes", e);
    }

    internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length));
    internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json");
    internalRequest.setContent(RestartableInputStream.wrap(json));

    CompleteMultipartUploadResponse response = this.invokeHttpClient(internalRequest,
            CompleteMultipartUploadResponse.class);
    response.setBucketName(request.getBucketName());
    return response;
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

@Override
public SerializerResult referenceCollection(final ServiceMetadata metadata, final EdmEntitySet edmEntitySet,
        final AbstractEntityCollection entityCollection, final ReferenceCollectionSerializerOptions options)
        throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    boolean pagination = false;

    try {//from  w w w  .  ja  va2s.  com
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        final UriHelper uriHelper = new UriHelperImpl();
        outputStream = buffer.getOutputStream();
        final JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();

        writeContextURL(contextURL, json);
        if (options != null && options.getCount() != null && options.getCount().getValue()) {
            writeInlineCount("", entityCollection.getCount(), json);
        }

        json.writeArrayFieldStart(Constants.VALUE);
        for (final Entity entity : entityCollection) {
            json.writeStartObject();
            json.writeStringField(constants.getId(), uriHelper.buildCanonicalURL(edmEntitySet, entity));
            json.writeEndObject();
        }
        json.writeEndArray();

        writeNextLink(entityCollection, json, pagination);

        json.writeEndObject();

        json.close();
        outputStream.close();
        return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final IOException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }

}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

/**
 * Process a GET request for the specified resource.
 *
 * @param request//w  w  w .jav  a 2s  .  com
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        JsonGenerator jg = null;
        String jsonpcb = null;
        PrintWriter writer = null;
        try {
            writer = response.getWriter();

            // "callback" parameter implies JSONP outpout
            jsonpcb = request.getParameter(CALLBACK_PARAM);
            if (jsonpcb != null) {
                response.setContentType("application/javascript; charset=utf8");
                writer.write(jsonpcb + "(");
            } else {
                response.setContentType("application/json; charset=utf8");
            }

            jg = jsonFactory.createGenerator(writer);
            jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
            jg.useDefaultPrettyPrinter();
            jg.writeStartObject();

            // query per mbean attribute
            String getmethod = request.getParameter("get");
            if (getmethod != null) {
                String[] splitStrings = getmethod.split("\\:\\:");
                if (splitStrings.length != 2) {
                    jg.writeStringField("result", "ERROR");
                    jg.writeStringField("message", "query format is not as expected.");
                    jg.flush();
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                listBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response);
                return;
            }

            // query per mbean
            String qry = request.getParameter("qry");
            if (qry == null) {
                qry = "*:*";
            }
            listBeans(jg, new ObjectName(qry), null, response);
        } finally {
            if (jg != null) {
                jg.close();
            }
            if (jsonpcb != null) {
                writer.write(");");
            }
            if (writer != null) {
                writer.close();
            }
        }
    } catch (IOException e) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

@Override
public SerializerResult primitiveCollection(final ServiceMetadata metadata, final EdmPrimitiveType type,
        final Property property, final PrimitiveSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {// w ww.  j a  v a  2s . c  o  m
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();
        writeContextURL(contextURL, json);
        writeMetadataETag(metadata, json);
        if (isODataMetadataFull) {
            json.writeStringField(constants.getType(),
                    "#Collection(" + type.getFullQualifiedName().getName() + ")");
        }
        writeOperations(property.getOperations(), json);
        json.writeFieldName(Constants.VALUE);
        writePrimitiveCollection(type, property, options == null ? null : options.isNullable(),
                options == null ? null : options.getMaxLength(),
                options == null ? null : options.getPrecision(), options == null ? null : options.getScale(),
                options == null ? null : options.isUnicode(), json);
        json.writeEndObject();

        json.close();
        outputStream.close();
        return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final IOException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

/***
 *
 * Returns a json representation of the Enumerator
 * The Enumerator must implements the IProperties interface
 * @param en    the Enumerator to serialize. It must implements the IProperties interface
 * @return       the representation of the Enumerator 
 *///from   w  ww .ja v a 2 s . c o  m
@SuppressWarnings("unchecked")
public static String dumpConfigurationAsJson(String section) {
    Class en = CONFIGURATION_SECTIONS.get(section);
    try {
        JsonFactory jfactory = new JsonFactory();
        StringWriter sw = new StringWriter();
        String enumDescription = "";
        JsonGenerator gen = jfactory.createJsonGenerator(sw);

        Method getEnumDescription = en.getMethod("getEnumDescription");
        if (getEnumDescription != null && getEnumDescription.getReturnType() == String.class
                && Modifier.isStatic(getEnumDescription.getModifiers()))
            enumDescription = (String) getEnumDescription.invoke(null);
        gen.writeStartObject(); //{
        gen.writeStringField("section", section); //    "configuration":"EnumName"
        gen.writeStringField("description", enumDescription); //   ,"description": "EnumDescription"
        gen.writeFieldName("sub sections"); //  ,"sections":
        gen.writeStartObject(); //      {
        String lastSection = "";
        EnumSet values = EnumSet.allOf(en);
        for (Object v : values) {
            String key = (String) (en.getMethod("getKey")).invoke(v);
            boolean isVisible = (Boolean) (en.getMethod("isVisible")).invoke(v);
            String valueAsString;
            if (isVisible)
                valueAsString = (String) (en.getMethod("getValueAsString")).invoke(v);
            else
                valueAsString = "--HIDDEN--";
            boolean isEditable = (Boolean) (en.getMethod("isEditable")).invoke(v);
            String valueDescription = (String) (en.getMethod("getValueDescription")).invoke(v);
            Class type = (Class) en.getMethod("getType").invoke(v);
            String subsection = key.substring(0, key.indexOf('.'));
            if (!lastSection.equals(subsection)) {
                if (gen.getOutputContext().inArray())
                    gen.writeEndArray();
                gen.writeFieldName(subsection); //         "sectionName":
                gen.writeStartArray(); //            [
                lastSection = subsection;
            }
            boolean isOverridden = (Boolean) (en.getMethod("isOverridden")).invoke(v);
            gen.writeStartObject(); //               {
            gen.writeStringField(key, valueAsString); //                     "key": "value"   
            gen.writeStringField("description", valueDescription); //                  ,"description":"description"
            gen.writeStringField("type", type.getSimpleName()); //                  ,"type":"type"
            gen.writeBooleanField("editable", isEditable); //                  ,"editable":"true|false"
            gen.writeBooleanField("visible", isVisible); //                  ,"visible":"true|false"
            gen.writeBooleanField("overridden", isOverridden); //                  ,"overridden":"true|false"
            gen.writeEndObject(); //               }
        }
        if (gen.getOutputContext().inArray())
            gen.writeEndArray(); //            ]
        gen.writeEndObject(); //      }
        gen.writeEndObject(); //}
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName()
                + " Enum. Is it an Enum that implements the IProperties interface?", e);
    }
    return "{}";
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

@Override
public SerializerResult primitive(final ServiceMetadata metadata, final EdmPrimitiveType type,
        final Property property, final PrimitiveSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {//from w ww.j a  va2  s .c om
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();
        writeContextURL(contextURL, json);
        writeMetadataETag(metadata, json);
        writeOperations(property.getOperations(), json);
        if (property.isNull()) {
            throw new SerializerException("Property value can not be null.",
                    SerializerException.MessageKeys.NULL_INPUT);
        } else {
            json.writeFieldName(Constants.VALUE);
            writePrimitive(type, property, options == null ? null : options.isNullable(),
                    options == null ? null : options.getMaxLength(),
                    options == null ? null : options.getPrecision(),
                    options == null ? null : options.getScale(), options == null ? null : options.isUnicode(),
                    json);
        }
        json.writeEndObject();

        json.close();
        outputStream.close();
        return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final IOException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } catch (final EdmPrimitiveTypeException e) {
        cachedException = new SerializerException("Wrong value for property!", e,
                SerializerException.MessageKeys.WRONG_PROPERTY_VALUE, property.getName(),
                property.getValue().toString());
        throw cachedException;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

From source file:org.sead.repositories.reference.RefRepository.java

protected static void generateIndex(InputStream ro, File descFile, File indexFile)
        throws JsonParseException, IOException {

    log.debug("Generating desc and index files");
    JsonFactory f = new MappingJsonFactory(); // reading
    JsonParser jp = f.createParser(ro);/*from ww w.  j  a  v a  2  s .  c o  m*/

    JsonGenerator generator = new JsonFactory().createGenerator(descFile, JsonEncoding.UTF8);

    JsonToken current;

    current = jp.nextToken();

    report(jp, current);
    while ((current = jp.nextToken()) != null) {
        if (current.equals(JsonToken.FIELD_NAME)) {
            String fName = jp.getText();
            if (fName.equals("describes")) {
                log.trace("describes");
                while (((current = jp.nextToken()) != null)) {
                    if (jp.isExpectedStartObjectToken()) {
                        generator.setCodec(new ObjectMapper());
                        generator.useDefaultPrettyPrinter();

                        generator.writeStartObject();

                        while (((current = jp.nextToken()) != JsonToken.END_OBJECT)) {
                            if (current != JsonToken.FIELD_NAME) {
                                log.warn("Unexpected Token!");
                                report(jp, current);

                            } else {
                                report(jp, current);
                                String name = jp.getText();
                                current = jp.nextToken(); // Get to start of
                                // value
                                if (!name.equals("aggregates")) {
                                    log.trace("Writing: " + name);
                                    generator.writeFieldName(name);
                                    generator.writeTree(jp.readValueAsTree());
                                } else {
                                    report(jp, current);
                                    log.trace("Skipping?");
                                    if (current.isStructStart()) {
                                        indexChildren(indexFile, jp);
                                        // jp.skipChildren();
                                    } else {
                                        log.warn("Was Not Struct start!");
                                    }
                                    log.trace("Hit aggregates");

                                }
                            }
                        }

                        generator.writeEndObject();

                        generator.close();
                    }
                }
            }
        }
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

public void entityCollectionIntoStream(final ServiceMetadata metadata, final EdmEntityType entityType,
        final EntityIterator entitySet, final EntityCollectionSerializerOptions options,
        final OutputStream outputStream) throws SerializerException {

    SerializerException cachedException;
    boolean pagination = false;
    try {/*from ww w .  jav a 2 s .  c  o  m*/
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();

        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        writeContextURL(contextURL, json);

        writeMetadataETag(metadata, json);

        if (options != null && options.getCount() != null && options.getCount().getValue()) {
            writeInlineCount("", entitySet.getCount(), json);
        }
        json.writeFieldName(Constants.VALUE);
        String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType();
        if (options == null) {
            writeEntitySet(metadata, entityType, entitySet, null, null, null, false, null, name, json);
        } else {
            writeEntitySet(metadata, entityType, entitySet, options.getExpand(), null, options.getSelect(),
                    options.getWriteOnlyReferences(), null, name, json);
        }
        // next link support for streaming results
        writeNextLink(entitySet, json, pagination);

        json.close();
    } catch (final IOException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } catch (DecoderException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    }
}

From source file:com.ntsync.shared.RawContact.java

/**
 * Convert the RawContact object into a DTO. From the JSONString interface.
 * /*w  w  w.j a  v a 2  s.c o  m*/
 * @return a JSON string representation of the object
 */
public byte[] toDTO(Key secret, String pwdSaltBase64) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream(DEFAULT_BYTEARRAY_SIZE);
        AEADBlockCipher ecipher = CryptoHelper.getCipher();

        byte[] iv = new byte[CryptoHelper.IV_LEN];
        SecureRandom random = new SecureRandom();

        StringBuilder hashValue = new StringBuilder();
        hashValue.append(pwdSaltBase64);
        hashValue.append(displayName);
        hashValue.append(lastName);
        hashValue.append(firstName);
        hashValue.append(middleName);

        out.write(ContactConstants.ROWID);
        byte[] rowId = String.valueOf(mRawContactId).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME);

        SyncDataHelper.writeInt(out, rowId.length);
        out.write(rowId);

        JsonFactory json = new JsonFactory();
        StringWriter writer = new StringWriter();
        JsonGenerator g = json.createGenerator(writer);
        g.writeStartObject();

        writeStructuredName(g);

        writeList(hashValue, g, ContactConstants.PHONE, phones, true);
        writeList(hashValue, g, ContactConstants.EMAIL, emails, true);
        writeList(hashValue, g, ContactConstants.EVENT, events, false);
        writeList(hashValue, g, ContactConstants.RELATION, relations, false);
        writeList(hashValue, g, ContactConstants.SIPADDRESS, sipAddresses, false);
        writeList(hashValue, g, ContactConstants.NICKNAME, nicknames, false);
        writeList(hashValue, g, ContactConstants.WEBSITE, websites, false);
        writeAddress(hashValue, g, addresses);
        writeImList(g, imAddresses);
        writeOrganization(g, organization);

        writeField(g, ContactConstants.NOTE, note);
        if (starred) {
            g.writeBooleanField(ContactConstants.STARRED, true);
        }
        if (sendToVoiceMail) {
            g.writeBooleanField(ContactConstants.SEND_TO_VOICE_MAIL, true);
        }
        writeField(g, ContactConstants.DROID_CUSTOM_RINGTONE, droidCustomRingtone);

        if (photoSuperPrimary) {
            g.writeBooleanField(ContactConstants.PHOTO_SUPERPRIMARY, true);
        }

        writeStringList(g, ContactConstants.GROUPMEMBERSHIP, groupSourceIds);

        g.writeEndObject();
        g.close();

        String textData = writer.toString();

        CryptoHelper.writeValue(secret, out, ecipher, iv, random, ContactConstants.TEXTDATA, textData);
        CryptoHelper.writeValue(secret, out, ecipher, iv, random, ContactConstants.PHOTO, photo);

        if (lastModified != null) {
            writeRawValue(out, ContactConstants.MODIFIED,
                    String.valueOf(lastModified.getTime()).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }

        if (mDeleted) {
            writeRawValue(out, ContactConstants.DELETED, "1".getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }
        writeRawValue(out, ContactConstants.HASH, createHash(hashValue));

        return out.toByteArray();
    } catch (final IOException ex) {
        LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex);
    } catch (GeneralSecurityException ex) {
        LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex);
    } catch (InvalidCipherTextException ex) {
        LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex);
    }
    return null;
}

From source file:tds.student.web.backing.TestShellScriptsBacking.java

private void addTestConfig() throws JsonGenerationException, IOException {
    // get test configp[
    TestConfig testConfig = _testOpportunity.getTestConfig();

    // get json config
    StringWriter sw = new StringWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator writer = jsonFactory.createGenerator(sw);

    // create test config json
    writer.writeStartObject();// {
    // writer.writeObjectField ("type", "object");

    // properties
    writer.writeStringField("urlBase", UrlHelper.getBase());
    writer.writeNumberField("reviewPage", getViewPageNumber());
    writer.writeBooleanField("hasAudio", _testProps.getRequirements().isHasAudio());
    writer.writeBooleanField("autoMute", shouldAutoMuteVolume());

    // test config (DB)
    writer.writeStringField("testName", _testProps.getDisplayName());
    writer.writeNumberField("testLength", testConfig.getTestLength());
    writer.writeNumberField("startPosition", testConfig.getStartPosition());
    writer.writeNumberField("contentLoadTimeout", testConfig.getContentLoadTimeout());
    writer.writeNumberField("requestInterfaceTimeout", testConfig.getRequestInterfaceTimeout());
    writer.writeNumberField("oppRestartMins", testConfig.getOppRestartMins());
    writer.writeNumberField("interfaceTimeout", testConfig.getInterfaceTimeout());

    // app settings (DB or settings.config)
    writer.writeNumberField("interfaceTimeoutDialog", TestShellSettings.getTimeoutDialog().getValue());
    writer.writeNumberField("autoSaveInterval", TestShellSettings.getAutoSaveInterval().getValue());
    writer.writeNumberField("forbiddenAppsInterval", TestShellSettings.getForbiddenAppsInterval().getValue());
    writer.writeBooleanField("disableSaveWhenInactive",
            TestShellSettings.isDisableSaveWhenInactive().getValue());
    writer.writeBooleanField("disableSaveWhenForbiddenApps",
            TestShellSettings.isDisableSaveWhenForbiddenApps().getValue());
    writer.writeBooleanField("allowSkipAudio", TestShellSettings.isAllowSkipAudio().getValue());
    writer.writeBooleanField("showSegmentLabels", TestShellSettings.isShowSegmentLabels().getValue());
    writer.writeNumberField("audioTimeout", TestShellSettings.getAudioTimeout().getValue());
    writer.writeBooleanField("enableLogging", TestShellSettings.isEnableLogging().getValue());

    writer.writeEndObject(); // }

    writer.close();

    // write out javascript
    StringBuilder javascript = new StringBuilder();
    javascript.append("var tdsTestConfig = ");
    javascript.append(sw.toString());/*from www  .j  a v  a 2s  .  co  m*/
    javascript.append("; ");

    this.getClientScript().addToJsCode(javascript.toString());
}