Java Code Examples for org.codehaus.jackson.JsonParser

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 Arecibo, under directory /util/src/main/java/com/ning/arecibo/util/timeline/persistent/.

Source file: Replayer.java

  22 
vote

@VisibleForTesting public void read(final File file,final Function<HostSamplesForTimestamp,Void> fn) throws IOException {
  final JsonParser smileParser=smileFactory.createJsonParser(file);
  if (smileParser.nextToken() != JsonToken.START_ARRAY) {
    return;
  }
  while (!shuttingDown.get() && smileParser.nextToken() != JsonToken.END_ARRAY) {
    final HostSamplesForTimestamp hostSamplesForTimestamp=smileParser.readValueAs(HostSamplesForTimestamp.class);
    fn.apply(hostSamplesForTimestamp);
  }
  smileParser.close();
}
 

Example 2

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

Source file: TestGenericData.java

  22 
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 3

From project com.cedarsoft.serialization, under directory /jackson/src/main/java/com/cedarsoft/serialization/jackson/.

Source file: AbstractJacksonSerializer.java

  22 
vote

@Nonnull public T deserialize(@Nonnull InputStream in,@Nullable Version version) throws IOException, VersionException {
  try {
    JsonFactory jsonFactory=JacksonSupport.getJsonFactory();
    JsonParser parser=jsonFactory.createJsonParser(in);
    T deserialized=deserializeInternal(parser,version);
    ensureParserClosed(parser);
    return deserialized;
  }
 catch (  InvalidTypeException e) {
    throw new IOException("Could not parse due to " + e.getMessage(),e);
  }
}
 

Example 4

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

Source file: S3Uploader.java

  22 
vote

private void verifyFile(File file) throws IOException {
  SnappyInputStream input=new SnappyInputStream(new FileInputStream(file));
  JsonParser parser=new ObjectMapper().getJsonFactory().createJsonParser(input);
  try {
    while (parser.readValueAsTree() != null) {
    }
  }
  finally {
    parser.close();
  }
}
 

Example 5

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

Source file: JacksonPageModelParser.java

  22 
vote

/** 
 * @param content
 * @throws JsonParseException
 * @throws IOException
 */
public PageInstance parse(String content) throws JsonParseException, IOException {
  JsonFactory f=new JsonFactory();
  JsonParser parser=f.createJsonParser(content);
  JsonToken current=parser.nextToken();
  String instanceId=getNextTextValue("sid",parser);
  String pageId=getNextTextValue("cid",parser);
  current=parser.nextToken();
  assertExpectedFiled(parser.getCurrentName(),"segments",parser.getCurrentLocation());
  PageInstance pageInstance=new PageInstance();
  pageInstance.setCid(pageId);
  pageInstance.setSid(Long.valueOf(instanceId));
  pageInstance.setSegments(parseSegments(parser));
  return pageInstance;
}
 

Example 6

From project gnip4j, under directory /core/src/test/java/com/zaubersoftware/gnip4j/http/.

Source file: JSONDeserializationTest.java

  22 
vote

/** 
 * test a complete unmarshal from the json 
 */
@Test public void testGeoCoordinates() throws Exception {
  final InputStream is=getClass().getClassLoader().getResourceAsStream("com/zaubersoftware/gnip4j/payload/payload-example-geo.json");
  try {
    final JsonParser parser=mapper.getJsonFactory().createJsonParser(is);
    final Activity activity=parser.readValueAs(Activity.class);
    assertNotNull(activity.getGeo());
    assertNotNull(activity.getGeo().getCoordinates());
    assertEquals(-34.58501869,((Point)activity.getGeo().getCoordinates()).getLatitude(),0.001);
    assertEquals(-58.43946468,((Point)activity.getGeo().getCoordinates()).getLongitude(),0.001);
  }
  finally {
    is.close();
  }
}
 

Example 7

From project jHipChat, under directory /src/main/java/com/github/hipchat/api/.

Source file: RoomParser.java

  22 
vote

public static Room parseRoom(HipChat origin,InputStream input) throws JsonParseException, JsonMappingException, IOException {
  JsonParser jp=HipChat.JSON_FACTORY.createJsonParser(input);
  ObjectMapper mapper=new ObjectMapper();
  Room room=null;
  jp.nextToken();
  while (jp.nextToken() != JsonToken.END_OBJECT) {
    String tag=jp.getText();
    if ("room".equals(tag)) {
      jp.nextToken();
      room=parseRoom(origin,mapper,jp);
    }
  }
  return room;
}
 

Example 8

From project meaningfulweb, under directory /meaningfulweb-core/src/main/java/org/meaningfulweb/util/.

Source file: JsonUtils.java

  22 
vote

public static Object deserializeFromJson(String json,Class valueType){
  try {
    ObjectMapper mapper=new ObjectMapper();
    MappingJsonFactory jsonFactory=new MappingJsonFactory();
    JsonParser jsonParser=jsonFactory.createJsonParser(json);
    return mapper.readValue(jsonParser,valueType);
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 9

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

Source file: JsonMapper.java

  21 
vote

public Object readFrom(Class<Object> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,String> httpHeaders,InputStream inputStream) throws IOException {
  Object object;
  try {
    JsonParser jsonParser=objectMapper.getJsonFactory().createJsonParser(inputStream);
    jsonParser.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
    object=objectMapper.readValue(jsonParser,TypeFactory.type(genericType));
  }
 catch (  Exception e) {
    if (e instanceof IOException && !(e instanceof JsonProcessingException) && !(e instanceof EOFException)) {
      throw (IOException)e;
    }
    log.debug(e,"Invalid json for Java type %s",type);
    throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid json for Java type " + type).build());
  }
  Set<ConstraintViolation<Object>> violations=VALIDATOR.validate(object);
  if (!violations.isEmpty()) {
    throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(messagesFor(violations)).build());
  }
  return object;
}
 

Example 10

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

Source file: ArtifactoryBuildInfoClient.java

  21 
vote

/** 
 * @return A list of local repositories available for deployment.
 * @throws IOException On any connection error
 */
public List<String> getLocalRepositoriesKeys() throws IOException {
  List<String> repositories=new ArrayList<String>();
  PreemptiveHttpClient client=httpClient.getHttpClient();
  String localReposUrl=artifactoryUrl + LOCAL_REPOS_REST_URL;
  log.debug("Requesting local repositories list from: " + localReposUrl);
  HttpGet httpget=new HttpGet(localReposUrl);
  HttpResponse response=client.execute(httpget);
  StatusLine statusLine=response.getStatusLine();
  HttpEntity entity=response.getEntity();
  if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
    if (entity != null) {
      entity.consumeContent();
    }
    throwHttpIOException("Failed to obtain list of repositories:",statusLine);
  }
 else {
    if (entity != null) {
      repositories=new ArrayList<String>();
      InputStream content=entity.getContent();
      JsonParser parser;
      try {
        parser=httpClient.createJsonParser(content);
        JsonNode result=parser.readValueAsTree();
        log.debug("Repositories result = " + result);
        for (        JsonNode jsonNode : result) {
          String repositoryKey=jsonNode.get("key").getTextValue();
          repositories.add(repositoryKey);
        }
      }
  finally {
        if (content != null) {
          content.close();
        }
      }
    }
  }
  return repositories;
}
 

Example 11

From project cloudify, under directory /tools/src/main/java/org/cloudifysource/restDoclet/generation/.

Source file: Utils.java

  21 
vote

public static String getIndentJson(String body) throws JsonParseException, IOException {
  if (StringUtils.isBlank(body))   return null;
  StringWriter out=new StringWriter();
  JsonParser parser=null;
  JsonGenerator gen=null;
  try {
    JsonFactory fac=new JsonFactory();
    parser=fac.createJsonParser(new StringReader(body));
    ObjectMapper mapper=new ObjectMapper();
    JsonNode node=mapper.readTree(parser);
    gen=fac.createJsonGenerator(out);
    gen.useDefaultPrettyPrinter();
    mapper.writeTree(gen,node);
    gen.close();
    parser.close();
    return out.toString();
  }
  finally {
    out.close();
    if (gen != null) {
      gen.close();
    }
    if (parser != null) {
      parser.close();
    }
  }
}
 

Example 12

From project core_3, under directory /src/test/java/org/animotron/.

Source file: JSONTest.java

  21 
vote

private void test(String in,String out) throws Throwable {
  JsonParser jp=FACTORY.createJsonParser(in);
  Expression e=new JSONExpression(jp);
  StringBuilder s=new StringBuilder();
  IndexHits<Relationship> it=Order._.queryDown(e.getEndNode());
  try {
    if (it.hasNext()) {
      Relationship i=it.next();
      s.append(truncate(CachedSerializer.ANIMO.serialize(i)));
      while (it.hasNext()) {
        i=it.next();
        s.append(" ");
        s.append(truncate(CachedSerializer.ANIMO.serialize(i)));
      }
      s.append(".");
      Assert.assertEquals(out,s.toString());
    }
  }
  finally {
    it.close();
  }
}
 

Example 13

From project DirectMemory, under directory /server/directmemory-server-commons/src/main/java/org/apache/directmemory/server/commons/.

Source file: DirectMemoryParser.java

  21 
vote

public DirectMemoryRequest buildRequest(InputStream inputStream) throws DirectMemoryException {
  try {
    JsonParser jp=this.jsonFactory.createJsonParser(inputStream);
    DirectMemoryRequest rq=new DirectMemoryRequest();
    JsonToken jsonToken=jp.nextToken();
    while (jsonToken != JsonToken.END_OBJECT && jsonToken != null) {
      String fieldName=jp.getCurrentName();
      if (DirectMemoryConstants.KEY_FIELD_NAME.equals(fieldName)) {
        rq.setKey(jp.getText());
      }
      if (DirectMemoryConstants.PUT_FIELD_NAME.equals(fieldName)) {
        rq.setUpdate(jp.getValueAsBoolean());
      }
      if (DirectMemoryConstants.EXPIRES_IN_FIELD_NAME.equals(fieldName)) {
        rq.setExpiresIn(jp.getValueAsInt());
      }
      if (DirectMemoryConstants.CACHE_CONTENT_FIELD_NAME.equals(fieldName)) {
        jp.nextToken();
        rq.setCacheContent(jp.getBinaryValue());
      }
      jsonToken=jp.nextToken();
    }
    jp.close();
    return rq;
  }
 catch (  JsonParseException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
catch (  IOException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
}
 

Example 14

From project distributed_loadgen, under directory /src/com/couchbase/loadgen/.

Source file: Config.java

  21 
vote

public void setConfig(String configjson){
  JsonFactory factory=new JsonFactory();
  try {
    JsonParser p=factory.createJsonParser(configjson.getBytes());
    p.nextToken();
    p.nextToken();
    if (p.getCurrentName().equals(PROPERTIES_JSON_ID)) {
      p.nextToken();
      while (p.nextToken() != JsonToken.END_OBJECT) {
        String key=p.getCurrentName();
        JsonToken token=p.nextToken();
        if (token == JsonToken.VALUE_NUMBER_INT && properties.get(key) instanceof Integer) {
          properties.put(key,new Integer(p.getIntValue()));
        }
 else         if (token == JsonToken.VALUE_NUMBER_FLOAT && properties.get(key) instanceof Double) {
          properties.put(key,new Double(p.getDoubleValue()));
        }
 else         if ((token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) && properties.get(key) instanceof Boolean) {
          properties.put(key,new Boolean(p.getBooleanValue()));
        }
 else         if (token == JsonToken.VALUE_STRING && properties.get(key) instanceof String) {
          properties.put(key,p.getText());
        }
 else {
          LOG.error("Field for " + key + " did not match type");
        }
      }
    }
 else {
      LOG.error("Attempted to set an invalid config");
    }
  }
 catch (  JsonParseException e) {
    LOG.error("Attempted to set an invalid config");
  }
catch (  IOException e) {
    LOG.error("Attempted to set an invalid config");
  }
}
 

Example 15

From project dynjs, under directory /src/main/java/org/dynjs/runtime/builtins/types/json/.

Source file: Parse.java

  21 
vote

@Override public Object call(ExecutionContext context,Object self,Object... args){
  String jsonText=Types.toString(context,args[0]);
  JsonFactory factory=new JsonFactory();
  Object unfiltered=null;
  try {
    JsonParser parser=factory.createJsonParser(jsonText);
    parser.nextToken();
    unfiltered=parse(context,parser);
  }
 catch (  IOException e) {
    JSObject error=context.createSyntaxError(e.getMessage());
    throw new ThrowException(context,error);
  }
  Object reviver=args[1];
  if (!Types.isCallable(reviver)) {
    return unfiltered;
  }
  JSObject root=BuiltinObject.newObject(context);
  root.put(context,"",unfiltered,false);
  return walk(context,(JSFunction)reviver,root,"");
}
 

Example 16

From project elw, under directory /datapath-gui/src/main/java/elw/dp/app/.

Source file: RunnableLoadTask.java

  21 
vote

protected static ResponseList readRespList(InputStream is) throws IOException {
  JsonFactory jf=new JsonFactory();
  JsonParser jp=jf.createJsonParser(is);
  ResponseList response=new ResponseList();
  if (jp.nextToken() != JsonToken.START_OBJECT) {
    throw new IllegalStateException("expecting start object");
  }
  while (jp.nextToken() != JsonToken.END_OBJECT) {
    String fieldname=jp.getCurrentName();
    jp.nextToken();
    if ("success".equals(fieldname)) {
      response.setSuccess(Boolean.parseBoolean(jp.getText()));
    }
    if ("message".equals(fieldname)) {
      response.setMessage(jp.getText());
    }
    if ("data".equals(fieldname)) {
      final Map<String,Map<String,String[]>> dataMap=new TreeMap<String,Map<String,String[]>>();
      while (jp.nextToken() != JsonToken.END_OBJECT) {
        String dataKeySlot=jp.getCurrentName();
        jp.nextToken();
        final Map<String,String[]> scopeToIdList=new TreeMap<String,String[]>();
        while (jp.nextToken() != JsonToken.END_OBJECT) {
          String dataKeyScope=jp.getCurrentName();
          jp.nextToken();
          List<String> idList=new ArrayList<String>();
          while (jp.nextToken() != JsonToken.END_ARRAY) {
            idList.add(jp.getText());
          }
          scopeToIdList.put(dataKeyScope,idList.toArray(new String[idList.size()]));
        }
        dataMap.put(dataKeySlot,scopeToIdList);
      }
      response.setData(dataMap);
    }
  }
  return response;
}
 

Example 17

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

Source file: FirewallResource.java

  21 
vote

/** 
 * Extracts subnet mask from a JSON string
 * @param fmJson The JSON formatted string
 * @return The subnet mask
 * @throws IOException If there was an error parsing the JSON
 */
public static String jsonExtractSubnetMask(String fmJson) throws IOException {
  String subnet_mask="";
  MappingJsonFactory f=new MappingJsonFactory();
  JsonParser jp;
  try {
    jp=f.createJsonParser(fmJson);
  }
 catch (  JsonParseException e) {
    throw new IOException(e);
  }
  jp.nextToken();
  if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
    throw new IOException("Expected START_OBJECT");
  }
  while (jp.nextToken() != JsonToken.END_OBJECT) {
    if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
      throw new IOException("Expected FIELD_NAME");
    }
    String n=jp.getCurrentName();
    jp.nextToken();
    if (jp.getText().equals(""))     continue;
    if (n == "subnet-mask") {
      subnet_mask=jp.getText();
      break;
    }
  }
  return subnet_mask;
}
 

Example 18

From project grouperfish, under directory /service/src/main/java/com/mozilla/grouperfish/base/json/.

Source file: JsonValidator.java

  21 
vote

public boolean isValid(String json) throws IOException {
  if (json.length() == 0) {
    return false;
  }
  try {
    JsonParser parser=jsonFactory.createJsonParser(json);
    while (parser.nextToken() != null) {
    }
  }
 catch (  JsonParseException e) {
    log.error("Error parsing JSON",e);
    return false;
  }
  return true;
}
 

Example 19

From project hcatalog, under directory /src/java/org/apache/hcatalog/data/.

Source file: JsonSerDe.java

  21 
vote

/** 
 * Takes JSON string in Text form, and has to return an object representation above it that's readable by the corresponding object inspector. For this implementation, since we're using the jackson parser, we can construct our own object implementation, and we use HCatRecord for it
 */
@Override public Object deserialize(Writable blob) throws SerDeException {
  Text t=(Text)blob;
  JsonParser p;
  List<Object> r=new ArrayList<Object>(Collections.nCopies(columnNames.size(),null));
  try {
    p=jsonFactory.createJsonParser(new ByteArrayInputStream((t.getBytes())));
    if (p.nextToken() != JsonToken.START_OBJECT) {
      throw new IOException("Start token not found where expected");
    }
    JsonToken token;
    while (((token=p.nextToken()) != JsonToken.END_OBJECT) && (token != null)) {
      populateRecord(r,token,p,schema);
    }
  }
 catch (  JsonParseException e) {
    LOG.warn("Error [{}] parsing json text [{}].",e,t);
    LOG.debug(null,e);
    throw new SerDeException(e);
  }
catch (  IOException e) {
    LOG.warn("Error [{}] parsing json text [{}].",e,t);
    LOG.debug(null,e);
    throw new SerDeException(e);
  }
  return new DefaultHCatRecord(r);
}
 

Example 20

From project ohmageServer, under directory /src/org/ohmage/request/observer/.

Source file: StreamUploadRequest.java

  21 
vote

/** 
 * Creates a stream upload request from the set of parameters.
 * @param httpRequest The HTTP request.
 * @param observerId The observer's ID.
 * @param observerVersion The observer's version.
 * @param data The data to be uploaded.
 * @throws InvalidRequestException Thrown if the parameters cannot be parsed.
 * @throws IOException There was an error reading from the request.
 */
public StreamUploadRequest(final HttpServletRequest httpRequest,final Map<String,String[]> parameters,final String observerId,final long observerVersion,final String data) throws IOException, InvalidRequestException {
  super(httpRequest,false,TokenLocation.PARAMETER,parameters);
  String tObserverId=null;
  Long tObserverVersion=null;
  JsonParser tData=null;
  if (!isFailed()) {
    LOGGER.info("Creating a stream upload request.");
    if (observerId == null) {
      setFailed(ErrorCode.OBSERVER_INVALID_ID,"The observer ID is missing.");
    }
    if (data == null) {
      setFailed(ErrorCode.OBSERVER_INVALID_STREAM_DATA,"The data is missing.");
    }
    try {
      tObserverId=ObserverValidators.validateObserverId(observerId);
      tObserverVersion=observerVersion;
      tData=ObserverValidators.validateData(data);
    }
 catch (    ValidationException e) {
      e.failRequest(this);
      e.logException(LOGGER);
    }
  }
  this.observerId=tObserverId;
  this.observerVersion=tObserverVersion;
  this.data=tData;
}
 

Example 21

From project org.ops4j.pax.url, under directory /pax-url-assembly/src/main/java/org/ops4j/pax/url/assembly/internal/.

Source file: AssemblyDescriptorParser.java

  21 
vote

/** 
 * Reads descriptor file.
 * @param url descriptor file url
 * @throws IOException - If a problem encountered while parsing descriptor file
 */
private void parseDescriptor(final URL url) throws IOException {
  final JsonFactory jFactory=new JsonFactory();
  jFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);
  final JsonParser jp=jFactory.createJsonParser(url);
  if (jp.nextToken() != JsonToken.START_OBJECT) {
    throw new IOException(String.format("Descriptor [%s] not in JSON format",url.toExternalForm()));
  }
  final Collection<Source> sources=new HashSet<Source>();
  try {
    while (jp.nextToken() != JsonToken.END_OBJECT) {
      final String currentName=jp.getCurrentName();
      jp.nextToken();
      if ("manifest".equals(currentName)) {
        m_manifest=jp.getText();
      }
 else       if ("assembly".equals(currentName)) {
        sources.addAll(parseAssembly(jp));
      }
 else       if ("mergePolicy".equals(currentName)) {
        m_mergePolicy="last".equalsIgnoreCase(jp.getText()) ? MergePolicy.LAST : MergePolicy.FIRST;
      }
    }
  }
  finally {
    jp.close();
  }
  m_sources=sources.toArray(new Source[sources.size()]);
}
 

Example 22

From project platform_3, under directory /jaxrs/src/main/java/com/proofpoint/jaxrs/.

Source file: JsonMapper.java

  21 
vote

public Object readFrom(Class<Object> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,String> httpHeaders,InputStream inputStream) throws IOException {
  Object object;
  try {
    JsonParser jsonParser=objectMapper.getJsonFactory().createJsonParser(inputStream);
    jsonParser.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
    object=objectMapper.readValue(jsonParser,TypeFactory.type(genericType));
  }
 catch (  Exception e) {
    if (e instanceof IOException && !(e instanceof JsonProcessingException) && !(e instanceof EOFException)) {
      throw (IOException)e;
    }
    log.debug(e,"Invalid json for Java type %s",type);
    throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid json for Java type " + type).build());
  }
  Set<ConstraintViolation<Object>> violations=VALIDATOR.validate(object);
  if (!violations.isEmpty()) {
    throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(messagesFor(violations)).build());
  }
  return object;
}
 

Example 23

From project programmingpig, under directory /udfs/java/com/acme/io/.

Source file: JsonLoader.java

  21 
vote

/** 
 * Retrieves the next tuple to be processed. Implementations should NOT reuse tuple objects (or inner member objects) they return across calls and should return a different tuple object in each call.
 * @return the next tuple to be processed or null if there are no moretuples to be processed.
 * @throws IOException if there is an exception while retrieving the nexttuple
 */
public Tuple getNext() throws IOException {
  Text val=null;
  try {
    if (!reader.nextKeyValue())     return null;
    val=(Text)reader.getCurrentValue();
  }
 catch (  InterruptedException ie) {
    throw new IOException(ie);
  }
  ByteArrayInputStream bais=new ByteArrayInputStream(val.getBytes());
  JsonParser p=jsonFactory.createJsonParser(bais);
  Tuple t=tupleFactory.newTuple(fields.length);
  if (p.nextToken() != JsonToken.START_OBJECT) {
    log.warn("Bad record, could not find start of record " + val.toString());
    return t;
  }
  for (int i=0; i < fields.length; i++) {
    t.set(i,readField(p,fields[i],i));
  }
  if (p.nextToken() != JsonToken.END_OBJECT) {
    log.warn("Bad record, could not find end of record " + val.toString());
    return t;
  }
  p.close();
  return t;
}
 

Example 24

From project RecordBreaker, under directory /src/java/com/cloudera/recordbreaker/fisheye/.

Source file: SchemaPage.java

  21 
vote

static List<List<JsonNode>> getSchemaDigest(String s) throws IOException {
  List<List<JsonNode>> listOfSchemaElts=new ArrayList<List<JsonNode>>();
  JsonParser parser=factory.createJsonParser(s);
  try {
    JsonNode root=parser.readValueAsTree();
    if (!root.isArray()) {
      JsonNode fieldSet=root.get("fields");
      if (fieldSet.isArray() && fieldSet.get(0).get("name").toString().equals("\"row\"")) {
        fieldSet=fieldSet.get(0).get("type").get(0).get("fields");
      }
      List<JsonNode> curListOfSchemaElts=new ArrayList<JsonNode>();
      listOfSchemaElts.add(curListOfSchemaElts);
      for (Iterator<JsonNode> it=fieldSet.getElements(); it.hasNext(); ) {
        curListOfSchemaElts.add(it.next());
      }
    }
 else {
      for (int i=0; i < root.size(); i++) {
        List<JsonNode> curListOfSchemaElts=new ArrayList<JsonNode>();
        JsonNode fieldSet=root.get(i).get("fields");
        listOfSchemaElts.add(curListOfSchemaElts);
        for (Iterator<JsonNode> it=fieldSet.getElements(); it.hasNext(); ) {
          curListOfSchemaElts.add(it.next());
        }
      }
    }
  }
  finally {
    parser.close();
  }
  return listOfSchemaElts;
}
 

Example 25

From project reddit-is-fun, under directory /src/com/andrewshu/android/reddit/mail/.

Source file: PeekEnvelopeTask.java

  21 
vote

/** 
 * Gets the author, title, body of the first inbox entry.
 */
private Integer processInboxJSON(InputStream in) throws IOException, JsonParseException, IllegalStateException {
  String genericListingError="Not a valid listing";
  Integer count=0;
  JsonParser jp=jsonFactory.createJsonParser(in);
  if (jp.nextToken() != JsonToken.START_OBJECT) {
    Log.w(TAG,"Non-JSON-object in inbox (not logged in?)");
    return 0;
  }
  while (!Constants.JSON_CHILDREN.equals(jp.getCurrentName())) {
    jp.nextToken();
  }
  jp.nextToken();
  if (jp.getCurrentToken() != JsonToken.START_ARRAY)   throw new IllegalStateException(genericListingError);
  while (jp.nextToken() != JsonToken.END_ARRAY) {
    if (JsonToken.FIELD_NAME != jp.getCurrentToken())     continue;
    String namefield=jp.getCurrentName();
    jp.nextToken();
    if (Constants.JSON_NEW.equals(namefield)) {
      if ("true".equals(jp.getText()))       count++;
 else       break;
    }
  }
  return count;
}
 

Example 26

From project Shopify4J, under directory /ShopifyAPI/src/com/shopify/api/resources/json/.

Source file: ShopifyResponseReader.java

  21 
vote

public <T extends ShopifyResource>List<T> read(Reader response,Class<T> type){
  ArrayList<T> resources=new ArrayList<T>();
  try {
    JsonParser parser=factory.createJsonParser(response);
    JsonToken token=parser.nextToken();
    assert(token == JsonToken.START_OBJECT);
    while ((token=parser.nextToken()) != null) {
      if (token == JsonToken.END_OBJECT)       break;
      token=parser.nextToken();
      if (token == JsonToken.START_ARRAY) {
        while ((token=parser.nextToken()) != JsonToken.END_ARRAY) {
          resources.add(mapper.readValue(parser,type));
        }
        break;
      }
 else       if (token == JsonToken.START_OBJECT) {
        resources.add(mapper.readValue(parser,type));
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return resources;
}
 

Example 27

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

Source file: AlbumMixin.java

  19 
vote

@Override public Type deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  try {
    return Type.valueOf(jp.getText().toUpperCase());
  }
 catch (  IllegalArgumentException e) {
    return Type.UNKNOWN;
  }
}
 

Example 28

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

Source file: CompanyMixin.java

  19 
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 29

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

Source file: LocalTrendsDeserializer.java

  19 
vote

@Override public LocalTrendsHolder deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  JsonNode tree=jp.readValueAsTree();
  Iterator<JsonNode> dayIt=tree.iterator();
  if (dayIt.hasNext()) {
    JsonNode day=dayIt.next();
    Date createdAt=toDate(day.get("created_at").asText());
    JsonNode trendNodes=day.get("trends");
    List<Trend> trends=new ArrayList<Trend>();
    for (Iterator<JsonNode> trendsIt=trendNodes.iterator(); trendsIt.hasNext(); ) {
      JsonNode trendNode=trendsIt.next();
      trends.add(new Trend(trendNode.get("name").asText(),trendNode.get("query").getTextValue()));
    }
    jp.skipChildren();
    return new LocalTrendsHolder(new Trends(createdAt,trends));
  }
  throw ctxt.mappingException(LocalTrendsHolder.class);
}
 

Example 30

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

Source file: JodaLocalDateDeserializer.java

  19 
vote

@Override public Date deserialize(JsonParser jsonParser,DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
  int[] jodaDate=jsonParser.readValueAs(int[].class);
  Calendar calendar=Calendar.getInstance();
  calendar.set(jodaDate[0],jodaDate[1] - 1,jodaDate[2]);
  return calendar.getTime();
}
 

Example 31

From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.

Source file: JacksonCustomSerializationTest.java

  19 
vote

@Override public Object deserialize(JsonParser jsonParser,DeserializationContext context) throws IOException, JsonProcessingException {
  Object object=super.deserialize(jsonParser,context);
  if (object instanceof Map) {
    Map<String,Object> map=(Map<String,Object>)object;
    if (Data.class.getName().equals(map.get("class")))     return new Data((String)map.get("content"));
  }
  return object;
}
 

Example 32

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

Source file: MapEntryModule.java

  19 
vote

@Override public Entry<?,?> deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException {
  DeserializerProvider provider=ctxt.getDeserializerProvider();
  JsonDeserializer<Object> deserK=provider.findValueDeserializer(ctxt.getConfig(),type.containedType(0),property);
  JsonDeserializer<Object> deserV=provider.findValueDeserializer(ctxt.getConfig(),type.containedType(1),property);
  Object k=null, v=null;
  if (!(jp.hasCurrentToken() && jp.getCurrentToken() == JsonToken.START_OBJECT)) {
    expect(jp.nextToken(),JsonToken.START_OBJECT,jp,ctxt);
  }
  while (true) {
    JsonToken nextToken=jp.nextToken();
    if (nextToken == JsonToken.END_OBJECT) {
      break;
    }
    expect(nextToken,JsonToken.FIELD_NAME,jp,ctxt);
    jp.nextToken();
    if ("key".equals(jp.getCurrentName())) {
      k=deserK.deserialize(jp,ctxt);
    }
 else     if ("value".equals(jp.getCurrentName())) {
      v=deserV.deserialize(jp,ctxt);
    }
 else {
      throw ctxt.unknownFieldException(Map.Entry.class,jp.getCurrentName());
    }
  }
  return Maps.immutableEntry(k,v);
}
 

Example 33

From project fairy, under directory /fairy-core/src/main/java/com/mewmew/fairy/v1/json/.

Source file: JsonArrayIterator.java

  19 
vote

public JsonArrayIterator(JsonParser parser,Class<T> clazz) throws IOException {
  this.parser=parser;
  this.clazz=clazz;
  while (parser.getCurrentToken() != JsonToken.START_ARRAY && parser.nextToken() != JsonToken.END_OBJECT)   ;
  parser.nextToken();
  next();
}
 

Example 34

From project gedcomx, under directory /gedcomx-model/src/main/java/org/gedcomx/common/.

Source file: ResourceReference.java

  19 
vote

@Override public ResourceReference deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException {
  String text=jp.getText();
  if (text == null) {
    return null;
  }
 else {
    return new ResourceReference(URI.create(text));
  }
}
 

Example 35

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

Source file: AbstractJsonDeserializer.java

  19 
vote

@Override public T deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException {
  Map<String,Object> originalParams=(Map<String,Object>)inputParams.get();
  try {
    Map<String,Object> newValue=(Map<String,Object>)jp.readValueAs(Object.class);
    inputParams.set(newValue);
  }
 catch (  ClassCastException exc) {
    throw new IOException("Expected a JSON Object, but this was not the case. ",exc);
  }
  T answer=deserialize(jp);
  inputParams.set(originalParams);
  return answer;
}
 

Example 36

From project GoFleetLSServer, under directory /osrm-connector/src/main/java/org/emergya/osrm/.

Source file: OSRM.java

  19 
vote

private List<JAXBElement<?>> decodeRouteGeometry(List<JAXBElement<?>> list,CoordinateReferenceSystem targetCRS,CoordinateReferenceSystem sourceCRS,JsonParser jp) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException, TransformException, JsonParseException, IOException {
  MathTransform transform=null;
  LOG.trace(targetCRS.toWKT());
  LOG.trace(sourceCRS.toWKT());
  jp.nextToken();
  while (jp.nextToken() == JsonToken.START_ARRAY && jp.getCurrentToken() != null) {
    jp.nextToken();
    Double lat=jp.getDoubleValue();
    jp.nextToken();
    Double lon=jp.getDoubleValue();
    jp.nextToken();
    Coordinate coord=new Coordinate(lat,lon);
    Point sourceGeometry=gf.createPoint(coord);
    LOG.trace(sourceGeometry);
    if (sourceCRS != targetCRS) {
      if (transform == null)       transform=CRS.findMathTransform(sourceCRS,targetCRS);
      sourceGeometry=JTS.transform(sourceGeometry,transform).getCentroid();
      LOG.trace(sourceGeometry);
    }
    DirectPositionListType e=new DirectPositionListType();
    e.getValue().add(sourceGeometry.getY());
    e.getValue().add(sourceGeometry.getX());
    JAXBElement<DirectPositionListType> elem=new JAXBElement<DirectPositionListType>(new QName("http://www.opengis.net/gml","pos","gml"),DirectPositionListType.class,e);
    list.add(elem);
  }
  return list;
}
 

Example 37

From project greenhouse, under directory /src/main/java/com/springsource/greenhouse/signup/.

Source file: SignupFormDeserializers.java

  19 
vote

@Override public List<Integer> deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  JsonNode tree=jp.readValueAsTree();
  List<Integer> fields=new ArrayList<Integer>();
  fields.add(tree.get("month").getIntValue());
  fields.add(tree.get("day").getIntValue());
  fields.add(tree.get("year").getIntValue());
  return fields;
}
 

Example 38

From project koshinuke.java, under directory /src/java/org/koshinuke/jackson/.

Source file: ObjectIdDeserializer.java

  19 
vote

@Override public ObjectId deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  String value=jp.getText();
  if (StringUtils.isEmptyOrNull(value) == false && value.length() == Constants.OBJECT_ID_STRING_LENGTH) {
    return ObjectId.fromString(value);
  }
  return ObjectId.zeroId();
}
 

Example 39

From project meteo, under directory /core/src/main/java/com/ning/metrics/meteo/subscribers/.

Source file: TopicListener.java

  19 
vote

public TopicListener(String esperTopicKey,EPServiceProvider esperSink){
  this.esperTopicKey=esperTopicKey;
  this.esperSink=esperSink;
  mapper=new ObjectMapper();
  mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
}
 

Example 40

From project mongo-jackson-mapper, under directory /src/main/java/net/vz/mongodb/jackson/internal/.

Source file: CalendarDeserializer.java

  19 
vote

@Override public Calendar deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException {
  JsonToken token=jp.getCurrentToken();
  Date date;
  if (token == JsonToken.VALUE_EMBEDDED_OBJECT) {
    Object object=jp.getEmbeddedObject();
    if (object instanceof Date) {
      date=(Date)object;
    }
 else {
      throw ctxt.mappingException(Calendar.class);
    }
  }
 else {
    date=_parseDate(jp,ctxt);
  }
  if (date == null) {
    return null;
  }
  return ctxt.constructCalendar(date);
}
 

Example 41

From project netty-socketio, under directory /src/main/java/com/corundumstudio/socketio/parser/.

Source file: JacksonJsonSupport.java

  19 
vote

@Override public JsonObject deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  ObjectMapper mapper=(ObjectMapper)jp.getCodec();
  JsonNode rootNode=mapper.readTree(jp);
  if (!rootNode.isObject()) {
    return null;
  }
  Object val=readObject(mapper,rootNode);
  return new JsonObject(val);
}
 

Example 42

From project pangool, under directory /core/src/main/java/com/datasalt/pangool/tuplemr/.

Source file: TupleMRConfig.java

  19 
vote

private static TupleMRConfig parse(JsonParser parser) throws IOException {
  try {
    return parse(MAPPER.readTree(parser));
  }
 catch (  JsonParseException e) {
    throw new IOException(e);
  }
}
 

Example 43

From project repose, under directory /project-set/core/core-lib/src/main/java/com/rackspace/papi/httpx/processor/json/.

Source file: JsonxStreamProcessor.java

  19 
vote

private void outputItem(JsonParser jp,ContentHandler handler) throws IOException, SAXException {
  JsonToken token=jp.getCurrentToken();
  String fieldName=jp.getCurrentName();
  if (token.isScalarValue()) {
    if (token.isNumeric()) {
      ElementFactory.getScalarElement(token.name(),fieldName,jp.getNumberValue()).outputElement(handler);
    }
 else {
      ElementFactory.getScalarElement(token.name(),fieldName,jp.getText()).outputElement(handler);
    }
  }
 else {
    Element element=ElementFactory.getElement(token.name(),fieldName);
    if (element != null) {
      element.outputElement(handler);
    }
  }
}
 

Example 44

From project riak-java-client, under directory /src/main/java/com/basho/riak/client/query/.

Source file: NodeStats.java

  19 
vote

@Override public BigInteger deserialize(JsonParser jp,DeserializationContext dc) throws IOException, JsonProcessingException {
  if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
    return BigInteger.valueOf(0L);
  }
 else   return BigInteger.valueOf(jp.getLongValue());
}
 

Example 45

From project seyren, under directory /seyren-core/src/main/java/com/seyren/core/util/datetime/.

Source file: LocalTimeDeserializer.java

  19 
vote

@Override public LocalTime deserialize(JsonParser parser,DeserializationContext context) throws IOException, JsonProcessingException {
  String raw=parser.getText();
  if (raw == null || raw.length() != 4) {
    return null;
  }
  int hours=Integer.valueOf(raw.substring(0,2));
  int mins=Integer.valueOf(raw.substring(2));
  return new LocalTime(hours,mins);
}
 

Example 46

From project sitebricks, under directory /sitebricks-client/src/main/java/com/google/sitebricks/client/transport/.

Source file: JacksonJsonTransportWithConverters.java

  19 
vote

public Object deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  Object source=getSourceObject(jp,ctxt);
  for (  ConverterDirection converterDirection : converterDirections) {
    Type sourceType=converterDirection.forward ? StandardTypeConverter.sourceType(converterDirection.converter) : StandardTypeConverter.targetType(converterDirection.converter);
    Class<?> converterSourceClass=Generics.erase(sourceType);
    if (converterSourceClass.isAssignableFrom(source.getClass())) {
      return converterDirection.forward ? StandardTypeConverter.typeSafeTo(converterDirection.converter,source) : StandardTypeConverter.typeSafeFrom(converterDirection.converter,source);
    }
  }
  throw new IllegalStateException("Cannot convert from " + source);
}
 

Example 47

From project social_1, under directory /services/facebook/src/main/java/org/jboss/seam/social/facebook/model/jackson/.

Source file: AlbumMixin.java

  19 
vote

@Override public Type deserialize(JsonParser jp,DeserializationContext ctxt) throws IOException, JsonProcessingException {
  try {
    return Type.valueOf(jp.getText().toUpperCase());
  }
 catch (  IllegalArgumentException e) {
    return Type.UNKNOWN;
  }
}