@Override
 public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args)
     throws Exception {
   if (args.size() != 2) {
     err.println("Expected 2 arguments: schema binary_data_file");
     err.println("Use '-' as binary_data_file for stdin.");
     return 1;
   }
   Schema schema = Schema.parse(args.get(0));
   InputStream input;
   boolean needsClosing;
   if (args.get(1).equals("-")) {
     input = stdin;
     needsClosing = false;
   } else {
     input = new FileInputStream(args.get(1));
     needsClosing = true;
   }
   try {
     DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
     Object datum = reader.read(null, DecoderFactory.get().binaryDecoder(input, null));
     DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
     JsonGenerator g = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
     g.useDefaultPrettyPrinter();
     writer.write(datum, EncoderFactory.get().jsonEncoder(schema, g));
     g.flush();
     out.println();
     out.flush();
   } finally {
     if (needsClosing) {
       input.close();
     }
   }
   return 0;
 }
 @Override
 public void flush() throws XMLStreamException {
   try {
     generator.flush();
   } catch (IOException e) {
     throw new XMLStreamException(e);
   }
 }
Exemple #3
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();
 }
  /**
   * 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);
  }
  public void toJson(JsonGenerator gen) throws IOException {

    gen.writeStartObject();

    if (type != null) {
      gen.writeStringField("type", type.getName());
    }

    if (tableName != null) {
      gen.writeStringField("tableName", tableName);
    }

    if (versionUpdated != -1) {
      gen.writeNumberField("versionUpdated", versionUpdated);
    }

    if (versionCreated != -1) {
      gen.writeNumberField("versionCreated", versionCreated);
    }

    if (recordTypeChanged) {
      gen.writeBooleanField("recordTypeChanged", true);
    }

    if (updatedFields != null && updatedFields.size() > 0) {
      gen.writeArrayFieldStart("updatedFields");
      for (SchemaId updatedField : updatedFields) {
        gen.writeBinary(updatedField.getBytes());
      }
      gen.writeEndArray();
    }

    if (vtagsToIndex != null && vtagsToIndex.size() > 0) {
      gen.writeArrayFieldStart("vtagsToIndex");
      for (SchemaId vtag : vtagsToIndex) {
        gen.writeBinary(vtag.getBytes());
      }
      gen.writeEndArray();
    }

    if (attributes != null && attributes.size() > 0) {
      gen.writeObjectFieldStart("attributes");
      for (String key : attributes.keySet()) {
        gen.writeStringField(key, attributes.get(key));
      }
      gen.writeEndObject();
    }

    if (indexRecordFilterData != null) {
      gen.writeFieldName("indexFilterData");
      indexRecordFilterData.toJson(gen);
    }

    gen.writeEndObject();
    gen.flush();
  }
  @Override
  public void writeTo(
      Object object,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    JsonGenerator writer = null;
    if (type.isAssignableFrom(ArtifactReadable.class)) {
      ArtifactReadable artifact = (ArtifactReadable) object;
      try {
        writer = jsonFactory.createJsonGenerator(entityStream);
        //         writer.setPrettyPrinter(new DefaultPr)
        writer.writeStartObject();
        writer.writeNumberField("uuid", artifact.getLocalId());
        if (matches(IdentityView.class, annotations)) {
          writer.writeStringField("Name", artifact.getName());
        } else {
          AttributeTypes attributeTypes = getAttibuteTypes();
          Collection<? extends IAttributeType> attrTypes = attributeTypes.getAll();
          ResultSet<? extends AttributeReadable<Object>> attributes = artifact.getAttributes();
          if (!attributes.isEmpty()) {
            for (IAttributeType attrType : attrTypes) {
              if (artifact.isAttributeTypeValid(attrType)) {
                List<Object> attributeValues = artifact.getAttributeValues(attrType);
                if (!attributeValues.isEmpty()) {

                  if (attributeValues.size() > 1) {
                    writer.writeArrayFieldStart(attrType.getName());
                    for (Object value : attributeValues) {
                      writer.writeObject(value);
                    }
                    writer.writeEndArray();
                  } else if (attributeValues.size() == 1) {
                    Object value = attributeValues.iterator().next();
                    writer.writeObjectField(attrType.getName(), value);
                  }
                }
              }
            }
          }
        }
        writer.writeEndObject();
      } finally {
        if (writer != null) {
          writer.flush();
        }
      }
    }
  }
Exemple #7
0
 protected String toJson(boolean pretty) {
   try {
     StringWriter writer = new StringWriter();
     JsonGenerator gen = FACTORY.createJsonGenerator(writer);
     if (pretty) gen.useDefaultPrettyPrinter();
     toJson(gen);
     gen.flush();
     return writer.toString();
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 private JsonNode write(Map<String, Object> row) throws IOException, JsonParseException {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   JsonGenerator json = jsonFactory.createJsonGenerator(out);
   json.writeStartObject();
   try {
     new GraphExtractionWriter().write(json, row.keySet(), new MapRow(row));
   } finally {
     json.writeEndObject();
     json.flush();
   }
   return JsonHelper.jsonNode(out.toString("UTF-8"));
 }
  public void dump(OutputStream os, BaseResponse res) {
    D2ResponseMessage d2Response = (D2ResponseMessage) res;

    try {
      OutputStreamWriter writer;

      writer = new OutputStreamWriter(os, charset);

      JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(writer);

      if (pretty) {
        JsonPrettyPrinter pp = new JsonPrettyPrinter();
        generator.setPrettyPrinter(pp);
      }

      //
      generator.writeStartArray();
      {
        List<D2ResponseMessageDoc> list = d2Response.getDocs();

        for (D2ResponseMessageDoc doc : list) {
          generator.writeStartObject();
          {
            generator.writeStringField("md5Lite", Md5Lite.toString(doc.getMd5Lite()));
            generator.writeNumberField("weight", doc.getWeight());

            generator.writeNumberField("indentValue", doc.getIndentValue());
            generator.writeNumberField("indentCount", doc.getIndentCount());
            generator.writeNumberField("indentPage", doc.getIndentPage());

            generator.writeNumberField("po", doc.getPo());
            generator.writeNumberField("ph", doc.getPh());
          }
          generator.writeEndObject();
        }
      }
      generator.writeEndArray();

      //
      generator.flush();
      writer.flush();

    } catch (UnsupportedEncodingException e) {
      logger.error("dump response failed.", e);
    } catch (IOException e) {
      logger.error("dump response failed.", e);
    } finally {

    }
  }
Exemple #10
0
 @Override
 public void onEvalEnd() {
   super.onEvalEnd();
   try {
     try {
       writeErrors();
       writeDebug();
     } finally {
       writer.writeEndObject();
       writer.flush();
     }
   } catch (IOException ex) {
     throw new OseeCoreException(ex);
   }
 }
Exemple #11
0
  @Override
  public void render(Map<String, ?> map, HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
    mapper.getSerializationConfig().setAnnotationIntrospector(introspector);

    // resp.setHeader("Content-Type", "text/html; charset=UTF-8"); // "application/json");

    JsonGenerator generator =
        mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);

    ObjectNode json = mapper.valueToTree(map);
    // json.put("success", true);
    mapper.writeTree(generator, json);
    // mapper.writeValue(generator, ret);
    generator.flush();
  }
 /**
  * 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();
 }
  private void _testBean(Class clazz, Object bean) throws Exception {
    Map<String, Object> props =
        JSONHelper.createPropertiesForJaxbContext(Collections.<String, Object>emptyMap());
    Class[] classes = new Class[] {clazz};

    JAXBContext ctx = JAXBContext.newInstance(classes, props);

    JsonFactory factory = new JsonFactory();
    Writer osWriter = new OutputStreamWriter(System.out);
    JsonGenerator g;

    g = factory.createJsonGenerator(osWriter);

    Marshaller marshaller = ctx.createMarshaller();
    marshaller.marshal(bean, new Stax2JacksonWriter(g, clazz, ctx));

    g.flush();
    System.out.println("");
  }
 public void writeJson(JsonGenerator g) throws JsonGenerationException, IOException {
   g.writeStartObject();
   g.writeBooleanField(SUCCESS, success);
   g.writeStringField(MESSAGE, message);
   g.writeArrayFieldStart(DATA);
   if (null != list && !list.isEmpty()) {
     for (T model : list) {
       // write model data
       g.writeStartObject();
       g.writeStringField("key", model.getKey());
       g.writeStringField("label", model.getLabel());
       g.writeEndObject();
     }
   }
   g.writeEndArray();
   // write model data end
   g.writeEndObject();
   g.flush();
   g.close();
 }
 @Override
 public void write(Property prop, JsonGenerator jg) throws IOException {
   writeProperty(jg, prop);
   jg.flush();
 }
Exemple #16
-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();
  }