예제 #1
0
  @Test
  public void testSerialization() throws IOException, ClassNotFoundException {
    Condition cond = new Condition();
    Set<UUID> ids = new HashSet<>();
    ids.add(UUID.randomUUID());
    ids.add(UUID.randomUUID());
    cond.inPortIds = ids;
    cond.portGroup = UUID.randomUUID();
    cond.tpSrc = new Range<>(40000, 41000);
    cond.tpSrcInv = false;
    cond.tpDst = new Range<>(42000, 43000);
    cond.tpDstInv = true;
    cond.etherType = 0x86DD;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStream out = new BufferedOutputStream(bos);
    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(new OutputStreamWriter(out));
    jsonGenerator.writeObject(cond);
    out.close();
    byte[] data = bos.toByteArray();
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    InputStream in = new BufferedInputStream(bis);
    JsonParser jsonParser = jsonFactory.createJsonParser(new InputStreamReader(in));
    Condition c = jsonParser.readValueAs(Condition.class);
    in.close();
    Assert.assertTrue(cond.equals(c));
  }
  private static String getChannelURL(String responseBody) {

    try {
      ObjectMapper mapper = new ObjectMapper();
      JsonFactory f = mapper.getJsonFactory();
      JsonParser jp = f.createJsonParser(responseBody);
      JsonToken current = jp.nextToken();

      if (current != JsonToken.START_OBJECT) {
        throw new IllegalStateException("FAIL - Error: root should be an object: quiting.");
      }

      JsonNode node = mapper.readTree(jp);
      if (node.has("notificationChannel")) {
        node = node.get("notificationChannel");
        if (node.has("channelData")) {
          node = node.get("channelData");
          if (node.has("channelURL")) {
            return node.get("channelURL").getTextValue();
          }
        }
      }

      jp.close();
    } catch (IOException e) {
      throw new IllegalStateException("FAIL - Error parsing the body, is a JSON?");
    }

    return null;
  }
예제 #3
0
  public static Row loadStreaming(String s, Pool pool) throws Exception {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createJsonParser(s);

    if (jp.nextToken() != JsonToken.START_OBJECT) {
      return null;
    }

    List<Cell> cells = new ArrayList<Cell>();
    boolean starred = false;
    boolean flagged = false;

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

      if (STARRED.equals(fieldName)) {
        starred = jp.getBooleanValue();
      } else if (FLAGGED.equals(fieldName)) {
        flagged = jp.getBooleanValue();
      } else if ("cells".equals(fieldName)) {
        if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
          return null;
        }

        while (jp.nextToken() != JsonToken.END_ARRAY) {
          Cell cell = Cell.loadStreaming(jp, pool);

          cells.add(cell);
        }
      }
    }

    return (cells.size() > 0) ? new Row(cells, flagged, starred) : null;
  }
예제 #4
0
    @Override
    protected DataHolder doInBackground(String... params) {

      try {
        URL contentURL = new URL(params[0]);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonFactory jsonFactory = new JsonFactory();

        String data =
            getStringFromInputStream(
                contentURL.openStream()); // mContext.getAssets().open("data.txt"));

        // Creating a parser object with the connection stream that contains the response from
        // service.
        JsonParser jp =
            jsonFactory.createJsonParser(
                new ByteArrayInputStream(data.getBytes("UTF-8"))); // contentURL.openStream()
        // reading the json into the DataHolder object.
        mDataHolder = objectMapper.readValue(jp, DataHolder.class);
      } catch (IOException e) {
        Log.e("error", "Error downloading data - " + e.getStackTrace());
      }
      return mDataHolder;
    }
예제 #5
0
  @Override
  public void onEvalStart() {
    super.onEvalStart();
    initalizeData();
    try {
      ObjectMapper mapper = new ObjectMapper();
      mapper.setDateFormat(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"));
      mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
      mapper.configure(SerializationConfig.Feature.WRAP_EXCEPTIONS, true);
      mapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false);
      mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true);

      SimpleModule module = new SimpleModule("DataProxy", new Version(1, 0, 0, null));
      module.addSerializer(DataProxy.class, new DataProxySerializer(DataProxy.class));
      mapper.registerModule(module);

      JsonFactory jsonFactory = mapper.getJsonFactory();
      writer = jsonFactory.createJsonGenerator(context.getWriter());
      writer.setPrettyPrinter(new DefaultPrettyPrinter());

      writer.writeStartObject();
    } catch (IOException ex) {
      throw new OseeCoreException(ex);
    }
  }
예제 #6
0
 public String marshall(String definitions)
     throws IOException { // TODO fix this when we have the EPN ecore model
   StringWriter writer = new StringWriter();
   JsonFactory f = new JsonFactory();
   JsonGenerator generator = f.createJsonGenerator(writer);
   // TODO do the heavy lifting here passing in the writer and the json generator
   generator.close();
   return writer.toString();
 }
예제 #7
0
  public TaskDeserializerTest(String path) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = new JsonFactory(mapper);

    StringWriter writer = new StringWriter();
    IOUtils.copy(this.getClass().getResourceAsStream(path), writer);

    jsonParser = jsonFactory.createJsonParser(writer.toString());
  }
예제 #8
0
  /**
   * Executes a query.
   *
   * @param command Name of the command to execute
   * @param parameters Parameters
   * @param manager Reference back to business layer
   * @return Parsed JSON object, empty object on error.
   */
  public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) {
    URLConnection uc = null;
    try {
      final ObjectMapper mapper = Client.MAPPER;

      if (mUrlSuffix == null) {
        throw new NoSettingsException();
      }

      final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP);
      uc = url.openConnection();
      uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
      uc.setReadTimeout(mSocketReadTimeout);
      if (authEncoded != null) {
        uc.setRequestProperty("Authorization", "Basic " + authEncoded);
      }
      uc.setRequestProperty("Content-Type", "application/json");
      uc.setDoOutput(true);

      final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1");
      if (parameters != null) {
        data.put("params", parameters);
      }

      final JsonFactory jsonFactory = new JsonFactory();
      final JsonGenerator jg =
          jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8);
      jg.setCodec(mapper);

      // POST data
      jg.writeTree(data);
      jg.flush();

      final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream());
      jp.setCodec(mapper);
      final JsonNode ret = jp.readValueAs(JsonNode.class);
      return ret;

    } catch (MalformedURLException e) {
      manager.onError(e);
    } catch (IOException e) {
      int responseCode = -1;
      try {
        responseCode = ((HttpURLConnection) uc).getResponseCode();
      } catch (IOException e1) {
      } // do nothing, getResponse code failed so treat as default i/o exception.
      if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));
      } else {
        manager.onError(e);
      }
    } catch (NoSettingsException e) {
      manager.onError(e);
    }
    return new ObjectNode(null);
  }
예제 #9
0
 public String toJSON(T object) throws IOException {
   JsonFactory jsonFactory = new JsonFactory();
   ObjectMapper mapper = new ObjectMapper(jsonFactory);
   mapper.getSerializationConfig().setAnnotationIntrospector(new JacksonAnnotationIntrospector());
   mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   jsonFactory.setCodec(mapper);
   StringWriter writer = new StringWriter();
   JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
   jsonGenerator.useDefaultPrettyPrinter();
   jsonGenerator.writeObject(object);
   return writer.getBuffer().toString();
 }
예제 #10
0
  static Geometry getGeometryFromJSon(String jsonStr) {
    JsonFactory jf = new JsonFactory();

    try {
      JsonParser jp = jf.createJsonParser(jsonStr);
      jp.nextToken();
      Geometry geom = GeometryEngine.jsonToGeometry(jp).getGeometry();
      return geom;
    } catch (Exception ex) {
      return null;
    }
  }
  public void jacksonTest() throws Exception {
    JsonFactory factory = new JsonFactory();
    StringWriter writer = new StringWriter();
    JsonGenerator generator = factory.createJsonGenerator(writer);
    generator.writeStartObject();
    generator.writeFieldName("bool");
    generator.writeBoolean(true);
    generator.writeFieldName("firstName");
    generator.writeString("john");
    generator.writeFieldName("age");
    generator.writeNumber(1);
    generator.writeFieldName("gg");
    generator.writeStartObject();
    generator.writeFieldName("firstName");
    generator.writeString("john");
    generator.writeEndObject();

    generator.writeEndObject();
    generator.close();
    String generated = writer.toString();
    System.out.print(generated);

    JsonParser parser = factory.createJsonParser(generated);
    assertTrue(parser.nextToken() == JsonToken.START_OBJECT);
    parser.nextToken();

    assertEquals("bool", parser.getCurrentName());
    assertTrue(parser.nextToken() == JsonToken.VALUE_TRUE);
    parser.nextToken();

    assertEquals("firstName", parser.getCurrentName());
    parser.nextToken();
    assertEquals("john", parser.getText());
    parser.nextToken();

    assertEquals("age", parser.getCurrentName());
    parser.nextToken();
    assertTrue(1 == parser.getIntValue());
    parser.nextToken();

    assertEquals("gg", parser.getCurrentName());
    assertTrue(parser.nextToken() == JsonToken.START_OBJECT);
    parser.nextToken();
    assertEquals("firstName", parser.getCurrentName());
    parser.nextToken();
    assertEquals("john", parser.getText());
    assertTrue(parser.nextToken() == JsonToken.END_OBJECT);

    assertTrue(parser.nextToken() == JsonToken.END_OBJECT);

    parser.close();
  }
예제 #12
0
 public IVRResponse parse(HttpResponse httpResponse) {
   String ivrResponseAsString = "not parsed yet";
   try {
     ivrResponseAsString = EntityUtils.toString(httpResponse.getEntity());
     LOGGER.info(String.format("Attempting to parse IVR response %s", ivrResponseAsString));
     ObjectMapper objectMapper = new ObjectMapper();
     JsonFactory jsonFactory = objectMapper.getJsonFactory();
     JsonParser jsonParser = jsonFactory.createJsonParser(ivrResponseAsString);
     return jsonParser.readValueAs(IVRResponse.class);
   } catch (IOException e) {
     LOGGER.error(String.format("Response returned %s", ivrResponseAsString));
     throw new MTrainingException("Could not parse httpResponse", e);
   }
 }
  public void open(InputStream inputStream) throws Exception {
    if ((_JsonParser != null) && (_JsonParser.getInputSource() == inputStream)) {
      return;
    }

    // TODO: reset other state?

    final JsonFactory jsonFactory = new JsonFactory();
    _JsonParser = jsonFactory.createJsonParser(inputStream);

    _Event = new Event<JsonParserModelGraphReader>(this);

    getNextToken();
    _CurrentName = null;
  }
예제 #14
0
  // allow json parsing to be unit tested from a local file
  public List<String> parseJson(final String fullFile) throws JsonParseException, IOException {
    final InputStream is = ClassLoader.getSystemResourceAsStream(fullFile);
    final JsonParser jp = factory.createJsonParser(is);
    final JsonNode node = mapper.readTree(jp);

    return parseJson(node);
  }
예제 #15
0
 public static JsonParser createJsonParser(String in) throws JsonException {
   try {
     return jf.createJsonParser(in);
   } catch (IOException ex) {
     throw new JsonException(ex);
   }
 }
예제 #16
0
 /**
  * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format.
  *
  * @param json a single vertex in GraphSON format
  * @param factory the factory responsible for constructing graph elements
  * @param hasEmbeddedTypes the GraphSON has embedded types
  */
 public static Vertex vertexFromJson(
     final JSONObject json, final ElementFactory factory, final boolean hasEmbeddedTypes)
     throws IOException {
   final JsonParser jp = jsonFactory.createJsonParser(json.toString());
   final JsonNode node = jp.readValueAsTree();
   return vertexFromJson(node, factory, hasEmbeddedTypes);
 }
예제 #17
0
 /**
  * Build and return a new {@link JsonParser} with the given {@link InputStream} assigned to it.
  */
 public static JsonParser newJsonParser(InputStream input) throws JsonParseException, IOException {
   if (sFactory == null) {
     sFactory = new JsonFactory();
   }
   final JsonParser parser = sFactory.createJsonParser(input);
   return parser;
 }
  /** @see com.amazonaws.http.HttpResponseHandler#handle(com.amazonaws.http.HttpResponse) */
  public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception {
    log.trace("Parsing service response JSON");
    JsonParser jsonParser = jsonFactory.createJsonParser(response.getContent());
    try {
      AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
      JsonUnmarshallerContext unmarshallerContext = new JsonUnmarshallerContext(jsonParser);

      // TODO: Anything else to do for JSON metadata?
      unmarshallerContext.registerMetadataExpression(
          "ResponseMetadata/RequestId", 2, ResponseMetadata.AWS_REQUEST_ID);
      unmarshallerContext.registerMetadataExpression(
          "requestId", 2, ResponseMetadata.AWS_REQUEST_ID);
      registerAdditionalMetadataExpressions(unmarshallerContext);

      T result = responseUnmarshaller.unmarshall(unmarshallerContext);
      awsResponse.setResult(result);

      Map<String, String> metadata = unmarshallerContext.getMetadata();
      awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

      log.trace("Done parsing service response");
      return awsResponse;
    } finally {
      try {
        jsonParser.close();
      } catch (Exception e) {
      }
    }
  }
예제 #19
0
 public static JsonGenerator createJsonGenerator(OutputStream os) throws JsonException {
   try {
     return jf.createJsonGenerator(os, JsonEncoding.UTF8);
   } catch (IOException ex) {
     throw new JsonException(ex);
   }
 }
예제 #20
0
 public static JsonGenerator createJsonGenerator(Writer w) throws JsonException {
   try {
     return jf.createJsonGenerator(w);
   } catch (IOException ex) {
     throw new JsonException(ex);
   }
 }
예제 #21
0
  private void process(File input) throws IOException {
    JsonFactory jsonF = new JsonFactory();
    JsonParser jp = jsonF.createJsonParser(input);
    TwitterEntry entry = read(jp);

    // let's write to a file, using UTF-8 encoding (only sensible one)
    StringWriter strw = new StringWriter();
    JsonGenerator jg = jsonF.createJsonGenerator(strw);
    jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier

    // Here we would modify it... for now, will just (re)indent it

    write(jg, entry);

    System.out.println("Result = [" + strw.toString() + "]");
  }
예제 #22
0
 /**
  * Method for reading sequence of Objects from parser stream.
  *
  * @since 1.8
  */
 public <T> MappingIterator<T> readValues(URL src) throws IOException, JsonProcessingException {
   JsonParser jp = _jsonFactory.createJsonParser(src);
   if (_schema != null) {
     jp.setSchema(_schema);
   }
   DeserializationContext ctxt = _createDeserializationContext(jp, _config);
   return new MappingIterator<T>(_valueType, jp, ctxt, _findRootDeserializer(_config, _valueType));
 }
예제 #23
0
 public static void toJson(Object pojo, Writer writer, boolean prettyPrint)
     throws JsonMappingException, JsonGenerationException, IOException {
   JsonGenerator jg = jf.createJsonGenerator(writer);
   if (prettyPrint) {
     jg.useDefaultPrettyPrinter();
   }
   m.writeValue(jg, pojo);
 }
예제 #24
0
 private String formatJson(Object data) {
   try {
     final StringWriter result = new StringWriter();
     jsonFactory.createJsonGenerator(result).writeObject(data);
     return result.toString();
   } catch (IOException e) {
     throw new RuntimeException("error formatting json", e);
   }
 }
예제 #25
0
 /** 将对象转换成json */
 public static String toJson(Object pojo) {
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator jg = jf.createJsonGenerator(sw);
     m.writeValue(jg, pojo);
   } catch (Exception e) {
   }
   return sw.toString();
 }
예제 #26
0
  /**
   * Makes HTTP get request and parses the responses JSON into HashMaps.
   *
   * @throws IOException
   */
  private void getData() throws IOException {
    String json = HttpRequest.get(URL).body();
    JsonFactory factory = new JsonFactory();
    JsonParser parser = factory.createJsonParser(json);

    Map<String, Object> region = null;

    parser.nextToken();
    while (parser.nextToken() == JsonToken.START_OBJECT) {
      region = mapper.readValue(parser, new TypeReference<Map<String, Object>>() {});
      if (region.containsKey(CATEGORY_FIELD)) {
        if (REGION_CATEGORY.equals(region.get(CATEGORY_FIELD))) {
          regionsByCode.put((String) region.get(CODE_FIELD), (Integer) region.get(ID_FIELD));
          regionsById.put((Integer) region.get(ID_FIELD), (String) region.get(CODE_FIELD));
        }
      }
    }
  }
예제 #27
0
 /**
  * リクエストボディを解析してEventオブジェクトを取得する.
  *
  * @param reader Http入力ストリーム
  * @return 解析したEventオブジェクト
  */
 protected JSONEvent getRequestBody(final Reader reader) {
   JSONEvent event = null;
   JsonParser jp = null;
   ObjectMapper mapper = new ObjectMapper();
   JsonFactory f = new JsonFactory();
   try {
     jp = f.createJsonParser(reader);
     JsonToken token = jp.nextToken(); // JSONルート要素("{")
     if (token == JsonToken.START_OBJECT) {
       event = mapper.readValue(jp, JSONEvent.class);
     } else {
       throw DcCoreException.Event.JSON_PARSE_ERROR;
     }
   } catch (IOException e) {
     throw DcCoreException.Event.JSON_PARSE_ERROR;
   }
   return event;
 }
예제 #28
0
 private String readBody(JsonParser jp) throws IOException {
   JsonNode node = mapper.readTree(jp);
   StringWriter out = new StringWriter();
   JsonGenerator gen = jsonFactory.createJsonGenerator(out);
   mapper.writeTree(gen, node);
   gen.flush();
   gen.close();
   return out.toString();
 }
예제 #29
0
 /**
  * Writes the response values back to the http response. This allows the calling code to parse the
  * response values for display to the user.
  *
  * @param responseMap the response params to write to the http response
  * @param response the http response
  * @throws IOException
  */
 private void writeToResponse(Map<String, String> responseMap, HttpServletResponse response)
     throws IOException {
   // Note: setting the content-type to text/html because otherwise IE prompt the user to download
   // the result rather than handing it off to the GWT form response handler.
   // See JIRA issue https://issues.jboss.org/browse/SRAMPUI-103
   response.setContentType("text/html; charset=UTF8"); // $NON-NLS-1$
   JsonFactory f = new JsonFactory();
   JsonGenerator g = f.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
   g.useDefaultPrettyPrinter();
   g.writeStartObject();
   for (java.util.Map.Entry<String, String> entry : responseMap.entrySet()) {
     String key = entry.getKey();
     String val = entry.getValue();
     g.writeStringField(key, val);
   }
   g.writeEndObject();
   g.flush();
   g.close();
 }
예제 #30
-1
  private void serialize(Query query, OutputStream outputStream) throws IOException {
    JsonGenerator g = jsonFactory.createJsonGenerator(outputStream, JsonEncoding.UTF8);
    g.useDefaultPrettyPrinter();
    g.writeStartObject();
    g.writeStringField("name", "jmxtrans");
    g.writeStringField("type", "metric");
    g.writeStringField("handler", sensuhandler);

    StringBuffer jsonoutput = new StringBuffer();
    List<String> typeNames = getTypeNames();
    for (Result result : query.getResults()) {
      Map<String, Object> resultValues = result.getValues();
      if (resultValues != null) {
        for (Map.Entry<String, Object> values : resultValues.entrySet()) {
          if (NumberUtils.isNumeric(values.getValue())) {
            Object value = values.getValue();
            jsonoutput
                .append(JmxUtils.getKeyString(query, result, values, typeNames, null))
                .append(" ")
                .append(value)
                .append(" ")
                .append(TimeUnit.SECONDS.convert(result.getEpoch(), TimeUnit.MILLISECONDS))
                .append(System.getProperty("line.separator"));
          }
        }
      }
    }
    g.writeStringField("output", jsonoutput.toString());
    g.writeEndObject();
    g.flush();
    g.close();
  }