List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory
public JsonFactory()
From source file:de.odysseus.staxon.json.stream.jackson.JacksonStreamSourceTest.java
@Test public void testWhitespace() throws IOException { StringReader reader = new StringReader("{\r \"alice\" : \"bob\"\r\n}"); JacksonStreamSource source = new JacksonStreamSource(new JsonFactory().createParser(reader)); Assert.assertEquals(JsonStreamToken.START_OBJECT, source.peek()); source.startObject();/*from ww w.j av a 2 s . c o m*/ Assert.assertEquals(JsonStreamToken.NAME, source.peek()); Assert.assertEquals("alice", source.name()); Assert.assertEquals(JsonStreamToken.VALUE, source.peek()); Assert.assertEquals("bob", source.value().text); Assert.assertEquals(JsonStreamToken.END_OBJECT, source.peek()); source.endObject(); Assert.assertEquals(JsonStreamToken.NONE, source.peek()); source.close(); }
From source file:com.apteligent.ApteligentJavaClient.java
/** * @param appID The app ID//from w w w.j a v a 2s .co m * @param hash The crash hash to retrieve * @return Array of impacted users */ public ArrayList<User> getCrashUsersAffected(String appID, String hash) { ArrayList<User> users = null; try { HttpsURLConnection conn = sendGetRequest( API_CRASH_USERS_AFFECTED.replace("{appId}", appID).replace("{hash}", hash)); JsonFactory jsonFactory = new JsonFactory(); JsonParser jp = jsonFactory.createParser(conn.getInputStream()); ObjectMapper mapper = getObjectMapper(); users = mapper.readValue(jp, new TypeReference<ArrayList<User>>() { }); } catch (IOException ioex) { ioex.printStackTrace(); } return users; }
From source file:mil.nga.giat.data.elasticsearch.FilterToElastic2.java
protected void visitLiteralGeometry(Literal expression) throws IOException { super.visitLiteralGeometry(expression); final GeometryJSON gjson = new GeometryJSON(); final String geoJson = gjson.toString(currentGeometry); final JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createJsonParser(geoJson); final JsonXContentParser xParser = new JsonXContentParser(parser); xParser.nextToken();//from w w w . j av a2 s . co m currentShapeBuilder = ShapeBuilder.parse(xParser); }
From source file:com.yahoo.ycsb.db.CouchbaseClient.java
/** * Encode the object for couchbase storage. * * @param source the source value./*from w w w .j ava2s.c o m*/ * @return the storable object. */ private Object encode(final HashMap<String, ByteIterator> source) { HashMap<String, String> stringMap = StringByteIterator.getStringMap(source); if (!useJson) { return stringMap; } ObjectNode node = JSON_MAPPER.createObjectNode(); for (Map.Entry<String, String> pair : stringMap.entrySet()) { node.put(pair.getKey(), pair.getValue()); } JsonFactory jsonFactory = new JsonFactory(); Writer writer = new StringWriter(); try { JsonGenerator jsonGenerator = jsonFactory.createGenerator(writer); JSON_MAPPER.writeTree(jsonGenerator, node); } catch (Exception e) { throw new RuntimeException("Could not encode JSON value"); } return writer.toString(); }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
/** * Write the group to the byte sink, but without adding the '$type' field. * To decode the JSON the receiver must know what group type to expect. * * @param group the group to encode./* w w w. j a v a2 s .c o m*/ * @param out the byte sink to write to, not null. * @throws IOException if the underlying byte sink throws an exception. * @throws IllegalArgumentException if the group is not correct or complete, e.g. a required field is missing. * Partial data may have been written to the byte sink. */ public void encodeStatic(Object group, ByteSink out) throws IOException { if (group == null) { out.write(NULL_BYTES); } else { JsonFactory f = new JsonFactory(); JsonGenerator g = f.createGenerator(new ByteSinkOutputStream(out)); StaticGroupHandler groupHandler = lookupGroupByValue(group); if (groupHandler == null) { throw new IllegalArgumentException("Cannot encode group (unknown type)"); } groupHandler.writeValue(group, g, false); g.flush(); } }
From source file:com.tage.calcite.adapter.druid.DruidQuery.java
private QuerySpec getQuery(RelDataType rowType, RexNode filter, List<RexNode> projects, ImmutableBitSet groupSet, List<AggregateCall> aggCalls, List<String> aggNames) { QueryType queryType = QueryType.SELECT; final Translator translator = new Translator(druidTable, rowType); List<String> fieldNames = rowType.getFieldNames(); Json jsonFilter = null;//from w w w .ja v a 2 s. c om if (filter != null) { jsonFilter = translator.translateFilter(filter); translator.metrics.clear(); translator.dimensions.clear(); } if (projects != null) { final ImmutableList.Builder<String> builder = ImmutableList.builder(); for (RexNode project : projects) { builder.add(translator.translate(project)); } fieldNames = builder.build(); } final List<String> dimensions = new ArrayList<>(); final List<JsonAggregation> aggregations = new ArrayList<>(); if (groupSet != null) { assert aggCalls != null; assert aggNames != null; assert aggCalls.size() == aggNames.size(); queryType = QueryType.GROUP_BY; final ImmutableList.Builder<String> builder = ImmutableList.builder(); for (int groupKey : groupSet) { final String s = fieldNames.get(groupKey); dimensions.add(s); builder.add(s); } for (Pair<AggregateCall, String> agg : Pair.zip(aggCalls, aggNames)) { final JsonAggregation jsonAggregation = getJsonAggregation(fieldNames, agg.right, agg.left); aggregations.add(jsonAggregation); builder.add(jsonAggregation.name); } fieldNames = builder.build(); } else { assert aggCalls == null; assert aggNames == null; } final StringWriter sw = new StringWriter(); final JsonFactory factory = new JsonFactory(); try { final JsonGenerator generator = factory.createGenerator(sw); switch (queryType) { case GROUP_BY: generator.writeStartObject(); if (aggregations.isEmpty()) { // Druid requires at least one aggregation, otherwise gives: // Must have at least one AggregatorFactory aggregations.add(new JsonAggregation("longSum", "unit_sales", "unit_sales")); } generator.writeStringField("queryType", "groupBy"); generator.writeStringField("dataSource", druidTable.dataSource); generator.writeStringField("granularity", "all"); writeField(generator, "dimensions", dimensions); writeFieldIf(generator, "limitSpec", null); writeFieldIf(generator, "filter", jsonFilter); writeField(generator, "aggregations", aggregations); writeFieldIf(generator, "postAggregations", null); writeField(generator, "intervals", druidTable.intervals); writeFieldIf(generator, "having", null); generator.writeEndObject(); break; case SELECT: generator.writeStartObject(); generator.writeStringField("queryType", "select"); generator.writeStringField("dataSource", druidTable.dataSource); generator.writeStringField("descending", "false"); writeField(generator, "intervals", druidTable.intervals); writeFieldIf(generator, "filter", jsonFilter); writeField(generator, "dimensions", translator.dimensions); writeField(generator, "metrics", translator.metrics); generator.writeStringField("granularity", "all"); generator.writeFieldName("pagingSpec"); generator.writeStartObject(); final int fetch = CalciteConnectionProperty.DRUID_FETCH.wrap(new Properties()).getInt(); generator.writeNumberField("threshold", fetch); generator.writeEndObject(); generator.writeEndObject(); break; default: throw new AssertionError("unknown query type " + queryType); } generator.close(); } catch (IOException e) { e.printStackTrace(); } return new QuerySpec(queryType, sw.toString(), fieldNames); }
From source file:com.ntsync.shared.RawContact.java
/** * Convert the RawContact object into a DTO. From the JSONString interface. * //from ww w . j av a2s .co m * @return a JSON string representation of the object */ public byte[] toDTO(Key secret, String pwdSaltBase64) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(DEFAULT_BYTEARRAY_SIZE); AEADBlockCipher ecipher = CryptoHelper.getCipher(); byte[] iv = new byte[CryptoHelper.IV_LEN]; SecureRandom random = new SecureRandom(); StringBuilder hashValue = new StringBuilder(); hashValue.append(pwdSaltBase64); hashValue.append(displayName); hashValue.append(lastName); hashValue.append(firstName); hashValue.append(middleName); out.write(ContactConstants.ROWID); byte[] rowId = String.valueOf(mRawContactId).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME); SyncDataHelper.writeInt(out, rowId.length); out.write(rowId); JsonFactory json = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator g = json.createGenerator(writer); g.writeStartObject(); writeStructuredName(g); writeList(hashValue, g, ContactConstants.PHONE, phones, true); writeList(hashValue, g, ContactConstants.EMAIL, emails, true); writeList(hashValue, g, ContactConstants.EVENT, events, false); writeList(hashValue, g, ContactConstants.RELATION, relations, false); writeList(hashValue, g, ContactConstants.SIPADDRESS, sipAddresses, false); writeList(hashValue, g, ContactConstants.NICKNAME, nicknames, false); writeList(hashValue, g, ContactConstants.WEBSITE, websites, false); writeAddress(hashValue, g, addresses); writeImList(g, imAddresses); writeOrganization(g, organization); writeField(g, ContactConstants.NOTE, note); if (starred) { g.writeBooleanField(ContactConstants.STARRED, true); } if (sendToVoiceMail) { g.writeBooleanField(ContactConstants.SEND_TO_VOICE_MAIL, true); } writeField(g, ContactConstants.DROID_CUSTOM_RINGTONE, droidCustomRingtone); if (photoSuperPrimary) { g.writeBooleanField(ContactConstants.PHOTO_SUPERPRIMARY, true); } writeStringList(g, ContactConstants.GROUPMEMBERSHIP, groupSourceIds); g.writeEndObject(); g.close(); String textData = writer.toString(); CryptoHelper.writeValue(secret, out, ecipher, iv, random, ContactConstants.TEXTDATA, textData); CryptoHelper.writeValue(secret, out, ecipher, iv, random, ContactConstants.PHOTO, photo); if (lastModified != null) { writeRawValue(out, ContactConstants.MODIFIED, String.valueOf(lastModified.getTime()).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } if (mDeleted) { writeRawValue(out, ContactConstants.DELETED, "1".getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } writeRawValue(out, ContactConstants.HASH, createHash(hashValue)); return out.toByteArray(); } catch (final IOException ex) { LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex); } catch (GeneralSecurityException ex) { LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex); } catch (InvalidCipherTextException ex) { LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex); } return null; }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
@Override public Object decode(InputStream in) throws IOException { JsonFactory f = new JsonFactory(); JsonParser p = f.createParser(in);// w w w . j av a2 s .com JsonToken token = p.nextToken(); if (token == JsonToken.VALUE_NULL) { return null; } else if (token != JsonToken.START_OBJECT) { throw new DecodeException("Expected {"); } return dynamicGroupHandler.readValue(p); }