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:eu.project.ttc.engines.exporter.JsonCasExporter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    /*//from w ww.j av  a  2 s  . c  om
     *  Cette mthode est appele par le framework UIMA
     *  pour chaque document  de ta collection (corpus).
     *
     *  Tu peux gnrer ton fichier compagnon dans cette mthode.
     *  (Je te donne l'astuce pour retrouver le nom et le chemin du fichier
     *  de ton corpus correspondant au CAS pass en paramtre de cette
     *  mthode plus tard)
     */

    FSIterator<Annotation> it = aJCas.getAnnotationIndex().iterator();
    Annotation a;
    JsonFactory jsonFactory = new JsonFactory();
    String name = this.getExportFilePath(aJCas, "json");
    File file = new File(this.directoryFile, name);
    FileWriter writer = null;
    try {
        writer = new FileWriter(file);
        LOGGER.debug("Writing " + file.getPath());
        JsonGenerator jg = jsonFactory.createGenerator(writer);
        jg.useDefaultPrettyPrinter();
        jg.writeStartObject();
        jg.writeStringField("file", name);
        jg.writeArrayFieldStart("tag");
        while (it.hasNext()) {
            a = it.next();
            if (a instanceof WordAnnotation) {
                jg.writeStartObject();
                WordAnnotation wordAnno = (WordAnnotation) a;
                for (Feature feat : wordAnno.getType().getFeatures()) {
                    FeatureStructure featureValue = wordAnno.getFeatureValue(feat);
                    if (featureValue != null) {
                        jg.writeFieldName(feat.getName());
                        jg.writeObject(featureValue);
                    }
                }
                jg.writeStringField("tag", wordAnno.getTag());
                jg.writeStringField("lemma", wordAnno.getLemma());
                jg.writeNumberField("begin", wordAnno.getBegin());
                jg.writeNumberField("end", wordAnno.getEnd());
                jg.writeEndObject();
            }
        }
        jg.writeEndArray();
        jg.writeEndObject();
        jg.flush();
        writer.close();
    } catch (IOException e) {
        LOGGER.error("Failure while serializing " + name + "\nCaused by" + e.getClass().getCanonicalName() + ":"
                + e.getMessage(), e);
    }
}

From source file:org.ojai.json.impl.JsonDocumentStream.java

public JsonDocumentStream(InputStream in, Map<FieldPath, Type> fieldPathTypeMap,
        Events.Delegate eventDelegate) {
    inputStream = in;/*  w  w w  . j a v a2s. c  o  m*/
    readStarted = false;
    iteratorOpened = false;
    this.eventDelegate = eventDelegate;
    this.fieldPathTypeMap = fieldPathTypeMap;
    try {
        JsonFactory jFactory = new JsonFactory();
        /* setting explicitly AUTO_CLOSE_SOURCE = false to ensure that
         * jsonParser.close() do not close the underlying inputstream.
         * It has to be closed by the owner of the stream.
         */
        jFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
        jsonParser = jFactory.createParser(inputStream);
    } catch (IOException e) {
        throw new DecodingException(e);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.LocationsTest.java

@Test
public void itGetsAListOfCaches() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/locations/caches");

    CloseableHttpResponse response = null;
    try {/*from  w w w. j  a  v  a2 s  . c  o m*/
        response = closeableHttpClient.execute(httpGet);

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity()));
        String locationName = jsonNode.get("locations").fieldNames().next();
        JsonNode cacheNode = jsonNode.get("locations").get(locationName).get(0);

        assertThat(cacheNode.get("cacheId").asText(), not(equalTo("")));
        assertThat(cacheNode.get("fqdn").asText(), not(equalTo("")));

        assertThat(cacheNode.get("ipAddresses").isArray(), equalTo(true));
        assertThat(cacheNode.has("adminStatus"), equalTo(true));

        assertThat(cacheNode.get("port").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("lastUpdateTime").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("connections").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("currentBW").asInt(-123456), not(equalTo(-123456)));
        assertThat(cacheNode.get("availBW").asInt(-123456), not(equalTo(-123456)));

        assertThat(cacheNode.get("cacheOnline").asText(), anyOf(equalTo("true"), equalTo("false")));
        assertThat(cacheNode.get("lastUpdateHealthy").asText(), anyOf(equalTo("true"), equalTo("false")));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:io.apiman.manager.ui.server.servlets.ConfigurationServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */// w w  w  .j ava 2  s .c  o  m
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        Class.forName("io.apiman.manager.ui.server.UIConfig"); //$NON-NLS-1$
    } catch (Throwable t) {
        t.printStackTrace();
    }

    JsonGenerator g = null;
    try {
        response.getOutputStream().write("window.APIMAN_CONFIG_DATA = ".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
        JsonFactory f = new JsonFactory();
        g = f.createGenerator(response.getOutputStream(), JsonEncoding.UTF8);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        g.setCodec(mapper);
        g.useDefaultPrettyPrinter();

        // Get data from various sources.
        String endpoint = getConfig().getManagementApiEndpoint();
        if (endpoint == null) {
            endpoint = getDefaultEndpoint(request);
        }
        UIVersion version = UIVersion.get();
        ApiAuthType authType = getConfig().getManagementApiAuthType();

        ConfigurationBean configBean = new ConfigurationBean();
        configBean.setApiman(new AppConfigurationBean());
        configBean.setUser(new UserConfigurationBean());
        configBean.setUi(new UiConfigurationBean());
        configBean.setApi(new ApiConfigurationBean());
        configBean.getUi().setHeader("community"); //$NON-NLS-1$
        configBean.getUi().setMetrics(getConfig().isMetricsEnabled());
        configBean.getUi().setPlatform(getConfig().getPlatform());
        configBean.getApiman().setVersion(version.getVersionString());
        configBean.getApiman().setBuiltOn(version.getVersionDate());
        configBean.getApiman().setLogoutUrl(getConfig().getLogoutUrl());
        configBean.getUser().setUsername(request.getRemoteUser());
        configBean.getApi().setEndpoint(endpoint);
        configBean.getApi().setAuth(new ApiAuthConfigurationBean());
        switch (authType) {
        case authToken: {
            configBean.getApi().getAuth().setType(ApiAuthType.authToken);
            String tokenGeneratorClassName = getConfig().getManagementApiAuthTokenGenerator();
            if (tokenGeneratorClassName == null) {
                throw new ServletException("No token generator class specified."); //$NON-NLS-1$
            }
            Class<?> c = Class.forName(tokenGeneratorClassName);
            ITokenGenerator tokenGenerator = (ITokenGenerator) c.newInstance();
            configBean.getApi().getAuth().setBearerToken(tokenGenerator.generateToken(request));
            break;
        }
        case basic: {
            configBean.getApi().getAuth().setType(ApiAuthType.basic);
            configBean.getApi().getAuth().setBasic(new BasicAuthCredentialsBean());
            String username = getConfig().getManagementApiAuthUsername();
            String password = getConfig().getManagementApiAuthPassword();
            configBean.getApi().getAuth().getBasic().setUsername(username);
            configBean.getApi().getAuth().getBasic().setPassword(password);
            break;
        }
        case bearerToken: {
            configBean.getApi().getAuth().setType(ApiAuthType.bearerToken);
            String tokenGeneratorClassName = getConfig().getManagementApiAuthTokenGenerator();
            if (tokenGeneratorClassName == null)
                throw new ServletException("No token generator class specified."); //$NON-NLS-1$
            Class<?> c = Class.forName(tokenGeneratorClassName);
            ITokenGenerator tokenGenerator = (ITokenGenerator) c.newInstance();
            configBean.getApi().getAuth().setBearerToken(tokenGenerator.generateToken(request));
            break;
        }
        case samlBearerToken: {
            configBean.getApi().getAuth().setType(ApiAuthType.samlBearerToken);
            String tokenGeneratorClassName = getConfig().getManagementApiAuthTokenGenerator();
            if (tokenGeneratorClassName == null)
                throw new ServletException("No token generator class specified."); //$NON-NLS-1$
            Class<?> c = Class.forName(tokenGeneratorClassName);
            ITokenGenerator tokenGenerator = (ITokenGenerator) c.newInstance();
            configBean.getApi().getAuth().setBearerToken(tokenGenerator.generateToken(request));
            break;
        }
        }
        g.writeObject(configBean);

        g.flush();
        response.getOutputStream().write(";".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        IOUtils.closeQuietly(g);
    }
}

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

/**
 * Initialize this servlet.// ww  w.j a  v  a  2 s.c  o  m
 */
@Override
public void init() throws ServletException {
    // Retrieve the MBean server
    mBeanServer = ManagementFactory.getPlatformMBeanServer();
    jsonFactory = new JsonFactory();
}

From source file:de.odysseus.staxon.json.stream.jackson.JacksonStreamTargetTest.java

@Test
public void testArray3() throws IOException {
    StringWriter writer = new StringWriter();
    JacksonStreamTarget target = new JacksonStreamTarget(new JsonFactory().createGenerator(writer));

    target.startObject();/*from  w w  w .  j  a  v  a2 s .  c  om*/
    target.name("alice");
    target.startObject();
    target.name("edgar");
    target.startArray();
    target.value("bob");
    target.endArray();
    target.name("charlie");
    target.startArray();
    target.value("bob");
    target.endArray();
    target.endObject();
    target.endObject();

    target.close();

    Assert.assertEquals("{\"alice\":{\"edgar\":[\"bob\"],\"charlie\":[\"bob\"]}}", writer.toString());
}

From source file:squash.deployment.lambdas.utils.CloudFormationResponder.java

/**
 *  Initialises the responder.//from ww  w  . ja  va  2 s  . c  o  m
 *  
 *  <p>This must be called before adding properties to the response or sending the response
 */
public void initialise() throws IOException {
    // Create the node factory that gives us nodes.
    this.factory = new JsonNodeFactory(false);
    // create a json factory to write the treenode as json.
    this.jsonFactory = new JsonFactory();
    this.cloudFormationJsonResponse = new ByteArrayOutputStream();
    this.printStream = new PrintStream(cloudFormationJsonResponse);
    this.generator = jsonFactory.createGenerator(printStream);
    this.mapper = new ObjectMapper();
    this.rootNode = factory.objectNode();
    this.dataOutputsNode = factory.objectNode();
    this.rootNode.set("Data", this.dataOutputsNode);
    this.initialised = true;
}

From source file:com.effektif.workflow.impl.json.JsonStreamMapper.java

public <T> void write(T bean, Writer writer) {
    try {//from w  ww.  ja  va 2  s.  c  om
        JsonGenerator jgen = new JsonFactory().createGenerator(writer);
        if (pretty) {
            jgen.setPrettyPrinter(new DefaultPrettyPrinter());
        }
        JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(mappings, jgen);
        jsonStreamWriter.writeObject(bean);
        jgen.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.loopj.android.http.sample.JsonSample.java

@Override
public ResponseHandlerInterface getResponseHandler() {
    return new BaseJsonHttpResponseHandler<SampleJSON>() {

        @Override//from  w ww.  j  av  a 2 s  .c om
        public void onStart() {
            clearOutputs();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, SampleJSON response) {
            debugHeaders(LOG_TAG, headers);
            debugStatusCode(LOG_TAG, statusCode);
            if (response != null) {
                debugResponse(LOG_TAG, rawJsonResponse);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData,
                SampleJSON errorResponse) {
            debugHeaders(LOG_TAG, headers);
            debugStatusCode(LOG_TAG, statusCode);
            debugThrowable(LOG_TAG, throwable);
            if (errorResponse != null) {
                debugResponse(LOG_TAG, rawJsonData);
            }
        }

        @Override
        protected SampleJSON parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
            return new ObjectMapper().readValues(new JsonFactory().createParser(rawJsonData), SampleJSON.class)
                    .next();
        }

    };
}

From source file:hr.ws4is.JsonDecoder.java

/**
 * Does actual conversion from JSON string to Java class instance
 * @param type/*  ww  w  .  j av  a2  s .  c o m*/
 * @param json
 * @throws IOException
 */
private void parse(final Class<T> type, final String json) throws IOException {
    final JsonFactory factory = new JsonFactory();
    final JsonParser jp = factory.createParser(json);
    final JsonNode jn = OBJECT_MAPPER.readTree(jp);

    if (jn.isArray()) {
        final TypeFactory tf = TypeFactory.defaultInstance();
        final JavaType jt = tf.constructCollectionType(ArrayList.class, type);
        objectList = OBJECT_MAPPER.readValues(jp, jt);
    } else {
        object = OBJECT_MAPPER.treeToValue(jn, type);
    }
}