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.streamsets.datacollector.http.JMXJsonServlet.java

private void listBeans(JsonGenerator jg, ObjectName qry, String attribute, HttpServletResponse response)
        throws IOException {

    Set<ObjectName> names = null;
    names = mBeanServer.queryNames(qry, null);

    jg.writeArrayFieldStart("beans");
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        MBeanInfo minfo;//  w ww. j a  v a 2 s .  c om
        String code = "";
        Object attributeinfo = null;
        try {
            minfo = mBeanServer.getMBeanInfo(oname);
            code = minfo.getClassName();
            String prs = "";
            try {
                if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                    prs = "modelerType";
                    code = (String) mBeanServer.getAttribute(oname, prs);
                }
                if (attribute != null) {
                    prs = attribute;
                    attributeinfo = mBeanServer.getAttribute(oname, prs);
                }
            } catch (AttributeNotFoundException e) {
                // If the modelerType attribute was not found, the class name is used
                // instead.

            } catch (MBeanException e) {
                // The code inside the attribute getter threw an exception so 
                // and fall back on the class name

            } catch (RuntimeException e) {
                // For some reason even with an MBeanException available to them
                // Runtime exceptionscan still find their way through, so treat them
                // the same as MBeanException

            } catch (ReflectionException e) {
                // This happens when the code inside the JMX bean (setter?? from the
                // java docs) threw an exception, so 
                // class name

            }
        } catch (InstanceNotFoundException e) {
            //Ignored for some reason the bean was not found so don't output it
            continue;
        } catch (IntrospectionException e) {
            // This is an internal error, something odd happened with reflection so
            // 

            continue;
        } catch (ReflectionException e) {
            // This happens when the code inside the JMX bean threw an exception, so
            // 

            continue;
        }

        jg.writeStartObject();
        jg.writeStringField("name", oname.toString());

        jg.writeStringField("modelerType", code);
        if ((attribute != null) && (attributeinfo == null)) {
            jg.writeStringField("result", "ERROR");
            jg.writeStringField("message", "No attribute with name " + attribute + " was found.");
            jg.writeEndObject();
            jg.writeEndArray();
            jg.close();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (attribute != null) {
            writeAttribute(jg, attribute, attributeinfo);
        } else {
            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            for (int i = 0; i < attrs.length; i++) {
                writeAttribute(jg, oname, attrs[i]);
            }
        }
        jg.writeEndObject();
    }
    jg.writeEndArray();
}

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

@Override
public SerializerResult complex(final ServiceMetadata metadata, final EdmComplexType type,
        final Property property, final ComplexSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {/*from  w  ww. ja v  a 2  s  . co m*/
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        final String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType();
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();
        writeContextURL(contextURL, json);
        writeMetadataETag(metadata, json);
        EdmComplexType resolvedType = null;
        if (!type.getFullQualifiedName().getFullQualifiedNameAsString().equals(property.getType())) {
            if (type.getBaseType() != null && type.getBaseType().getFullQualifiedName()
                    .getFullQualifiedNameAsString().equals(property.getType())) {
                resolvedType = resolveComplexType(metadata, type.getBaseType(),
                        type.getFullQualifiedName().getFullQualifiedNameAsString());
            } else {
                resolvedType = resolveComplexType(metadata, type, property.getType());
            }
        } else {
            resolvedType = resolveComplexType(metadata, type, property.getType());
        }
        if (!isODataMetadataNone && !resolvedType.equals(type) || isODataMetadataFull) {
            json.writeStringField(constants.getType(),
                    "#" + resolvedType.getFullQualifiedName().getFullQualifiedNameAsString());
        }
        writeOperations(property.getOperations(), json);
        final List<Property> values = property.isNull() ? Collections.<Property>emptyList()
                : property.asComplex().getValue();
        writeProperties(metadata, type, values,
                options == null ? null : options == null ? null : options.getSelect(), json,
                property.asComplex(), options == null ? null : options.getExpand());
        if (!property.isNull() && property.isComplex()) {
            writeNavigationProperties(metadata, type, property.asComplex(),
                    options == null ? null : options.getExpand(), null, null, name, 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 (DecoderException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

From source file:msearch.filmlisten.MSFilmlisteSchreiben.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {
    MSLog.systemMeldung("Filme schreiben (" + listeFilme.size() + " Filme) :");
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(915236478, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }/*from ww w .j av  a2  s  . c o  m*/
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    try {
        String sender = "", thema = "";
        JsonFactory jsonF = new JsonFactory();
        JsonGenerator jg;
        if (datei.endsWith(MSConst.FORMAT_XZ)) {
            LZMA2Options options = new LZMA2Options();
            XZOutputStream out = new XZOutputStream(new FileOutputStream(file), options);
            jg = jsonF.createGenerator(out);
        } else if (datei.endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                    9 /*Blocksize: 1 - 9*/);
            jg = jsonF.createGenerator(bZip2CompressorOutputStream, JsonEncoding.UTF8);
        } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
            zipOutputStream.putNextEntry(entry);
            jg = jsonF.createGenerator(zipOutputStream, JsonEncoding.UTF8);
        } else {
            jg = jsonF.createGenerator(new File(datei), JsonEncoding.UTF8);
        }
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();
        // Infos zur Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < ListeFilme.MAX_ELEM; ++i) {
            jg.writeString(listeFilme.metaDaten[i]);
        }
        jg.writeEndArray();
        // Infos der Felder in der Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
            jg.writeString(DatenFilm.COLUMN_NAMES[DatenFilm.COLUMN_NAMES_JSON[i]]);
        }
        jg.writeEndArray();
        //Filme schreiben
        ListIterator<DatenFilm> iterator;
        DatenFilm datenFilm;
        iterator = listeFilme.listIterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            jg.writeArrayFieldStart(DatenFilm.FILME_);
            for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                int m = DatenFilm.COLUMN_NAMES_JSON[i];
                if (m == DatenFilm.FILM_SENDER_NR) {
                    if (datenFilm.arr[m].equals(sender)) {
                        jg.writeString("");
                    } else {
                        sender = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else if (m == DatenFilm.FILM_THEMA_NR) {
                    if (datenFilm.arr[m].equals(thema)) {
                        jg.writeString("");
                    } else {
                        thema = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else {
                    jg.writeString(datenFilm.arr[m]);
                }
            }
            jg.writeEndArray();
        }
        jg.writeEndObject();
        jg.close();
        MSLog.systemMeldung("   --> geschrieben!");
    } catch (Exception ex) {
        MSLog.fehlerMeldung(846930145, MSLog.FEHLER_ART_PROG, "IoXmlSchreiben.FilmeSchreiben", ex,
                "nach: " + datei);
    }
}

From source file:msearch.io.MSFilmlisteSchreiben.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {
    MSLog.systemMeldung("Filme Schreiben (" + listeFilme.size() + " Filme) :");
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(915236478, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }/*from w  w w  . j av  a2s.  co m*/
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    try {
        String sender = "", thema = "";
        JsonFactory jsonF = new JsonFactory();
        JsonGenerator jg;
        if (datei.endsWith(MSConst.FORMAT_XZ)) {
            LZMA2Options options = new LZMA2Options();
            XZOutputStream out = new XZOutputStream(new FileOutputStream(file), options);
            jg = jsonF.createGenerator(out);
        } else if (datei.endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                    9 /*Blocksize: 1 - 9*/);
            jg = jsonF.createGenerator(bZip2CompressorOutputStream, JsonEncoding.UTF8);
        } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
            zipOutputStream.putNextEntry(entry);
            jg = jsonF.createGenerator(zipOutputStream, JsonEncoding.UTF8);
        } else {
            jg = jsonF.createGenerator(new File(datei), JsonEncoding.UTF8);
        }
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();
        // Infos zur Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < ListeFilme.MAX_ELEM; ++i) {
            jg.writeString(listeFilme.metaDaten[i]);
        }
        jg.writeEndArray();
        // Infos der Felder in der Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
            jg.writeString(DatenFilm.COLUMN_NAMES[DatenFilm.COLUMN_NAMES_JSON[i]]);
        }
        jg.writeEndArray();
        //Filme schreiben
        ListIterator<DatenFilm> iterator;
        DatenFilm datenFilm;
        iterator = listeFilme.listIterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            jg.writeArrayFieldStart(DatenFilm.FILME_);
            for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                int m = DatenFilm.COLUMN_NAMES_JSON[i];
                if (m == DatenFilm.FILM_SENDER_NR) {
                    if (datenFilm.arr[m].equals(sender)) {
                        jg.writeString("");
                    } else {
                        sender = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else if (m == DatenFilm.FILM_THEMA_NR) {
                    if (datenFilm.arr[m].equals(thema)) {
                        jg.writeString("");
                    } else {
                        thema = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else {
                    jg.writeString(datenFilm.arr[m]);
                }
            }
            jg.writeEndArray();
        }
        jg.writeEndObject();
        jg.close();
        MSLog.systemMeldung("   --> geschrieben!");
    } catch (Exception ex) {
        MSLog.fehlerMeldung(846930145, MSLog.FEHLER_ART_PROG, "IoXmlSchreiben.FilmeSchreiben", ex,
                "nach: " + datei);
    }
}

From source file:org.eclipse.winery.repository.rest.resources.AbstractComponentsResource.java

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI//ww w  . j  av  a  2  s . co  m
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. <br /> Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>. <br /><br /> If grouped is set, the list will be grouped by namespace.
 * <br /> <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped) {
    Class<? extends TOSCAComponentId> idClass = RestUtils
            .getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = RepositoryFactory.getRepository()
            .getAllTOSCAComponentIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (TOSCAComponentId id : allTOSCAcomponentIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                            .getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends TOSCAComponentId>> groupedIds = allTOSCAcomponentIds
                    .stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                                        .getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}

From source file:org.eclipse.winery.repository.resources.entitytypes.relationshiptypes.VisualAppearanceResource.java

@GET
@RestDoc(methodDescription = "@return JSON object to be used at jsPlumb.registerConnectionType('NAME', <data>)")
@Produces(MediaType.APPLICATION_JSON)//ww w  . ja v  a2s  . c  o m
public Response getConnectionTypeForJsPlumbData() {
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        jg.writeStartObject();

        jg.writeFieldName("connector");
        jg.writeString("Flowchart");

        jg.writeFieldName("paintStyle");
        jg.writeStartObject();
        jg.writeFieldName("lineWidth");
        jg.writeNumber(this.getLineWidth());
        jg.writeFieldName("strokeStyle");
        jg.writeObject(this.getColor());
        String dash = this.getDash();
        if (!StringUtils.isEmpty(dash)) {
            String dashStyle = null;
            switch (dash) {
            case "dotted":
                dashStyle = "1 5";
                break;
            case "dotted2":
                dashStyle = "3 4";
                break;
            case "plain":
                // default works
                // otherwise, "1 0" can be used
                break;
            }
            if (dashStyle != null) {
                jg.writeStringField("dashstyle", dashStyle);
            }
        }
        jg.writeEndObject();

        jg.writeFieldName("hoverPaintStyle");
        jg.writeStartObject();
        jg.writeFieldName("strokeStyle");
        jg.writeObject(this.getHoverColor());
        jg.writeEndObject();

        // BEGIN: Overlays

        jg.writeFieldName("overlays");
        jg.writeStartArray();

        // source arrow head
        String head = this.getSourceArrowHead();
        if (!head.equals("none")) {
            jg.writeStartArray();
            jg.writeString(head);

            jg.writeStartObject();

            jg.writeFieldName("location");
            jg.writeNumber(0);

            // arrow should point towards the node and not away from it
            jg.writeFieldName("direction");
            jg.writeNumber(-1);

            jg.writeFieldName("width");
            jg.writeNumber(20);

            jg.writeFieldName("length");
            jg.writeNumber(12);

            jg.writeEndObject();
            jg.writeEndArray();
        }

        // target arrow head
        head = this.getTargetArrowHead();
        if (!head.equals("none")) {
            jg.writeStartArray();
            jg.writeString(head);
            jg.writeStartObject();
            jg.writeFieldName("location");
            jg.writeNumber(1);
            jg.writeFieldName("width");
            jg.writeNumber(20);
            jg.writeFieldName("length");
            jg.writeNumber(12);
            jg.writeEndObject();
            jg.writeEndArray();
        }

        // Type in brackets on the arrow
        jg.writeStartArray();
        jg.writeString("Label");
        jg.writeStartObject();
        jg.writeStringField("id", "label");
        //jg.writeStringField("label", "(" + ((RelationshipTypeResource) this.res).getName() + ")");
        jg.writeStringField("label", "");
        jg.writeStringField("cssClass", "relationshipTypeLabel");
        jg.writeFieldName("location");
        jg.writeNumber(0.5);
        jg.writeEndObject();
        jg.writeEndArray();

        jg.writeEndArray();

        // END: Overlays

        jg.writeEndObject();

        jg.close();
    } catch (Exception e) {
        VisualAppearanceResource.logger.error(e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build();
    }
    String res = sw.toString();
    return Response.ok(res).build();
}

From source file:com.rhfung.P2PDictionary.DataConnection.java

private byte[] GetDictionaryAsJson() {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
    JsonGenerator jg;
    try {// w w  w .j  av  a  2s  .com
        jg = jsonFactory.createJsonGenerator(stream, JsonEncoding.UTF8);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return new byte[0];
    } // or Stream, Reader

    List<DataEntry> entries; // make a local copy for access without worry about changes thereafter
    this.dataLock.readLock().lock();
    try {
        entries = new Vector<DataEntry>(this.data.size());
        //entries.AddRange(this.data.Values.Where(x => x.subscribed));
        entries.addAll(this.data.values());
    } finally {
        this.dataLock.readLock().unlock();
    }

    // write count of data entries
    //writer.write(DATA_NAMESPACE + "/\t" + this.local_uid + "\t0\tRW\t" + entries.size() + "\t" + this.local_uid + NEWLINE) ;
    try {
        jg.writeStartObject();
        jg.writeObjectField("size", entries.size());
        jg.writeObjectField("localid", this.local_uid);

        jg.writeArrayFieldStart("keys");

        // write each data entry, converting simple data immediately
        // (pretend i don't know about these non-subscribed entries)
        for (DataEntry d : entries) {
            WriteJSONForEntry(jg, d);
        }

        jg.writeEndArray();
        jg.writeEndObject();

        jg.close();
    } catch (JsonGenerationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return stream.toByteArray();
}