org.codehaus.jackson.JsonProcessingException Java Examples
The following examples show how to use
org.codehaus.jackson.JsonProcessingException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AttributesSearchQueryImpl.java From bintray-client-java with Apache License 2.0 | 6 votes |
@Override public void serialize(AttributesSearchQueryImpl value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartArray(); jgen.writeStartObject(); jgen.writeArrayFieldStart(value.attributeName); @SuppressWarnings("unchecked") List<AttributesSearchQueryClauseImpl> clauses = value.getQueryClauses(); for (AttributesSearchQueryClauseImpl clause : clauses) { if (clause.getType().equals(Attribute.Type.Boolean)) { jgen.writeBoolean((Boolean) clause.getClauseValue()); } else if (clause.getType().equals(Attribute.Type.number)) { jgen.writeNumber(String.valueOf(clause.getClauseValue())); } else { //String or Date jgen.writeString((String) clause.getClauseValue()); } } jgen.writeEndArray(); jgen.writeEndObject(); jgen.writeEndArray(); }
Example #2
Source File: TupleRecorder.java From Bats with Apache License 2.0 | 6 votes |
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); } } }
Example #3
Source File: HadoopLogsAnalyzer.java From big-c with Apache License 2.0 | 6 votes |
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 { } } }
Example #4
Source File: StateDeserializer.java From big-c with Apache License 2.0 | 6 votes |
@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); }
Example #5
Source File: FhirIO.java From beam with Apache License 2.0 | 6 votes |
/** * Add to batch. * * @param context the context * @throws IOException the io exception */ @ProcessElement public void addToFile(ProcessContext context, BoundedWindow window) throws IOException { this.window = window; String httpBody = context.element(); try { // This will error if not valid JSON an convert Pretty JSON to raw JSON. Object data = this.mapper.readValue(httpBody, Object.class); String ndJson = this.mapper.writeValueAsString(data) + "\n"; this.ndJsonChannel.write(ByteBuffer.wrap(ndJson.getBytes(StandardCharsets.UTF_8))); } catch (JsonProcessingException e) { String resource = String.format( "Failed to parse payload: %s as json at: %s : %s." + "Dropping message from batch import.", httpBody.toString(), e.getLocation().getCharOffset(), e.getMessage()); LOG.warn(resource); context.output( Write.FAILED_BODY, HealthcareIOError.of(httpBody, new IOException(resource))); } }
Example #6
Source File: Simulator.java From realtime-analytics with GNU General Public License v2.0 | 6 votes |
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()); }
Example #7
Source File: EnrichmentOperator.java From examples with Apache License 2.0 | 6 votes |
/** * Reloads mapping data from file. */ private void reloadData() throws IOException { /* Reload data from file, if it is modified after last scan */ long mtime = loader.getModificationTime(); if (mtime < lastKnownMtime) { return; } lastKnownMtime = mtime; InputStream in = loader.getInputStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); cache.clear(); String line; while ((line = bin.readLine()) != null) { try { Map<String, Object> tuple = reader.readValue(line); updateLookupCache(tuple); } catch (JsonProcessingException parseExp) { logger.info("Unable to parse line {}", line); } } IOUtils.closeQuietly(bin); IOUtils.closeQuietly(in); }
Example #8
Source File: CustomJsonDateDeserializer.java From jeecg with Apache License 2.0 | 6 votes |
@Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String text = jp.getText(); if (StringUtils.hasText(text)) { try { if (text.indexOf(":") == -1 && text.length() == 10) { return this.dateFormat.parse(text); } else if (text.indexOf(":") > 0 && text.length() == 19) { return this.datetimeFormat.parse(text); } else { throw new IllegalArgumentException("Could not parse date, date format is error "); } } catch (ParseException ex) { IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage()); iae.initCause(ex); throw iae; } } else { return null; } }
Example #9
Source File: TupleRecorder.java From attic-apex-core with Apache License 2.0 | 6 votes |
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); } } }
Example #10
Source File: HadoopLogsAnalyzer.java From hadoop with Apache License 2.0 | 6 votes |
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 { } } }
Example #11
Source File: JsonSerDeser.java From hadoop with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #12
Source File: CustomObjectMapper.java From jeecg with Apache License 2.0 | 6 votes |
public CustomObjectMapper() { CustomSerializerFactory factory = new CustomSerializerFactory(); factory.addGenericMapping(Date.class, new JsonSerializer<Date>() { @Override public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = sdf.format(value); if (dateStr.endsWith(" 00:00:00")) { dateStr = dateStr.substring(0, 10); } else if (dateStr.endsWith(":00")) { dateStr = dateStr.substring(0, 16); } jsonGenerator.writeString(dateStr); } }); this.setSerializerFactory(factory); }
Example #13
Source File: StateDeserializer.java From hadoop with Apache License 2.0 | 6 votes |
@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); }
Example #14
Source File: JSONRPCParser.java From bitcoin-transaction-explorer with MIT License | 6 votes |
public static TransactionInformation getTransactionInformation(final InputStream jsonData) throws JsonProcessingException, IOException { final JsonNode tree = getResultNode(jsonData); final TransactionInformation transactionInformation = new TransactionInformation(); final JsonNode confirmationsNode = tree.get("confirmations"); if (confirmationsNode == null) { transactionInformation.setConfirmations(0); transactionInformation.setState(TransactionState.UNCONFIRMED); } else { transactionInformation.setConfirmations(confirmationsNode.getIntValue()); transactionInformation.setState(TransactionState.CONFIRMED); transactionInformation.setTime(new Date(tree.get("time").getLongValue() * 1000)); transactionInformation.setBlockHash(tree.get("blockhash").getTextValue()); } transactionInformation.setRawHex(tree.get("hex").getTextValue()); return transactionInformation; }
Example #15
Source File: GenericDataTSV.java From iow-hadoop-streaming with Apache License 2.0 | 6 votes |
private Array<java.io.Serializable> createArray(Schema type, String t) throws IOException, JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(t); Iterator <JsonNode> i = node.iterator(); Array<java.io.Serializable> arr = new GenericData.Array<java.io.Serializable>(node.size(), Schema.createArray(type)); while(i.hasNext()) { switch (type.getType()) { case INT: arr.add(i.next().getIntValue()); break; case FLOAT: case DOUBLE: arr.add(i.next().getDoubleValue()); break; default: arr.add(i.next().getTextValue()); // No array-of-objects! } } return arr; }
Example #16
Source File: HadoopLogsAnalyzer.java From RDFS with Apache License 2.0 | 6 votes |
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 { } } }
Example #17
Source File: SamzaObjectMapper.java From samza with Apache License 2.0 | 5 votes |
@Override public void serialize(SystemStreamPartition systemStreamPartition, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException { Map<String, Object> systemStreamPartitionMap = new HashMap<String, Object>(); systemStreamPartitionMap.put("system", systemStreamPartition.getSystem()); systemStreamPartitionMap.put("stream", systemStreamPartition.getStream()); systemStreamPartitionMap.put("partition", systemStreamPartition.getPartition()); jsonGenerator.writeObject(systemStreamPartitionMap); }
Example #18
Source File: SamzaObjectMapper.java From samza with Apache License 2.0 | 5 votes |
@Override public SystemStreamPartition deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); String system = node.get("system").getTextValue(); String stream = node.get("stream").getTextValue(); Partition partition = new Partition(node.get("partition").getIntValue()); return new SystemStreamPartition(system, stream, partition); }
Example #19
Source File: CustomFieldDeSerializer.java From jira-rest-client with Apache License 2.0 | 5 votes |
@Override public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { logger.info("Deserialize..."); ObjectCodec oc = jp.getCodec(); JsonNode node = oc.readTree(jp); for (int i = 0; i < node.size(); i++) { JsonNode child = node.get(i); if (child == null) { logger.info(i + "th Child node is null"); continue; } //String if (child.isTextual()) { Iterator<String> it = child.getFieldNames(); while (it.hasNext()) { String field = it.next(); logger.info("in while loop " + field); if (field.startsWith("customfield")) { } } } } return null; }
Example #20
Source File: JSONRPCParser.java From bitcoin-transaction-explorer with MIT License | 5 votes |
public static ArrayList<String> getTransactionList(final InputStream jsonData) throws JsonProcessingException, IOException { final JsonNode tree = getResultNode(jsonData); // Array of txs final ArrayList<String> txs = new ArrayList<>(); final JsonNode txNode = tree.get("tx"); for (int i = 0; i < txNode.size(); i++) { txs.add(txNode.get(i).getTextValue()); } return txs; }
Example #21
Source File: CustomJsonDateSerializer.java From demo-restWS-spring-jersey-jpa2-hibernate with MIT License | 5 votes |
@Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm"); String dateString = dateFormat.format(value); jgen.writeString(dateString); }
Example #22
Source File: CustomJsonDateDeserializer.java From demo-restWS-spring-jersey-jpa2-hibernate with MIT License | 5 votes |
@Override public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JsonProcessingException { SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm"); String date = jsonparser.getText(); try { return format.parse(date); } catch (ParseException e) { throw new RuntimeException(e); } }
Example #23
Source File: JsonDateDeSerializer.java From AIDR with GNU Affero General Public License v3.0 | 5 votes |
@Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { String date = jp.getText(); if(date!= null && !date.equals("")){ try { return dateFormat.parse(date); } catch (ParseException e) { throw new RuntimeException(e); } } return null; }
Example #24
Source File: CustomerGenreMovieTO.java From big-data-lite with MIT License | 5 votes |
public CustomerGenreMovieTO(String jsonTxt) { try { custGenreNode = super.parseJson(jsonTxt); } catch (JsonProcessingException e) { e.printStackTrace(); } this.setJsonObject(custGenreNode); }
Example #25
Source File: CastCrewTO.java From big-data-lite with MIT License | 5 votes |
public CastCrewTO(String jsonTxt) { super(); try { castCrewNode = super.parseJson(jsonTxt); } catch (JsonProcessingException e) { e.printStackTrace(); } this.setJsonObject(castCrewNode); }
Example #26
Source File: ActivityTO.java From big-data-lite with MIT License | 5 votes |
public ActivityTO(String actJsonTxt) { super(); try { objectNode = super.parseJson(actJsonTxt); } catch (JsonProcessingException e) { e.printStackTrace(); } this.setActivityJson(objectNode); }
Example #27
Source File: ExamAction.java From ExamStack with GNU General Public License v2.0 | 5 votes |
@RequestMapping(value = "addAnswerSheet4Test", method = RequestMethod.GET) public @ResponseBody Message addAnswerSheet4Test(Model model) throws JsonProcessingException, IOException { Message msg = new Message(); AnswerSheet as = new AnswerSheet(); as.setExamPaperId(2); ObjectMapper om = new ObjectMapper(); qmqpTemplate.convertAndSend(Constants.ANSWERSHEET_DATA_QUEUE, om.writeValueAsBytes(as)); return msg; }
Example #28
Source File: CastMovieTO.java From big-data-lite with MIT License | 5 votes |
public CastMovieTO(String jsonTxt) { super(); try { castMovieNode = super.parseJson(jsonTxt); } catch (JsonProcessingException e) { e.printStackTrace(); } this.setJsonObject(castMovieNode); }
Example #29
Source File: EntityWriterTest.java From secure-data-service with Apache License 2.0 | 5 votes |
@Test public void testIOException() throws IOException { JsonFileWriter file = Mockito.mock(JsonFileWriter.class); Mockito.doThrow(new IOException("Mock IOException")).when(file).write(Mockito.any(Entity.class)); ErrorFile errorFile = Mockito.mock(ErrorFile.class); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("MOCK_ENTITY_TYPE"); writer.write(entity, file, errorFile); Mockito.verify(errorFile).logEntityError(entity); Mockito.doThrow(Mockito.mock(JsonProcessingException.class)).when(file).write(Mockito.any(Entity.class)); writer.write(entity, file, errorFile); Mockito.verify(errorFile, Mockito.times(2)).logEntityError(entity); // twice because we're reusing the mocked logger. }
Example #30
Source File: MovieTO.java From big-data-lite with MIT License | 5 votes |
/** * This constructor takes JSON text as an input argument and constructs * JSON object from this string object. Once JSON object is constructed * values are read and set into MovieTO object. * @param movieJsonTxt */ public MovieTO(String movieJsonTxt) { super(); try { objectNode = super.parseJson(movieJsonTxt); } catch (JsonProcessingException e) { e.printStackTrace(); } this.setMovieJson(objectNode); }