Example #1
0
  private void parseItemIdList(Reader in, IItemIdListHandler handler)
      throws JsonParseException, IOException, RemoteException {
    JsonFactory f = new JsonFactory();
    JsonParser jp = f.createParser(in);

    String currName;

    List<String> idList = new ArrayList<String>();

    jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
    while (jp.nextToken() != JsonToken.END_OBJECT) {
      currName = jp.getCurrentName();
      jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY
      if (currName.equals("itemRefs")) { // contains an object
        // start items
        while (jp.nextToken() != JsonToken.END_ARRAY) {
          currName = jp.getCurrentName();
          if (currName == null) continue;
          jp.nextToken();
          if (currName.equals("id")) {
            idList.add(Utils.dec2Hex(jp.getText())); // convert dec to hex
          } else {
            jp.skipChildren();
          }
        }

        handler.items(idList);

      } else {
        jp.skipChildren();
      }
    }
  }
 private void expectObjectField(JsonParser parser, String name) throws IOException {
   expect(parser, JsonToken.FIELD_NAME);
   if (!parser.getCurrentName().equals(name)) {
     throw new RuntimeException("expected field " + name + ", got " + parser.getCurrentName());
   }
   expect(parser, JsonToken.START_OBJECT);
   while (parser.nextToken() != JsonToken.END_OBJECT) {
     // empty
   }
 }
Example #3
0
  private void parseTagList(Reader in, ITagListHandler handler)
      throws JsonParseException, IOException, RemoteException {
    JsonFactory f = new JsonFactory();
    JsonParser jp = f.createParser(in);

    String currName;

    ITag tag = null;
    List<ITag> tagList = new ArrayList<ITag>();

    jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
    while (jp.nextToken() != JsonToken.END_OBJECT) {
      currName = jp.getCurrentName();
      jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY
      if (currName.equals("tags")) { // contains an object
        // start items
        while (jp.nextToken() != JsonToken.END_ARRAY) {
          if (jp.getCurrentToken() == JsonToken.START_OBJECT) {
            tag = new ITag();
          } else if (jp.getCurrentToken() == JsonToken.END_OBJECT) {
            tagList.add(tag);
            tag = null;
          }

          currName = jp.getCurrentName();
          if (currName == null) continue;
          jp.nextToken();
          if (currName.equals("id")) {
            tag.uid = jp.getText();
            int i = tag.uid.indexOf("/label/");
            if (i != -1) {
              tag.label = tag.uid.substring(i + "/label/".length());
              // NOTE: @see ReaderManager#updateTagTypes
              tag.type = ITag.TYPE_TAG_LABEL;
            } else if (tag.uid.endsWith("state/com.google/starred")) {
              tag.label = "state/com.google/starred";
              tag.type = ITag.TYPE_TAG_STARRED;
            }
          } else if (currName.equals("sortid")) {
            tag.sortid = jp.getText();
          } else {
            jp.skipChildren();
          }
        }

        handler.tags(tagList);

      } else {
        jp.skipChildren();
      }
    }
  }
Example #4
0
  private Map<String, Long> parseUnreadCountList(Reader in) throws JsonParseException, IOException {
    JsonFactory f = new JsonFactory();
    JsonParser jp = f.createParser(in);

    String currName;

    String uid = null;
    Long timestamp = null;
    int len;
    String text = null;
    Map<String, Long> unreadList = new HashMap<String, Long>();

    jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
    while (jp.nextToken() != JsonToken.END_OBJECT) {
      currName = jp.getCurrentName();
      jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY
      if (currName.equals("unreadcounts")) { // contains an object
        // start items
        while (jp.nextToken() != JsonToken.END_ARRAY) {
          if (jp.getCurrentToken() == JsonToken.START_OBJECT) {
            // do nothing
          } else if (jp.getCurrentToken() == JsonToken.END_OBJECT) {
            if (!unreadList.containsKey(uid)) unreadList.put(uid, timestamp);
          }

          currName = jp.getCurrentName();
          if (currName == null) continue;

          jp.nextToken();
          if (currName.equals("id")) {
            uid = jp.getText();
          } else if (currName.equals("newestItemTimestampUsec")) {
            text = jp.getText();
            len = text.length();
            if (len > 13) text = jp.getText().substring(0, jp.getText().length() - 6);
            else if (len > 10) text = jp.getText().substring(0, jp.getText().length() - 3);
            timestamp = Utils.asLong(text); // millis -> unixtime
          } else {
            jp.skipChildren();
          }
        }
      } else {
        jp.skipChildren();
      }
    }

    return unreadList;
  }
 protected ConstExprConstruct parseAnnotationConstExprConstruct(final JsonParser jp)
     throws IOException {
   final ConstExprConstruct constExpr = new ConstExprConstruct();
   constExpr.setType(ConstExprConstruct.Type.fromString(jp.getCurrentName()));
   constExpr.setValue(jp.nextTextValue());
   return constExpr;
 }
  /**
   * Constructs a configuration file from a past configuration file that was saved to the disk.
   *
   * @param fileName - the path to the file on disk
   * @throws IOException - if there is any problem reading the file
   */
  public Configuration(final String fileName) throws IOException {
    final JsonFactory jf = new JsonFactory();
    final JsonParser jp = jf.createParser(new File(fileName));
    jp.nextToken();

    while (jp.nextToken() != JsonToken.END_OBJECT) {
      final String fieldName = jp.getCurrentName();
      jp.nextToken();
      switch (fieldName) {
        case IN_FILE_KEY:
          this.inputFileName = jp.getText();
          break;
        case IN_FILE_DIR_KEY:
          this.inputFileDirName = jp.getText();
          break;
        case SPLIT_PATTERN_KEY:
          this.splitPattern = jp.getText();
          break;
        case OUT_FILE_KEY:
          this.outDirName = jp.getText();
          break;
        case EXEC_LOC_KEY:
          this.execPath = jp.getText();
          break;
        case NUM_PROCESSES_KEY:
          this.numberOfThreads = jp.getIntValue();
          break;
        case STATS_KEY:
          this.makeStats = jp.getBooleanValue();
          break;
        case NUM_HEADER_KEY:
          this.numberOfHeaderLines = jp.getIntValue();
          break;
        case DEFAULT_MERGE_KEY:
          if (jp.getBooleanValue()) {
            this.mergeMethod = 0;
          }
          break;
        case CUSTOM_MERGE_KEY:
          if (jp.getBooleanValue()) {
            this.mergeMethod = 1;
          }
          break;
        case EXTERNAL_MERGE_KEY:
          if (jp.getBooleanValue()) {
            this.mergeMethod = 2;
          }
          break;
        case ARGUMENT_KEY:
          this.argument = jp.getText();
          break;
        case OUTPUT_FMT_KEY:
          this.outputFmt = jp.getBooleanValue();
          break;
        default:
          assert (false);
      }
    }
    jp.close();
  }
 private <T> String processData(
     final CrestApiProcessor<T> processor, final CrestContainer<T> container, final String data) {
   String next = null;
   try {
     final JsonFactory parserFactory = new JsonFactory();
     final JsonParser jsonParser = parserFactory.createParser(data);
     jsonParser.nextToken();
     while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
       final String fieldname = jsonParser.getCurrentName();
       jsonParser.nextToken();
       switch (fieldname) {
         case "totalCount":
           container.setTotalCount(jsonParser.getIntValue());
           break;
         case "pageCount":
           container.setPageCount(jsonParser.getIntValue());
           break;
         case "items":
           processItems(processor, container, jsonParser);
           break;
         case "next":
           next = processNext(jsonParser);
           break;
         default:
           break;
       }
     }
   } catch (final IOException e) {
     if (LOGGER.isWarnEnabled()) {
       LOGGER.warn("Problems while parsing json data: " + e.getMessage(), e);
     }
   }
   return next;
 }
  /**
   * Method for copying contents of the current event <b>and following events that it encloses</b>
   * the given parser instance points to.
   *
   * <p>So what constitutes enclosing? Here is the list of events that have associated enclosed
   * events that will get copied:
   *
   * <ul>
   *   <li>{@link JsonToken#START_OBJECT}: all events up to and including matching (closing) {@link
   *       JsonToken#END_OBJECT} will be copied
   *   <li>{@link JsonToken#START_ARRAY} all events up to and including matching (closing) {@link
   *       JsonToken#END_ARRAY} will be copied
   *   <li>{@link JsonToken#FIELD_NAME} the logical value (which can consist of a single scalar
   *       value; or a sequence of related events for structured types (Json Arrays, Objects)) will
   *       be copied along with the name itself. So essentially the whole <b>field entry</b> (name
   *       and value) will be copied.
   * </ul>
   *
   * <p>After calling this method, parser will point to the <b>last event</b> that was copied. This
   * will either be the event parser already pointed to (if there were no enclosed events), or the
   * last enclosed event copied.
   */
  @Override
  public void copyCurrentStructure(JsonParser jp) throws IOException, JsonProcessingException {
    JsonToken t = jp.getCurrentToken();

    // Let's handle field-name separately first
    if (t == JsonToken.FIELD_NAME) {
      writeFieldName(jp.getCurrentName());
      t = jp.nextToken();
      // fall-through to copy the associated value
    }

    switch (t) {
      case START_ARRAY:
        writeStartArray();
        while (jp.nextToken() != JsonToken.END_ARRAY) {
          copyCurrentStructure(jp);
        }
        writeEndArray();
        break;
      case START_OBJECT:
        writeStartObject();
        while (jp.nextToken() != JsonToken.END_OBJECT) {
          copyCurrentStructure(jp);
        }
        writeEndObject();
        break;
      default: // others are simple:
        copyCurrentEvent(jp);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.codehaus.jackson.map.JsonDeserializer#deserialize(org.codehaus.jackson
   * .JsonParser, org.codehaus.jackson.map.DeserializationContext)
   */
  @Override
  public NamedErlangFunction deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {

    JsonToken token = jp.getCurrentToken();

    if (JsonToken.START_OBJECT.equals(token)) {

      String mod = null;
      String fun = null;

      while (!JsonToken.END_OBJECT.equals(token)) {
        String field = jp.getCurrentName();

        if (Constants.FL_SCHEMA_FUN_MOD.equals(field)) {
          jp.nextToken();
          mod = jp.getText();
        } else if (Constants.FL_SCHEMA_FUN_FUN.equals(field)) {
          jp.nextToken();
          fun = jp.getText();
        }
        token = jp.nextToken();
      }
      if (mod != null && fun != null) {
        return new NamedErlangFunction(mod, fun);
      } else {
        return null;
      }
    }
    throw ctxt.mappingException(NamedErlangFunction.class);
  }
Example #10
0
  @Override
  public void parse(T translator, JsonParser jsonParser) throws IOException {
    JsonParserWrapper wrapper = new JsonParserWrapper(jsonParser);
    wrapper.setShouldThrowExceptions(shouldThrowFieldExceptions());
    if (jsonParser.getCurrentToken() == null) {
      jsonParser.nextToken();
    }

    if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT) {
      jsonParser.skipChildren();
    } else {
      if (translator instanceof ParseStatusListener) {
        ((ParseStatusListener) translator).onPreParse();
      }

      while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = jsonParser.getCurrentName();
        jsonParser.nextToken();
        handleParse(translator, wrapper, jsonParser, key);
        jsonParser.skipChildren();
      }

      if (translator instanceof ParseStatusListener) {
        ((ParseStatusListener) translator).onParseComplete();
      }
    }
  }
  public static RoomLocationReturn fromServerJson(JsonParser p)
      throws JsonParseException, IOException {

    RoomLocationReturn ret = new RoomLocationReturn();

    RoomLocationEntry entry = new RoomLocationEntry();

    while (p.nextToken() != JsonToken.END_OBJECT) {

      String fieldName = p.getCurrentName();
      if (KEY_BUILDING.equals(fieldName)) {
        p.nextToken();
        entry.setBuildingName(p.getText());
      } else if (KEY_ROOM.equals(fieldName)) {
        p.nextToken();
        entry.setRoomName(p.getText());
      } else if (KEY_LATITUDE.equals(fieldName)) {
        p.nextToken();
        entry.setLatitude(p.getDoubleValue());
      } else if (KEY_LONGITUDE.equals(fieldName)) {
        p.nextToken();
        entry.setLongitude(p.getDoubleValue());
      } else if (KEY_RATING.equals(fieldName)) {
        p.nextToken();
        // We assume that rating <--> productivity (they are interchangeable)
        entry.setProductivity(p.getDoubleValue());
      } else if (KEY_CAPACITY.equals(fieldName)) {
        p.nextToken();
        entry.setCapacity(p.getDoubleValue());
      } else if (KEY_CROWD.equals(fieldName)) {
        p.nextToken();
        entry.setAglCrowd(p.getDoubleValue());
      } else if (KEY_NUM_SURVEYS.equals(fieldName)) {
        p.nextToken();
        entry.setAglSurveys(p.getIntValue());

      } else if (KEY_INTERPOLATED.equals(fieldName)) {
        p.nextToken(); // take the "[" token
        List<NoiseEntry> noises = new ArrayList<NoiseEntry>();
        while (p.nextToken() != JsonToken.END_ARRAY) {
          noises.add(NoiseEntry.fromServerJson(p, entry));
        }
        ret.noises = noises;
      } else if (KEY_COMMENTS.equals(fieldName)) {
        p.nextToken(); // take the "[" token
        List<CommentEntry> comments = new ArrayList<CommentEntry>();
        while (p.nextToken() != JsonToken.END_ARRAY) {
          comments.add(CommentEntry.fromServerJson(p, entry));
        }
        ret.comments = comments;
      }
    }
    entry.setLocal(false);

    ret.entry = entry;

    return ret;
  }
 /** Sends a POST request to obtain an access token. */
 private void obtainAccessToken() {
   try {
     token = new OAuth2Token();
     error = new OAuth2Error();
     /* build the request and send it to the token server */
     CloseableHttpClient client = HttpClients.createDefault();
     HttpPost request = new HttpPost(tokenServer);
     request.setEntity(new UrlEncodedFormEntity(Utils.mapToList(tokenParams)));
     CloseableHttpResponse response = client.execute(request);
     HttpEntity entity = response.getEntity();
     /* get the response and parse it */
     JsonParser jp = json.getFactory().createParser(entity.getContent());
     while (jp.nextToken() != null) {
       JsonToken jsonToken = jp.getCurrentToken();
       switch (jsonToken) {
         case FIELD_NAME:
           String name = jp.getCurrentName();
           jsonToken = jp.nextToken();
           if (name.equals("access_token")) {
             token.setAccessToken(jp.getValueAsString());
           } else if (name.equals("token_type")) {
             token.setType(OAuth2TokenType.valueOf(jp.getValueAsString().toUpperCase()));
           } else if (name.equals("expires_in")) {
             token.setExpiresIn(jp.getValueAsInt());
           } else if (name.equals("refresh_token")) {
             token.setRefreshToken(jp.getValueAsString());
           } else if (name.equals("kid")) {
             token.setKeyId(jp.getValueAsString());
           } else if (name.equals("mac_key")) {
             token.setMacKey(jp.getValueAsString());
           } else if (name.equals("mac_algorithm")) {
             token.setMacAlgorithm(jp.getValueAsString());
           } else if (name.equals("error")) {
             error.setType(OAuth2ErrorType.valueOf(jp.getValueAsString().toUpperCase()));
           } else if (name.equals("error_description")) {
             error.setDescription(jp.getValueAsString());
           } else if (name.equals("error_uri")) {
             error.setUri(jp.getValueAsString());
           }
           ready = true;
           break;
         default:
           break;
       }
     }
     jp.close();
     response.close();
     client.close();
   } catch (IOException e) {
     error.setType(OAuth2ErrorType.SERVER_ERROR);
     error.setDescription("Failed to obtain access token from the server.");
   }
   /* notify all waiting objects */
   synchronized (waitObject) {
     ready = true;
     waitObject.notifyAll();
   }
 }
 private void expectScalarField(JsonParser parser, String name) throws IOException {
   expect(parser, JsonToken.FIELD_NAME);
   if (!parser.getCurrentName().equals(name)) {
     throw new RuntimeException("expected field " + name + ", got " + parser.getCurrentName());
   }
   final JsonToken t = parser.nextToken();
   switch (t) {
     case VALUE_NULL:
     case VALUE_FALSE:
     case VALUE_TRUE:
     case VALUE_NUMBER_INT:
     case VALUE_NUMBER_FLOAT:
     case VALUE_STRING:
       break;
     default:
       throw new RuntimeException("expected scalar field, got  " + t);
   }
 }
 private void reportIllegal(JsonParser parser, JsonToken expToken) throws IOException {
   JsonToken curr = parser.getCurrentToken();
   String msg = "Expected token " + expToken + "; got " + curr;
   if (curr == JsonToken.FIELD_NAME) {
     msg += " (current field name '" + parser.getCurrentName() + "')";
   }
   msg += ", location: " + parser.getTokenLocation();
   throw new IllegalStateException(msg);
 }
  @Override
  public ScimGroup deserialize(JsonParser jp, DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
    ScimGroup group = new ScimGroup();

    Map<ScimGroupMember.Role, List<ScimGroupMember>> roles =
        new HashMap<ScimGroupMember.Role, List<ScimGroupMember>>();
    for (ScimGroupMember.Role role : ScimGroupMember.Role.values()) {
      roles.put(role, new ArrayList<ScimGroupMember>());
    }
    Set<ScimGroupMember> allMembers = new HashSet<ScimGroupMember>();

    while (jp.nextToken() != JsonToken.END_OBJECT) {
      if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken();

        if ("id".equalsIgnoreCase(fieldName)) {
          group.setId(jp.readValueAs(String.class));
        } else if ("displayname".equalsIgnoreCase(fieldName)) {
          group.setDisplayName(jp.readValueAs(String.class));
        } else if ("meta".equalsIgnoreCase(fieldName)) {
          group.setMeta(jp.readValueAs(ScimMeta.class));
        } else if ("schemas".equalsIgnoreCase(fieldName)) {
          group.setSchemas(jp.readValueAs(String[].class));
        } else {
          String value = fieldName.substring(0, fieldName.length() - 1);
          ScimGroupMember.Role role;
          try {
            role = ScimGroupMember.Role.valueOf(value.toUpperCase());
          } catch (IllegalArgumentException ex) {
            role = null;
          }
          if (role != null) {
            ScimGroupMember[] members = jp.readValueAs(ScimGroupMember[].class);
            for (ScimGroupMember member : members) {
              member.setRoles(new ArrayList<ScimGroupMember.Role>());
            }
            roles.get(role).addAll(Arrays.asList(members));
            allMembers.addAll(Arrays.asList(members));
          }
        }
      }
    }

    for (ScimGroupMember member : allMembers) {
      for (ScimGroupMember.Role role : roles.keySet()) {
        if (roles.get(role).contains(member)) {
          member.getRoles().add(role);
        }
      }
    }
    group.setMembers(new ArrayList<ScimGroupMember>(allMembers));

    return group;
  }
 private String processNext(final JsonParser jsonParser) throws IOException {
   String next = null;
   jsonParser.nextToken();
   if (JsonPaths.HREF.equals(jsonParser.getCurrentName())) {
     jsonParser.nextToken();
     next = jsonParser.getText();
     jsonParser.nextToken();
   }
   return next;
 }
 private Map<String, Object> readHeaders(JsonParser parser, String jsonMessage) throws Exception {
   Map<String, Object> headers = new LinkedHashMap<String, Object>();
   while (JsonToken.END_OBJECT != parser.nextToken()) {
     String headerName = parser.getCurrentName();
     parser.nextToken();
     Object headerValue = this.readHeader(parser, headerName, jsonMessage);
     headers.put(headerName, headerValue);
   }
   return headers;
 }
  @Override
  protected ReferentialConstraintRole doDeserialize(
      final JsonParser jp, final DeserializationContext ctxt)
      throws IOException, JsonProcessingException {

    final ReferentialConstraintRole refConstRole = new ReferentialConstraintRole();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
      final JsonToken token = jp.getCurrentToken();
      if (token == JsonToken.FIELD_NAME) {
        if ("Role".equals(jp.getCurrentName())) {
          refConstRole.setRole(jp.nextTextValue());
        } else if ("PropertyRef".equals(jp.getCurrentName())) {
          jp.nextToken();
          refConstRole.getPropertyRefs().add(jp.getCodec().readValue(jp, PropertyRef.class));
        }
      }
    }

    return refConstRole;
  }
  @Override
  public EnumMap<?, ?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    // Ok: must point to START_OBJECT
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
      return _deserializeFromEmpty(jp, ctxt);
    }
    EnumMap result = constructMap();
    final JsonDeserializer<Object> valueDes = _valueDeserializer;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;

    while ((jp.nextToken()) == JsonToken.FIELD_NAME) {
      String keyName = jp.getCurrentName(); // just for error message
      // but we need to let key deserializer handle it separately, nonetheless
      Enum<?> key = (Enum<?>) _keyDeserializer.deserializeKey(keyName, ctxt);
      if (key == null) {
        if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
          throw ctxt.weirdStringException(
              keyName,
              _enumClass,
              "value not one of declared Enum instance names for " + _mapType.getKeyType());
        }
        /* 24-Mar-2012, tatu: Null won't work as a key anyway, so let's
         *  just skip the entry then. But we must skip the value as well, if so.
         */
        jp.nextToken();
        jp.skipChildren();
        continue;
      }
      // And then the value...
      JsonToken t = jp.nextToken();
      /* note: MUST check for nulls separately: deserializers will
       * not handle them (and maybe fail or return bogus data)
       */
      Object value;

      try {
        if (t == JsonToken.VALUE_NULL) {
          value = valueDes.getNullValue(ctxt);
        } else if (typeDeser == null) {
          value = valueDes.deserialize(jp, ctxt);
        } else {
          value = valueDes.deserializeWithType(jp, ctxt, typeDeser);
        }
      } catch (Exception e) {
        wrapAndThrow(e, result, keyName);
        return null;
      }
      result.put(key, value);
    }
    return result;
  }
Example #20
0
 @Override
 public UserMembershipInfo deserialize(JsonParser p, boolean collapsed)
     throws IOException, JsonParseException {
   UserMembershipInfo value;
   String tag = null;
   if (!collapsed) {
     expectStartObject(p);
     tag = readTag(p);
   }
   if (tag == null) {
     AccessLevel f_accessType = null;
     UserInfo f_user = null;
     List<MemberPermission> f_permissions = null;
     String f_initials = null;
     Boolean f_isInherited = false;
     while (p.getCurrentToken() == JsonToken.FIELD_NAME) {
       String field = p.getCurrentName();
       p.nextToken();
       if ("access_type".equals(field)) {
         f_accessType = AccessLevel.Serializer.INSTANCE.deserialize(p);
       } else if ("user".equals(field)) {
         f_user = UserInfo.Serializer.INSTANCE.deserialize(p);
       } else if ("permissions".equals(field)) {
         f_permissions =
             StoneSerializers.nullable(
                     StoneSerializers.list(MemberPermission.Serializer.INSTANCE))
                 .deserialize(p);
       } else if ("initials".equals(field)) {
         f_initials = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p);
       } else if ("is_inherited".equals(field)) {
         f_isInherited = StoneSerializers.boolean_().deserialize(p);
       } else {
         skipValue(p);
       }
     }
     if (f_accessType == null) {
       throw new JsonParseException(p, "Required field \"access_type\" missing.");
     }
     if (f_user == null) {
       throw new JsonParseException(p, "Required field \"user\" missing.");
     }
     value =
         new UserMembershipInfo(f_accessType, f_user, f_permissions, f_initials, f_isInherited);
   } else {
     throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\"");
   }
   if (!collapsed) {
     expectEndObject(p);
   }
   return value;
 }
 @Override
 public JSONObject deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   JSONObject ob = new JSONObject();
   JsonToken t = jp.getCurrentToken();
   if (t == JsonToken.START_OBJECT) {
     t = jp.nextToken();
   }
   for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
     String fieldName = jp.getCurrentName();
     t = jp.nextToken();
     try {
       switch (t) {
         case START_ARRAY:
           ob.put(fieldName, JSONArrayDeserializer.instance.deserialize(jp, ctxt));
           continue;
         case START_OBJECT:
           ob.put(fieldName, deserialize(jp, ctxt));
           continue;
         case VALUE_STRING:
           ob.put(fieldName, jp.getText());
           continue;
         case VALUE_NULL:
           ob.put(fieldName, JSONObject.NULL);
           continue;
         case VALUE_TRUE:
           ob.put(fieldName, Boolean.TRUE);
           continue;
         case VALUE_FALSE:
           ob.put(fieldName, Boolean.FALSE);
           continue;
         case VALUE_NUMBER_INT:
           ob.put(fieldName, jp.getNumberValue());
           continue;
         case VALUE_NUMBER_FLOAT:
           ob.put(fieldName, jp.getNumberValue());
           continue;
         case VALUE_EMBEDDED_OBJECT:
           ob.put(fieldName, jp.getEmbeddedObject());
           continue;
       }
     } catch (JSONException e) {
       throw ctxt.mappingException("Failed to construct JSONObject: " + e.getMessage());
     }
     throw ctxt.mappingException("Urecognized or unsupported JsonToken type: " + t);
   }
   return ob;
 }
 public static void nextExpect(JsonParser jp, String name) throws IOException {
   jp.nextToken();
   String fieldName = jp.getCurrentName();
   if (!fieldName.equals(name))
     throw new IOException(
         "Expected "
             + name
             + " element, got: "
             + fieldName
             + " "
             + jp.getCurrentLocation()
             + " tokenType: ["
             + jp.getCurrentToken()
             + "]");
   jp.nextToken();
 }
 /**
  * Parses generic object.
  *
  * @return number of elements written
  * @throws IOException
  * @throws JsonParseException
  * @throws Exception
  */
 private int parseObject() throws IOException, JsonParseException, Exception {
   int elementsWritten = 0;
   while (jsonParser.nextToken() != null && jsonParser.getCurrentToken() != END_OBJECT) {
     if (FIELD_NAME.equals(jsonParser.getCurrentToken())) {
       String elementName = jsonParser.getCurrentName();
       // jump to element value
       jsonParser.nextToken();
       parseElement(elementName);
       elementsWritten++;
     } else {
       throw new ParserException(
           "Error when parsing. Expected field name got " + jsonParser.getCurrentToken());
     }
   }
   return elementsWritten;
 }
  /** 解析prline */
  public static PRLine parseFromJson(JsonParser jp) throws IOException {
    PRLine instance = new PRLine();

    // validate that we're on the right token
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
      jp.skipChildren();
      return null;
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
      String fieldName = jp.getCurrentName();
      jp.nextToken();
      processSingleField(instance, fieldName, jp);
      jp.skipChildren();
    }

    return instance;
  }
    @Override
    public AnInterface deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
      if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new AssertionError("Expected start object.");
      }

      String name = null;

      while (jp.nextToken() != JsonToken.END_OBJECT) {
        switch (jp.getCurrentName()) {
          case "name":
            name = jp.getValueAsString();
            break;
        }
      }

      return new AnImplementation(name);
    }
  @Override
  public JsonObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonObjectBuilder builder = JsonObjectBuilder.object();

    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.START_OBJECT) {
      t = jp.nextToken();
    }
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
      String fieldName = jp.getCurrentName();
      t = jp.nextToken();

      switch (t) {
        case START_ARRAY:
          builder.put(fieldName, JsonArrayDeserializer.INSTANCE.deserialize(jp, ctxt));
          continue;
        case START_OBJECT:
          builder.put(fieldName, deserialize(jp, ctxt));
          continue;
        case VALUE_STRING:
          builder.put(fieldName, jp.getText());
          continue;
        case VALUE_NULL:
          builder.putNull(fieldName);
          continue;
        case VALUE_TRUE:
          builder.put(fieldName, Boolean.TRUE);
          continue;
        case VALUE_FALSE:
          builder.put(fieldName, Boolean.FALSE);
          continue;
        case VALUE_NUMBER_INT:
          builder.put(fieldName, jp.getNumberValue());
          continue;
        case VALUE_NUMBER_FLOAT:
          builder.put(fieldName, jp.getNumberValue());
          continue;
        default:
          throw ctxt.mappingException("Unrecognized or unsupported JsonToken type: " + t);
      }
    }

    return builder.build();
  }
Example #27
0
  @Override
  public List<Video> fetchSource(String embedPageUrl) throws OnErrorThrowable {

    String body = GeneralUtils.getWebPage(embedPageUrl);

    String elementHtml =
        Jsoup.parse(body).select("div.progress").first().nextElementSibling().html();

    String onlyJson =
        elementHtml.substring(
            elementHtml.indexOf("var vars = ") + 11, elementHtml.indexOf("var fixed_player_size"));

    List<Video> videos = new ArrayList<>(1);

    try {
      String regex = "url\\d+";
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

      JsonParser jsonParser = new JsonFactory().createParser(onlyJson);

      while (!jsonParser.isClosed()) {
        JsonToken jsonToken = jsonParser.nextToken();
        String currentName = jsonParser.getCurrentName();

        if (jsonToken != null && currentName != null) {
          Matcher matcher = pattern.matcher(currentName);

          if (matcher.find()) {
            String nextValue = jsonParser.nextTextValue();

            if (nextValue != null) {
              videos.add(new Video(currentName.substring(3) + "p", nextValue));
            }
          }
        }
      }

    } catch (IOException io) {
      throw OnErrorThrowable.from(new Throwable("Vk video retrieval failed.", io));
    }

    return videos;
  }
Example #28
0
  /**
   * @param args
   * @throws IOException
   * @throws JsonParseException
   */
  public static void main(String[] args) throws JsonParseException, IOException {

    JsonFactory jfactory = new JsonFactory();

    JsonParser jParser = jfactory.createJsonParser(new File(FILE_PATH));

    // loop until token equal to "}"
    while (jParser.nextToken() != JsonToken.END_OBJECT) {

      String fieldname = jParser.getCurrentName();
      if ("name".equals(fieldname)) {

        // current token is "name",
        // move to next, which is "name"'s value
        jParser.nextToken();
        System.out.println(jParser.getText()); // display mkyong
      }

      if ("age".equals(fieldname)) {

        // current token is "age",
        // move to next, which is "name"'s value
        jParser.nextToken();
        System.out.println(jParser.getIntValue()); // display 29
      }

      if ("messages".equals(fieldname)) {

        jParser.nextToken(); // current token is "[", move next

        // messages is array, loop until token equal to "]"
        while (jParser.nextToken() != JsonToken.END_ARRAY) {

          // display msg1, msg2, msg3
          System.out.println(jParser.getText());
        }
      }
    }
    jParser.close();
  }
 @Override
 protected Message<?> parseWithHeaders(JsonParser parser, String jsonMessage) throws Exception {
   String error = AbstractJsonInboundMessageMapper.MESSAGE_FORMAT_ERROR + jsonMessage;
   Assert.isTrue(JsonToken.START_OBJECT == parser.nextToken(), error);
   Map<String, Object> headers = null;
   Object payload = null;
   while (JsonToken.END_OBJECT != parser.nextToken()) {
     Assert.isTrue(JsonToken.FIELD_NAME == parser.getCurrentToken(), error);
     boolean isHeadersToken = "headers".equals(parser.getCurrentName());
     boolean isPayloadToken = "payload".equals(parser.getCurrentName());
     Assert.isTrue(isHeadersToken || isPayloadToken, error);
     if (isHeadersToken) {
       Assert.isTrue(parser.nextToken() == JsonToken.START_OBJECT, error);
       headers = readHeaders(parser, jsonMessage);
     } else if (isPayloadToken) {
       parser.nextToken();
       payload = this.readPayload(parser, jsonMessage);
     }
   }
   Assert.notNull(headers, error);
   return MessageBuilder.withPayload(payload).copyHeaders(headers).build();
 }
  protected MediaContent readMediaContent(JsonParser parser) throws IOException {
    MediaContent mc = new MediaContent();
    if (parser.nextToken() != JsonToken.START_OBJECT) {
      reportIllegal(parser, JsonToken.START_OBJECT);
    }
    // first fast version when field-order is as expected
    if (parser.nextFieldName(FIELD_MEDIA)) {
      mc.media = readMedia(parser);
      if (parser.nextFieldName(FIELD_IMAGES)) {
        mc.images = readImages(parser);
        parser.nextToken();
        verifyCurrent(parser, JsonToken.END_OBJECT);
        return mc;
      }
    }

    // and fallback if order was changed
    for (; parser.getCurrentToken() == JsonToken.FIELD_NAME; parser.nextToken()) {
      String field = parser.getCurrentName();
      Integer I = fullFieldToIndex.get(field);
      if (I != null) {
        switch (I) {
          case FIELD_IX_MEDIA:
            mc.media = readMedia(parser);
            continue;
          case FIELD_IX_IMAGES:
            mc.images = readImages(parser);
            continue;
        }
      }
      throw new IllegalStateException("Unexpected field '" + field + "'");
    }
    verifyCurrent(parser, JsonToken.END_OBJECT);

    if (mc.media == null) throw new IllegalStateException("Missing field: " + FIELD_MEDIA);
    if (mc.images == null) mc.images = new ArrayList<Image>();

    return mc;
  }