org.codehaus.jackson.map.ObjectMapper Java Examples

The following examples show how to use org.codehaus.jackson.map.ObjectMapper. 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 Project: vespa   Author: vespa-engine   File: VespaDocumentOperationTest.java    License: Apache License 2.0 6 votes vote down vote up
private JsonNode setupSimpleArrayOperation(String name, String[] array, String... params) throws IOException {
    Schema schema = new Schema();
    Tuple tuple = TupleFactory.getInstance().newTuple();

    DataBag bag = new SortedDataBag(null);
    for (String s : array) {
        Tuple stringTuple = TupleFactory.getInstance().newTuple();
        stringTuple.append(s);
        bag.add(stringTuple);
    }
    addToTuple(name, DataType.BAG, bag, schema, tuple);

    VespaDocumentOperation docOp = new VespaDocumentOperation(params);
    docOp.setInputSchema(schema);
    String json = docOp.exec(tuple);

    ObjectMapper m = new ObjectMapper();
    JsonNode root = m.readTree(json);
    JsonNode fields = root.get("fields");
    return fields.get(name);
}
 
Example #2
Source Project: Bats   Author: lealone   File: StramWebServices.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId:\\d+}/properties")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getPhysicalOperatorProperties(@PathParam("operatorId") int operatorId, @QueryParam("propertyName") String propertyName, @QueryParam("waitTime") long waitTime)
{
  init();
  if (waitTime == 0) {
    waitTime = WAIT_TIME;
  }

  Future<?> future = dagManager.getPhysicalOperatorProperty(operatorId, propertyName, waitTime);

  try {
    Object object = future.get(waitTime, TimeUnit.MILLISECONDS);
    if (object != null) {
      return new JSONObject(new ObjectMapper().writeValueAsString(object));
    }
  } catch (Exception ex) {
    LOG.warn("Caught exception", ex);
    throw new RuntimeException(ex);
  }
  return new JSONObject();
}
 
Example #3
Source Project: AIDR   Author: qcri-social   File: JsonDataValidator.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean isEmptySON(String json) {
    boolean isEmpty = true;
    try {
        final JsonParser parser = new ObjectMapper().getJsonFactory()
                .createJsonParser(json);
        while (parser.nextToken() != null) {
            String fieldname = parser.getCurrentName();
            if(fieldname != null){
                isEmpty = false;
                break;
            }

        }

    } catch (JsonParseException jpe) {
        System.out.println("isEmptySON: " + jpe.getMessage());
        jpe.printStackTrace();
    } catch (IOException ioe) {
        System.out.println("isEmptySON: " + ioe.getMessage());
        ioe.printStackTrace();
    }

    return isEmpty;
}
 
Example #4
Source Project: hadoop   Author: naver   File: JsonObjectMapperWriter.java    License: Apache License 2.0 6 votes vote down vote up
public JsonObjectMapperWriter(OutputStream output, boolean prettyPrint) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(
      SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);

  // define a module
  SimpleModule module = new SimpleModule("Default Serializer",  
                                         new Version(0, 1, 1, "FINAL"));
  // add various serializers to the module
  //   add default (all-pass) serializer for all rumen specific data types
  module.addSerializer(DataType.class, new DefaultRumenSerializer());
  //   add a serializer to use object.toString() while serializing
  module.addSerializer(ID.class, new ObjectStringSerializer<ID>());
  
  // register the module with the object-mapper
  mapper.registerModule(module);

  mapper.getJsonFactory();
  writer = mapper.getJsonFactory().createJsonGenerator(
      output, JsonEncoding.UTF8);
  if (prettyPrint) {
    writer.useDefaultPrettyPrinter();
  }
}
 
Example #5
Source Project: sakai   Author: sakaiproject   File: ListMetadataType.java    License: Educational Community License v2.0 6 votes vote down vote up
public String toString(List<T> metadataValues)
{
	try
	{
		List<String> stringValues = new ArrayList<String>();

		if (metadataValues != null && !metadataValues.isEmpty())
		{
			for (T metadataValue : metadataValues)
			{
				String stringValue = metadataConverter.toString(metadataValue);
				if (stringValue != null)
					stringValues.add(stringValue);
			}
		}
		return new ObjectMapper().writeValueAsString(stringValues);
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
}
 
Example #6
Source Project: nifi   Author: apache   File: AbstractSiteToSiteReportingTask.java    License: Apache License 2.0 6 votes vote down vote up
public JsonRecordReader(final InputStream in, RecordSchema recordSchema) throws IOException, MalformedRecordException {
    this.recordSchema = recordSchema;
    try {
        jsonParser = new JsonFactory().createJsonParser(in);
        jsonParser.setCodec(new ObjectMapper());
        JsonToken token = jsonParser.nextToken();
        if (token == JsonToken.START_ARRAY) {
            array = true;
            token = jsonParser.nextToken();
        } else {
            array = false;
        }
        if (token == JsonToken.START_OBJECT) {
            firstJsonNode = jsonParser.readValueAsTree();
        } else {
            firstJsonNode = null;
        }
    } catch (final JsonParseException e) {
        throw new MalformedRecordException("Could not parse data as JSON", e);
    }
}
 
Example #7
Source Project: SI   Author: iotoasis   File: OpenApiService.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public HashMap<String, Object> execute(String operation, String content) 
		throws JsonGenerationException, JsonMappingException, IOException, UserSysException
{	
	HashMap<String, Object> res = callOpenAPI(operation, content);
	
	
	//try {
		//int status = (Integer)res.get("status");
		String body = (String)res.get("body");
		ObjectMapper mapper = new ObjectMapper();
		Object json = mapper.readValue(body, Object.class);
		res.put("json", json);
	//} catch (JsonGenerationException ex) {
	//	res.put("exception", ex);
	//} catch (JsonMappingException ex) {
	//	res.put("exception", ex);
	//} catch (IOException ex) {
	//	res.put("exception", ex);
	//} catch (UserSysException ex) {
		
	//}
	
	return res;
}
 
Example #8
Source Project: hadoop   Author: naver   File: WebHdfsFileSystem.java    License: Apache License 2.0 6 votes vote down vote up
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
    ) throws IOException {
  if (c.getContentLength() == 0) {
    return null;
  }
  final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
  if (in == null) {
    throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
  }
  try {
    final String contentType = c.getContentType();
    if (contentType != null) {
      final MediaType parsed = MediaType.valueOf(contentType);
      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
        throw new IOException("Content-Type \"" + contentType
            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
            + "\" (parsed=\"" + parsed + "\")");
      }
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.reader(Map.class).readValue(in);
  } finally {
    in.close();
  }
}
 
Example #9
Source Project: ambry   Author: linkedin   File: StatsSnapshotTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Serialization unit test of {@link StatsSnapshot}.
 * Test if subMap and null fields are removed from serialized result.
 */
@Test
public void serializeStatsSnapshotTest() throws IOException {
  Long val = 100L;
  Map<String, StatsSnapshot> subMap = new HashMap<>();
  subMap.put("first", new StatsSnapshot(40L, null));
  subMap.put("second", new StatsSnapshot(60L, null));
  StatsSnapshot snapshot = new StatsSnapshot(val, subMap);

  String result = new ObjectMapper().writeValueAsString(snapshot);

  assertThat("Result should contain \"first\" keyword and associated entry", result, containsString("first"));
  assertThat("Result should contain \"second\" keyword and associated entry", result, containsString("second"));
  assertThat("Result should not contain \"subMap\" keyword", result, not(containsString("subMap")));
  assertThat("Result should ignore any null fields", result, not(containsString("null")));
}
 
Example #10
Source Project: hadoop   Author: naver   File: JsonUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static List<String> toXAttrNames(final Map<?, ?> json)
    throws IOException {
  if (json == null) {
    return null;
  }

  final String namesInJson = (String) json.get("XAttrNames");
  ObjectReader reader = new ObjectMapper().reader(List.class);
  final List<Object> xattrs = reader.readValue(namesInJson);
  final List<String> names =
    Lists.newArrayListWithCapacity(json.keySet().size());

  for (Object xattr : xattrs) {
    names.add((String) xattr);
  }
  return names;
}
 
Example #11
Source Project: hadoop   Author: naver   File: TestJsonUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testToXAttrMap() throws IOException {
  String jsonString = 
      "{\"XAttrs\":[{\"name\":\"user.a1\",\"value\":\"0x313233\"}," +
      "{\"name\":\"user.a2\",\"value\":\"0x313131\"}]}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);
  XAttr xAttr1 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a1").setValue(XAttrCodec.decodeValue("0x313233")).build();
  XAttr xAttr2 = (new XAttr.Builder()).setNameSpace(XAttr.NameSpace.USER).
      setName("a2").setValue(XAttrCodec.decodeValue("0x313131")).build();
  List<XAttr> xAttrs = Lists.newArrayList();
  xAttrs.add(xAttr1);
  xAttrs.add(xAttr2);
  Map<String, byte[]> xAttrMap = XAttrHelper.buildXAttrMap(xAttrs);
  Map<String, byte[]> parsedXAttrMap = JsonUtil.toXAttrs(json);
  
  Assert.assertEquals(xAttrMap.size(), parsedXAttrMap.size());
  Iterator<Entry<String, byte[]>> iter = xAttrMap.entrySet().iterator();
  while(iter.hasNext()) {
    Entry<String, byte[]> entry = iter.next();
    Assert.assertArrayEquals(entry.getValue(), 
        parsedXAttrMap.get(entry.getKey()));
  }
}
 
Example #12
Source Project: attic-apex-malhar   Author: apache   File: ZKAssistedDiscovery.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setup(com.datatorrent.api.Context context)
{
  ObjectMapper om = new ObjectMapper();
  instanceSerializerFactory = new InstanceSerializerFactory(om.reader(), om.writer());

  curatorFramework = CuratorFrameworkFactory.builder()
          .connectionTimeoutMs(connectionTimeoutMillis)
          .retryPolicy(new RetryNTimes(connectionRetryCount, conntectionRetrySleepMillis))
          .connectString(connectionString)
          .build();
  curatorFramework.start();

  discovery = getDiscovery(curatorFramework);
  try {
    discovery.start();
  } catch (Exception ex) {
    Throwables.propagate(ex);
  }
}
 
Example #13
Source Project: AIDR   Author: qcri-social   File: JsonDataValidator.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean isValidJSON(String json) {
    boolean valid = false;
    try {
        final JsonParser parser = new ObjectMapper().getJsonFactory()
                .createJsonParser(json);
        while (parser.nextToken() != null) {
            String fieldname = parser.getCurrentName();
            System.out.println("fieldname: " + fieldname);
        }
        valid = true;
    } catch (JsonParseException jpe) {
        jpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return valid;
}
 
Example #14
Source Project: jwala   Author: cerner   File: JsonCreateJvmDeserializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeJsonCreateJvm() throws Exception {
    final InputStream in = this.getClass().getResourceAsStream("/json-create-jvm-data.json");
    final String jsonData = IOUtils.toString(in, Charset.defaultCharset());

    final ObjectMapper mapper = new ObjectMapper();

    final JsonCreateJvm jsonCreateJvm = mapper.readValue(jsonData, JsonCreateJvm.class);
    assertEquals("my-jvm", jsonCreateJvm.getJvmName());
    assertEquals("some-host", jsonCreateJvm.getHostName());
    assertEquals("jwala", jsonCreateJvm.getUserName());
    assertEquals("/manager", jsonCreateJvm.getStatusPath());
    assertEquals("1", jsonCreateJvm.getJdkMediaId());
    assertTrue(StringUtils.isNotEmpty(jsonCreateJvm.getEncryptedPassword()));
    assertNotEquals("password", jsonCreateJvm.getEncryptedPassword());
    assertEquals("8893", jsonCreateJvm.getAjpPort());
    assertEquals("8889", jsonCreateJvm.getHttpPort());
    assertEquals("8890", jsonCreateJvm.getHttpsPort());
    assertEquals("8891", jsonCreateJvm.getRedirectPort());
    assertEquals("8892", jsonCreateJvm.getShutdownPort());
    assertEquals("1", jsonCreateJvm.getGroupIds().get(0).getGroupId());
}
 
Example #15
Source Project: seppb   Author: purang-fintech   File: JenkinsBuildService.java    License: MIT License 6 votes vote down vote up
private void retryBuild(BuildHistory buildHistory) {
	List<String> repeatBuildInstance = Lists.newArrayList();
	buildHistory.setBuildStatus(START);
	String buildParams = buildHistory.getBuildParams();
	ObjectMapper mapper = new ObjectMapper();
	try {
		List<BuildFile> buildFiles = mapper.readValue(buildParams, new TypeReference<List<BuildFile>>() {
		});
		BuildInstance buildInstance = buildInstanceDAO.findInstance(buildHistory.getInstance(), ParameterThreadLocal.getProductId());
		buildHistory.setType(buildInstance.getType());
		build(repeatBuildInstance, buildHistory, buildFilesToParamsMap(buildFiles));
	} catch (IOException e) {
		log.error("构建id为:{}的buildParams序列化失败{}", buildHistory.getId(), e);
		throw new SeppServerException(1001, "服务器异常");
	}
}
 
Example #16
Source Project: big-c   Author: yncxcw   File: TestJsonUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testToAclStatus() throws IOException {
  String jsonString =
      "{\"AclStatus\":{\"entries\":[\"user::rwx\",\"user:user1:rw-\",\"group::rw-\",\"other::r-x\"],\"group\":\"supergroup\",\"owner\":\"testuser\",\"stickyBit\":false}}";
  ObjectReader reader = new ObjectMapper().reader(Map.class);
  Map<?, ?> json = reader.readValue(jsonString);

  List<AclEntry> aclSpec =
      Lists.newArrayList(aclEntry(ACCESS, USER, ALL),
          aclEntry(ACCESS, USER, "user1", READ_WRITE),
          aclEntry(ACCESS, GROUP, READ_WRITE),
          aclEntry(ACCESS, OTHER, READ_EXECUTE));

  AclStatus.Builder aclStatusBuilder = new AclStatus.Builder();
  aclStatusBuilder.owner("testuser");
  aclStatusBuilder.group("supergroup");
  aclStatusBuilder.addEntries(aclSpec);
  aclStatusBuilder.stickyBit(false);

  Assert.assertEquals("Should be equal", aclStatusBuilder.build(),
      JsonUtil.toAclStatus(json));
}
 
Example #17
Source Project: iow-hadoop-streaming   Author: whale2   File: AvroInOutFormatsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAvroAsJsonFmt() throws IOException {

    AvroAsJsonOutputFormat outfmt = new AvroAsJsonOutputFormat();
    FileOutputFormat.setOutputPath(defaultConf, file2);
            RecordWriter<Text, NullWritable> writer = outfmt.getRecordWriter(file2.getFileSystem(defaultConf),
            defaultConf, fname2, new dummyReporter());

    writer.write(new Text(json), NullWritable.get());
    writer.close(null);

    FileInputFormat.setInputPaths(defaultConf, FileOutputFormat.getTaskOutputPath(defaultConf, fname2 +
        AvroOutputFormat.EXT));
    AvroAsJsonInputFormat informat = new AvroAsJsonInputFormat();
    RecordReader<Text, Text> reader = informat.getRecordReader(informat.getSplits(defaultConf, 1)[0],
            defaultConf, new dummyReporter());

    Text k = new Text();
    Text v = new Text();

    reader.next(k, v);
    ObjectMapper mapper = new ObjectMapper();
    JsonNode n0 = mapper.readTree(k.toString());
    JsonNode n1 = mapper.readTree(json);
    Assert.assertEquals("read back json", n0, n1);
}
 
Example #18
Source Project: io   Author: fujitsu-pio   File: JSONManifestTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * manifest_jsonのschemaの指定がない場合falseが返却されること.
 * @throws IOException IOException
 */
@SuppressWarnings("unchecked")
@Test
public void manifest_jsonのschemaの指定がない場合falseが返却されること() throws IOException {
    JsonFactory f = new JsonFactory();
    JSONObject json = new JSONObject();
    json.put("bar_version", "1");
    json.put("box_version", "1");
    json.put("DefaultPath", "boxName");
    JsonParser jp = f.createJsonParser(json.toJSONString());
    ObjectMapper mapper = new ObjectMapper();
    jp.nextToken();

    JSONManifest manifest = mapper.readValue(jp, JSONManifest.class);

    assertFalse(manifest.checkSchema());
}
 
Example #19
Source Project: AthenaServing   Author: xfyun   File: JacksonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String toJson(Object o) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(o);
    } catch (IOException e) {
        logger.error(e);
    }

    return null;
}
 
Example #20
Source Project: AthenaServing   Author: xfyun   File: JacksonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> T toObject(String json, Class<T> valueType) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(json, valueType);
    } catch (IOException e) {
        logger.error(e);
    }
    return null;
}
 
Example #21
Source Project: data-highway   Author: HotelsDotCom   File: WebSocketHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterConnectionEstablished(WebSocketSession session) throws java.io.IOException {
  ObjectMapper mapper = new ObjectMapper();
  String event = mapper.writeValueAsString(TestMessage.getTestMessage());
  int half = event.length() / 2;
  String part1 = event.substring(0, half);
  String part2 = event.substring(half);
  session.sendMessage(new BinaryMessage(part1.getBytes(UTF_8), false));
  session.sendMessage(new BinaryMessage(part2.getBytes(UTF_8), true));
}
 
Example #22
Source Project: Cubert   Author: linkedin   File: TestOperators.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupByWithSum1() throws JsonGenerationException,
        JsonMappingException,
        IOException,
        InterruptedException
{
    Object[][] rows1 = { { 0 }, { 2 }, { 2 }, { 5 }, { 10 }, { 100 } };
    Block block = new ArrayBlock(Arrays.asList(rows1), new String[] { "a" }, 1);

    TupleOperator operator = new GroupByOperator();
    Map<String, Block> input = new HashMap<String, Block>();
    input.put("first", block);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode json = mapper.createObjectNode();
    json.put("input", "first");
    ArrayNode anode = mapper.createArrayNode();
    anode.add("a");
    json.put("groupBy", anode);
    anode = mapper.createArrayNode();
    ObjectNode onode = mapper.createObjectNode();
    onode.put("type", "SUM");
    onode.put("input", "a");
    onode.put("output", "sum");
    anode.add(onode);
    json.put("aggregates", anode);

    BlockProperties props =
            new BlockProperties(null,
                                new BlockSchema("INT a, INT sum"),
                                (BlockProperties) null);
    operator.setInput(input, json, props);

    Block output = new TupleOperatorBlock(operator, props);

    ArrayBlock.assertData(output, new Object[][] { { 0, 0 }, { 2, 4 }, { 5, 5 },
            { 10, 10 }, { 100, 100 } }, new String[] { "a", "sum" });
}
 
Example #23
Source Project: olat   Author: huihoo   File: OlatJerseyTestCase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<LinkVO> parseLinkArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<LinkVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #24
Source Project: gocd-git-path-material-plugin   Author: TWChennai   File: JsonUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static GoPluginApiResponse renderJSON(final int responseCode, Object response) {
    String tempJson = null;
    try {
        tempJson = response == null ? null : new ObjectMapper().writeValueAsString(response);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    LOGGER.debug("GoPluginApiResponse: " + tempJson);

    final String json = tempJson;
    return new GoPluginApiResponse() {
        @Override
        public int responseCode() {
            return responseCode;
        }

        @Override
        public Map<String, String> responseHeaders() {
            return null;
        }

        @Override
        public String responseBody() {
            return json;
        }
    };
}
 
Example #25
Source Project: libdynticker   Author: drpout   File: ItBitExchangeTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testParseTicker() {
	try {
		Pair pair = new Pair("XBT", "USD");
		JsonNode node = (new ObjectMapper().readTree(new File("src/test/json/itbit-ticker.json")));
		String lastValue = testExchange.parseTicker(node, pair);
		Assert.assertEquals("376.94000000", lastValue);
	} catch (IOException e) {
		Assert.fail();
	}
}
 
Example #26
Source Project: Bats   Author: lealone   File: LogicalPlanRequest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString()
{
  try {
    return new ObjectMapper().writeValueAsString(this);
  } catch (IOException ex) {
    return ex.toString();
  }
}
 
Example #27
Source Project: cloud-pubsub-samples-java   Author: googlearchive   File: FetchMessagesServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public final void doGet(final HttpServletRequest req,
                        final HttpServletResponse resp)
        throws IOException {
    // First retrieve messages from the memcache
    MemcacheService memcacheService = MemcacheServiceFactory
            .getMemcacheService();
    List<String> messages =
            (List<String>) memcacheService.get(Constants.MESSAGE_CACHE_KEY);
    if (messages == null) {
        // If no messages in the memcache, look for the datastore
        DatastoreService datastore =
                DatastoreServiceFactory.getDatastoreService();
        PreparedQuery query = datastore.prepare(
                new Query("PubsubMessage").addSort("receipt-time",
                        Query.SortDirection.DESCENDING));
        messages = new ArrayList<>();
        for (Entity entity : query.asIterable(
                FetchOptions.Builder.withLimit(MAX_COUNT))) {
            String message = (String) entity.getProperty("message");
            messages.add(message);
        }
        // Store them to the memcache for future use.
        memcacheService.put(Constants.MESSAGE_CACHE_KEY, messages);
    }
    ObjectMapper mapper = new ObjectMapper();
    resp.setContentType("application/json; charset=UTF-8");
    mapper.writeValue(resp.getWriter(), messages);
    resp.getWriter().close();
}
 
Example #28
Source Project: Bats   Author: lealone   File: StringCodec.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString(T pojo)
{
  try {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ObjectWriter writer = mapper.writer();
    return writer.writeValueAsString(pojo);
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #29
Source Project: Eagle   Author: eBay   File: TestJacksonMarshalling.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJSonArrayMarshalling(){
	String[] array = {"cluster", "datacenter", "rack", "hostname"};
	JsonFactory factory = new JsonFactory(); 
    ObjectMapper mapper = new ObjectMapper(factory);
    String result = null;
    try{
    	result = mapper.writeValueAsString(array);
    }catch(Exception ex){
    	LOG.error("Cannot marshall", ex);
    	Assert.fail("cannot marshall an String array");
    }
    Assert.assertEquals("[\"cluster\",\"datacenter\",\"rack\",\"hostname\"]", result);
}
 
Example #30
Source Project: AIDR   Author: qcri-social   File: TaggerServiceImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<TaggerCrisisType> getAllCrisisTypes() throws AidrException {
	Client client = ClientBuilder.newBuilder()
			.register(JacksonFeature.class).build();
	try {
		/**
		 * Rest call to Tagger
		 */
		logger.info("Received request to fetch all crisisTypes");
		WebTarget webResource = client.target(taggerMainUrl
				+ "/crisisType/all");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).get();

		String jsonResponse = clientResponse.readEntity(String.class);

		//logger.error("URL: " + taggerMainUrl + " " + jsonResponse);

		TaggerAllCrisesTypesResponse crisesTypesResponse = objectMapper
				.readValue(jsonResponse, TaggerAllCrisesTypesResponse.class);

		if (crisesTypesResponse.getCrisisTypes() != null) {
			logger.info("Tagger returned "
					+ crisesTypesResponse.getCrisisTypes().size()
					+ " crises types");
		}

		return crisesTypesResponse.getCrisisTypes();
	} catch (Exception e) {
		logger.error("Error while getting all crisis from Tagger", e);
		throw new AidrException(
				"Error while getting all crisis from Tagger", e);
	}
}