@Override public Window deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); Double value = node.get("value").asDouble(); Window window = new Window(value); if (node.has("bounds")) { long lowerBound = node.get("bounds").get(0).asLong(); long upperBound = node.get("bounds").get(1).asLong(); window.withLowerBound(lowerBound).withUpperBound(upperBound); } return window; }
private Object convert2Object(Object value) throws JsonProcessingException, IOException { if (value == null) { return null; } else if (value instanceof InputStream) { return new ObjectMapper().reader(Object.class).readValue((InputStream) value); } else if (value instanceof byte[]) { return new ObjectMapper().reader(Object.class).readValue((byte[]) value); } else if (value instanceof CharSequence) { String trimmed = ((CharSequence) value).toString().trim(); if (trimmed.startsWith("[") || trimmed.startsWith("{")) { return new ObjectMapper().reader(Object.class).readValue(trimmed); } else { return value; } } else { return value; } }
@Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType()); JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding); // A workaround for JsonGenerators not applying serialization features // https://github.com/FasterXML/jackson-databind/issues/12 if (this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) { jsonGenerator.useDefaultPrettyPrinter(); } try { if (this.jsonPrefix != null) { jsonGenerator.writeRaw(this.jsonPrefix); } this.objectMapper.writeValue(jsonGenerator, object); } catch (JsonProcessingException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
/** * Deserialize from a byte array, optionally checking for a marker string. * <p> * If the marker parameter is supplied (and not empty), then its presence * will be verified before the JSON parsing takes place; it is a fast-fail * check. If not found, an {@link InvalidRecordException} exception will be * raised * @param path path the data came from * @param bytes byte array * @param marker an optional string which, if set, MUST be present in the * UTF-8 parsed payload. * @return The parsed record * @throws IOException all problems * @throws EOFException not enough data * @throws InvalidRecordException if the JSON parsing failed. * @throws NoRecordException if the data is not considered a record: either * it is too short or it did not contain the marker string. */ public T fromBytes(String path, byte[] bytes, String marker) throws IOException, NoRecordException, InvalidRecordException { int len = bytes.length; if (len == 0 ) { throw new NoRecordException(path, E_NO_DATA); } if (StringUtils.isNotEmpty(marker) && len < marker.length()) { throw new NoRecordException(path, E_DATA_TOO_SHORT); } String json = new String(bytes, 0, len, UTF_8); if (StringUtils.isNotEmpty(marker) && !json.contains(marker)) { throw new NoRecordException(path, E_MISSING_MARKER_STRING + marker); } try { return fromJson(json); } catch (JsonProcessingException e) { throw new InvalidRecordException(path, e.toString(), e); } }
@Override public StatePair deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) parser.getCodec(); // set the state-pair object tree ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser); Class<?> stateClass = null; try { stateClass = Class.forName(statePairObject.get("className").getTextValue().trim()); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Invalid classname!", cnfe); } String stateJsonString = statePairObject.get("state").toString(); State state = (State) mapper.readValue(stateJsonString, stateClass); return new StatePair(state); }
private void processParsedLine(ParsedLine line) throws JsonProcessingException, IOException { if (!collecting) { // "Job", "MapAttempt", "ReduceAttempt", "Task" LogRecordType myType = line.getType(); if (myType == canonicalJob) { processJobLine(line); } else if (myType == canonicalTask) { processTaskLine(line); } else if (myType == canonicalMapAttempt) { processMapAttemptLine(line); } else if (myType == canonicalReduceAttempt) { processReduceAttemptLine(line); } else { } } }
@Override public ProducedEventsResult deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); if (node.isArray()) { List<ProducedEventResult> responses = new ArrayList<>(); Iterator<JsonNode> it = node.iterator(); while (it.hasNext()) { JsonNode n = it.next(); responses.add(new ProducedEventResult(n.get("created").asBoolean())); } return new ProducedEventsResult(responses); } else { String reason = node.get("reason").asText(); return new ProducedEventsResult(reason); } }
@Override public TopicRecord deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); String topic = node.get("topic").asText(); long partition = node.get("partition").asLong(); long offset = node.get("offset").asLong(); long timestamp = node.get("timestamp").asLong(); String key = null; if (node.has("key")) { key = node.get("key").asText(); } Map<Object, Object> value = new ObjectMapper().readValue(node.get("value").toString(), Map.class); return new TopicRecord(topic, key, partition, offset, timestamp, value); }
@Override public SubscribeToTopicResult deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); boolean success = false; String reason = null; if (node.has("subscribed")) { success = node.get("subscribed").asBoolean(); } if (node.has("reason")) { reason = node.get("reason").asText(); } return new SubscribeToTopicResult(success, reason); }
@Override public Instant deserialize(final JsonParser parser, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final JsonToken jsonToken = parser.getCurrentToken(); if (jsonToken == JsonToken.VALUE_NUMBER_INT) { return new Instant(parser.getLongValue()); } else if (jsonToken == JsonToken.VALUE_STRING) { final String str = parser.getText().trim(); if (str.length() == 0) { return null; } final DateTimeFormatter formatter = ISODateTimeFormat.dateTimeParser(); final DateTime dateTime = formatter.parseDateTime(str); return new Instant(dateTime.getMillis()); } throw ctxt.mappingException(Instant.class); }
private void publishTupleData(int portId, Object obj) { try { if (wsClient != null && wsClient.isConnectionOpen()) { HashMap<String, Object> map = new HashMap<>(); map.put("portId", String.valueOf(portId)); map.put("windowId", currentWindowId); map.put("tupleCount", totalTupleCount); map.put("data", obj); wsClient.publish(recordingNameTopic, map); } } catch (Exception ex) { if (ex instanceof JsonProcessingException) { checkLogTuple(ex, "publish", obj); } else { logger.warn("Error publishing tuple", ex); } } }
/** * Performs the serialization of a OFFeaturesReply object */ @Override public void serialize(OFFeaturesReply reply, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeNumberField("actions", reply.getActions()); jGen.writeNumberField("buffers", reply.getBuffers()); jGen.writeNumberField("capabilities", reply.getCapabilities()); jGen.writeStringField("datapathId", HexString.toHexString(reply.getDatapathId())); jGen.writeNumberField("length", reply.getLength()); serializer.defaultSerializeField("ports", reply.getPorts(), jGen); jGen.writeNumberField("tables", reply.getTables()); jGen.writeStringField("type", reply.getType().toString()); jGen.writeNumberField("version", reply.getVersion()); jGen.writeNumberField("xid", reply.getXid()); jGen.writeEndObject(); }
/** * Performs the serialization of a OneComponentTime object */ @Override public void serialize(CumulativeTimeBucket ctb, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); Timestamp ts = new Timestamp(ctb.getStartTimeNs()/1000000); jGen.writeStringField("start-time", ts.toString()); jGen.writeStringField("current-time", new Timestamp(System.currentTimeMillis()).toString()); jGen.writeNumberField("total-packets", ctb.getTotalPktCnt()); jGen.writeNumberField("average", ctb.getAverageProcTimeNs()); jGen.writeNumberField("min", ctb.getMinTotalProcTimeNs()); jGen.writeNumberField("max", ctb.getMaxTotalProcTimeNs()); jGen.writeNumberField("std-dev", ctb.getTotalSigmaProcTimeNs()); jGen.writeArrayFieldStart("modules"); for (OneComponentTime oct : ctb.getModules()) { serializer.defaultSerializeValue(oct, jGen); } jGen.writeEndArray(); jGen.writeEndObject(); }
@Override public void serialize(VirtualNetwork vNet, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeStringField("name", vNet.name); jGen.writeStringField("guid", vNet.guid); jGen.writeStringField("gateway", vNet.gateway); jGen.writeArrayFieldStart("mac"); Iterator<MACAddress> hit = vNet.hosts.iterator(); while (hit.hasNext()) jGen.writeString(hit.next().toString()); jGen.writeEndArray(); jGen.writeEndObject(); }
/** * Performs the serialization of a EventHistory.BaseInfo object */ @Override public void serialize(EventHistoryBaseInfo base_info, JsonGenerator jGen, SerializerProvider serializer) throws IOException, JsonProcessingException { jGen.writeStartObject(); jGen.writeNumberField("Idx", base_info.getIdx()); Timestamp ts = new Timestamp(base_info.getTime_ms()); String tsStr = ts.toString(); while (tsStr.length() < 23) { tsStr = tsStr.concat("0"); } jGen.writeStringField("Time", tsStr); jGen.writeStringField("State", base_info.getState().name()); String acStr = base_info.getAction().name().toLowerCase(); // Capitalize the first letter acStr = acStr.substring(0,1).toUpperCase().concat(acStr.substring(1)); jGen.writeStringField("Action", acStr); jGen.writeEndObject(); }
public static AbstractTableConfig init(String jsonString) throws JSONException, JsonParseException, JsonMappingException, JsonProcessingException, IOException { JSONObject o = new JSONObject(jsonString); String tableType = o.getString("tableType").toLowerCase(); String tableName = new TableNameBuilder(TableType.valueOf(tableType.toUpperCase())).forTable(o.getString("tableName")); SegmentsValidationAndRetentionConfig validationConfig = loadSegmentsConfig(new ObjectMapper().readTree(o.getJSONObject("segmentsConfig").toString())); TenantConfig tenantConfig = loadTenantsConfig(new ObjectMapper().readTree(o.getJSONObject("tenants").toString())); TableCustomConfig customConfig = loadCustomConfig(new ObjectMapper().readTree(o.getJSONObject("metadata").toString())); IndexingConfig config = loadIndexingConfig(new ObjectMapper().readTree(o.getJSONObject("tableIndexConfig").toString())); if (tableType.equals("offline")) { return new OfflineTableConfig(tableName, tableType, validationConfig, tenantConfig, customConfig, config); } else if (tableType.equals("realtime")) { return new RealtimeTableConfig(tableName, tableType, validationConfig, tenantConfig, customConfig, config); } throw new UnsupportedOperationException("unknown tableType : " + tableType); }
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException, JsonMappingException, UnsupportedEncodingException, HttpException { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> m = new HashMap<String, Object>(); m.put("si", "12345"); m.put("ct", System.currentTimeMillis()); String payload = mapper.writeValueAsString(m); HttpClient client = new HttpClient(); PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent"); // method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8")); int status = client.executeMethod(method); System.out.println(Arrays.toString(method.getResponseHeaders())); System.out.println("Status code: " + status + ", Body: " + method.getResponseBodyAsString()); }
@Override public void serialize(Map<String, Object> fields, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); for (Entry<String, Object> entry : fields.entrySet()) { Object objectValue = entry.getValue(); if (objectValue instanceof Date) { Date date = (Date) objectValue; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland")); String formattedDate = simpleDateFormat.format(date); jgen.writeObjectField(entry.getKey().toString(), formattedDate); } else { jgen.writeObjectField(entry.getKey().toString(), objectValue); } } jgen.writeEndObject(); }
@Override public IPv4 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { IPv4 ipv4 = null; jp.nextToken(); // Move to JsonToken.START_OBJECT while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldname = jp.getCurrentName(); if ("value".equals(fieldname)) { String value = jp.getText(); log.debug("Fieldname: {} Value: {}", fieldname, value); ipv4 = new IPv4(value); } } return ipv4; }
private Collection<String> deserializeUsingCustom(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext, Collection<String> paramCollection) throws IOException, JsonProcessingException { JsonDeserializer localJsonDeserializer = this._valueDeserializer; JsonToken localJsonToken = paramJsonParser.nextToken(); if (localJsonToken != JsonToken.END_ARRAY) { if (localJsonToken == JsonToken.VALUE_NULL); for (Object localObject = null; ; localObject = (String)localJsonDeserializer.deserialize(paramJsonParser, paramDeserializationContext)) { paramCollection.add(localObject); break; } } return (Collection<String>)paramCollection; }
private void serializePagination(SerializablePagedCollection pagedCol, JsonGenerator jgen) throws IOException, JsonProcessingException { jgen.writeFieldName("pagination"); jgen.writeStartObject(); jgen.writeNumberField("count", pagedCol.getCollection().size()); jgen.writeBooleanField("hasMoreItems", pagedCol.hasMoreItems()); Integer totalItems = pagedCol.getTotalItems(); if(totalItems != null) { jgen.writeNumberField("totalItems", totalItems); } if (pagedCol.getPaging() != null) { jgen.writeNumberField(RecognizedParamsExtractor.PARAM_PAGING_SKIP, pagedCol.getPaging().getSkipCount()); jgen.writeNumberField(RecognizedParamsExtractor.PARAM_PAGING_MAX, pagedCol.getPaging().getMaxItems()); } jgen.writeEndObject(); }
@Override public NodeRef deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken curr = jp.getCurrentToken(); if (curr == JsonToken.VALUE_STRING) { String nodeRefString = jp.getText(); NodeRef nodeRef = getNodeRef(nodeRefString); return nodeRef; } else { throw new IOException("Unable to deserialize nodeRef: " + curr.asString()); } }
private final Collection<Object> handleNonArray(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext, Collection<Object> paramCollection) throws IOException, JsonProcessingException { if (!paramDeserializationContext.isEnabled(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)) throw paramDeserializationContext.mappingException(this._collectionType.getRawClass()); JsonDeserializer localJsonDeserializer = this._valueDeserializer; TypeDeserializer localTypeDeserializer = this._valueTypeDeserializer; Object localObject; if (paramJsonParser.getCurrentToken() == JsonToken.VALUE_NULL) localObject = null; while (true) { paramCollection.add(localObject); return paramCollection; if (localTypeDeserializer == null) { localObject = localJsonDeserializer.deserialize(paramJsonParser, paramDeserializationContext); continue; } localObject = localJsonDeserializer.deserializeWithType(paramJsonParser, paramDeserializationContext, localTypeDeserializer); } }
public Object deserialize(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext) throws IOException, JsonProcessingException { Object localObject1 = this._deserializer.deserialize(paramJsonParser, paramDeserializationContext); try { if (this._ctor != null) return this._ctor.newInstance(new Object[] { localObject1 }); Object localObject2 = this._factoryMethod.invoke(null, new Object[] { localObject1 }); return localObject2; } catch (Exception localException) { ClassUtil.unwrapAndThrowAsIAE(localException); } return null; }