Java Code Examples for javax.json.stream.JsonGenerator#writeStartObject()

The following examples show how to use javax.json.stream.JsonGenerator#writeStartObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonSecurityMessage.java    From aceql-http with GNU Lesser General Public License v2.1 7 votes vote down vote up
/**
    * 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;
}

   }
 
Example 2
Source File: HalEntityWrapperJsonbSerializer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(HalEntityWrapper wrapper, JsonGenerator generator, SerializationContext context) {
    Marshaller marshaller = (Marshaller) context;
    Object entity = wrapper.getEntity();

    if (!marshaller.addProcessedObject(entity)) {
        throw new RuntimeException("Cyclic dependency when marshaling an object");
    }

    try {
        generator.writeStartObject();
        ClassModel classModel = marshaller.getMappingContext().getOrCreateClassModel(entity.getClass());

        for (PropertyModel property : classModel.getSortedProperties()) {
            if (property.isReadable()) {
                context.serialize(property.getWriteName(), property.getValue(entity), generator);
            }
        }

        writeLinks(entity, generator, context);
        generator.writeEnd();
    } finally {
        marshaller.removeProcessedObject(entity);
    }
}
 
Example 3
Source File: InstanceBodyWriterTools.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private static void writeLeaf(List<PartLink> currentPath, List<Integer> copyInstanceIds, PartIteration partI, Matrix4d combinedMatrix, JsonGenerator jg) {
    String partIterationId = partI.toString();
    List<InstanceAttributeDTO> attributes = new ArrayList<>();
    for (InstanceAttribute attr : partI.getInstanceAttributes()) {
        attributes.add(mapper.map(attr, InstanceAttributeDTO.class));
    }

    jg.writeStartObject();
    jg.write("id", Tools.getPathInstanceAsString(currentPath, copyInstanceIds));
    jg.write("partIterationId", partIterationId);
    jg.write("path", Tools.getPathAsString(currentPath));

    writeMatrix(combinedMatrix, jg);
    writeGeometries(partI.getSortedGeometries(), jg);
    writeAttributes(attributes, jg);

    jg.writeEnd();
    jg.flush();
}
 
Example 4
Source File: JsonDocumentContainer.java    From iaf with Apache License 2.0 6 votes vote down vote up
protected void generate(JsonGenerator g, String key, Object item) {
	if (item==null) {
		if (key!=null) g.writeNull(key); else g.writeNull(); 
	} else if (item instanceof String) {
		if (key!=null) g.write(key,(String)item); else g.write((String)item); 
	} else if (item instanceof Map) {
		if (key!=null) g.writeStartObject(key); else g.writeStartObject(); 
		for (Entry<String,Object> entry:((Map<String,Object>)item).entrySet()) {
			generate(g, entry.getKey(), entry.getValue());
		}
		g.writeEnd();
	} else if (item instanceof List) {
		if (key!=null) g.writeStartArray(key); else g.writeStartArray(); 
		for (Object subitem:(List)item) {
			generate(g, null, subitem);
		}
		g.writeEnd();
	} else {
		throw new NotImplementedException("cannot handle class ["+item.getClass().getName()+"]");
	}
}
 
Example 5
Source File: JSONDomainFacade.java    From jcypher with Apache License 2.0 6 votes vote down vote up
/**
 * Answer a JSON representation of the domain model
 * @return
 */
public String getDomainModel() {
	DomainModel model = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDomainModel();
	StringWriter sw = new StringWriter();
	JsonGenerator generator;
	if (this.prettyFormat != Format.NONE) {
		JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory();
		generator = gf.createGenerator(sw);
	} else
		generator = Json.createGenerator(sw);
	
	generator.writeStartObject();
	generator.write("domainName", model.getDomainName());
	writeModel(model, generator);
	generator.writeEnd();

	generator.flush();
	return sw.toString();
}
 
Example 6
Source File: JSONConverter.java    From jcypher with Apache License 2.0 6 votes vote down vote up
private void writeQuery(RecordedQuery query, JsonGenerator generator) {
	generator.write(GENERIC, query.isGeneric());
	if (query.getAugmentations() != null) {
		generator.writeStartArray(AUGMENTATIONS);
		Iterator<Entry<String, String>> it = query.getAugmentations().entrySet().iterator();
		while(it.hasNext()) {
			Entry<String, String> entry = it.next();
			generator.writeStartObject();
			generator.write(KEY, entry.getKey());
			generator.write(VALUE, entry.getValue());
			generator.writeEnd();
		}
		generator.writeEnd();
	}
	generator.writeStartArray(STATEMENTS);
	for(Statement s : query.getStatements()) {
		writeStatement(s, generator);
	}
	generator.writeEnd();
}
 
Example 7
Source File: CadfMapItem.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public static void generate(CadfMapItem obj, JsonGenerator generator)
        throws IOException {
    generator.writeStartObject();

    if (obj.getKey() != null) {
        generator.write("key", obj.getKey());
    }

    if (obj.getValue() != null) {
        Object tmpObj = obj.getValue();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream objStream = new ObjectOutputStream(baos);) {
            objStream.writeObject(tmpObj);
            generator.write("value",
                    java.util.Base64.getEncoder().encodeToString(baos.toByteArray()));
        }
    }

    generator.writeEnd();
}
 
Example 8
Source File: JSONWriter.java    From jcypher with Apache License 2.0 6 votes vote down vote up
private static void writeStatements(Statement[] statements, JsonGenerator generator) {
	generator.writeStartArray("statements");
	for (Statement statement : statements) {
		generator.writeStartObject();
		writeQuery("statement", statement.cypher, statement.context, generator);
		if (ContextAccess.getResultDataContents( statement.context).size() > 0) {
			generator.writeStartArray("resultDataContents");
			for (String contentDescription : ContextAccess.getResultDataContents( statement.context)) {
				generator.write(contentDescription);
			}
			generator.writeEnd();
		}
		generator.writeEnd();
	}
	generator.writeEnd();
}
 
Example 9
Source File: CadfAttachment.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void generate(CadfAttachment obj, JsonGenerator generator)
        throws IOException {
    // If the CADF attachment is null, then simply skip it.
    if (obj == null) {
        return;
    }
    generator.writeStartObject();

    if (obj.getName() != null) {
        generator.write("name", obj.getName());
    }

    if (obj.getContentType() != null) {
        generator.write("contentType", obj.getContentType());
    }

    if (obj.getContent() != null) {
        Object tmpObj = obj.getContent();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream objStream = new ObjectOutputStream(baos);) {
            objStream.writeObject(tmpObj);
            generator.write("content",
                    java.util.Base64.getEncoder().encodeToString(baos.toByteArray()));
        }
    }

    generator.writeEnd();
}
 
Example 10
Source File: CadfMeasurement.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void generate(CadfMeasurement obj, JsonGenerator generator)
        throws IOException {
    if (obj == null) {
        return;
    }
    generator.writeStartObject();

    if (obj.getResult() != null) {
        Object tmpObj = obj.getResult();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream objStream = new ObjectOutputStream(baos);) {
            objStream.writeObject(tmpObj);
            generator.write("result",
                    java.util.Base64.getEncoder().encodeToString(baos.toByteArray()));
        }
    }

    if (obj.getMetricId() != null) {
        generator.write("metricId", obj.getMetricId());
    }

    if (obj.getMetric() != null) {
        generator.writeStartObject("metric");
        CadfMetric.Writer.generate(obj.getMetric(), generator);
        generator.writeEnd();
    }

    if (obj.getCalculatedBy() != null) {
        generator.writeStartObject("calculatedBy");
        CadfResource.Writer.generate(obj.getCalculatedBy(), generator);
        generator.writeEnd();
    }

    if (obj.getCalculatedById() != null) {
        generator.write("calculatedById", obj.getCalculatedById());
    }

    generator.writeEnd();
}
 
Example 11
Source File: JSONConverter.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private void writeLiteral(Object val, JsonGenerator generator) {
	boolean isParam = val instanceof iot.jcypher.domainquery.ast.Parameter;
	if (isParam) {
		generator.write(TYPE_KEY, PARAM);
		generator.write(PARAM_NAME, ((iot.jcypher.domainquery.ast.Parameter)val).getName());
		val = ((iot.jcypher.domainquery.ast.Parameter)val).getValue();
	} else
		generator.write(TYPE_KEY, LITERAL);
	if (val != null) {
		boolean isColl = Collection.class.isAssignableFrom(val.getClass());
		boolean isArray = val.getClass().isArray();
		if (isArray) {
			StringBuilder sb = new StringBuilder();
			sb.append(ARRAY_PREF);
			sb.append(val.getClass().getComponentType().getName());
			sb.append(ARRAY_POST);
			generator.write(LITERAL_TYPE, sb.toString());
		} else
			generator.write(LITERAL_TYPE, val.getClass().getName());
		if (isArray || isColl) {
			generator.writeStartArray(LITERAL_VALUE);
			if (isColl) {
				Iterator<?> it = ((Collection<?>)val).iterator();
				while(it.hasNext()) {
					generator.writeStartObject();
					writeLiteral(it.next(), generator);
					generator.writeEnd();
				}
			} else { // an array
				for (int i = 0; i < Array.getLength(val); i++) {
					generator.writeStartObject();
					writeLiteral(Array.get(val, i), generator);
					generator.writeEnd();
				}
			}
			generator.writeEnd();
		} else
			generator.write(LITERAL_VALUE, val.toString());
	}
}
 
Example 12
Source File: HalCollectionWrapperJsonbSerializer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(HalCollectionWrapper wrapper, JsonGenerator generator, SerializationContext context) {
    generator.writeStartObject();
    writeEmbedded(wrapper, generator, context);
    writeLinks(wrapper, generator, context);
    generator.writeEnd();
}
 
Example 13
Source File: JSONDomainFacade.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private void writeField(DOField f, JsonGenerator generator) {
	generator.writeStartObject();
	generator.write("name", f.getName());
	generator.write("type", f.getTypeName());
	String ct = f.getComponentTypeName();
	if (ct != null) {
		generator.write("componentType", ct);
		generator.write("buildIn", DomainModel.isBuildIn(ct));
	} else
		generator.write("buildIn", f.isBuidInType());
	generator.writeEnd();
}
 
Example 14
Source File: CadfReporterStep.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void generate(CadfReporterStep obj, JsonGenerator generator)
        throws IOException {
    // If the CADF reporter step is null, then simply skip it.
    if (obj == null) {
        return;
    }
    generator.writeStartObject();

    if (obj.getReporter() != null) {
        generator.writeStartObject("reporter");
        CadfResource.Writer.generate(obj.getReporter(), generator);
        generator.writeEnd();
    }

    if (obj.getReporterId() != null) {
        generator.write("reporterId", obj.getReporterId());
    }

    if (obj.getReporterTime() != null) {
        generator.write("reporterTime", formatterFullTimestamp.format(obj.getReporterTime()));
    }

    if (obj.getRole() != null) {
        generator.write("role", obj.getRole().toString());
    }

    //Attachments
    if (obj.getAttachments() != null) {
        generator.writeStartArray("attachments");
        for (CadfAttachment item : obj.getAttachments()) {
            CadfAttachment.Writer.generate(item, generator);
        }
        generator.writeEnd();
    }
    generator.writeEnd();
}
 
Example 15
Source File: BookSerializer.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Override
public void serialize(Book book, JsonGenerator generator, SerializationContext ctx) {
    generator.writeStartObject();
    generator.write("id", "QWE-123-RTS");
    generator.write("title", book.getTitle());
    generator.write("firstName", book.getAuthor().split(" ")[0]);
    generator.write("lastName", book.getAuthor().split(" ")[1]);
    generator.writeEnd();
}
 
Example 16
Source File: EventJsonbSerializer.java    From scalable-coffee-shop with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final CoffeeEvent event, final JsonGenerator generator, final SerializationContext ctx) {
    generator.writeStartObject();
    generator.write("class", event.getClass().getCanonicalName());
    ctx.serialize("data", event, generator);
    generator.writeEnd();
    generator.close();
}
 
Example 17
Source File: Index.java    From FHIR with Apache License 2.0 5 votes vote down vote up
private void write(JsonGenerator generator, Entry entry) {
    generator.writeStartObject();
    generator.write("filename", entry.getFileName());
    generator.write("resourceType", entry.getResourceType());
    generator.write("id", entry.getId());
    generator.write("url", entry.getUrl());
    generator.write("version", entry.getVersion());
    if (entry.getKind() != null) {
        generator.write("kind", entry.getKind());
    }
    if (entry.getType() != null) {
        generator.write("type", entry.getType());
    }
    generator.writeEnd();
}
 
Example 18
Source File: ModelWithSerializerAndDeserializerOnField.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(Inner obj, JsonGenerator gen, SerializationContext ctx) {
    gen.writeStartObject();
    gen.write("someValue", "unchangeable");
    gen.writeEnd();
}
 
Example 19
Source File: JSONWriter.java    From jcypher with Apache License 2.0 4 votes vote down vote up
public static String toJSON(PreparedQueries preparedQueries) {
	if (preparedQueries.hasdSLParams()) { // parameters part of json must be recreated
		WriterContext context = new WriterContext();
		List<PreparedQuery> prepQs = preparedQueries.getPreparedQueries();
		if (prepQs.isEmpty())
			return new String();
		PreparedQuery prepQ = prepQs.get(0);
		PQContext pqContext = prepQ.getContext();
		List<Statement> statements = new ArrayList<Statement>(prepQs.size());
		Format cf = pqContext.cypherFormat;
		pqContext.fillContext(context);
		context.cypherFormat = Format.NONE;
		// needed for multiple statements
		ContextAccess.setUseTransactionalEndpoint(true, context);
		for (PreparedQuery pq : prepQs) {
			WriterContext ctxt = new WriterContext();
			PQContext pqCtxt = pq.getContext();
			pqCtxt.fillContext(ctxt);
			
			String cypher = pq.getCypher();
			statements.add(new Statement(ctxt, cypher));
		}
		context.cypherFormat = cf;
		
		StringWriter sw = new StringWriter();
		JsonGenerator generator;
		if (context.cypherFormat != Format.NONE) {
			JsonGeneratorFactory gf = getPrettyGeneratorFactory();
			generator = gf.createGenerator(sw);
		} else
			generator = Json.createGenerator(sw);
		
		generator.writeStartObject();
		Statement[] statementsArray = statements.toArray(new Statement[statements.size()]);
		writeStatements(statementsArray, generator);
		generator.writeEnd();

		generator.flush();
		context.buffer.append(sw.getBuffer());
		preparedQueries.setJson(context.buffer.toString());
		return preparedQueries.getJson();
	} else
		return preparedQueries.getJson();
}
 
Example 20
Source File: Data.java    From NOVA-Core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void writeData(JsonGenerator writer, Data data, String key) {
	boolean isCollection;
	if (data.containsKey("isCollection") && Boolean.TRUE.equals(data.get("isCollection"))) {
		isCollection = true;
		if (key == null)
			writer.writeStartArray();
		else
			writer.writeStartArray(key);
	} else {
		isCollection = false;
		if (key == null)
			writer.writeStartObject();
		else
			writer.writeStartObject(key);
	}

	if (!isCollection)
		data.forEach((k, v) -> {
			if (v instanceof Data) {
				writeData(writer, (Data) v, k);
			} else if (v instanceof Number) {
				if (v instanceof Byte) {
					writer.write(k, (Byte) v);
				} else if (v instanceof Short) {
					writer.write(k, (Short) v);
				} else if (v instanceof Integer) {
					writer.write(k, (Integer) v);
				} else if (v instanceof Long) {
					writer.write(k, (Long) v);
				} else if (v instanceof Float) {
					writer.write(k, (Float) v);
				} else if (v instanceof Double) {
					writer.write(k, (Double) v);
				} else if (v instanceof BigInteger) {
					writer.write(k, (BigInteger) v);
				} else if (v instanceof BigDecimal) {
					writer.write(k, (BigDecimal) v);
				}
			} else {
				if (v instanceof Boolean) {
					writer.write(k, (Boolean) v);
				} else if (v instanceof Character) {
					writer.write(k, (Character) v);
				} else if (v instanceof String) {
					writer.write(k, (String) v);
				} else if (v instanceof JsonValue) {
					writer.write(k, (JsonValue) v);
				}
			}
		});
	else
		LongStream.range(0, data.size()).mapToObj(l -> data.get(Long.toUnsignedString(l))).forEachOrdered(v -> {
			if (v instanceof Data) {
				writeData(writer, (Data) v, null);
			} else if (v instanceof Number) {
				if (v instanceof Byte) {
					writer.write((Byte) v);
				} else if (v instanceof Short) {
					writer.write((Short) v);
				} else if (v instanceof Integer) {
					writer.write((Integer) v);
				} else if (v instanceof Long) {
					writer.write((Long) v);
				} else if (v instanceof Float) {
					writer.write((Float) v);
				} else if (v instanceof Double) {
					writer.write((Double) v);
				} else if (v instanceof BigInteger) {
					writer.write((BigInteger) v);
				} else if (v instanceof BigDecimal) {
					writer.write((BigDecimal) v);
				}
			} else {
				if (v instanceof Boolean) {
					writer.write((Boolean) v);
				} else if (v instanceof Character) {
					writer.write((Character) v);
				} else if (v instanceof String) {
					writer.write((String) v);
				} else if (v instanceof JsonValue) {
					writer.write((JsonValue) v);
				}
			}
		});

	writer.writeEnd();
}