Java Code Examples for org.codehaus.jackson.map.ObjectMapper

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project agorava-facebook, under directory /agorava-facebook-cdi/src/main/java/org/agorava/facebook/jackson/.

Source file: QuestionOptionListDeserializer.java

  22 
vote

@SuppressWarnings("unchecked") @Override public List<QuestionOption> deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  ObjectMapper mapper=new ObjectMapper();
  mapper.setDeserializationConfig(ctxt.getConfig());
  jp.setCodec(mapper);
  if (jp.hasCurrentToken()) {
    JsonNode dataNode=jp.readValueAsTree().get("data");
    if (dataNode != null) {
      return (List<QuestionOption>)mapper.readValue(dataNode,new TypeReference<List<QuestionOption>>(){
      }
);
    }
  }
  return null;
}
 

Example 2

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: ArtifactoryHttpClient.java

  20 
vote

public JsonFactory createJsonFactory(){
  JsonFactory jsonFactory=new JsonFactory();
  ObjectMapper mapper=new ObjectMapper(jsonFactory);
  mapper.getSerializationConfig().setAnnotationIntrospector(new JacksonAnnotationIntrospector());
  mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
  jsonFactory.setCodec(mapper);
  return jsonFactory;
}
 

Example 3

From project agorava-linkedin, under directory /agorava-linkedin-cdi/src/main/java/org/agorava/linkedin/jackson/.

Source file: CompanyMixin.java

  18 
vote

@Override public List<CompanyLocation> deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  ObjectMapper mapper=new ObjectMapper();
  mapper.setDeserializationConfig(ctxt.getConfig());
  jp.setCodec(mapper);
  if (jp.hasCurrentToken()) {
    JsonNode dataNode=jp.readValueAsTree().get("values");
    if (dataNode != null) {
      return mapper.readValue(dataNode,new TypeReference<List<CompanyLocation>>(){
      }
);
    }
  }
  return null;
}
 

Example 4

From project agorava-twitter, under directory /agorava-twitter-cdi/src/main/java/org/agorava/twitter/jackson/.

Source file: PlacesList.java

  18 
vote

@SuppressWarnings("unchecked") @Override public List<Place> deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  ObjectMapper mapper=new ObjectMapper();
  mapper.setDeserializationConfig(ctxt.getConfig());
  jp.setCodec(mapper);
  JsonNode dataNode=jp.readValueAsTree().get("places");
  return (List<Place>)mapper.readValue(dataNode,new TypeReference<List<Place>>(){
  }
);
}
 

Example 5

From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/util/.

Source file: JSONUtil.java

  18 
vote

/** 
 * Writes object to the writer as JSON using Jackson and adds a new-line before flushing.
 * @param writer the writer to write the JSON to
 * @param object the object to write as JSON
 * @throws IOException if the object can't be serialized as JSON or written to the writer
 */
public static void writeJson(Writer writer,Object object) throws IOException {
  ObjectMapper om=new ObjectMapper();
  om.configure(SerializationConfig.Feature.INDENT_OUTPUT,true);
  om.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
  writer.write(om.writeValueAsString(object));
  writer.write("\n");
  writer.flush();
}
 

Example 6

From project Arecibo, under directory /dashboard/src/test/java/com/ning/arecibo/dashboard/config/.

Source file: TestLegendConfiguration.java

  18 
vote

@Test(groups="fast") public void testSerialization() throws Exception {
  final ObjectMapper mapper=new ObjectMapper();
  final String legendConfigurationString="{\n" + "  \"JVMMemory\": {\n" + "    \"heapMax\": \"formatBase1024KMGTP\",\n"+ "    \"nonHeapMax\": \"formatBase1024KMGTP\",\n"+ "    \"heapUsed\": \"formatBase1024KMGTP\",\n"+ "    \"nonHeapUsed\": \"formatBase1024KMGTP\"\n"+ "  },\n"+ "  \"ParSurvivorSpace\": {\n"+ "    \"memoryPoolMax\": \"formatBase1024KMGTP\",\n"+ "    \"memoryPoolUsed\": \"formatBase1024KMGTP\"\n"+ "  }\n"+ "}";
  final LegendConfiguration legendConfiguration=mapper.readValue(legendConfigurationString,LegendConfiguration.class);
  Assert.assertEquals(legendConfiguration.size(),2);
  Assert.assertEquals(legendConfiguration.get("JVMMemory").size(),4);
  Assert.assertEquals(legendConfiguration.get("JVMMemory").get("heapMax"),"formatBase1024KMGTP");
  Assert.assertEquals(legendConfiguration.get("ParSurvivorSpace").size(),2);
  Assert.assertEquals(legendConfiguration.get("ParSurvivorSpace").get("memoryPoolMax"),"formatBase1024KMGTP");
  Assert.assertNull(legendConfiguration.get("foo"));
}
 

Example 7

From project atlas, under directory /src/main/java/com/ning/atlas/.

Source file: AtlasInstaller.java

  18 
vote

ObjectMapper makeMapper(Space space,Environment environment){
  ObjectMapper mapper=new ObjectMapper();
  mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,true);
  SimpleModule module=new SimpleModule("host-thing",new Version(1,0,0,""));
  module.addSerializer(new HostSerializer(space,environment));
  mapper.registerModule(module);
  return mapper;
}
 

Example 8

From project avro, under directory /lang/java/avro/src/test/java/org/apache/avro/generic/.

Source file: TestGenericData.java

  18 
vote

@Test public void testToStringIsJson() throws JsonParseException, IOException {
  Field stringField=new Field("string",Schema.create(Type.STRING),null,null);
  Field enumField=new Field("enum",Schema.createEnum("my_enum","doc",null,Arrays.asList("a","b","c")),null,null);
  Schema schema=Schema.createRecord("my_record","doc","mytest",false);
  schema.setFields(Arrays.asList(stringField,enumField));
  GenericRecord r=new GenericData.Record(schema);
  r.put(stringField.name(),"hello\nthere\"\tyou\u2013}");
  r.put(enumField.name(),new GenericData.EnumSymbol(enumField.schema(),"a"));
  String json=r.toString();
  JsonFactory factory=new JsonFactory();
  JsonParser parser=factory.createJsonParser(json);
  ObjectMapper mapper=new ObjectMapper();
  mapper.readTree(parser);
}
 

Example 9

From project bam, under directory /modules/activity-management/activity/src/test/java/org/overlord/bam/activity/server/.

Source file: QuerySpecTest.java

  18 
vote

@Test public void testQuerySerialize(){
  QuerySpec qs=new QuerySpec().setId("TestId").setFromTimestamp(500).setToTimestamp(600).setExpression(new QuerySpec.Expression(Operator.Or,new Context(Context.Type.Conversation,"123"),new Context(Context.Type.Message,"5")));
  qs.getExpression().getProperties().put("trader","joe");
  ObjectMapper mapper=new ObjectMapper();
  try {
    java.io.ByteArrayOutputStream baos=new java.io.ByteArrayOutputStream();
    mapper.writeValue(baos,qs);
    baos.close();
    System.out.println("QUERY SPEC=\r\n" + new String(baos.toByteArray()));
  }
 catch (  Exception e) {
    fail("Failed to serialize: " + e);
  }
}
 

Example 10

From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/mongo/.

Source file: JacksonPojoCollectionHelper.java

  18 
vote

/** 
 * Create our customized object mapper that f.ex. takes care of removing invalid characters from map keys.
 */
private static ObjectMapper createCustomizedObjectMapper(){
  SimpleModule mapKeyModule=new SimpleModule("MyMapKeySanitizingSerializerModule",new Version(1,0,0,null));
  mapKeyModule.addKeySerializer(String.class,new KeySanitizingSerializer());
  final ObjectMapper customizedMapper=new ObjectMapper();
  customizedMapper.registerModule(mapKeyModule);
  customizedMapper.registerModule(MongoJacksonMapperModule.INSTANCE);
  customizedMapper.setHandlerInstantiator(new MongoJacksonHandlerInstantiator(new MongoAnnotationIntrospector(customizedMapper.getDeserializationConfig())));
  return customizedMapper;
}
 

Example 11

From project candlepin, under directory /src/main/java/org/candlepin/resteasy/.

Source file: JsonProvider.java

  18 
vote

@Inject public JsonProvider(Config config){
  super(Annotations.JACKSON,Annotations.JAXB);
  ObjectMapper mapper=_mapperConfig.getDefaultMapper();
  configureHateoasObjectMapper(mapper,config);
  setMapper(mapper);
}
 

Example 12

From project chombo, under directory /src/main/java/org/chombo/mr/.

Source file: Histogram.java

  18 
vote

protected void setup(Context context) throws IOException, InterruptedException {
  Configuration conf=context.getConfiguration();
  fieldDelim=conf.get("field.delim","[]");
  fieldDelimRegex=conf.get("field.delim.regex","\\[\\]");
  String filePath=conf.get("histogram.schema.file.path");
  FileSystem dfs=FileSystem.get(conf);
  Path src=new Path(filePath);
  FSDataInputStream fs=dfs.open(src);
  ObjectMapper mapper=new ObjectMapper();
  schema=mapper.readValue(fs,HistogramSchema.class);
}
 

Example 13

From project com.cedarsoft.serialization, under directory /test/performance/src/test/java/com/cedarsoft/serialization/test/performance/.

Source file: JacksonTest.java

  18 
vote

@Test public void testMapper() throws Exception {
  ObjectMapper mapper=new ObjectMapper();
  com.cedarsoft.serialization.test.performance.jaxb.FileType fileType=new com.cedarsoft.serialization.test.performance.jaxb.FileType("Canon Raw",new com.cedarsoft.serialization.test.performance.jaxb.Extension(".","cr2",true),false);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  mapper.writeValue(out,fileType);
  JsonUtils.assertJsonEquals(JSON,out.toString());
}
 

Example 14

From project components-ness-httpclient, under directory /testing/src/test/java/com/nesscomputing/httpclient/testing/.

Source file: TestingHttpClientBuilderTest.java

  18 
vote

@Test public void testJsonResponse() throws Exception {
  ObjectMapper mapper=new ObjectMapper();
  TestingHttpClientBuilder builder=new TestingHttpClientBuilder().withObjectMapper(mapper);
  Map<String,String> superImportantMap=Collections.singletonMap("foo","bar");
  builder.on(GET).of("/json").respondWith(Response.ok(superImportantMap));
  HttpClient httpClient=builder.build();
  HttpClientResponse response=httpClient.get("/json",handler).perform();
  assertEquals(Status.OK.getStatusCode(),response.getStatusCode());
  assertEquals(MediaType.APPLICATION_JSON,response.getContentType());
  Map<String,String> result=mapper.readValue(response.getResponseBodyAsStream(),new TypeReference<Map<String,String>>(){
  }
);
  assertEquals(superImportantMap,result);
}
 

Example 15

From project components-ness-jackson, under directory /src/test/java/com/nesscomputing/jackson/.

Source file: TestNessJacksonModule.java

  18 
vote

@Ignore @Test public void testSafeToMultiplyInject(){
  final Injector injector=Guice.createInjector(Stage.PRODUCTION,ConfigModule.forTesting(),new NessJacksonModule(),new AbstractModule(){
    @Override protected void configure(){
      install(new NessJacksonModule());
    }
  }
);
  final ObjectMapper mapper=injector.getInstance(ObjectMapper.class);
  Assert.assertNotNull(mapper);
}
 

Example 16

From project crest, under directory /core/src/test/java/org/codegist/crest/serializer/jackson/.

Source file: JacksonFactoryTest.java

  18 
vote

@Test public void shouldNotCreateAnObjectMapperButUseTheCustomOn(){
  ObjectMapper mockObjectMapper=mock(ObjectMapper.class);
  when(mockCRestConfig.get(JacksonFactoryTest.class.getName() + JacksonFactory.JACKSON_OBJECT_MAPPER)).thenReturn(mockObjectMapper);
  ObjectMapper actual=JacksonFactory.createObjectMapper(mockCRestConfig,getClass());
  assertEquals(mockObjectMapper,actual);
}
 

Example 17

From project curator, under directory /curator-x-discovery-server/src/main/java/com/netflix/curator/x/discovery/server/entity/.

Source file: JsonServiceInstanceMarshaller.java

  18 
vote

@Override public ServiceInstance<T> readFrom(Class<ServiceInstance<T>> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,String> httpHeaders,InputStream entityStream) throws IOException, WebApplicationException {
  try {
    ObjectMapper mapper=new ObjectMapper();
    JsonNode node=mapper.reader().readTree(entityStream);
    return readInstance(node,context);
  }
 catch (  Exception e) {
    throw new WebApplicationException(e);
  }
}
 

Example 18

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/io/json/.

Source file: TwitterRemoteExecutor.java

  18 
vote

private <T>T readData(InputStream input,Class<T> mappingClass) throws JsonProcessingException, IOException {
  T jsonObjects=null;
  ObjectMapper mapper=MapperFactory.getMapperInstance();
  jsonObjects=mapper.readValue(input,mappingClass);
  return jsonObjects;
}
 

Example 19

From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.

Source file: JSonBatchExecutionTest.java

  18 
vote

public void assertXMLEqual(String expectedXml,String resultXml){
  try {
    ObjectMapper mapper=new ObjectMapper();
    JsonNode expectedTree=mapper.readTree(expectedXml);
    JsonNode resultTree=mapper.readTree(resultXml);
    assertEquals("Expected:" + expectedXml + "\nwas:"+ resultXml,expectedTree,resultTree);
  }
 catch (  Exception e) {
    throw new RuntimeException("XML Assertion failure",e);
  }
}
 

Example 20

From project elasticsearch-jetty, under directory /src/test/java/com/sonian/elasticsearch/http/jetty/.

Source file: HttpClient.java

  18 
vote

@SuppressWarnings({"unchecked"}) public HttpClientResponse request(String method,String path,Map<String,Object> data){
  ObjectMapper mapper=new ObjectMapper();
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  try {
    mapper.writeValue(out,data);
  }
 catch (  IOException e) {
    throw new ElasticSearchException("",e);
  }
  return request(method,path,out.toByteArray());
}
 

Example 21

From project emf4sw, under directory /bundles/com.emf4sw.rdf.json/src/com/emf4sw/rdf/resource/impl/.

Source file: RDFJSONResourceImpl.java

  18 
vote

@Override protected void doSave(OutputStream outputStream,Map<?,?> options) throws IOException {
  if (!getContents().isEmpty()) {
    if (getContents().get(0) instanceof RDFGraph) {
      ObjectMapper mapper=new ObjectMapper();
      mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,true);
      JsonNode root=RDFGraph2Json.createJsonTree((DocumentGraph)getContents().get(0));
      mapper.writeValue(outputStream,root);
    }
  }
}
 

Example 22

From project event-collector, under directory /event-collector/src/test/java/com/proofpoint/event/collector/.

Source file: TestLocalEventClient.java

  18 
vote

@BeforeMethod public void setup(){
  JsonEventSerializer eventSerializer=new JsonEventSerializer(TestEvent.class);
  ObjectMapper objectMapper=new ObjectMapper();
  eventWriter=new InMemoryEventWriter();
  ImmutableSet<EventWriter> eventWriters=ImmutableSet.of((EventWriter)eventWriter);
  eventClient=new LocalEventClient(eventWriters,eventSerializer,objectMapper);
}
 

Example 23

From project fastjson, under directory /src/test/java/com/alibaba/json/test/.

Source file: Bug_0_Test.java

  18 
vote

private void f_jackson() throws Exception {
  long startNano=System.nanoTime();
  for (int i=0; i < COUNT; ++i) {
    ObjectMapper mapper=new ObjectMapper();
    ArrayNode node=(ArrayNode)mapper.readTree(text);
    JsonNode head=node.get(0);
    JsonNode body=node.get(1);
  }
  long nano=System.nanoTime() - startNano;
  System.out.println(NumberFormat.getInstance().format(nano));
}
 

Example 24

From project floodlight, under directory /src/main/java/net/floodlightcontroller/storage/web/.

Source file: StorageNotifyResource.java

  18 
vote

@Post("json") public Map<String,Object> notify(String entity) throws Exception {
  List<StorageSourceNotification> notifications=null;
  ObjectMapper mapper=new ObjectMapper();
  notifications=mapper.readValue(entity,new TypeReference<List<StorageSourceNotification>>(){
  }
);
  IStorageSourceService storageSource=(IStorageSourceService)getContext().getAttributes().get(IStorageSourceService.class.getCanonicalName());
  storageSource.notifyListeners(notifications);
  HashMap<String,Object> model=new HashMap<String,Object>();
  model.put("output","OK");
  return model;
}
 

Example 25

From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/reporter/.

Source file: TestReportEvent.java

  18 
vote

/** 
 * This just checks to make sure the value was json parsable. Throws exception on parse failure.
 */
@SuppressWarnings("unchecked") @Test public void testReportJsonParse() throws IOException {
  StringWriter w=new StringWriter();
  e.toJson(w);
  w.flush();
  System.out.println(w.getBuffer());
  StringReader r=new StringReader(w.getBuffer().toString());
  ObjectMapper m=new ObjectMapper();
  HashMap<String,Object> node=m.readValue(r,HashMap.class);
  System.out.println(node);
}
 

Example 26

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/reporter/.

Source file: TestReportEvent.java

  18 
vote

/** 
 * This just checks to make sure the value was json parsable. Throws exception on parse failure.
 */
@SuppressWarnings("unchecked") @Test public void testReportJsonParse() throws IOException {
  StringWriter w=new StringWriter();
  e.toJson(w);
  w.flush();
  System.out.println(w.getBuffer());
  StringReader r=new StringReader(w.getBuffer().toString());
  ObjectMapper m=new ObjectMapper();
  HashMap<String,Object> node=m.readValue(r,HashMap.class);
  System.out.println(node);
}
 

Example 27

From project gedcomx, under directory /gedcomx-rt-support/src/main/java/org/gedcomx/rt/json/.

Source file: GedcomJsonProvider.java

  18 
vote

/** 
 * Creates an object mapper given the specified context classes.
 * @param classes the context classes.
 * @return The object mapper.
 */
public static ObjectMapper createObjectMapper(Class<?>... classes){
  ObjectMapper mapper=new ObjectMapper();
  AnnotationIntrospector introspector=AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(),new JaxbAnnotationIntrospector());
  mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
  mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);
  mapper.registerModule(new GedcomJacksonModule());
  for (  Class<?> contextClass : classes) {
    GedcomNamespaceManager.registerKnownJsonType(contextClass);
  }
  return mapper;
}
 

Example 28

From project gnip4j, under directory /core/src/main/java/com/zaubersoftware/gnip4j/api/impl/.

Source file: DefaultGnipStream.java

  18 
vote

public static final ObjectMapper getObjectMapper(){
  final ObjectMapper mapper=new ObjectMapper();
  SimpleModule gnipActivityModule=new SimpleModule("gnip.activity",new Version(1,0,0,null));
  gnipActivityModule.addDeserializer(Geo.class,new GeoDeserializer(Geo.class));
  mapper.registerModule(gnipActivityModule);
  mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
  return mapper;
}
 

Example 29

From project greenhouse-android, under directory /src/org/springframework/social/greenhouse/api/impl/.

Source file: GreenhouseTemplate.java

  18 
vote

private void registerGreenhouseJsonModule(){
  List<HttpMessageConverter<?>> converters=getRestTemplate().getMessageConverters();
  for (  HttpMessageConverter<?> converter : converters) {
    if (converter instanceof MappingJacksonHttpMessageConverter) {
      MappingJacksonHttpMessageConverter jsonConverter=(MappingJacksonHttpMessageConverter)converter;
      ObjectMapper objectMapper=new ObjectMapper();
      objectMapper.registerModule(new GreenhouseModule());
      jsonConverter.setObjectMapper(objectMapper);
    }
  }
}
 

Example 30

From project gxa, under directory /atlas-web/src/main/java/ae3/util/.

Source file: JsonUtil.java

  18 
vote

public static String toJson(Object obj){
  try {
    StringWriter out=new StringWriter();
    ObjectMapper mapper=new ObjectMapper();
    mapper.writeValue(out,obj);
    return out.toString();
  }
 catch (  IOException e) {
    log.error("JSON serialization error",e);
  }
  return "null";
}
 

Example 31

From project handlebars.java_1, under directory /handlebars-json/src/test/java/com/github/jknack/handlebars/.

Source file: JSONHelperTest.java

  18 
vote

@Test public void toJSONViewExclusive() throws IOException {
  Handlebars handlebars=new Handlebars();
  ObjectMapper mapper=new ObjectMapper();
  mapper.configure(Feature.DEFAULT_VIEW_INCLUSION,false);
  handlebars.registerHelper("@json",new JSONHelper(mapper));
  Template template=handlebars.compile("{{@json this view=\"com.github.jknack.handlebars.Blog$Views$Public\"}}");
  CharSequence result=template.apply(new Blog("First Post","..."));
  assertEquals("{\"title\":\"First Post\"}",result);
}
 

Example 32

From project hcatalog, under directory /webhcat/svr/src/main/java/org/apache/hcatalog/templeton/.

Source file: JsonBuilder.java

  18 
vote

/** 
 * Convert a json string to a Map.
 */
public static Map jsonToMap(String json) throws IOException {
  if (!TempletonUtils.isset(json))   return new HashMap<String,Object>();
 else {
    ObjectMapper mapper=new ObjectMapper();
    return mapper.readValue(json,Map.class);
  }
}
 

Example 33

From project hiho, under directory /src/co/nubetech/hiho/mapreduce/.

Source file: GenericDBLoadDataMapper.java

  18 
vote

protected void setup(Mapper.Context context) throws IOException, InterruptedException {
  delimiter=context.getConfiguration().get(HIHOConf.INPUT_OUTPUT_DELIMITER);
  logger.debug("delimiter is: " + delimiter);
  String columnInfoJsonString=context.getConfiguration().get(HIHOConf.COLUMN_INFO);
  logger.debug("columnInfoJsonString is: " + columnInfoJsonString);
  ObjectMapper mapper=new ObjectMapper();
  tableInfo=mapper.readValue(columnInfoJsonString,new TypeReference<ArrayList<ColumnInfo>>(){
  }
);
}
 

Example 34

From project IronCount, under directory /src/main/java/com/jointhegrid/ironcount/manager/.

Source file: WorkloadManager.java

  18 
vote

public byte[] serializeWorkload(Workload w){
  ObjectMapper map=new ObjectMapper();
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    map.writeValue(baos,w);
  }
 catch (  IOException ex) {
    logger.error(ex);
  }
  return baos.toByteArray();
}
 

Example 35

From project isohealth, under directory /isohealth/src/com/isobar/isohealth/wrappers/.

Source file: BackgroundActivityWrapper.java

  18 
vote

public BackgroundActivity getBackgroundActivity(String url) throws Exception {
  ObjectMapper mapper=new ObjectMapper();
  url=GraphConstants.REST_URL + url;
  HttpURLConnection conn=(HttpURLConnection)new URL(url).openConnection();
  conn.setRequestProperty("Accept",GraphConstants.MEDIA_BACKGROUND_ACTIVITY);
  conn.setRequestProperty("Authorization","Bearer " + authToken);
  if (conn.getResponseCode() != 200) {
    throw new IOException(conn.getResponseMessage());
  }
  BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream()));
  BackgroundActivity backgroundActivity=mapper.readValue(rd,BackgroundActivity.class);
  conn.disconnect();
  return backgroundActivity;
}
 

Example 36

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.

Source file: JsonConfigLoader.java

  17 
vote

/** 
 * Read the configuration from an input stream
 * @param configFile
 * @return the configuration or null if there was a problem reading.
 * @throws ConfigurationException 
 */
public C readConfiguration(InputStream is) throws ConfigurationException {
  try {
    ObjectMapper mapper=new ObjectMapper();
    C res=mapper.readValue(is,clazz);
    return res;
  }
 catch (  JsonParseException ex) {
    throw new ConfigurationException("The input is not valid JSON",ex);
  }
catch (  JsonMappingException ex) {
    throw new ConfigurationException("The input JSON doesn't match " + "the " + clazz.getCanonicalName() + " class",ex);
  }
catch (  IOException ex) {
    throw new ConfigurationException("IO error while reading the JSON",ex);
  }
}
 

Example 37

From project Activiti-KickStart, under directory /activiti-kickstart-rest/src/main/java/org/activiti/kickstart/.

Source file: WorkflowResource.java

  17 
vote

protected ObjectNode deployWorkflow(KickstartWorkflow workflow,String json){
  String workflowId=getKickstartService().deployWorkflow(workflow,Collections.singletonMap(MetaDataKeys.WORKFLOW_JSON_SOURCE,json));
  ObjectNode idNode=new ObjectMapper().createObjectNode();
  idNode.put("id",workflowId);
  return idNode;
}
 

Example 38

From project airlift, under directory /json/src/main/java/io/airlift/json/.

Source file: JsonCodecFactory.java

  17 
vote

private ObjectMapper createObjectMapper(){
  ObjectMapper objectMapper=null;
  RuntimeException lastException=null;
  for (int i=0; objectMapper == null && i < 10; i++) {
    try {
      objectMapper=objectMapperProvider.get();
    }
 catch (    RuntimeException e) {
      lastException=e;
    }
  }
  if (objectMapper == null) {
    throw lastException;
  }
  if (prettyPrint) {
    objectMapper.getSerializationConfig().enable(INDENT_OUTPUT);
  }
 else {
    objectMapper.getSerializationConfig().disable(INDENT_OUTPUT);
  }
  return objectMapper;
}
 

Example 39

From project android-client_2, under directory /src/org/mifos/androidclient/main/.

Source file: ApplyCollectionSheetActivity.java

  17 
vote

@Override protected Map<String,String> onPrepareParameters() throws IOException {
  TableLayout tableLayout=(TableLayout)findViewById(R.id.collectionSheet_summary);
  tableLayout.setVisibility(View.GONE);
  Map<String,String> params=new HashMap<String,String>();
  params.put("json",new ObjectMapper().writeValueAsString(mSaveCustomer));
  return params;
}
 

Example 40

From project ANNIS, under directory /annis-service/src/main/java/annis/.

Source file: AnnisRunner.java

  17 
vote

public void doAnnotations(String doListValues){
  boolean listValues="values".equals(doListValues);
  List<AnnisAttribute> annotations=annisDao.listAnnotations(getCorpusList(),listValues,true);
  try {
    ObjectMapper om=new ObjectMapper();
    AnnotationIntrospector ai=new JaxbAnnotationIntrospector();
    DeserializationConfig config=om.getDeserializationConfig().withAnnotationIntrospector(ai);
    om.setDeserializationConfig(config);
    om.configure(SerializationConfig.Feature.INDENT_OUTPUT,true);
    System.out.println(om.writeValueAsString(annotations));
  }
 catch (  IOException ex) {
    log.error("problems with writing result",ex);
  }
}
 

Example 41

From project AutobahnAndroid, under directory /Autobahn/src/de/tavendo/autobahn/.

Source file: WampReader.java

  17 
vote

/** 
 * A reader object is created in AutobahnConnection.
 * @param calls         The call map created on master.
 * @param subs          The event subscription map created on master.
 * @param master        Message handler of master (used by us to notify the master).
 * @param socket        The TCP socket.
 * @param options       WebSockets connection options.
 * @param threadName    The thread name we announce.
 */
public WampReader(ConcurrentHashMap<String,CallMeta> calls,ConcurrentHashMap<String,SubMeta> subs,Handler master,SocketChannel socket,WebSocketOptions options,String threadName){
  super(master,socket,options,threadName);
  mCalls=calls;
  mSubs=subs;
  mJsonMapper=new ObjectMapper();
  mJsonMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
  mJsonFactory=mJsonMapper.getJsonFactory();
  if (DEBUG)   Log.d(TAG,"created");
}
 

Example 42

From project beanstalker, under directory /simpledb-maven-plugin/src/main/java/br/com/ingenieux/mojo/simpledb/cmd/.

Source file: PutAttributesCommand.java

  17 
vote

public void execute(PutAttributesContext ctx) throws Exception {
  if (ctx.isCreateDomainIfNeeded())   createIfNeeded(ctx);
  ArrayNode attributesArray=(ArrayNode)new ObjectMapper().readTree(ctx.getSource());
  for (int i=0; i < attributesArray.size(); i++) {
    ObjectNode putAttributeNode=(ObjectNode)attributesArray.get(i);
    putAttribute(ctx,putAttributeNode);
  }
}
 

Example 43

From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/util/.

Source file: TripleStoreQueryServiceMulgaraImpl.java

  17 
vote

public TripleStoreQueryServiceMulgaraImpl(){
  this.multiThreadedHttpConnectionManager=new MultiThreadedHttpConnectionManager();
  this.httpClient=new HttpClient(this.multiThreadedHttpConnectionManager);
  this.mapper=new ObjectMapper();
  this.collections=null;
}
 

Example 44

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/openstack/.

Source file: OpenstackCloudDriver.java

  17 
vote

@SuppressWarnings("rawtypes") List<FloatingIP> listFloatingIPs(final String token) throws SAXException, IOException {
  final String response=service.path(this.pathPrefix + "os-floating-ips").header("X-Auth-Token",token).accept(MediaType.APPLICATION_JSON).get(String.class);
  final ObjectMapper mapper=new ObjectMapper();
  final Map map=mapper.readValue(new StringReader(response),Map.class);
  @SuppressWarnings("unchecked") final List<Map> list=(List<Map>)map.get("floating_ips");
  final List<FloatingIP> floatingIps=new ArrayList<FloatingIP>(map.size());
  for (  final Map floatingIpMap : list) {
    final FloatingIP ip=new FloatingIP();
    final Object instanceId=floatingIpMap.get("instance_id");
    ip.setInstanceId(instanceId == null ? null : instanceId.toString());
    ip.setIp((String)floatingIpMap.get("ip"));
    ip.setFixedIp((String)floatingIpMap.get("fixed_ip"));
    ip.setId(floatingIpMap.get("id").toString());
    floatingIps.add(ip);
  }
  return floatingIps;
}
 

Example 45

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/grabber/.

Source file: DatasetMetadata.java

  17 
vote

public void serialize(Writer writer) throws IOException {
  try {
    ObjectMapper mapper=new ObjectMapper();
    JsonFactory jf=new JsonFactory();
    JsonGenerator jg=jf.createJsonGenerator(writer);
    jg.useDefaultPrettyPrinter();
    mapper.writeValue(jg,this);
  }
 catch (  JsonParseException ex) {
    throw new PaulException(ex);
  }
catch (  JsonMappingException ex) {
    throw new PaulException(ex);
  }
}
 

Example 46

From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/cluster/zookeeper/.

Source file: ZookeeperSession.java

  17 
vote

public JSONSerializer(){
  objectMapper=new ObjectMapper();
  objectMapper.enableDefaultTyping();
  objectMapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS,true);
  objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
  objectMapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES,true);
}
 

Example 47

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/.

Source file: DragonJobRunner.java

  17 
vote

@SuppressWarnings("unchecked") private void readTokensFromFiles(Configuration conf,Credentials credentials) throws IOException {
  String binaryTokenFilename=conf.get(DragonJobConfig.DRAGON_JOB_CREDENTIALS_BINARY);
  if (binaryTokenFilename != null) {
    Credentials binary=Credentials.readTokenStorageFile(new Path("file:///" + binaryTokenFilename),conf);
    credentials.addAll(binary);
  }
  String tokensFileName=conf.get(DragonJobConfig.DRAGON_JOB_CREDENTIALS_JSON);
  if (tokensFileName != null) {
    LOG.info("loading user's secret keys from " + tokensFileName);
    String localFileName=new Path(tokensFileName).toUri().getPath();
    boolean json_error=false;
    try {
      ObjectMapper mapper=new ObjectMapper();
      Map<String,String> nm=mapper.readValue(new File(localFileName),Map.class);
      for (      Map.Entry<String,String> ent : nm.entrySet()) {
        credentials.addSecretKey(new Text(ent.getKey()),ent.getValue().getBytes());
      }
    }
 catch (    JsonMappingException e) {
      json_error=true;
    }
catch (    JsonParseException e) {
      json_error=true;
    }
    if (json_error)     LOG.warn("couldn't parse Token Cache JSON file with user secret keys");
  }
}
 

Example 48

From project email-preview, under directory /src/main/java/org/jasig/portlet/emailpreview/dao/demo/.

Source file: DemoAccountService.java

  17 
vote

/** 
 * Builds a fresh collection of messages.
 */
private List<EmailMessage> getEmailMessages(PortletRequest req){
  File jsonFile=new File(getClass().getResource(jsonLocation).getFile());
  List<EmailMessage> messages=new ArrayList<EmailMessage>();
  try {
    ObjectMapper mapper=new ObjectMapper();
    ArrayNode json=mapper.readValue(jsonFile,ArrayNode.class);
    for (    JsonNode msg : json) {
      long uid=msg.path("uid").getLongValue();
      String sender=msg.path("from").getTextValue();
      String subject=msg.path("subject").getTextValue();
      Date sentDate=new Date(msg.path("sentDate").getLongValue());
      boolean unread=msg.path("unread").getBooleanValue();
      boolean answered=false;
      boolean deleted=false;
      EmailMessageContent content=new EmailMessageContent(msg.path("body").getTextValue(),true);
      messages.add(new EmailMessage(messages.size(),uid,sender,subject,sentDate,unread,answered,deleted,false,"text/plain",content));
    }
  }
 catch (  Exception e) {
    log.error("Failed to load messages collection",e);
  }
  return messages;
}
 

Example 49

From project Faye-Android, under directory /src/com/b3rwynmobile/fayeclient/autobahn/.

Source file: WampReader.java

  17 
vote

/** 
 * A reader object is created in AutobahnConnection.
 * @param calls         The call map created on master.
 * @param subs          The event subscription map created on master.
 * @param master        Message handler of master (used by us to notify the master).
 * @param socket        The TCP socket.
 * @param options       WebSockets connection options.
 * @param threadName    The thread name we announce.
 */
public WampReader(ConcurrentHashMap<String,CallMeta> calls,ConcurrentHashMap<String,SubMeta> subs,Handler master,SocketChannel socket,WebSocketOptions options,String threadName){
  super(master,socket,options,threadName);
  mCalls=calls;
  mSubs=subs;
  mJsonMapper=new ObjectMapper();
  mJsonMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
  mJsonFactory=mJsonMapper.getJsonFactory();
  if (DEBUG)   Log.d(TAG,"created");
}
 

Example 50

From project geolatte-common, under directory /src/test/java/org/geolatte/common/dataformats/json/.

Source file: GeoJsonToDeserializationTest.java

  17 
vote

@BeforeClass public static void setupSuite(){
  assembler=new GeoJsonToAssembler();
  mapper=new ObjectMapper();
  JacksonConfiguration.applyMixin(mapper);
  mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
 

Example 51

From project grouperfish, under directory /transforms/coclustering/src/main/java/com/mozilla/grouperfish/transforms/coclustering/display/.

Source file: WriteCoClusteringOutput.java

  17 
vote

public void writeTags() throws IOException {
  Map<String,List<Integer>> tags=new LinkedHashMap<String,List<Integer>>();
  List<Integer> clusterIDList;
  List<String> currDocuments;
  int currNumDocs;
  Integer currClusterID;
  for (  Map.Entry<Integer,CoCluster> entry : coclusters.entrySet()) {
    currClusterID=entry.getKey();
    currNumDocs=entry.getValue().getNumDocuments();
    currDocuments=entry.getValue().getDocuments(currNumDocs);
    for (    String s : currDocuments) {
      clusterIDList=new ArrayList<Integer>();
      clusterIDList.add(currClusterID);
      tags.put(s,clusterIDList);
    }
  }
  ObjectMapper mapper=new ObjectMapper();
  FSDataOutputStream out=null;
  fs=FileSystem.get(conf);
  out=fs.create(tagPath);
  out.write(mapper.writeValueAsBytes(tags));
  if (fs != null) {
    fs.close();
  }
  if (out != null) {
    out.close();
  }
}
 

Example 52

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/json/validator/.

Source file: ALPJSONValidator.java

  16 
vote

/** 
 * Instantiates a new ALPJSON validator.
 * @param JSONSchemasPath - represent path to folder with all schemas
 * @param in_schemaName the in_schema name
 * @throws IOException Signals that an I/O exception has occurred.
 */
public ALPJSONValidator(String JSONSchemasPath,String in_schemaName) throws IOException {
  schemaName=in_schemaName;
  JSONFactory=new JsonFactory();
  JSONStack=new LinkedList<String>();
  ErrorsStack=new LinkedList<String>();
  first_try=true;
  JSONMapper=new ObjectMapper();
  File dir=new File(JSONSchemasPath);
  FilenameFilter jsonFilter=new FilenameFilter(){
    public boolean accept(    File dir,    String name){
      return name.toLowerCase().endsWith(".json");
    }
  }
;
  schemasList=dir.listFiles(jsonFilter);
}
 

Example 53

From project aranea, under directory /webapp/src/test/java/no/dusken/aranea/integration/test/.

Source file: AbstractIntegrationTest.java

  16 
vote

@Before public void before(){
  webDriver=new HtmlUnitDriver(false){
    @Override public WebElement findElement(    By by){
      WebElement element=super.findElement(by);
      checkValidity();
      return element;
    }
    @Override public List<WebElement> findElements(    By by){
      List<WebElement> elements=super.findElements(by);
      checkValidity();
      return elements;
    }
    @Override public String getPageSource(){
      Page page=lastPage();
      if (page == null) {
        return null;
      }
      WebResponse response=page.getWebResponse();
      return response.getContentAsString();
    }
  }
;
  webDriver.get(host);
  httpclient=new DefaultHttpClient();
  mapper=new ObjectMapper();
  allowedErrorMessages.add("Attribute property not allowed on element meta at this point.");
  allowedErrorMessages.add("Element meta is missing one or more of the following attributes: http-equiv, itemprop, name.");
  allowedErrorMessages.add("Element fb:like not allowed as child of element div in this context. (Suppressing further errors from this subtree.)");
}
 

Example 54

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/dbunit/dataset/json/.

Source file: JsonDataSetProducer.java

  16 
vote

@Override Map<String,List<Map<String,String>>> loadDataSet() throws DataSetException {
  Map<String,List<Map<String,String>>> dataset=Collections.emptyMap();
  try {
    dataset=new ObjectMapper().readValue(input,Map.class);
  }
 catch (  JsonParseException e) {
    throw new DataSetException("Error parsing json data set",e);
  }
catch (  JsonMappingException e) {
    throw new DataSetException("Error mapping json data set",e);
  }
catch (  IOException e) {
    throw new DataSetException("Error opening json data set",e);
  }
  return dataset;
}
 

Example 55

From project core_1, under directory /transform/src/main/java/org/switchyard/transform/json/internal/.

Source file: JSONTransformFactory.java

  15 
vote

/** 
 * Create a  {@link Transformer} instance from the supplied {@link JSONTransformModel}.
 * @param model the JSON transformer model. 
 * @return the Transformer instance.
 */
public Transformer newTransformer(JSONTransformModel model){
  QName from=model.getFrom();
  QName to=model.getTo();
  assertValidJSONTransformSpec(from,to);
  if (QNameUtil.isJavaMessageType(from)) {
    Class clazz=toJavaMessageType(from);
    return new Java2JSONTransformer(from,to,new ObjectMapper(),clazz);
  }
 else {
    Class clazz=toJavaMessageType(to);
    return new JSON2JavaTransformer(from,to,new ObjectMapper(),clazz);
  }
}
 

Example 56

From project fast-http, under directory /src/test/java/org/neo4j/smack/serialization/.

Source file: TestDeserializationStrategy.java

  15 
vote

@Test public void testSimpleDeserializationStrategy() throws Exception {
  InputStream in=new ByteArrayInputStream("{\"firstkey\":1,\"secondkey\":2}".getBytes("UTF-8"));
  JsonDeserializer d=new JsonDeserializer(new JsonFactory(new ObjectMapper()),in);
  DeserializationStrategy<Object> objectStrategy=new DeserializationStrategy<Object>(){
    @Override public Object deserialize(    Deserializer in) throws DeserializationException {
      return in.readObject();
    }
  }
;
  assertThat(objectStrategy.deserialize(d),not(nullValue()));
}
 

Example 57

From project GNDMS, under directory /stuff/test-src/de/zib/gndms/stuff/confuror/.

Source file: ConfigHolderTest.java

  15 
vote

@Test public void pathTest() throws IOException, ConfigEditor.UpdateRejectedException {
  ConfigEditor editor=tree.newEditor(visitor);
  JsonNode init=parseSingle(factory,"{ 'a': 12, 'b': { 'x': { 'c' : 4 } } }");
  tree.update(editor,init);
  final AtomicReference<Object[]> ref=new AtomicReference<Object[]>(null);
  ConfigEditor reportingEditor=tree.newEditor(new ConfigEditor.Visitor(){
    public ObjectMapper getObjectMapper(){
      return objectMapper;
    }
    public void updateNode(    @NotNull ConfigEditor.Update updater){
      ref.getAndSet(updater.getPath());
      updater.accept();
    }
  }
);
  tree.update(reportingEditor,parseSingle(factory,"{ '+b': { '+x': { 'q': 5 } } }"));
  final Object[] result=ref.get();
  Assert.assertTrue(result.length == 3);
  Assert.assertTrue(result[0].equals("b"));
  Assert.assertTrue(result[1].equals("x"));
  Assert.assertTrue(result[2].equals("q"));
}
 

Example 58

From project httpobjects, under directory /jackson/src/main/java/org/httpobjects/jackson/.

Source file: JacksonDSL.java

  15 
vote

public static Representation JacksonJson(final Object object,final ObjectMapper jackson){
  return new Representation(){
    @Override public void write(    OutputStream out){
      try {
        jackson.writeValue(out,object);
      }
 catch (      Exception e) {
        throw new RuntimeException(e);
      }
    }
    @Override public String contentType(){
      return "application/json";
    }
  }
;
}