List of usage examples for com.fasterxml.jackson.core JsonFactory createParser
public JsonParser createParser(String content) throws IOException, JsonParseException
From source file:org.jberet.support.io.MongoItemReaderTest.java
static void addTestData(final String dataResource, final String mongoCollection, final int minSizeIfExists) throws Exception { final DBCollection collection = db.getCollection(mongoCollection); if (collection.find().count() >= minSizeIfExists) { System.out.printf("The readCollection %s already contains 100 items, skip adding test data.%n", mongoCollection);//from w ww . ja v a 2s .c o m return; } InputStream inputStream = MongoItemReaderTest.class.getClassLoader().getResourceAsStream(dataResource); if (inputStream == null) { try { final URL url = new URI(dataResource).toURL(); inputStream = url.openStream(); } catch (final Exception e) { System.out.printf("Failed to convert dataResource %s to URL: %s%n", dataResource, e); } } if (inputStream == null) { throw new IllegalStateException("The inputStream for the test data is null"); } final JsonFactory jsonFactory = new MappingJsonFactory(); final JsonParser parser = jsonFactory.createParser(inputStream); final JsonNode arrayNode = parser.readValueAs(ArrayNode.class); final Iterator<JsonNode> elements = arrayNode.elements(); final List<DBObject> dbObjects = new ArrayList<DBObject>(); while (elements.hasNext()) { final DBObject dbObject = (DBObject) JSON.parse(elements.next().toString()); dbObjects.add(dbObject); } collection.insert(dbObjects); }
From source file:com.github.heuermh.ensemblrestclient.JacksonArchivedSequenceConverter.java
static ArchivedSequence parseArchivedSequence(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException { JsonParser parser = null;//from w w w . j ava 2 s. c om try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String type = null; String assembly = null; String release = null; String version = null; String latest = null; String peptide = null; boolean current = false; List<String> possibleReplacement = new ArrayList<String>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("type".equals(field)) { type = parser.getText(); } else if ("assembly".equals(field)) { assembly = parser.getText(); } else if ("release".equals(field)) { release = parser.getText(); } else if ("version".equals(field)) { version = parser.getText(); } else if ("latest".equals(field)) { latest = parser.getText(); } else if ("peptide".equals(field)) { peptide = parser.getText(); } else if ("is_current".equals(field)) { current = (Integer.parseInt(parser.getText()) > 0); } else if ("possible_replacement".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { possibleReplacement.add(parser.getText()); } } } return new ArchivedSequence(id, type, assembly, release, version, latest, peptide, current, possibleReplacement.toArray(new String[possibleReplacement.size()])); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } }
From source file:ch.rasc.wampspring.message.WampMessage.java
@SuppressWarnings("unchecked") public static <T extends WampMessage> T fromJson(JsonFactory jsonFactory, String json, WampSession wampSession) throws IOException { try (JsonParser jp = jsonFactory.createParser(json)) { if (jp.nextToken() != JsonToken.START_ARRAY) { throw new IOException("Not a JSON array"); }/*from w w w . j a va 2 s . c om*/ if (jp.nextToken() != JsonToken.VALUE_NUMBER_INT) { throw new IOException("Wrong message format"); } WampMessageType messageType = WampMessageType.fromTypeId(jp.getValueAsInt()); switch (messageType) { case WELCOME: return (T) new WelcomeMessage(jp); case PREFIX: return (T) new PrefixMessage(jp); case CALL: return (T) new CallMessage(jp, wampSession); case CALLRESULT: return (T) new CallResultMessage(jp); case CALLERROR: return (T) new CallErrorMessage(jp); case SUBSCRIBE: return (T) new SubscribeMessage(jp, wampSession); case UNSUBSCRIBE: return (T) new UnsubscribeMessage(jp, wampSession); case PUBLISH: return (T) new PublishMessage(jp, wampSession); case EVENT: return (T) new EventMessage(jp, wampSession); default: return null; } } }
From source file:com.github.heuermh.ensemblrestclient.JacksonOverlapConverter.java
static List<Variation> parseOverlap(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException { JsonParser parser = null;/*from ww w . jav a 2 s . c o m*/ try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String reference = null; List<String> alternateAlleles = new ArrayList<String>(); String locationName = null; String coordinateSystem = "chromosome"; int start = -1; int end = -1; int strand = -1; List<Variation> variationFeatures = new ArrayList<Variation>(); while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("seq_region_name".equals(field)) { locationName = parser.getText(); } else if ("start".equals(field)) { start = Integer.parseInt(parser.getText()); } else if ("end".equals(field)) { end = Integer.parseInt(parser.getText()); } else if ("strand".equals(field)) { strand = Integer.parseInt(parser.getText()); } else if ("alt_alleles".equals(field)) { int index = 0; while (parser.nextToken() != JsonToken.END_ARRAY) { if (index == 0) { reference = parser.getText(); } else if (index == 1) { alternateAlleles.add(parser.getText()); } index++; } } } variationFeatures.add(new Variation(id, reference, alternateAlleles, new Location(locationName, coordinateSystem, start, end, strand))); id = null; reference = null; alternateAlleles.clear(); locationName = null; start = -1; end = -1; strand = -1; } return variationFeatures; } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } }
From source file:org.n52.movingcode.runtime.processors.config.ProcessorConfig.java
/** * Properties reader/* w w w. java 2 s . c o m*/ * * @return */ private static final HashMap<String, ProcessorDescription> readProperties() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream is = classLoader.getResourceAsStream(configFile); HashMap<String, ProcessorDescription> processorMap = new HashMap<String, ProcessorDescription>(); JsonFactory f = new JsonFactory(); JsonParser jp; try { jp = f.createParser(is); jp.nextToken(); // will return JsonToken.START_OBJECT while (jp.nextToken() != END_OBJECT) { String field = jp.getCurrentName(); if (field.equalsIgnoreCase(KEY_PROCESSORS)) { // get next token, make sure it is the beginning of an array if (jp.nextToken() != START_ARRAY) { break; } while (jp.nextToken() != END_ARRAY) { // do the parsing if (jp.getCurrentToken() == START_OBJECT) { ProcessorDescription p = parseProcessorJSON(jp); // only add those processor that have a valid ID if (p.getId() != null) { processorMap.put(p.getId(), p); } } } } else { if (field.equalsIgnoreCase(KEY_DEFAULTS)) { // parse defaults ProcessorDescription p = parseProcessorJSON(jp); p.setId(DEFAULT_PROCESSOR_CONFIG_ID); processorMap.put(p.getId(), p); } } } } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return processorMap; }
From source file:org.apache.streams.data.util.JsonUtil.java
public static JsonNode getFromFile(String filePath) { JsonFactory factory = mapper.getFactory(); // since 2.1 use mapper.getFactory() instead JsonNode node = null;/*from w w w. j av a2s . c o m*/ try { InputStream stream = getStreamForLocation(filePath); JsonParser jp = factory.createParser(stream); node = mapper.readTree(jp); } catch (IOException e) { throw new RuntimeException(e); } return node; }
From source file:com.ntsync.shared.ContactGroup.java
/** * Creates and returns an instance of the RawContact from encrypted data * //from w w w . j a v a 2 s .co m * */ public static ContactGroup valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey) throws InvalidKeyException { try { String sourceId = null; Long rawId = null; if (values.containsKey(GroupConstants.SERVERROW_ID)) { sourceId = readRawString(values.get(GroupConstants.SERVERROW_ID)); } if (sourceId == null || !sourceId.equals(rowId)) { // If ServerContactId is different, then rowId is the clientId rawId = Long.parseLong(rowId); } if (sourceId == null && rawId < 0) { throw new IllegalArgumentException("Missing RowId in data"); } AEADBlockCipher cipher = CryptoHelper.getCipher(); final boolean deleted = values.containsKey(GroupConstants.DELETED); final String textData = CryptoHelper.decodeStringValue(GroupConstants.TEXTDATA, values, cipher, privateKey); if (textData == null && !deleted) { LOG.error("No textdata found for row with Id:" + rowId); return null; } String title = null; String notes = null; if (!isEmpty(textData)) { JsonFactory fac = new JsonFactory(); JsonParser jp = fac.createParser(textData); jp.nextToken(); while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); // move to value, or START_OBJECT/START_ARRAY jp.nextToken(); if (GroupConstants.TITLE.equals(fieldname)) { title = jp.getValueAsString(); } else if (GroupConstants.NOTES.equals(fieldname)) { notes = jp.getValueAsString(); } else { LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname); } } jp.close(); } String modStr = readRawString(values.get(GroupConstants.MODIFIED)); Date lastModified = null; if (!isEmpty(modStr)) { lastModified = new Date(Long.parseLong(modStr)); } return new ContactGroup(rawId, sourceId, title, notes, deleted, lastModified, -1); } catch (InvalidCipherTextException ex) { throw new InvalidKeyException("Invalid key detected.", ex); } catch (final Exception ex) { LOG.info("Error parsing contactgroup data. Reason:" + ex.toString(), ex); } return null; }
From source file:org.mstc.zmq.json.Decoder.java
@SuppressWarnings("unchecked") public static void decode(String input, Field[] fields, Object b) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); if (logger.isDebugEnabled()) logger.debug(input);//from w ww . ja v a 2 s .c o m JsonFactory factory = mapper.getFactory(); try (JsonParser jp = factory.createParser(input)) { /* Sanity check: verify that we got "Json Object" */ if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } /* Iterate over object fields */ while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); jp.nextToken(); Field field = getField(fieldName, fields); if (field == null) { throw new IOException( "Could not find field [" + fieldName + "] on class " + b.getClass().getName()); } try { if (field.getType().isAssignableFrom(List.class)) { String adder = getAdder(fieldName); TypeFactory t = TypeFactory.defaultInstance(); ParameterizedType listType = (ParameterizedType) field.getGenericType(); Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0]; List list = mapper.readValue(jp.getValueAsString(), t.constructCollectionType(List.class, listClass)); Method m = b.getClass().getDeclaredMethod(adder, Collection.class); m.invoke(b, list); } else if (field.getType().isArray()) { Class<?> type = field.getType(); String setter = getSetter(fieldName); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); logger.info("Field {} is array of {}[], {}, using method {}", field.getName(), field.getType().getComponentType(), jp.getCurrentToken().name(), m); if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) { List list = new ArrayList(); while (jp.nextToken() != JsonToken.END_ARRAY) { String value = jp.getText(); switch (jp.getCurrentToken()) { case VALUE_STRING: list.add(value); break; case VALUE_NUMBER_INT: if (type.getComponentType().isAssignableFrom(double.class)) { list.add(Double.parseDouble(value)); } else if (type.getComponentType().isAssignableFrom(float.class)) { list.add(Float.parseFloat(value)); } else { list.add(Integer.parseInt(value)); } break; case VALUE_NUMBER_FLOAT: logger.info("Add float"); list.add(jp.getFloatValue()); break; case VALUE_NULL: break; default: logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } Object array = Array.newInstance(field.getType().getComponentType(), list.size()); for (int i = 0; i < list.size(); i++) { Object val = list.get(i); Array.set(array, i, val); } m.invoke(b, array); } else { if (type.getComponentType().isAssignableFrom(byte.class)) { m.invoke(b, jp.getBinaryValue()); } } } else { String setter = getSetter(fieldName); logger.debug("{}: {}", setter, field.getType().getName()); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); switch (jp.getCurrentToken()) { case VALUE_STRING: m.invoke(b, jp.getText()); break; case VALUE_NUMBER_INT: m.invoke(b, jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: m.invoke(b, jp.getFloatValue()); break; case VALUE_NULL: logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(), m.getName()); break; case START_OBJECT: StringBuilder sb = new StringBuilder(); while (jp.nextToken() != JsonToken.END_OBJECT) { switch (jp.getCurrentToken()) { case VALUE_STRING: sb.append("\"").append(jp.getText()).append("\""); break; case FIELD_NAME: if (sb.length() > 0) sb.append(","); sb.append("\"").append(jp.getText()).append("\"").append(":"); break; case VALUE_NUMBER_INT: sb.append(jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: sb.append(jp.getFloatValue()); break; case VALUE_NULL: sb.append("null"); break; default: logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(), JsonToken.END_OBJECT.asString()); Object parsed = getNested(field.getType(), s.getBytes()); m.invoke(b, parsed); break; default: logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException e) { logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e); } } } }
From source file:info.bonjean.quinkana.Main.java
private static void run(String[] args) throws QuinkanaException { Properties properties = new Properties(); InputStream inputstream = Main.class.getResourceAsStream("/config.properties"); try {//w ww . ja v a 2s. c o m properties.load(inputstream); inputstream.close(); } catch (IOException e) { throw new QuinkanaException("cannot load internal properties", e); } String name = (String) properties.get("name"); String description = (String) properties.get("description"); String url = (String) properties.get("url"); String version = (String) properties.get("version"); String usage = (String) properties.get("help.usage"); String defaultHost = (String) properties.get("default.host"); int defaultPort = Integer.valueOf(properties.getProperty("default.port")); ArgumentParser parser = ArgumentParsers.newArgumentParser(name).description(description) .epilog("For more information, go to " + url).version("${prog} " + version).usage(usage); parser.addArgument("ACTION").type(Action.class).choices(Action.tail, Action.list).dest("action"); parser.addArgument("-H", "--host").setDefault(defaultHost) .help(String.format("logstash host (default: %s)", defaultHost)); parser.addArgument("-P", "--port").type(Integer.class).setDefault(defaultPort) .help(String.format("logstash TCP port (default: %d)", defaultPort)); parser.addArgument("-f", "--fields").nargs("+").help("fields to display"); parser.addArgument("-i", "--include").nargs("+").help("include filter (OR), example host=example.com") .metavar("FILTER").type(Filter.class); parser.addArgument("-x", "--exclude").nargs("+") .help("exclude filter (OR, applied after include), example: severity=debug").metavar("FILTER") .type(Filter.class); parser.addArgument("-s", "--single").action(Arguments.storeTrue()).help("display single result and exit"); parser.addArgument("--version").action(Arguments.version()).help("output version information and exit"); Namespace ns = parser.parseArgsOrFail(args); Action action = ns.get("action"); List<String> fields = ns.getList("fields"); List<Filter> includes = ns.getList("include"); List<Filter> excludes = ns.getList("exclude"); boolean single = ns.getBoolean("single"); String host = ns.getString("host"); int port = ns.getInt("port"); final Socket clientSocket; final InputStream is; try { clientSocket = new Socket(host, port); is = clientSocket.getInputStream(); } catch (IOException e) { throw new QuinkanaException("cannot connect to the server " + host + ":" + port, e); } // add a hook to ensure we clean the resources when leaving Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }); // prepare JSON parser ObjectMapper mapper = new ObjectMapper(); JsonFactory jsonFactory = mapper.getFactory(); JsonParser jp; try { jp = jsonFactory.createParser(is); } catch (IOException e) { throw new QuinkanaException("error during JSON parser creation", e); } JsonToken token; // action=list if (action.equals(Action.list)) { try { // do this in a separate loop to not pollute the main loop while ((token = jp.nextToken()) != null) { if (token != JsonToken.START_OBJECT) continue; // parse object JsonNode node = jp.readValueAsTree(); // print fields Iterator<String> fieldNames = node.fieldNames(); while (fieldNames.hasNext()) System.out.println(fieldNames.next()); System.exit(0); } } catch (IOException e) { throw new QuinkanaException("error during JSON parsing", e); } } // action=tail try { while ((token = jp.nextToken()) != null) { if (token != JsonToken.START_OBJECT) continue; // parse object JsonNode node = jp.readValueAsTree(); // filtering (includes) if (includes != null) { boolean skip = true; for (Filter include : includes) { if (include.match(node)) { skip = false; break; } } if (skip) continue; } // filtering (excludes) if (excludes != null) { boolean skip = false; for (Filter exclude : excludes) { if (exclude.match(node)) { skip = true; break; } } if (skip) continue; } // if no field specified, print raw output (JSON) if (fields == null) { System.out.println(node.toString()); if (single) break; continue; } // formatted output, build and print the string StringBuilder sb = new StringBuilder(128); for (String field : fields) { if (sb.length() > 0) sb.append(" "); if (node.get(field) != null && node.get(field).textValue() != null) sb.append(node.get(field).textValue()); } System.out.println(sb.toString()); if (single) break; } } catch (IOException e) { throw new QuinkanaException("error during JSON parsing", e); } }
From source file:org.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java
static List<Node> readHosts(HttpEntity entity, Scheme scheme, JsonFactory jsonFactory) throws IOException { try (InputStream inputStream = entity.getContent()) { JsonParser parser = jsonFactory.createParser(inputStream); if (parser.nextToken() != JsonToken.START_OBJECT) { throw new IOException("expected data to start with an object"); }/*from ww w. j a v a 2 s .com*/ List<Node> nodes = new ArrayList<>(); while (parser.nextToken() != JsonToken.END_OBJECT) { if (parser.getCurrentToken() == JsonToken.START_OBJECT) { if ("nodes".equals(parser.getCurrentName())) { while (parser.nextToken() != JsonToken.END_OBJECT) { JsonToken token = parser.nextToken(); assert token == JsonToken.START_OBJECT; String nodeId = parser.getCurrentName(); Node node = readNode(nodeId, parser, scheme); if (node != null) { nodes.add(node); } } } else { parser.skipChildren(); } } } return nodes; } }