List of usage examples for javax.json.stream JsonGenerator writeStartArray
JsonGenerator writeStartArray(String name);
From source file:edu.harvard.hms.dbmi.bd2k.irct.ws.rs.resultconverter.JSONTabularDataConverter.java
@Override public StreamingOutput createStream(final Result result) { StreamingOutput stream = new StreamingOutput() { @Override/*from w w w . jav a 2 s . c om*/ public void write(OutputStream outputStream) throws IOException, WebApplicationException { JsonGenerator jg = null; ResultSet rs = null; try { rs = (ResultSet) result.getData(); rs.load(result.getResultSetLocation()); Map<String, Object> properties = new HashMap<String, Object>(1); JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties); jg = jgf.createGenerator(outputStream); jg.writeStartObject(); //Start Object jg.writeStartArray("columns"); // Get columns for (Column column : rs.getColumns()) { jg.write(column.toJson()); } jg.writeEnd(); //End columns jg.writeStartArray("data"); rs.beforeFirst(); while (rs.next()) { jg.writeStartArray(); //Begin Row Array for (int columnIndex = 0; columnIndex < rs.getColumnSize(); columnIndex++) { String value = rs.getString(columnIndex); if (value != null) { jg.writeStartObject(); jg.write(rs.getColumn(columnIndex).getName(), rs.getString(columnIndex)); jg.writeEnd(); } } jg.writeEnd(); //End Row Array } jg.writeEnd(); //End data jg.writeEnd(); //End Full Object } catch (ResultSetException | PersistableException e) { log.info("Error creating JSON Stream: " + e.getMessage()); } finally { if (jg != null) { jg.close(); } if (rs != null && !rs.isClosed()) { try { rs.close(); } catch (ResultSetException e) { e.printStackTrace(); } } if (outputStream != null) { outputStream.close(); } } } }; return stream; }
From source file:iing.uabc.edu.mx.persistencia.util.JSON.java
private static void stringifyObject(JsonGenerator generator, BeanManager manager) { String keyName;/*from w w w. j a v a2 s . c om*/ Field[] fields = manager.getFields(); //Read every field and transform it to a json property string for (Field field : fields) { Class fieldType = manager.getType(field.getName()); keyName = field.getName(); Object value = manager.getProperty(keyName); System.out.println("KeyName: " + keyName); System.out.println("Valor " + keyName + ": " + value); if (value == null) { //Set to null the property generator.writeNull(keyName); continue; } //Is a String if (fieldType == String.class) { generator.write(keyName, String.valueOf(value)); } //Is a Date else if (fieldType == Date.class) { String date = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(value); generator.write(keyName, date); } //Is a integer else if (fieldType == Integer.class || fieldType == Integer.TYPE) { generator.write(keyName, (int) value); } //Is a double else if (fieldType == Double.class || fieldType == Double.TYPE) { generator.write(keyName, (double) value); } //Is boolean else if (fieldType == Boolean.class || fieldType == Boolean.TYPE) { generator.write(keyName, (boolean) value); } //Is a collection else if (value instanceof Collection) { Class elementClass = manager.getCollectionElementType(keyName); System.out.println("Nueva Colleccion [] de clase: " + elementClass.getSimpleName()); generator.writeStartArray(keyName); //Create new collection manager with the given class CollectionManager collectionManager = new CollectionManager((Collection) value, elementClass); stringifyArray(generator, collectionManager); generator.writeEnd(); } else { //Is a object... probably BeanManager objectManager = new BeanManager(value); System.out.println("Nuevo Objecto {}: " + value.getClass().getSimpleName()); generator.writeStartObject(keyName); stringifyObject(generator, objectManager); generator.writeEnd(); } } }
From source file:net.acesinc.data.json.generator.RandomJsonGenerator.java
private javax.json.stream.JsonGenerator processProperties(javax.json.stream.JsonGenerator gen, Map<String, Object> props, String currentContext) { // Map<String, Object> outputValues = new LinkedHashMap<>(); for (String propName : props.keySet()) { Object value = props.get(propName); if (value == null) { // outputValues.put(propName, null); generatedValues.put(currentContext + propName, null); addValue(gen, propName, null); } else if (String.class.isAssignableFrom(value.getClass())) { String type = (String) value; if (type.startsWith("this.") || type.startsWith("cur.")) { String refPropName = null; if (type.startsWith("this.")) { refPropName = type.substring("this.".length(), type.length()); } else if (type.startsWith("cur.")) { refPropName = currentContext + type.substring("cur.".length(), type.length()); }/*ww w .j a v a 2 s . c o m*/ Object refPropValue = generatedValues.get(refPropName); if (refPropValue != null) { addValue(gen, propName, refPropValue); } else { log.warn("Sorry, unable to reference property [ " + refPropName + " ]. Maybe it hasn't been generated yet?"); } } else { try { TypeHandler th = TypeHandlerFactory.getInstance().getTypeHandler(type, generatedValues, currentContext); if (th != null) { Object val = th.getNextRandomValue(); // outputValues.put(propName, val); generatedValues.put(currentContext + propName, val); addValue(gen, propName, val); } else { // log.debug("Unknown Type: [ " + type + " ] for prop [ " + propName + " ]. Attempting to echo literal value."); // outputValues.put(propName, type); generatedValues.put(currentContext + propName, type); addValue(gen, propName, type); } } catch (IllegalArgumentException iae) { log.warn("Error creating type [ " + type + " ]. Prop [ " + propName + " ] being ignored in output. Reason: " + iae.getMessage()); log.debug("Error creating type [ " + type + " ]. Prop [ " + propName + " ] being ignored in output.", iae); } } } else if (Map.class.isAssignableFrom(value.getClass())) { //nested object Map<String, Object> nestedProps = (Map<String, Object>) value; if (propName == null) { gen.writeStartObject(); } else { gen.writeStartObject(propName); } String newContext = ""; if (propName != null) { if (currentContext.isEmpty()) { newContext = propName + "."; } else { newContext = currentContext + propName + "."; } } processProperties(gen, nestedProps, newContext); gen.writeEnd(); } else if (List.class.isAssignableFrom(value.getClass())) { //array List<Object> listOfItems = (List<Object>) value; String newContext = ""; if (propName != null) { gen.writeStartArray(propName); if (currentContext.isEmpty()) { newContext = propName; } else { newContext = currentContext + propName; } } else { gen.writeStartArray(); } if (!listOfItems.isEmpty()) { //Check if this is a special function at the start of the array if (String.class.isAssignableFrom(listOfItems.get(0).getClass()) && ((String) listOfItems.get(0)).contains("(")) { //special function in array String name = (String) listOfItems.get(0); String specialFunc = null; String[] specialFuncArgs = {}; specialFunc = name.substring(0, name.indexOf("(")); String args = name.substring(name.indexOf("(") + 1, name.indexOf(")")); if (!args.isEmpty()) { specialFuncArgs = args.split(","); } switch (specialFunc) { case "repeat": { int timesToRepeat = 1; if (specialFuncArgs.length == 1) { timesToRepeat = Integer.parseInt(specialFuncArgs[0]); } else { timesToRepeat = new RandomDataGenerator().nextInt(0, 10); } List<Object> subList = listOfItems.subList(1, listOfItems.size()); for (int i = 0; i < timesToRepeat; i++) { processList(subList, gen, newContext); } break; } case "random": { //choose one of the items in the list at random List<Object> subList = listOfItems.subList(1, listOfItems.size()); Object item = subList.get(new RandomDataGenerator().nextInt(0, subList.size() - 1)); processItem(item, gen, newContext + "[0]"); break; } } } else { //it's not a special function, so just add it processList(listOfItems, gen, newContext); } } gen.writeEnd(); } else { //literals generatedValues.put(currentContext + propName, value); addValue(gen, propName, value); } } return gen; }
From source file:com.mapr.data.sputnik.RandomJsonGenerator.java
private javax.json.stream.JsonGenerator processProperties(javax.json.stream.JsonGenerator gen, Map<String, Object> props, String currentContext) { // Map<String, Object> outputValues = new LinkedHashMap<>(); for (String propName : props.keySet()) { Object value = props.get(propName); if (value == null) { // outputValues.put(propName, null); generatedValues.put(currentContext + propName, null); addValue(gen, propName, null); } else if (String.class.isAssignableFrom(value.getClass())) { String type = (String) value; if (type.startsWith("this.") || type.startsWith("cur.")) { String refPropName = null; if (type.startsWith("this.")) { refPropName = type.substring("this.".length(), type.length()); } else if (type.startsWith("cur.")) { refPropName = currentContext + type.substring("cur.".length(), type.length()); }/*from ww w .j ava2 s . com*/ Object refPropValue = generatedValues.get(refPropName); if (refPropValue != null) { addValue(gen, propName, refPropValue); } else { log.warn("Sorry, unable to reference property [ " + refPropName + " ]. Maybe it hasn't been generated yet?"); } } else { try { TypeHandler th = TypeHandlerFactory.getInstance().getTypeHandler(type, generatedValues, currentContext); if (th != null) { Object val = th.getNextRandomValue(); // outputValues.put(propName, val); generatedValues.put(currentContext + propName, val); addValue(gen, propName, val); } else { // log.debug("Unknown Type: [ " + type + " ] for prop [ " + propName + " ]. Attempting to echo literal value."); // outputValues.put(propName, type); generatedValues.put(currentContext + propName, type); addValue(gen, propName, type); } } catch (IllegalArgumentException iae) { log.warn("Error creating type [ " + type + " ]. Prop [ " + propName + " ] being ignored in output. Reason: " + iae.getMessage()); log.debug("Error creating type [ " + type + " ]. Prop [ " + propName + " ] being ignored in output.", iae); } } } else if (Map.class.isAssignableFrom(value.getClass())) { //nested object Map<String, Object> nestedProps = (Map<String, Object>) value; if (propName == null) { gen.writeStartObject(); } else { gen.writeStartObject(propName); } String newContext = ""; if (propName != null) { if (currentContext.isEmpty()) { newContext = propName + "."; } else { newContext = currentContext + propName + "."; } } processProperties(gen, nestedProps, newContext); gen.writeEnd(); } else if (List.class.isAssignableFrom(value.getClass())) { //array List<Object> listOfItems = (List<Object>) value; String newContext = ""; if (propName != null) { gen.writeStartArray(propName); if (currentContext.isEmpty()) { newContext = propName; } else { newContext = currentContext + propName; } } else { gen.writeStartArray(); } if (!listOfItems.isEmpty()) { //Check if this is a special function at the start of the array if (String.class.isAssignableFrom(listOfItems.get(0).getClass()) && ((String) listOfItems.get(0)).contains("(")) { //special function in array String name = (String) listOfItems.get(0); String specialFunc = null; String[] specialFuncArgs = {}; specialFunc = name.substring(0, name.indexOf("(")); String args = name.substring(name.indexOf("(") + 1, name.indexOf(")")); if (!args.isEmpty()) { specialFuncArgs = args.split(","); } switch (specialFunc) { case "repeat": { int timesToRepeat = 1; if (specialFuncArgs.length == 1) { timesToRepeat = Integer.parseInt(specialFuncArgs[0]); } else if (specialFuncArgs.length == 2) { int low = Integer.parseInt(specialFuncArgs[0]); int high = Integer.parseInt(specialFuncArgs[1]); timesToRepeat = rdg.randInt(low, high); } else { timesToRepeat = rdg.randInt(0, 10); } List<Object> subList = listOfItems.subList(1, listOfItems.size()); for (int i = 0; i < timesToRepeat; i++) { processList(subList, gen, newContext); } break; } case "random": { //choose one of the items in the list at random List<Object> subList = listOfItems.subList(1, listOfItems.size()); Object item = subList.get(rdg.randInt(0, subList.size() - 1)); processItem(item, gen, newContext + "[0]"); break; } case "array": { String largs = name.substring(name.indexOf("(") + 1, name.lastIndexOf(")")); String dtype = largs.substring(0, largs.indexOf(")") + 1); String[] arrayArgs = StringUtils .strip(largs.substring(largs.indexOf(")") + 1).trim(), ",").split(","); int min = Integer.parseInt(arrayArgs[0]); int max = Integer.parseInt(arrayArgs[1]); min = min > max || min == max ? 0 : min; try { Map<String, Object> vals = new LinkedHashMap<String, Object>(); for (int i = min; i < max; i++) { TypeHandler th = TypeHandlerFactory.getInstance().getTypeHandler(dtype, vals, currentContext); if (th != null) { Object val = th.getNextRandomValue(); addValue(gen, null, val); } else { addValue(gen, null, dtype); } } } catch (IllegalArgumentException iae) { log.warn("Error creating type [ " + dtype + " ]. Prop [ " + propName + " ] being ignored in output. Reason: " + iae.getMessage()); log.debug("Error creating type [ " + dtype + " ]. Prop [ " + propName + " ] being ignored in output.", iae); } break; } } } else { //it's not a special function, so just add it processList(listOfItems, gen, newContext); } } gen.writeEnd(); } else { //literals generatedValues.put(currentContext + propName, value); addValue(gen, propName, value); } } return gen; }
From source file:nl.nn.adapterframework.align.content.JsonDocumentContainer.java
protected void generate(JsonGenerator g, String key, Object item) { if (item == null) { if (key != null) g.writeNull(key);//from w w w . j av a2 s . c o m 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() + "]"); } }