コード例 #1
1
  /** Unit test to check for regression of [JACKSON-18]. */
  public void testSmallNumbers() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    for (int i = -20; i <= 20; ++i) {
      JsonNode n = root.numberNode(i);
      root.add(n);
      // Hmmh. Not sure why toString() won't be triggered otherwise...
      assertEquals(String.valueOf(i), n.toString());
    }

    // Loop over 2 different serialization methods
    for (int type = 0; type < 2; ++type) {
      StringWriter sw = new StringWriter();
      if (type == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }

      String doc = sw.toString();
      JsonParser p = new JsonFactory().createParser(new StringReader(doc));

      assertEquals(JsonToken.START_ARRAY, p.nextToken());
      for (int i = -20; i <= 20; ++i) {
        assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(i, p.getIntValue());
        assertEquals("" + i, p.getText());
      }
      assertEquals(JsonToken.END_ARRAY, p.nextToken());
      p.close();
    }
  }
コード例 #2
0
  // And then one more test just for Bytes-based symbol table
  public void testByteBasedSymbolTable() throws Exception {
    // combination of short, medium1/2, long names...
    final String JSON =
        aposToQuotes(
            "{'abc':1, 'abc\\u0000':2, '\\u0000abc':3, "
                // then some medium
                + "'abc123':4,'abcd1234':5,"
                + "'abcd1234a':6,'abcd1234abcd':7,"
                + "'abcd1234abcd1':8"
                + "}");

    JsonFactory f = new JsonFactory();
    JsonParser p = f.createParser(JSON.getBytes("UTF-8"));
    ByteQuadsCanonicalizer symbols = _findSymbols(p);
    assertEquals(0, symbols.size());
    _streamThrough(p);
    assertEquals(8, symbols.size());
    p.close();

    // and, for fun, try again
    p = f.createParser(JSON.getBytes("UTF-8"));
    _streamThrough(p);
    symbols = _findSymbols(p);
    assertEquals(8, symbols.size());
    p.close();

    p = f.createParser(JSON.getBytes("UTF-8"));
    _streamThrough(p);
    symbols = _findSymbols(p);
    assertEquals(8, symbols.size());
    p.close();
  }
コード例 #3
0
  public void testEmptyArrayWrite() throws Exception {
    StringWriter sw = new StringWriter();
    JsonGenerator gen = new JsonFactory().createGenerator(sw);

    JsonStreamContext ctxt = gen.getOutputContext();
    assertTrue(ctxt.inRoot());
    assertFalse(ctxt.inArray());
    assertFalse(ctxt.inObject());
    assertEquals(0, ctxt.getEntryCount());
    assertEquals(0, ctxt.getCurrentIndex());

    gen.writeStartArray();

    ctxt = gen.getOutputContext();
    assertFalse(ctxt.inRoot());
    assertTrue(ctxt.inArray());
    assertFalse(ctxt.inObject());
    assertEquals(0, ctxt.getEntryCount());
    assertEquals(0, ctxt.getCurrentIndex());

    gen.writeEndArray();

    ctxt = gen.getOutputContext();
    assertTrue("Should be in root, was " + ctxt.getTypeDesc(), ctxt.inRoot());
    assertFalse(ctxt.inArray());
    assertFalse(ctxt.inObject());
    assertEquals(1, ctxt.getEntryCount());
    // Index won't yet move
    assertEquals(0, ctxt.getCurrentIndex());

    gen.close();
    String docStr = sw.toString();
    JsonParser jp = createParserUsingReader(docStr);
    assertEquals(JsonToken.START_ARRAY, jp.nextToken());
    assertEquals(JsonToken.END_ARRAY, jp.nextToken());
    jp.close();

    // Ok, then array with nested empty array
    sw = new StringWriter();
    gen = new JsonFactory().createGenerator(sw);
    gen.writeStartArray();
    gen.writeStartArray();
    gen.writeEndArray();
    gen.writeEndArray();
    gen.close();
    docStr = sw.toString();
    jp = createParserUsingReader(docStr);
    assertEquals(JsonToken.START_ARRAY, jp.nextToken());
    assertEquals(JsonToken.START_ARRAY, jp.nextToken());
    assertEquals(JsonToken.END_ARRAY, jp.nextToken());
    assertEquals(JsonToken.END_ARRAY, jp.nextToken());
    assertEquals(null, jp.nextToken());
    jp.close();
  }
コード例 #4
0
  // [core#191]: similarly, but for "short" symbols:
  public void testShortNameCollisionsViaParser() throws Exception {
    JsonFactory f = new JsonFactory();
    String json = _shortDoc191();
    JsonParser p;

    // First: ensure that char-based is fine
    p = f.createParser(json);
    while (p.nextToken() != null) {}
    p.close();

    // and then that byte-based
    p = f.createParser(json.getBytes("UTF-8"));
    while (p.nextToken() != null) {}
    p.close();
  }
コード例 #5
0
  public void testUtf8Issue462() throws Exception {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    IOContext ioc = new IOContext(new BufferRecycler(), bytes, true);
    JsonGenerator gen = new UTF8JsonGenerator(ioc, 0, null, bytes);
    String str = "Natuurlijk is alles gelukt en weer een tevreden klant\uD83D\uDE04";
    int length = 4000 - 38;

    for (int i = 1; i <= length; ++i) {
      gen.writeNumber(1);
    }
    gen.writeString(str);
    gen.flush();
    gen.close();

    // Also verify it's parsable?
    JsonFactory f = new JsonFactory();
    JsonParser p = f.createParser(bytes.toByteArray());
    for (int i = 1; i <= length; ++i) {
      assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
      assertEquals(1, p.getIntValue());
    }
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(str, p.getText());
    assertNull(p.nextToken());
    p.close();
  }
コード例 #6
0
  /**
   * Reserved for internal use. Parses the operation response as an entity. Reads entity data from
   * the specified <code>JsonParser</code> using the specified class type and optionally projects
   * the entity result with the specified resolver into a {@link TableResult} object.
   *
   * @param parser The <code>JsonParser</code> to read the data to parse from.
   * @param httpStatusCode The HTTP status code returned with the operation response.
   * @param clazzType The class type <code>T</code> implementing {@link TableEntity} for the entity
   *     returned. Set to <code>null</code> to ignore the returned entity and copy only response
   *     properties into the {@link TableResult} object.
   * @param resolver An {@link EntityResolver} instance to project the entity into an instance of
   *     type <code>R</code>. Set to <code>null</code> to return the entitys as instance of the
   *     class type <code>T</code>.
   * @param options A {@link TableRequestOptions} object that specifies execution options such as
   *     retry policy and timeout settings for the operation.
   * @param opContext An {@link OperationContext} object used to track the execution of the
   *     operation.
   * @return A {@link TableResult} object with the parsed operation response.
   * @throws InstantiationException if an error occurs while constructing the result.
   * @throws IllegalAccessException if an error occurs in reflection while parsing the result.
   * @throws StorageException if a storage service error occurs.
   * @throws IOException if an error occurs while accessing the stream.
   * @throws JsonParseException if an error occurs while parsing the stream.
   */
  static <T extends TableEntity, R> TableResult parseSingleOpResponse(
      final InputStream inStream,
      final TableRequestOptions options,
      final int httpStatusCode,
      final Class<T> clazzType,
      final EntityResolver<R> resolver,
      final OperationContext opContext)
      throws JsonParseException, IOException, InstantiationException, IllegalAccessException,
          StorageException {
    JsonParser parser = createJsonParserFromStream(inStream);

    try {
      final TableResult res =
          parseJsonEntity(
              parser,
              clazzType,
              null /*HashMap<String, PropertyPair> classProperties*/,
              resolver,
              options,
              opContext);
      res.setHttpStatusCode(httpStatusCode);
      return res;
    } finally {
      parser.close();
    }
  }
コード例 #7
0
  /** @param bioID */
  private boolean setBioID(String bioID) {
    boolean toRet = false;
    try {
      JsonFactory factory = new JsonFactory();
      JsonParser jparser = factory.createParser(bioID);

      String key = "";
      // Get StartObject for JSON, after first {
      jparser.nextToken();
      while (jparser.nextToken() != JsonToken.END_OBJECT) {
        key = jparser.getText();

        if (key.equals("id")) {
          key = jparser.nextTextValue();

          // Set bioID in Experiment
          selExp.setBioID(key);

          toRet = true;
        } else {
          jparser.skipChildren();
        }
      }
      jparser.close();

    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return toRet;
  }
コード例 #8
0
 @Override
 public final MediaContent deserialize(byte[] array) throws IOException {
   JsonParser parser = constructParser(array);
   MediaContent mc = readMediaContent(parser);
   parser.close();
   return mc;
 }
コード例 #9
0
  private void verifyFromMap(String input) throws Exception {
    JsonParser p = new JsonFactory().createParser(input);
    assertEquals(JsonToken.START_OBJECT, p.nextToken());
    assertEquals(JsonToken.FIELD_NAME, p.nextToken());
    assertEquals(FIELD4, getAndVerifyText(p));
    assertEquals(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(TEXT2, getAndVerifyText(p));

    assertEquals(JsonToken.FIELD_NAME, p.nextToken());
    assertEquals(FIELD3, getAndVerifyText(p));
    assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
    assertEquals(-1, p.getIntValue());

    assertEquals(JsonToken.FIELD_NAME, p.nextToken());
    assertEquals(FIELD2, getAndVerifyText(p));
    assertEquals(JsonToken.START_ARRAY, p.nextToken());
    assertEquals(JsonToken.END_ARRAY, p.nextToken());

    assertEquals(JsonToken.FIELD_NAME, p.nextToken());
    assertEquals(FIELD1, getAndVerifyText(p));
    assertEquals(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());
    assertEquals(DOUBLE_VALUE, p.getDoubleValue(), 0);

    assertEquals(JsonToken.END_OBJECT, p.nextToken());

    assertNull(p.nextToken());
    p.close();
  }
コード例 #10
0
  private void verifyFromArray(String input) throws Exception {
    JsonParser p = new JsonFactory().createParser(new StringReader(input));

    assertEquals(JsonToken.START_ARRAY, p.nextToken());

    assertEquals(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(TEXT1, getAndVerifyText(p));

    assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
    assertEquals(3, p.getIntValue());

    assertEquals(JsonToken.START_OBJECT, p.nextToken());
    assertEquals(JsonToken.FIELD_NAME, p.nextToken());
    assertEquals(FIELD1, getAndVerifyText(p));

    assertEquals(JsonToken.VALUE_TRUE, p.nextToken());
    assertEquals(JsonToken.FIELD_NAME, p.nextToken());
    assertEquals(FIELD2, getAndVerifyText(p));

    assertEquals(JsonToken.START_ARRAY, p.nextToken());
    assertEquals(JsonToken.END_ARRAY, p.nextToken());
    assertEquals(JsonToken.END_OBJECT, p.nextToken());

    assertEquals(JsonToken.VALUE_FALSE, p.nextToken());

    assertEquals(JsonToken.END_ARRAY, p.nextToken());
    assertNull(p.nextToken());
    p.close();
  }
コード例 #11
0
  /**
   * 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();
  }
コード例 #12
0
 /** 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();
   }
 }
コード例 #13
0
 @Override
 public MediaContent[] deserializeItems(InputStream in, int numberOfItems) throws IOException {
   MediaContent[] result = new MediaContent[numberOfItems];
   JsonParser parser = constructParser(in);
   for (int i = 0; i < numberOfItems; ++i) {
     result[i] = readMediaContent(parser);
   }
   parser.close();
   return result;
 }
コード例 #14
0
 private void closeParsers() {
   if (parsers != null) {
     for (JsonParser parser : parsers) {
       try {
         parser.close();
       } catch (IOException ignored) {
       }
     }
   }
 }
コード例 #15
0
  /** @see com.amazonaws.http.HttpResponseHandler#handle(com.amazonaws.http.HttpResponse) */
  public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception {
    log.trace("Parsing service response JSON");

    String CRC32Checksum = response.getHeaders().get("x-amz-crc32");
    CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = null;

    JsonParser jsonParser = null;

    if (!needsConnectionLeftOpen) {
      if (CRC32Checksum != null) {
        crc32ChecksumInputStream = new CRC32ChecksumCalculatingInputStream(response.getContent());
        jsonParser = jsonFactory.createParser(crc32ChecksumInputStream);
      } else {
        jsonParser = jsonFactory.createParser(response.getContent());
      }
    }

    try {
      AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
      JsonUnmarshallerContext unmarshallerContext =
          new JsonUnmarshallerContext(jsonParser, response);
      registerAdditionalMetadataExpressions(unmarshallerContext);

      T result = responseUnmarshaller.unmarshall(unmarshallerContext);

      if (CRC32Checksum != null) {
        long serverSideCRC = Long.parseLong(CRC32Checksum);
        long clientSideCRC = crc32ChecksumInputStream.getCRC32Checksum();
        if (clientSideCRC != serverSideCRC) {
          throw new CRC32MismatchException(
              "Client calculated crc32 checksum didn't match that calculated by server side");
        }
      }

      awsResponse.setResult(result);

      Map<String, String> metadata = unmarshallerContext.getMetadata();
      metadata.put(ResponseMetadata.AWS_REQUEST_ID, response.getHeaders().get("x-amzn-RequestId"));
      awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

      log.trace("Done parsing service response");
      return awsResponse;
    } finally {
      if (!needsConnectionLeftOpen) {
        try {
          jsonParser.close();
        } catch (IOException e) {
          log.warn("Error closing json parser", e);
        }
      }
    }
  }
コード例 #16
0
ファイル: ResourceLeaks.java プロジェクト: RobinYin/infer
 public void parseFromInputStreamAndLeak(JsonFactory factory) throws IOException {
   JsonParser parser = null;
   FileInputStream in = null;
   try {
     in = new FileInputStream("");
     parser = factory.createParser(in);
     Object o = parser.readValueAs(Object.class);
     ignore(o);
   } catch (Exception e) {
   } finally {
     if (parser != null) parser.close();
   }
   // parser does not own a resource which is leaked
 }
コード例 #17
0
ファイル: JsonRpcServer.java プロジェクト: sdhjob/jsonrpc4j
 @SuppressWarnings("unchecked")
 public <T extends JsonNode> T valueToTree(ObjectWriter writer, Object fromValue)
     throws IllegalArgumentException {
   if (fromValue == null) return null;
   TokenBuffer buf = new TokenBuffer(mapper);
   JsonNode result;
   try {
     writer.writeValue(buf, fromValue);
     JsonParser jp = buf.asParser();
     result = mapper.readTree(jp);
     jp.close();
   } catch (IOException e) { // should not occur, no real i/o...
     throw new IllegalArgumentException(e.getMessage(), e);
   }
   return (T) result;
 }
コード例 #18
0
  public void testBinary() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    final int LENGTH = 13045;
    byte[] data = new byte[LENGTH];
    for (int i = 0; i < LENGTH; ++i) {
      data[i] = (byte) i;
    }
    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, BinaryNode.valueOf(data));

    JsonParser p = new JsonFactory().createParser(sw.toString());
    // note: can't determine it's binary from json alone:
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertArrayEquals(data, p.getBinaryValue());
    p.close();
  }
コード例 #19
0
 protected final double _testRawDeser(int reps, byte[] json, ObjectReader reader)
     throws IOException {
   long start = System.nanoTime();
   final JsonFactory f = reader.getFactory();
   while (--reps >= 0) {
     JsonParser p = f.createParser(new ByteArrayInputStream(json));
     JsonToken t;
     while ((t = p.nextToken()) != null) {
       if (t == JsonToken.VALUE_STRING) {
         p.getText();
       } else if (t.isNumeric()) {
         p.getNumberValue();
       }
       ;
     }
     p.close();
   }
   hash = f.hashCode();
   return _msecsFromNanos(System.nanoTime() - start);
 }
コード例 #20
0
 public void testSimpleArrayWrite() throws Exception {
   StringWriter sw = new StringWriter();
   JsonGenerator gen = new JsonFactory().createGenerator(sw);
   gen.writeStartArray();
   gen.writeNumber(13);
   gen.writeBoolean(true);
   gen.writeString("foobar");
   gen.writeEndArray();
   gen.close();
   String docStr = sw.toString();
   JsonParser jp = createParserUsingReader(docStr);
   assertEquals(JsonToken.START_ARRAY, jp.nextToken());
   assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
   assertEquals(13, jp.getIntValue());
   assertEquals(JsonToken.VALUE_TRUE, jp.nextToken());
   assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
   assertEquals("foobar", jp.getText());
   assertEquals(JsonToken.END_ARRAY, jp.nextToken());
   assertEquals(null, jp.nextToken());
   jp.close();
 }
コード例 #21
0
ファイル: JsonParserDemo.java プロジェクト: gf5353/websocket
  /**
   * @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();
  }
コード例 #22
0
 @Override
 protected Void doInBackground(String... urls) {
   locationsList = new ArrayList<>();
   final JsonFactory jfactory = new JsonFactory();
   JsonParser jParser = null;
   try {
     jParser = jfactory.createParser(new URL(urls[0]));
     Log.d("MyLogs", "URL - " + urls[0]);
     while (jParser.nextToken() != JsonToken.END_ARRAY) {
       String fieldname = jParser.getCurrentName();
       if ("id".equals(fieldname)) {
         map = new HashMap<>();
         jParser.nextToken();
         map.put("id", jParser.getText());
       } else if ("name".equals(fieldname)) {
         jParser.nextToken();
         map.put("name", jParser.getText());
         locationsList.add(map);
       }
     }
   } catch (IOException | RuntimeException e) {
     e.printStackTrace();
   } finally {
     if (jParser != null) {
       try {
         jParser.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   list = new ArrayList<>();
   for (HashMap<String, String> a : locationsList) {
     list.add(a.get("name"));
   }
   return null;
 }
コード例 #23
0
  public streamParser(CommandLine line) {
    try {

      JsonFactory jfactory = new JsonFactory();
      JsonParser jParser = null;

      if (line.hasOption("f")) {
        jParser = jfactory.createJsonParser(new File(line.getOptionValue("file")));
      } else {
        jParser = jfactory.createJsonParser(System.in);
      }

      String idElement = null;
      String idValue = null;

      if (line.hasOption("key")) idElement = line.getOptionValue("key");

      String[] remainingArguments = line.getArgs();
      if (remainingArguments.length != 1) {
        throw new IOException("table name not provided or too many table arguments");
      }
      Table table = MapRDB.getTable(remainingArguments[0]); // get the table
      DocumentBuilder b = MapRDB.newDocumentBuilder();

      while (jParser.nextToken() != null) {
        String fieldName = jParser.getCurrentName();

        switch (jParser.getCurrentToken()) {
          case END_ARRAY:
            depth--;
            b.endArray();
            break;
          case END_OBJECT:
            b.endMap();
            depth--;
            // When the depth reaches zero on an end of object, this means we
            // have constructed a complete JSON object in the DocumentBuilder.
            // At this point, we can call insert() or insertandreplace()
            if (depth == 0) {
              System.out.println(b.getDocument().asJsonString());
              if (idElement != null) table.insert(idValue, b.getDocument());
              else table.insert(b.getDocument());
            }
            break;
          case START_ARRAY:
            if (fieldName == null) {
              b.addNewArray();
            } else {
              b.putNewArray(fieldName);
            }
            depth++;
            break;
          case START_OBJECT:
            if (fieldName == null) {
              b.addNewMap();
            } else {
              b.putNewMap(fieldName);
            }
            depth++;
            break;

            // Not sure about these guys
          case FIELD_NAME:
          case NOT_AVAILABLE:
          case VALUE_EMBEDDED_OBJECT:
            break;

            // These actually add things to the array or object
          case VALUE_NULL:
            if (fieldName != null) {
              b.putNull(fieldName);
            } else {
              b.addNull();
            }
            break;
          case VALUE_NUMBER_FLOAT:
            if (fieldName != null) {
              b.put(fieldName, jParser.getDoubleValue());
            } else {
              b.add(jParser.getDoubleValue());
            }
            break;
          case VALUE_NUMBER_INT:
            if (fieldName != null) {
              b.put(fieldName, jParser.getLongValue());
            } else {
              b.add(jParser.getLongValue());
            }
            break;
          case VALUE_STRING:
            if (fieldName != null) {
              if (fieldName.equals(idElement)) idValue = jParser.getText();
              b.put(fieldName, jParser.getText());
            } else {
              b.add(jParser.getText());
            }
            break;
          case VALUE_FALSE:
          case VALUE_TRUE:
            if (fieldName != null) {
              b.put(fieldName, jParser.getBooleanValue());
            } else {
              b.add(jParser.getBooleanValue());
            }
            break;
        }
        System.out.println(
            "["
                + depth
                + "]   "
                + jParser.getCurrentToken().toString()
                + ": "
                + fieldName); // display mkyong
      }
      jParser.close();

    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #24
0
  protected LBPool jsonToPool(String json) throws IOException {
    if (json == null) return null;

    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBPool pool = new LBPool();

    try {
      jp = f.createJsonParser(json);
    } 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.equals("id")) {
        pool.id = jp.getText();
        continue;
      }
      if (n.equals("tenant_id")) {
        pool.tenantId = jp.getText();
        continue;
      }
      if (n.equals("name")) {
        pool.name = jp.getText();
        continue;
      }
      if (n.equals("network_id")) {
        pool.netId = jp.getText();
        continue;
      }
      if (n.equals("lb_method")) {
        pool.lbMethod = Short.parseShort(jp.getText());
        continue;
      }
      if (n.equals("protocol")) {
        String tmp = jp.getText();
        if (tmp.equalsIgnoreCase("TCP")) {
          pool.protocol = IPv4.PROTOCOL_TCP;
        } else if (tmp.equalsIgnoreCase("UDP")) {
          pool.protocol = IPv4.PROTOCOL_UDP;
        } else if (tmp.equalsIgnoreCase("ICMP")) {
          pool.protocol = IPv4.PROTOCOL_ICMP;
        }
        continue;
      }
      if (n.equals("vip_id")) {
        pool.vipId = jp.getText();
        continue;
      }

      log.warn("Unrecognized field {} in " + "parsing Pools", jp.getText());
    }
    jp.close();

    return pool;
  }
コード例 #25
0
  /*
   * Parse JSON with JackSON Parser directly into Java Objects
   */
  @SuppressWarnings("deprecation")
  public void parseJSON() throws JsonParseException, IOException {
    JsonFactory f = new JsonFactory();
    boolean breakLoop = false;
    boolean breakOuterLoop = false;
    JsonParser jp = null;
    try {
      //				jp = f.createJsonParser(context.getAssets().open("kadajsondata.txt"));
      jp =
          f.createJsonParser(
              RestClient.connect(AppConstants.URLS.PRODUCT_SEARCH_URL + urlSearchText));
    } catch (JsonParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    while (jp.nextToken() != JsonToken.END_ARRAY) {
      if (breakLoop) {
        break;
      }
      String fieldname = jp.getCurrentName();
      if ("SearchResults".equals(fieldname)) {
        while (jp.nextToken() != JsonToken.END_ARRAY) {
          if ("}".equals(jp.getText())) {
            productListDTO.add(productDTO);
            productDTO = new ProductDTO();
          }
          if (jp.getText().equals(JsonToken.END_OBJECT)) {
            break;
          }

          String responsefield = jp.getCurrentName();
          jp.nextToken(); // move to value

          if ("pdtId".equals(responsefield)) {
            productDTO.setPdtId(jp.getText());
          } else if ("versionId".equals(responsefield)) {
            productDTO.setVersionId(jp.getText());
          } else if ("pdtName".equals(responsefield)) {
            productDTO.setPdtName(jp.getText());
          } else if ("isFeatured".equals(responsefield)) {
            productDTO.setIsFeatured(jp.getText());
          } else if ("pdtFeaturedPrice".equals(responsefield)) {
            productDTO.setPdtFeaturedPrice(jp.getText());
          } else if ("pdtPrice".equals(responsefield)) {
            productDTO.setPdtPrice(jp.getText());
          } else if ("isStockout".equals(responsefield)) {
            productDTO.setIsStockout(jp.getText());
          } else if ("isLimited".equals(responsefield)) {
            productDTO.setIsLimited(jp.getText());
          } else if ("isFoodCoupon".equals(responsefield)) {
            productDTO.setIsFoodCoupon(jp.getText());
          } else if ("stockAvailable".equals(responsefield)) {
            productDTO.setStockAvailable(jp.getText());
          } else if ("imagePath".equals(responsefield)) {
            productDTO.setImagePath(jp.getText());
          } else if (jp.getText().equals("]")) {
            Log.i("Jackson", "Outta Products");
            breakLoop = true;
            break;
          } else {
            Log.i("Jackson", "Unrecognized Token");
          }
        }
      }
    }
    jp.close();
  }
コード例 #26
0
  /**
   * Reserved for internal use. Parses the operation response as a collection of entities. Reads
   * entity data from the specified input stream using the specified class type and optionally
   * projects each entity result with the specified resolver into an {@link ODataPayload} containing
   * a collection of {@link TableResult} objects.
   *
   * @param inStream The <code>InputStream</code> to read the data to parse from.
   * @param clazzType The class type <code>T</code> implementing {@link TableEntity} for the
   *     entities returned. Set to <code>null</code> to ignore the returned entities and copy only
   *     response properties into the {@link TableResult} objects.
   * @param resolver An {@link EntityResolver} instance to project the entities into instances of
   *     type <code>R</code>. Set to <code>null</code> to return the entities as instances of the
   *     class type <code>T</code>.
   * @param options A {@link TableRequestOptions} object that specifies execution options such as
   *     retry policy and timeout settings for the operation.
   * @param opContext An {@link OperationContext} object used to track the execution of the
   *     operation.
   * @return An {@link ODataPayload} containing a collection of {@link TableResult} objects with the
   *     parsed operation response.
   * @throws InstantiationException if an error occurs while constructing the result.
   * @throws IllegalAccessException if an error occurs in reflection while parsing the result.
   * @throws StorageException if a storage service error occurs.
   * @throws IOException if an error occurs while accessing the stream.
   * @throws JsonParseException if an error occurs while parsing the stream.
   */
  @SuppressWarnings("unchecked")
  static <T extends TableEntity, R> ODataPayload<?> parseQueryResponse(
      final InputStream inStream,
      final TableRequestOptions options,
      final Class<T> clazzType,
      final EntityResolver<R> resolver,
      final OperationContext opContext)
      throws JsonParseException, IOException, InstantiationException, IllegalAccessException,
          StorageException {
    ODataPayload<T> corePayload = null;
    ODataPayload<R> resolvedPayload = null;
    ODataPayload<?> commonPayload = null;

    JsonParser parser = createJsonParserFromStream(inStream);

    try {

      if (resolver != null) {
        resolvedPayload = new ODataPayload<R>();
        commonPayload = resolvedPayload;
      } else {
        corePayload = new ODataPayload<T>();
        commonPayload = corePayload;
      }

      if (!parser.hasCurrentToken()) {
        parser.nextToken();
      }

      JsonUtilities.assertIsStartObjectJsonToken(parser);

      // move into data
      parser.nextToken();

      // if there is a clazz type and if JsonNoMetadata, create a classProperties dictionary to use
      // for type inference once
      // instead of querying the cache many times
      HashMap<String, PropertyPair> classProperties = null;
      if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata
          && clazzType != null) {
        classProperties = PropertyPair.generatePropertyPairs(clazzType);
      }

      while (parser.getCurrentToken() != null) {
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME
            && parser.getCurrentName().equals(ODataConstants.VALUE)) {
          // move to start of array
          parser.nextToken();

          JsonUtilities.assertIsStartArrayJsonToken(parser);

          // go to properties
          parser.nextToken();

          while (parser.getCurrentToken() == JsonToken.START_OBJECT) {
            final TableResult res =
                parseJsonEntity(parser, clazzType, classProperties, resolver, options, opContext);
            if (corePayload != null) {
              corePayload.tableResults.add(res);
            }

            if (resolver != null) {
              resolvedPayload.results.add((R) res.getResult());
            } else {
              corePayload.results.add((T) res.getResult());
            }

            parser.nextToken();
          }

          JsonUtilities.assertIsEndArrayJsonToken(parser);
        }

        parser.nextToken();
      }
    } finally {
      parser.close();
    }

    return commonPayload;
  }
コード例 #27
0
 /**
  * closes the json parser and the stream
  *
  * @throws IOException
  */
 public void close() throws IOException {
   parser.close();
 }