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.springframework.social.exfm.api.impl.ExFmErrorHandler.java

private Status extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());

    try {/*from   w w  w . ja  va  2  s. c o m*/
        String json = readFully(response.getBody());
        Status responseStatus = mapper.<Status>readValue(json, new TypeReference<Status>() {
        });
        if (!responseStatus.getStatus_code().equals("200")) {
            return responseStatus;
        } else {
            return null;
        }
    } catch (JsonParseException e) {
        return null;
    }

}

From source file:org.graylog2.gelfclient.encoder.GelfMessageJsonEncoderTest.java

@Test
public void testOptionalFullMessage() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageJsonEncoder());
    final GelfMessage message = new GelfMessageBuilder("test").build();
    assertTrue(channel.writeOutbound(message));
    assertTrue(channel.finish());//from  w  w  w .j  av a 2s  . c o  m

    final ByteBuf byteBuf = (ByteBuf) channel.readOutbound();
    final byte[] bytes = new byte[byteBuf.readableBytes()];
    byteBuf.getBytes(0, bytes).release();
    final JsonFactory json = new JsonFactory();
    final JsonParser parser = json.createParser(bytes);

    String version = null;
    Number timestamp = null;
    String host = null;
    String short_message = null;
    String full_message = null;
    Number level = null;

    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String key = parser.getCurrentName();

        if (key == null) {
            continue;
        }

        parser.nextToken();

        switch (key) {
        case "version":
            version = parser.getText();
            break;
        case "timestamp":
            timestamp = parser.getNumberValue();
            break;
        case "host":
            host = parser.getText();
            break;
        case "short_message":
            short_message = parser.getText();
            break;
        case "full_message":
            full_message = parser.getText();
            break;
        case "level":
            level = parser.getNumberValue();
            break;
        default:
            throw new Exception("Found unexpected field in JSON payload: " + key);
        }
    }

    assertEquals(message.getVersion().toString(), version);
    assertEquals(message.getTimestamp(), timestamp);
    assertEquals(message.getHost(), host);
    assertEquals(message.getMessage(), short_message);
    assertNull(full_message);
    assertEquals(message.getLevel().getNumericLevel(), level);
}

From source file:edu.cmu.cs.lti.discoursedb.io.prosolo.blog.converter.BlogConverter.java

@Override
public void run(String... args) throws Exception {
    if (args.length < 3) {
        logger.error(/*from w  w w  . j  a  v  a 2 s.  c  o m*/
                "USAGE: BlogConverterApplication <DiscourseName> <DataSetName> <blogDump> <userMapping (optional)> <dumpIsWrappedInJsonArray (optional, default=false)>");
        throw new RuntimeException("Incorrect number of launch parameters.");

    }
    final String discourseName = args[0];

    final String dataSetName = args[1];
    if (dataSourceService.dataSourceExists(dataSetName)) {
        logger.warn("Dataset " + dataSetName + " has already been imported into DiscourseDB. Terminating...");
        return;
    }

    final String forumDumpFileName = args[2];
    File blogDumpFile = new File(forumDumpFileName);
    if (!blogDumpFile.exists() || !blogDumpFile.isFile() || !blogDumpFile.canRead()) {
        logger.error("Forum dump file does not exist or is not readable.");
        throw new RuntimeException("Can't read file " + forumDumpFileName);
    }

    //parse the optional fourth and fifth parameter
    String userMappingFileName = null;
    String jsonarray = null;
    if (args.length == 4) {
        if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("false")) {
            jsonarray = args[3];
        } else {
            userMappingFileName = args[3];
        }
    } else {
        if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("false")) {
            jsonarray = args[3];
            userMappingFileName = args[4];
        } else {
            jsonarray = args[4];
            userMappingFileName = args[3];
        }
    }

    //read the blog author to edX user mapping, if available
    if (userMappingFileName != null) {
        logger.trace("Reading user mapping from " + userMappingFileName);
        File userMappingFile = new File(userMappingFileName);
        if (!userMappingFile.exists() || !userMappingFile.isFile() || !userMappingFile.canRead()) {
            logger.error("User mappiong file does not exist or is not readable.");
            throw new RuntimeException("Can't read file " + userMappingFileName);
        }
        List<String> lines = FileUtils.readLines(userMappingFile);
        lines.remove(0); //remove header
        for (String line : lines) {
            String[] blogToedx = line.split(MAPPING_SEPARATOR);
            //if the current line contained a valid mapping, add it to the map
            if (blogToedx.length == 2 && blogToedx[0] != null && !blogToedx[0].isEmpty() && blogToedx[1] != null
                    && !blogToedx[1].isEmpty()) {
                blogToedxMap.put(blogToedx[0], blogToedx[1]);
            }
        }
    }

    if (jsonarray != null && jsonarray.equalsIgnoreCase(("true"))) {
        logger.trace("Set reader to expect a json array rather than regular json input.");
        this.dumpWrappedInJsonArray = true;
    }

    /*
     * Map data to DiscourseDB
     */

    logger.info("Mapping blog posts and comments to DiscourseDB");
    try (InputStream in = new FileInputStream(blogDumpFile)) {
        if (dumpWrappedInJsonArray) {
            //if the json dump is wrapped in a top-level array
            @SuppressWarnings("unchecked")
            List<ProsoloBlogPost> posts = (List<ProsoloBlogPost>) new ObjectMapper()
                    .readValues(new JsonFactory().createParser(in), new TypeReference<List<ProsoloBlogPost>>() {
                    }).next();
            posts.stream().forEach(p -> converterService.mapPost(p, discourseName, dataSetName, blogToedxMap));
        } else {
            //if the json dump is NOT wrapped in a top-level array
            Iterator<ProsoloBlogPost> pit = new ObjectMapper().readValues(new JsonFactory().createParser(in),
                    ProsoloBlogPost.class);
            Iterable<ProsoloBlogPost> iterable = () -> pit;
            StreamSupport.stream(iterable.spliterator(), false)
                    .forEach(p -> converterService.mapPost(p, discourseName, dataSetName, blogToedxMap));
        }
    }

    logger.info("All done.");
}

From source file:de.ii.ogc.wfs.proxy.AbstractWfsProxyService.java

public final void initialize(String[] path, HttpClient httpClient, HttpClient sslHttpClient,
        SMInputFactory staxFactory, ObjectMapper jsonMapper, CrsTransformation crsTransformation) {
    this.httpClient = httpClient;
    this.sslHttpClient = sslHttpClient;
    this.staxFactory = staxFactory;
    this.jsonMapper = jsonMapper;
    this.jsonFactory = new JsonFactory();

    if (this.wfsAdapter != null) {
        this.wfsAdapter.initialize(this.httpClient, this.sslHttpClient);
    }/*from www  . j av a 2 s. co  m*/

    this.crsTransformations = new WfsProxyCrsTransformations(crsTransformation,
            wfsAdapter != null ? wfsAdapter.getDefaultCrs() : null, new EpsgCrs(4326, true));

}

From source file:com.ryan.ryanreader.jsonwrap.JsonValue.java

/**
 * Begins parsing a JSON stream into a tree structure. The JsonValue object
 * created contains the value at the root of the tree.
 * /*from ww w. j  a v a 2  s.  c o  m*/
 * This constructor will block until the first JSON token is received. To
 * continue building the tree, the "build" method (inherited from
 * JsonBuffered) must be called in another thread.
 * 
 * @param source
 *         The source of incoming JSON data.
 * @throws java.io.IOException
 */
public JsonValue(final Reader source) throws IOException {
    this(new JsonFactory().createParser(source));
}

From source file:com.greplin.gec.GecLogbackAppender.java

/**
 * Writes a formatted msg for errors that don't have exceptions.
 *
 * @param message the log message/*  w  w  w .j  a v  a2 s .  c om*/
 * @param level   the error level
 * @param out     the destination
 * @throws IOException if there are IO errors in the destination
 */
void writeFormattedException(final String message, final Level level, final Writer out) throws IOException {
    JsonGenerator generator = new JsonFactory().createJsonGenerator(out);

    String backtrace = GecLogbackAppender.getStackTrace(new Throwable());
    String[] lines = backtrace.split("\n");
    StringBuilder builder = new StringBuilder();
    for (String line : lines) {
        if (!line.contains("com.greplin.gec.GecLogbackAppender.")) {
            builder.append(line);
            builder.append("\n");
        }
    }
    backtrace = builder.toString();

    generator.writeStartObject();
    generator.writeStringField("project", this.project);
    generator.writeStringField("environment", this.environment);
    generator.writeStringField("serverName", this.serverName);
    generator.writeStringField("backtrace", backtrace);
    generator.writeStringField("message", message);
    generator.writeStringField("logMessage", message);
    generator.writeStringField("type", "N/A");
    if (level != Level.ERROR) {
        generator.writeStringField("errorLevel", level.toString());
    }
    writeContext(generator);
    generator.writeEndObject();
    generator.close();
}

From source file:org.londonsburning.proxy.ProxyPrinter.java

/**
 *
 * @param cardName  cardName/*  w w w.  ja  v a 2  s.c o m*/
 * @return  Url
 * @throws IOException Exception
 */
public final String parseTokens(final String cardName) throws IOException {
    InputStream is;
    String url = "";
    is = Thread.currentThread().getContextClassLoader().getResourceAsStream("tokens.json");
    JsonParser jsonParser = new JsonFactory().createParser(is);
    Iterator<Token> it = new ObjectMapper().readValues(jsonParser, Token.class);
    try {
        while (it.hasNext()) {
            Token token = it.next();
            if (token.getName().equalsIgnoreCase(cardName)) {
                url = token.getUrl();
            }
        }
    } finally {
        is.close();
    }
    return url;
}

From source file:org.fluentd.jvmwatcher.JvmWatcher.java

/**
 * @param paramFilePath/* ww w.j a  v a 2 s  .c  om*/
 */
public void loadProperty(String paramFilePath) {
    if (null == paramFilePath) {
        return;
    }

    try {
        // load JSON property file.
        File file = new File(paramFilePath);

        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(file);

        JsonToken token = null;
        while ((token = parser.nextToken()) != null) {
            if (token == JsonToken.FIELD_NAME) {
                if (parser.getText().compareTo("target") == 0) {
                    this.loadTarget(parser);
                }
            }
        }
        parser.close();
    } catch (JsonParseException e) {
        log.error("Property parse error.", e);
    } catch (IOException e) {
        log.error("Property file open error.", e);
    } catch (Exception e) {
        log.error("Property file open error.", e);
    }
}

From source file:com.ning.metrics.action.hdfs.data.Row.java

public String toJSON() throws IOException {
    final StringWriter s = new StringWriter();
    final JsonGenerator generator = new JsonFactory().createJsonGenerator(s);
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    toJSON(generator);// w w  w  .ja v a  2s .  co m
    generator.close();

    return s.toString();
}

From source file:org.springframework.social.soundcloud.api.impl.SoundCloudErrorHandler.java

@SuppressWarnings("unchecked")
private List<Map<String, String>> extractErrorDetailsFromResponse(ClientHttpResponse response)
        throws IOException {

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());

    List<String> authenticateHeaders = response.getHeaders().get("Www-Authenticate");
    String authenticateHeader = authenticateHeaders == null || authenticateHeaders.size() == 0 ? null
            : authenticateHeaders.get(0);
    String json = null;/*from   ww  w  . ja va 2 s.  c  om*/
    if (authenticateHeader != null) {
        json = "{" + authenticateHeader.replace('=', ':').replace("OAuth realm", "\"OAuth realm\"")
                .replace("error", "\"error\"") + "}";
        try {
            Map<String, String> responseMap = mapper.<Map<String, String>>readValue(json,
                    new TypeReference<Map<String, String>>() {
                    });
            List<Map<String, String>> errorsList = new ArrayList<Map<String, String>>();
            if (responseMap.containsKey("error")) {
                Map<String, String> errorMap = new HashMap<String, String>();
                errorMap.put("error_message", responseMap.get("error"));
                errorsList.add(errorMap);
                return errorsList;
            }

        } catch (JsonParseException e) {
            return null;
        }
    } else {
        json = readFully(response.getBody());
        try {
            Map<String, Object> responseMap = mapper.<Map<String, Object>>readValue(json,
                    new TypeReference<Map<String, Object>>() {
                    });
            if (responseMap.containsKey("errors")) {
                return (List<Map<String, String>>) responseMap.get("errors");
            } else {
                return null;
            }
        } catch (JsonParseException e) {
            return null;
        }
    }
    return null;

}