Java 类javax.json.stream.JsonGenerator 实例源码

项目:continuous-performance-evaluation    文件:RealtimeCargoTrackingService.java   
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) {
    Writer writer = new StringWriter();

    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator
                .writeStartObject()
                .write("trackingId", cargo.getTrackingId().getIdString())
                .write("origin", cargo.getOrigin().getName())
                .write("destination", cargo.getRouteSpecification().getDestination().getName())
                .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName())
                .write("transportStatus", cargo.getDelivery().getTransportStatus().toString())
                .writeEnd();
    }

    String jsonValue = writer.toString();

    for (Session session : sessions) {
        try {
            session.getBasicRemote().sendText(jsonValue);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Unable to publish WebSocket message", ex);
        }
    }

}
项目:aceql-http    文件:JsonOkReturn.java   
/**
    * Returns a name and a value after the OK
    * @return just OK
    */
   public static String build(String name, String value) {

if (name == null) {
    throw new NullPointerException("name is null");
}
if (value == null) {
    throw new NullPointerException("value is null");
}

JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING);

StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);

gen.writeStartObject()
.write("status", "OK")    
.write(name, value)
.writeEnd();
gen.close();

return sw.toString();
   }
项目:aceql-http    文件:JsonOkReturn.java   
/**
    * Build a Json with name and values rom the passed map
    * @param namesAndValues the map of (name, value) to add to the JsonGenerator
    * @return
    */
   public static String build(Map<String, String> namesAndValues) {

if (namesAndValues == null) {
    throw new NullPointerException("namesAndValues is null");
}

JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING);

StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);

gen.writeStartObject()
.write("status", "OK")  ;

for (Map.Entry<String, String> entry : namesAndValues.entrySet()) {

    // trace(entry.getKey() + "/" + entry.getValue());
    gen.write(entry.getKey(), entry.getValue());
}

gen.writeEnd();
gen.close();

return sw.toString();
   }
项目:aceql-http    文件:JsonSecurityMessage.java   
/**
    * Builds a security error message in JSON format for Statements
    * @param sqlOrder
    * @param errorMessage
    * @param doPrettyPrinting
    * @return
    */
   public static String statementNotAllowedBuild(String sqlOrder, String errorMessage, boolean doPrettyPrinting) {

try {
    JsonGeneratorFactory jf = JsonUtil
        .getJsonGeneratorFactory(doPrettyPrinting);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    JsonGenerator gen = jf.createGenerator(out);
    gen.writeStartObject();
    gen.write(Tag.PRODUCT_SECURITY, errorMessage);
    gen.write("SQL order", sqlOrder);
    gen.writeEnd();
    gen.close();
    return out.toString("UTF-8");
} catch (Exception e) {
    String returnString = Tag.PRODUCT_SECURITY + " " + errorMessage
        + " " + sqlOrder;
    return returnString;
}

   }
项目:tap17-muggl-javaee    文件:StatusEndpoint.java   
private static String jsonStudentList(List<Student> students) {

        StringWriter swriter = new StringWriter();
        try (JsonGenerator gen = Json.createGenerator(swriter)) {
            gen.writeStartObject();
            gen.write("type", "list");
            gen.writeStartArray("body");
            for (Student student : students) {
                gen.writeStartObject();
                gen.write("name", student.getName());
                gen.write("status", student.getStatus().toString());
                gen.writeEnd();
            }
            gen.writeEnd();
            gen.writeEnd();
        }

        return swriter.toString();
    }
项目:cookjson    文件:TextJsonParserTest.java   
void testFile (String f, int buffType) throws IOException
{
    File file = new File (f.replace ('/', File.separatorChar));

    StringWriter out1 = new StringWriter ();
    TextJsonParser p1 = getJsonParser (file, buffType);
    TextJsonGenerator g1 = new TextJsonGenerator (out1);
    Utils.convert (p1, g1);
    p1.close ();
    g1.close ();

    StringWriter out2 = new StringWriter ();
    JsonProvider provider = new org.glassfish.json.JsonProviderImpl ();
    JsonParser p2 = provider.createParser (new FileInputStream (file));
    JsonGenerator g2 = new TextJsonGenerator (out2);
    Utils.convert (p2, g2);
    p2.close ();
    g2.close ();

    Assert.assertEquals (out2.toString (), out1.toString ());
}
项目:PrOfESSOS    文件:TestStepLogger.java   
private String formatBody(String contentType, String body) {
    if (body != null && contentType != null) {
        if (contentType.startsWith("application/json")) {
            try {
                JsonStructure json = Json.createReader(new StringReader(body)).read();
                StringWriter w = new StringWriter();
                HashMap<String, Object> p = new HashMap<>();
                p.put(JsonGenerator.PRETTY_PRINTING, true);
                Json.createWriterFactory(p).createWriter(w).write(json);
                return w.toString();
            } catch (JsonException ex) {
                return body;
            }
        } else {
            return body;
        }
    } else {
        return null;
    }
}
项目:cookjson    文件:JsonParserFactoryTest.java   
void testInputStream (String fileName, HashMap<String, Object> config) throws IOException
{
    File file = new File (fileName.replace ('/', File.separatorChar));

    JsonProvider provider1 = new CookJsonProvider ();

    JsonParserFactory f1 = provider1.createParserFactory (config);

    StringWriter out1 = new StringWriter ();
    JsonParser p1 = f1.createParser (new FileInputStream (file));
    JsonGenerator g1 = new TextJsonGenerator (out1);
    Utils.convert (p1, g1);
    p1.close ();
    g1.close ();

    StringWriter out2 = new StringWriter ();
    JsonProvider provider2 = new org.glassfish.json.JsonProviderImpl ();
    JsonParserFactory f2 = provider2.createParserFactory (config);
    JsonParser p2 = f2.createParser (new FileInputStream (file));
    JsonGenerator g2 = new TextJsonGenerator (out2);
    Utils.convert (p2, g2);
    p2.close ();
    g2.close ();

    Assert.assertEquals (out1.toString (), out2.toString ());
}
项目:cookjson    文件:BinaryTest.java   
@Test
public void testJsonValueJsonHex () throws IOException
{
    File file1 = new File ("../tests/data/binary.bson".replace ('/', File.separatorChar));
    File file2 = new File ("../tests/data/binary2.json".replace ('/', File.separatorChar));

    CookJsonProvider provider = new CookJsonProvider ();
    HashMap<String, Object> bsonConfig = new HashMap<String, Object> ();
    bsonConfig.put (CookJsonProvider.FORMAT, CookJsonProvider.FORMAT_BSON);
    bsonConfig.put (CookJsonProvider.ROOT_AS_ARRAY, Boolean.TRUE);

    HashMap<String, Object> jsonConfig = new HashMap<String, Object> ();
    jsonConfig.put (CookJsonProvider.BINARY_FORMAT, CookJsonProvider.BINARY_FORMAT_HEX);

    File jsonFile = testFolder.newFile ();
    CookJsonParser p = (CookJsonParser) provider.createParserFactory (bsonConfig).createParser (new FileInputStream (file1));
    p.next ();
    JsonValue value = p.getValue ();
    JsonGenerator g = provider.createGeneratorFactory (jsonConfig).createGenerator (new FileOutputStream (jsonFile));
    g.write (value);
    p.close ();
    g.close ();

    FileAssert.assertBinaryEquals (file2, jsonFile);
}
项目:cookjson    文件:BsonGenerator.java   
@Override
    public JsonGenerator write (JsonValue value)
    {
//      assert Debug.debug ("WRITE: JsonValue");
        if (m_state != GeneratorState.IN_ARRAY)
        {
            if (m_state == GeneratorState.INITIAL)
            {
                if (!(value instanceof JsonArray) &&
                    !(value instanceof JsonObject))
                    throw new JsonGenerationException (ErrorMessage.invalidContext);
            }
            else
                throw new JsonGenerationException (ErrorMessage.notInArrayContext);
        }
        return writeValue (value);
    }
项目:ipst    文件:SecurityRulesChangeMessage.java   
@Override
public void toJson(JsonGenerator generator) {
    generator.write("workflowId", workflowId);
    generator.writeStartArray("ruleIds");
    for (RuleId ruleId : ruleIds) {
        generator.writeStartObject();
        generator.write("attributeSet", ruleId.getAttributeSet().toString());
        generator.writeStartObject("securityIndexId");
        generator.write("contingencyId", ruleId.getSecurityIndexId().getContingencyId());
        generator.writeStartObject("securityIndexType");
        generator.write("name", ruleId.getSecurityIndexId().getSecurityIndexType().name());
        generator.write("label", ruleId.getSecurityIndexId().getSecurityIndexType().getLabel());
        generator.write("dynamic", ruleId.getSecurityIndexId().getSecurityIndexType().isDynamic());
        generator.writeEnd();
        generator.writeEnd();
        generator.writeEnd();
    }
    generator.writeEnd();
}
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator write (BigInteger value)
    {
//      assert Debug.debug ("WRITE: VALUE_NUMBER: (BigInteger)" + value);
        if (m_state != GeneratorState.IN_ARRAY)
            throw new JsonGenerationException (ErrorMessage.notInArrayContext);
        try
        {
            writeComma ();
            w (value.toString ());
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
        return this;
    }
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator write (BigDecimal value)
    {
//      assert Debug.debug ("WRITE: VALUE_NUMBER: (BigDecimal)" + value);
        if (m_state != GeneratorState.IN_ARRAY)
            throw new JsonGenerationException (ErrorMessage.notInArrayContext);
        try
        {
            writeComma ();
            w (value.toString ());
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
        return this;
    }
项目:ipst    文件:SamplesSynthesisMessage.java   
@Override
public void toJson(JsonGenerator generator) {
    generator.write("workflowId", workflowId);
    generator.writeStartArray("samplesSynthesis");
    for (SampleSynthesis sample : samples) {
        generator.writeStartObject()
                    .write("id", sample.getId())
                    .writeStartObject("lastTaskEvent")
                        .write("type", sample.getLastTaskEvent().getTaskType().name())
                        .write("status", sample.getLastTaskEvent().getTaskStatus().name());
        if (sample.getLastTaskEvent().getFailureReason() != null) {
            generator.write("failureReason", sample.getLastTaskEvent().getFailureReason());
        }
        generator.writeEnd()
                .writeEnd();
    }
    generator.writeEnd();
}
项目:gluon-samples    文件:FrontHandler.java   
@RequestMapping(value = "whiteboard", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + "; " + CHARSET)
public String whiteboard() {
    try (StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) {
        jsonGenerator.writeStartArray();
        service.listItems().stream()
                .map(item -> Json.createObjectBuilder()
                        .add("id", item.getId())
                        .add("title", item.getTitle())
                        .add("creationDate", item.getCreationDate())
                        .build())
                .forEach(jsonGenerator::write);
        jsonGenerator.writeEnd();
        jsonGenerator.close();
        return stringWriter.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "[]";
}
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator writeNull ()
    {
//      assert Debug.debug ("WRITE: VALUE_NULL");
        if (m_state != GeneratorState.IN_ARRAY)
            throw new JsonGenerationException (ErrorMessage.notInArrayContext);
        try
        {
            writeComma ();
            w ("null");
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
        return this;
    }
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator writeEnd ()
    {
        if (m_state == GeneratorState.END)
            throw new JsonGenerationException (ErrorMessage.invalidContext);
        boolean isArray = popState ();
//      assert Debug.debug ("WRITE: " + (isArray ? "END_ARRAY" : "END_OBJECT"));
        m_first = false;
        char ch = isArray ? ']' : '}';
        try
        {
            w (ch);
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
        return this;
    }
项目:eplmp    文件:InstanceBodyWriterTools.java   
private static void writeGeometries(List<Geometry> files, JsonGenerator jg) {
    jg.write("qualities", files.size());

    if (!files.isEmpty()) {
        Geometry geometry = files.get(0);
        jg.write("xMin", geometry.getxMin());
        jg.write("yMin", geometry.getyMin());
        jg.write("zMin", geometry.getzMin());
        jg.write("xMax", geometry.getxMax());
        jg.write("yMax", geometry.getyMax());
        jg.write("zMax", geometry.getzMax());
    }

    jg.writeStartArray("files");

    for (Geometry g : files) {
        jg.writeStartObject();
        jg.write("fullName", "api/files/" + g.getFullName());
        jg.writeEnd();
    }
    jg.writeEnd();
}
项目:cookjson    文件:BinaryTest.java   
@Test
public void testJsonHex () throws IOException
{
    File file1 = new File ("../tests/data/binary.bson".replace ('/', File.separatorChar));
    File file2 = new File ("../tests/data/binary2.json".replace ('/', File.separatorChar));

    CookJsonProvider provider = new CookJsonProvider ();
    HashMap<String, Object> bsonConfig = new HashMap<String, Object> ();
    bsonConfig.put (CookJsonProvider.FORMAT, CookJsonProvider.FORMAT_BSON);
    bsonConfig.put (CookJsonProvider.ROOT_AS_ARRAY, Boolean.TRUE);

    HashMap<String, Object> jsonConfig = new HashMap<String, Object> ();
    jsonConfig.put (CookJsonProvider.BINARY_FORMAT, CookJsonProvider.BINARY_FORMAT_HEX);

    File jsonFile = testFolder.newFile ();
    JsonParser p = provider.createParserFactory (bsonConfig).createParser (new FileInputStream (file1));
    JsonGenerator g = provider.createGeneratorFactory (jsonConfig).createGenerator (new FileOutputStream (jsonFile));
    Utils.convert (p, g);
    p.close ();
    g.close ();

    FileAssert.assertBinaryEquals (file2, jsonFile);
}
项目:albaum    文件:Log.java   
public void commitFact(final Fact f, final Change.Type ct, final JsonGenerator json, final boolean recursive) {     
    json
        .write("key", f.key)
        .write("createdAt", context.formatJS(f.createdAt));

    switch(ct) {
        case DELETE: {
            json.write("deleted", true);
            break;
        }           
        case INSERT: {
            json.write("version", f.version);   
            if (!recursive || f.previousVersion == null) {
                json.writeNull("previousVersion");
            } else {
                json.writeStartObject("previousVersion");
                commitFact(f.previousVersion, ct, json, false);
                json.writeEnd();
            }
            break;
        }
        default:
            throw new RuntimeException("Unknown change type: " + ct);
    }
}
项目:pragmatic-microservices-lab    文件:RealtimeCargoTrackingService.java   
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) {
    Writer writer = new StringWriter();

    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator
                .writeStartObject()
                .write("trackingId", cargo.getTrackingId().getIdString())
                .write("origin", cargo.getOrigin().getName())
                .write("destination", cargo.getRouteSpecification().getDestination().getName())
                .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName())
                .write("transportStatus", cargo.getDelivery().getTransportStatus().toString())
                .writeEnd();
    }

    String jsonValue = writer.toString();

    for (Session session : sessions) {
        try {
            session.getBasicRemote().sendText(jsonValue);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Unable to publish WebSocket message", ex);
        }
    }

}
项目:cookjson    文件:TextJsonGeneratorTest.java   
void testFile (String f) throws IOException
{
    File file = new File (f.replace ('/', File.separatorChar));

    JsonProvider provider = new org.glassfish.json.JsonProviderImpl ();

    StringWriter out1 = new StringWriter ();
    JsonParser p1 = provider.createParser (new FileInputStream (file));
    TextJsonGenerator g1 = new TextJsonGenerator (out1);
    Utils.convert (p1, g1);
    p1.close ();
    g1.close ();

    StringWriter out2 = new StringWriter ();
    JsonParser p2 = provider.createParser (new FileInputStream (file));
    JsonGenerator g2 = provider.createGenerator (out2);
    Utils.convert (p2, g2);
    p2.close ();
    g2.close ();

    Assert.assertEquals (out1.toString (), out2.toString ());
}
项目:pragmatic-microservices-lab    文件:RealtimeCargoTrackingService.java   
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) {
    Writer writer = new StringWriter();

    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator
                .writeStartObject()
                .write("trackingId", cargo.getTrackingId().getIdString())
                .write("origin", cargo.getOrigin().getName())
                .write("destination", cargo.getRouteSpecification().getDestination().getName())
                .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName())
                .write("transportStatus", cargo.getDelivery().getTransportStatus().toString())
                .writeEnd();
    }

    String jsonValue = writer.toString();

    for (Session session : sessions) {
        try {
            session.getBasicRemote().sendText(jsonValue);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Unable to publish WebSocket message", ex);
        }
    }

}
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator write (byte[] value)
    {
//      assert Debug.debug ("WRITE: VALUE_STRING");
        if (m_state != GeneratorState.IN_ARRAY)
            throw new JsonGenerationException (ErrorMessage.notInObjectContext);
        try
        {
            writeComma ();
            if (m_binaryFormat == BinaryFormat.BINARY_FORMAT_BASE64)
                base64Encode (value);
            else
                hexEncode (value);
            return this;
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
    }
项目:Java-EE-7-Development-with-NetBeans-8    文件:JsonPStreamingApiBean.java   
public String generateJson() {
    StringWriter stringWriter = new StringWriter();
    try (JsonGenerator jsonGenerator
            = Json.createGenerator(stringWriter)) {
        jsonGenerator.writeStartObject().
                write("firstName", person.getFirstName()).
                write("middleName", person.getMiddleName()).
                write("lastName", person.getLastName()).
                write("gender", person.getGender()).
                write("age", person.getAge()).
                writeEnd();
    }

    setJsonStr(stringWriter.toString());
    return "generated_json";
}
项目:LevelEditor    文件:EditorWindow.java   
private void doSaveProject() {
  try {
    OutputStream fileStream = new FileOutputStream(projectFile);
    OutputStream bufferedStream = new BufferedOutputStream(fileStream);
    StringWriter stringWriter = new StringWriter();
    Map<String, Boolean> config = new HashMap<>();
    config.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriter writer = Json.createWriterFactory(config).createWriter(
               stringWriter);
    writer.writeObject(project.toJSON().build());
    writer.close();
    bufferedStream.write(stringWriter.toString().getBytes());
    bufferedStream.close();
  } catch (Exception ex) {
    Logger.getLogger(EditorWindow.class.getName()).log(Level.SEVERE, null, ex);
  }
}
项目:sonarqube-licensecheck    文件:License.java   
public static String createString(Collection<License> licenses)
{
    TreeSet<License> licenseSet = new TreeSet<>();
    licenseSet.addAll(licenses);

    StringWriter jsonString = new StringWriter();
    JsonGenerator generator = Json.createGenerator(jsonString);
    generator.writeStartArray();
    for (License license : licenseSet)
    {
        generator.writeStartObject();
        generator.write("name", license.getName());
        generator.write("identifier", license.getIdentifier());
        generator.write("status", license.getStatus());
        generator.writeEnd();
    }
    generator.writeEnd();
    generator.close();

    return jsonString.toString();
}
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator write (String name, BigDecimal value)
    {
//      assert Debug.debug ("WRITE: KEY_NAME: " + name);
//      assert Debug.debug ("WRITE: VALUE_NUMBER: (BigDecimal)" + value);
        if (m_state != GeneratorState.IN_OBJECT)
            throw new JsonGenerationException (ErrorMessage.notInObjectContext);
        try
        {
            writeName (name);
            w (value.toString ());
            return this;
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
    }
项目:cookjson    文件:TextJsonGenerator2Test.java   
void testFile (String f) throws IOException
{
    File file = new File (f.replace ('/', File.separatorChar));

    StringWriter out1 = new StringWriter ();
    CookJsonParser p1 = TextJsonConfigHandler.getJsonParser (new FileInputStream (file));
    p1.next ();
    JsonValue v = p1.getValue ();
    TextJsonGenerator g1 = new TextJsonGenerator (out1);
    g1.write (v);
    p1.close ();
    g1.close ();

    StringWriter out2 = new StringWriter ();
    CookJsonParser p2 = TextJsonConfigHandler.getJsonParser (new FileInputStream (file));
    JsonGenerator g2 = new TextJsonGenerator (out2);
    Utils.convert (p2, g2);
    p2.close ();
    g2.close ();

    // because JsonObject ordering is based on hash, we cannot directly
    // compare the output.  Instead, we compare the length.
    Assert.assertEquals (out1.toString ().length (), out2.toString ().length ());
}
项目:cookjson    文件:BinaryTest.java   
@Test
public void testJsonValueJson () throws IOException
{
    File file1 = new File ("../tests/data/binary.bson".replace ('/', File.separatorChar));
    File file2 = new File ("../tests/data/binary.json".replace ('/', File.separatorChar));

    CookJsonProvider provider = new CookJsonProvider ();
    HashMap<String, Object> bsonConfig = new HashMap<String, Object> ();
    bsonConfig.put (CookJsonProvider.FORMAT, CookJsonProvider.FORMAT_BSON);
    bsonConfig.put (CookJsonProvider.ROOT_AS_ARRAY, Boolean.TRUE);

    HashMap<String, Object> jsonConfig = new HashMap<String, Object> ();

    File jsonFile = testFolder.newFile ();
    CookJsonParser p = (CookJsonParser) provider.createParserFactory (bsonConfig).createParser (new FileInputStream (file1));
    p.next ();
    JsonValue value = p.getValue ();
    JsonGenerator g = provider.createGeneratorFactory (jsonConfig).createGenerator (new FileOutputStream (jsonFile));
    g.write (value);
    p.close ();
    g.close ();

    FileAssert.assertBinaryEquals (file2, jsonFile);
}
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator writeStartArray (String name)
    {
//      assert Debug.debug ("WRITE: KEY_NAME: " + name);
//      assert Debug.debug ("WRITE: START_ARRAY");
        if (m_state != GeneratorState.IN_OBJECT)
            throw new JsonGenerationException (ErrorMessage.notInObjectContext);
        try
        {
            writeName (name);
            w ('[');
            pushState (true);
            m_first = true;
            return this;
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
    }
项目:yasson    文件:JsonBinding.java   
/**
 * Propagates properties from JsonbConfig to JSONP generator / parser factories.
 *
 * @param jsonbConfig jsonb config
 * @return properties for JSONP generator / parser
 */
protected Map<String, ?> createJsonpProperties(JsonbConfig jsonbConfig) {
    //JSONP 1.0 actually ignores the value, just checks the key is present. Only set if JsonbConfig.FORMATTING is true.
    final Optional<Object> property = jsonbConfig.getProperty(JsonbConfig.FORMATTING);
    final Map<String, Object> factoryProperties = new HashMap<>();
    if (property.isPresent()) {
        final Object value = property.get();
        if (!(value instanceof Boolean)) {
            throw new JsonbException(Messages.getMessage(MessageKeys.JSONB_CONFIG_FORMATTING_ILLEGAL_VALUE));
        }
        if ((Boolean) value) {
            factoryProperties.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE);
        }
        return factoryProperties;
    }
    return factoryProperties;
}
项目:cookjson    文件:BOMTest.java   
private void testFile (Charset charset) throws IOException
{
    File file = new File ("../tests/data/types.json".replace ('/', File.separatorChar));

    CookJsonProvider provider = new CookJsonProvider ();
    ByteArrayOutputStream bos = new ByteArrayOutputStream ();
    JsonParser p = TextJsonConfigHandler.getJsonParser (new FileInputStream (file));
    JsonGenerator g = provider.createGeneratorFactory (new HashMap<String, Object> ()).createGenerator (bos, charset);
    Utils.convert (p, g);
    p.close ();
    g.close ();

    StringWriter sw = new StringWriter ();
    p = provider.createParser (new ByteArrayInputStream (bos.toByteArray ()));
    g = provider.createGenerator (sw);
    Utils.convert (p, g);
    p.close ();
    g.close ();

    Assert.assertEquals (Utils.getString (file), sw.toString ());
}
项目:cookjson    文件:BinaryTest.java   
@Test
public void testJson () throws IOException
{
    File file1 = new File ("../tests/data/binary.bson".replace ('/', File.separatorChar));
    File file2 = new File ("../tests/data/binary.json".replace ('/', File.separatorChar));

    CookJsonProvider provider = new CookJsonProvider ();
    HashMap<String, Object> bsonConfig = new HashMap<String, Object> ();
    bsonConfig.put (CookJsonProvider.FORMAT, CookJsonProvider.FORMAT_BSON);
    bsonConfig.put (CookJsonProvider.ROOT_AS_ARRAY, Boolean.TRUE);

    HashMap<String, Object> jsonConfig = new HashMap<String, Object> ();

    File jsonFile = testFolder.newFile ();
    JsonParser p = provider.createParserFactory (bsonConfig).createParser (new FileInputStream (file1));
    JsonGenerator g = provider.createGeneratorFactory (jsonConfig).createGenerator (new FileOutputStream (jsonFile));
    Utils.convert (p, g);
    p.close ();
    g.close ();

    FileAssert.assertBinaryEquals (file2, jsonFile);
}
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator write (int value)
    {
//      assert Debug.debug ("WRITE: VALUE_NUMBER: (int)" + value);
        if (m_state != GeneratorState.IN_ARRAY)
            throw new JsonGenerationException (ErrorMessage.notInArrayContext);
        try
        {
            writeComma ();
            wi (value);
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
        return this;
    }
项目:cookjson    文件:TextJsonGenerator.java   
@Override
    public JsonGenerator write (String name, String value)
    {
//      assert Debug.debug ("WRITE: KEY_NAME: " + name);
//      assert Debug.debug ("WRITE: VALUE_STRING");
        if (m_state != GeneratorState.IN_OBJECT)
            throw new JsonGenerationException (ErrorMessage.notInObjectContext);
        try
        {
            writeName (name);
            quote (value);
            return this;
        }
        catch (IOException ex)
        {
            throw new JsonGenerationException (ex.getMessage (), ex);
        }
    }
项目:AccessConverter    文件:AccessConverter.java   
public static void ExitJson(boolean pretyPrint) {
    JsonObjectBuilder json = Json.createObjectBuilder();

    if(result.length() == 0)
        result = "fail";

    json.add("result", result);
    if(outputFile != null)
        json.add("outputFile", outputFile.getAbsolutePath());

    if(logFile != null)
        json.add("logFile", logFile.getAbsolutePath());

    if(zipFile != null && zipFile.exists())
        json.add("zipFile", zipFile.getAbsolutePath());

    if(pretyPrint) {
        Map<String, Object> properties = new HashMap<>(1);
        properties.put(JsonGenerator.PRETTY_PRINTING, true);
        StringWriter stringWriter = new StringWriter();
        try (JsonWriter jsonWriter = Json.createWriterFactory(properties).createWriter(stringWriter)) {
            jsonWriter.write(json.build());
        }

        System.out.println(stringWriter.toString());
    } else         
        System.out.print(json.build().toString());
}
项目:AccessConverter    文件:JSONConverter.java   
public String getPrettyPrinted() {
    Map<String, Object> properties = new HashMap<String, Object>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    factory = Json.createBuilderFactory(properties);
    StringWriter stringWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriterFactory(properties).createWriter(stringWriter);
    jsonWriter.write(json.build());
    jsonWriter.close();
    return stringWriter.toString();
}
项目:NGSI-LD_Wrapper    文件:Ngsi2NGSILD.java   
public static void main(String[] args) {
    CEntity ent = new EntityImpl("urn:c3im:Test:abcde", "Test");

    CProperty propSt = new CPropertyImpl("testProperty", 45);
    propSt.setTimestamp("2017-10-10T12:00:00");

    CRelationship relSt = new CRelationshipImpl("testRel", "urn:c3im:Test2:abcdef");
    ent.addRelationship(relSt);
    ent.addProperty(propSt);

    CRelationship relst2 = new CRelationshipImpl("relOfProp",
            "urn:c3im:Test3:xxxxx");

    propSt.addProperty(new CPropertyImpl("timestamp",
            "2017-10-22T12:00:00","DateTime"));
    propSt.addRelationship(relst2);

    relSt.addProperty(new CPropertyImpl("propOfRel", "TestValue"));
    relSt.addProperty(new CPropertyImpl("timestamp",
            "2017-10-22T12:00:00","DateTime"));
    propSt.addRelationship(relst2);

    JsonObject obj = Ngsi2NGSILD.toNgsi(ent);

    JsonWriter writer = Json.createWriterFactory(
            Collections.singletonMap(
                    JsonGenerator.PRETTY_PRINTING,
                    true
            )
    ).createWriter(System.out);

    writer.writeObject(obj);
}
项目:Java-EE-8-Sampler    文件:BookSerializer.java   
@Override
public void serialize(Book book, JsonGenerator generator, SerializationContext ctx) {

    if (book != null) {
        generator.writeStartObject();
        ctx.serialize(book.getClass().getName(), book, generator);
        generator.writeEnd();
    } else {
        ctx.serialize(null, generator);
    }
}