Example usage for com.fasterxml.jackson.core JsonFactory JsonFactory

List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory

Introduction

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

Prototype

public JsonFactory() 

Source Link

Document

Default constructor used to create factory instances.

Usage

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  www . j  av  a2 s  .co  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);
        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.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  ww  w.  j av  a  2s  . c om*/
        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: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 w w . j  a v  a 2 s  .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:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

@Override
public SerializerResult complexCollection(final ServiceMetadata metadata, final EdmComplexType type,
        final Property property, final ComplexSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {/*from  ww w  .j  a va2  s.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().getFullQualifiedNameAsString() + ")");
        }
        writeOperations(property.getOperations(), json);
        json.writeFieldName(Constants.VALUE);
        Set<List<String>> selectedPaths = null;
        if (null != options && null != options.getSelect()) {
            final boolean all = ExpandSelectHelper.isAll(options.getSelect());
            selectedPaths = all || property.isPrimitive() ? null
                    : ExpandSelectHelper.getSelectedPaths(options.getSelect().getSelectItems());
        }
        Set<List<String>> expandPaths = null;
        if (null != options && null != options.getExpand()) {
            expandPaths = ExpandSelectHelper.getExpandedItemsPath(options.getExpand());
        }
        writeComplexCollection(metadata, type, property, selectedPaths, json, expandPaths, null,
                options == null ? null : options.getExpand());
        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.rhfung.P2PDictionary.DataConnection.java

private byte[] GetEntryMetadataAsJson(DataEntry entry) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
    JsonGenerator jg;/*from  ww w  .  ja  va  2s  .  c  o m*/
    try {
        jg = jsonFactory.createJsonGenerator(stream, JsonEncoding.UTF8);
        WriteJSONForEntry(jg, entry);
        jg.flush();
    } catch (JsonGenerationException ex) {
        return new byte[0];

    } catch (IOException e) {
        // TODO Auto-generated catch block
        return new byte[0];
    } // or Stream, Reader

    return stream.toByteArray();
}

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;//ww  w . ja  v  a2s.  c om
    try {
        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();
}

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

@Override
public SerializerResult reference(final ServiceMetadata metadata, final EdmEntitySet edmEntitySet,
        final Entity entity, final ReferenceSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;

    try {/*from  www  .j  a  va 2s.  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);
        json.writeStringField(constants.getId(), uriHelper.buildCanonicalURL(edmEntitySet, entity));
        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: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.j  av  a2  s. c  o m
        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.buaa.cfs.conf.Configuration.java

/**
 * Writes out all the parameters and their properties (final and resource) to the given {@link Writer} The format of
 * the output would be { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
 * key2.isFinal,key2.resource}... ] } It does not output the parameters of the configuration object which is loaded
 * from an input stream.//from  w w w.ja  v  a2s . c  o  m
 *
 * @param out the Writer to write to
 *
 * @throws IOException
 */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            String[] resources = config.updatingResource.get(item.getKey());
            String resource = UNKNOWN_RESOURCE;
            if (resources != null && resources.length > 0) {
                resource = resources[0];
            }
            dumpGenerator.writeStringField("resource", resource);
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}

From source file:com.marklogic.client.functionaltest.TestBiTemporal.java

@Test
// Test Period Range Query using ALN_CONTAINS. We use a single axis during query
public void testPeriodRangeQuerySingleAxisBasedOnALNContains() throws Exception {
    System.out.println("Inside testPeriodRangeQuerySingleAxisBasedOnALNContains");

    // Read documents based on document URI and ALN Contains. We are just
    // looking for count of documents to be correct

    String docId = "javaSingleJSONDoc.json";

    insertJSONSingleDocument(temporalCollectionName, docId, null);

    updateJSONSingleDocument(temporalCollectionName, docId);

    // Fetch documents associated with a search term (such as XML) in Address
    // element/* w  ww  . j a  va  2  s. c  o m*/
    QueryManager queryMgr = readerClient.newQueryManager();
    StructuredQueryBuilder sqb = queryMgr.newStructuredQueryBuilder();

    StructuredQueryDefinition termQuery = sqb.collection(docId);

    StructuredQueryBuilder.Axis validAxis = sqb.axis(axisValidName);
    Calendar start1 = DatatypeConverter.parseDateTime("2001-01-01T00:00:01");
    Calendar end1 = DatatypeConverter.parseDateTime("2011-12-31T23:59:58");
    StructuredQueryBuilder.Period period1 = sqb.period(start1, end1);
    StructuredQueryDefinition periodQuery = sqb.and(termQuery,
            sqb.temporalPeriodRange(validAxis, TemporalOperator.ALN_CONTAINS, period1));

    long start = 1;
    JSONDocumentManager docMgr = readerClient.newJSONDocumentManager();
    docMgr.setMetadataCategories(Metadata.ALL); // Get all metadata
    DocumentPage termQueryResults = docMgr.search(periodQuery, start);

    long count = 0;
    while (termQueryResults.hasNext()) {
        ++count;
        DocumentRecord record = termQueryResults.next();
        System.out.println("URI = " + record.getUri());

        DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle();
        record.getMetadata(metadataHandle);
        Iterator<String> resCollections = metadataHandle.getCollections().iterator();
        while (resCollections.hasNext()) {
            System.out.println("Collection = " + resCollections.next());
        }

        if (record.getFormat() == Format.XML) {
            DOMHandle recordHandle = new DOMHandle();
            record.getContent(recordHandle);
            System.out.println("Content = " + recordHandle.toString());
        } else {
            JacksonDatabindHandle<ObjectNode> recordHandle = new JacksonDatabindHandle<ObjectNode>(
                    ObjectNode.class);
            record.getContent(recordHandle);
            System.out.println("Content = " + recordHandle.toString());

            JsonFactory factory = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(factory);
            TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
            };

            HashMap<String, Object> docObject = mapper.readValue(recordHandle.toString(), typeRef);

            @SuppressWarnings("unchecked")
            HashMap<String, Object> systemNode = (HashMap<String, Object>) (docObject.get(systemNodeName));

            String systemStartDate = (String) systemNode.get(systemStartERIName);
            String systemEndDate = (String) systemNode.get(systemEndERIName);
            System.out.println("systemStartDate = " + systemStartDate);
            System.out.println("systemEndDate = " + systemEndDate);

            @SuppressWarnings("unchecked")
            HashMap<String, Object> validNode = (HashMap<String, Object>) (docObject.get(validNodeName));

            String validStartDate = (String) validNode.get(validStartERIName);
            String validEndDate = (String) validNode.get(validEndERIName);
            System.out.println("validStartDate = " + validStartDate);
            System.out.println("validEndDate = " + validEndDate);

            assertTrue("Valid start date check failed", (validStartDate.equals("2001-01-01T00:00:00")
                    && validEndDate.equals("2011-12-31T23:59:59")));
        }
    }

    System.out.println("Number of results using SQB = " + count);
    assertEquals("Wrong number of results", 1, count);
}