List of usage examples for javax.json.stream JsonGenerator writeStartObject
JsonGenerator writeStartObject();
From source file:at.porscheinformatik.sonarqube.licensecheck.mavenlicense.MavenLicense.java
public static String createString(Collection<MavenLicense> mavenLicenses) { TreeSet<MavenLicense> mavenLicenseSet = new TreeSet<>(); mavenLicenseSet.addAll(mavenLicenses); StringWriter jsonString = new StringWriter(); JsonGenerator generator = Json.createGenerator(jsonString); generator.writeStartArray();//from ww w.j a v a 2 s. c o m for (MavenLicense mavenLicense : mavenLicenseSet) { generator.writeStartObject(); generator.write("licenseNameRegEx", mavenLicense.getLicenseNameRegEx().pattern()); generator.write("license", mavenLicense.getLicense()); generator.writeEnd(); } generator.writeEnd(); generator.close(); return jsonString.toString(); }
From source file:at.porscheinformatik.sonarqube.licensecheck.license.License.java
public static String createString(Collection<License> licenses) { TreeSet<License> licenseSet = new TreeSet<>(); licenseSet.addAll(licenses);/*from w ww. ja va 2 s . c o m*/ 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(); }
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 ww w . ja v a2 s.c o m 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:com.mapr.data.sputnik.RandomJsonGenerator.java
protected void processItem(Object item, JsonGenerator gen, String currentContext) { if (String.class.isAssignableFrom(item.getClass())) { //literal string, just add it addValue(gen, null, (String) item); generatedValues.put(currentContext, (String) item); } else if (Map.class.isAssignableFrom(item.getClass())) { Map<String, Object> nestedProps = (Map<String, Object>) item; gen.writeStartObject(); processProperties(gen, nestedProps, currentContext + "."); gen.writeEnd();/* www .j a va 2 s. c o m*/ } }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
/** * creates a data model from given resource + configuration JSON (+ optional input schema) * * @param resourceJSON//ww w .j a v a2 s . com * @param configurationJSON * @param optionalInputSchema * @param name * @param description * @return responseJson * @throws Exception */ private String createDataModel(final JsonObject resourceJSON, final JsonObject configurationJSON, final Optional<JsonObject> optionalInputSchema, final String name, final String description, final String serviceName, final String engineDswarmAPI, final boolean doIngest) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { final String uri = engineDswarmAPI + DswarmBackendStatics.DATAMODELS_ENDPOINT + APIStatics.QUESTION_MARK + DswarmBackendStatics.DO_DATA_MODEL_INGEST_IDENTIFIER + APIStatics.EQUALS + doIngest; final HttpPost httpPost = new HttpPost(uri); final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DswarmBackendStatics.NAME_IDENTIFIER, name); jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, description); jp.write(CONFIGURATION_IDENTIFIER, configurationJSON); jp.write(DswarmBackendStatics.DATA_RESOURCE_IDENTIFIER, resourceJSON); if (optionalInputSchema.isPresent()) { LOG.info("[{}][{}] add existing input schema to input data model", serviceName, cnt); jp.write(DswarmBackendStatics.SCHEMA_IDENTIFIER, optionalInputSchema.get()); } jp.writeEnd(); jp.flush(); jp.close(); final StringEntity reqEntity = new StringEntity(stringWriter.toString(), ContentType.create(APIStatics.APPLICATION_JSON_MIMETYPE, Consts.UTF_8)); stringWriter.flush(); stringWriter.close(); httpPost.setEntity(reqEntity); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine())); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase()); final String response = TPUUtil.getResponseMessage(httpResponse); switch (statusCode) { case 201: { LOG.info(message); LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, response)); return response; } default: { LOG.error(message); throw new Exception("something went wrong at data model creation: " + message + " " + response); } } } } }
From source file:de.tu_dortmund.ub.data.dswarm.Transform.java
/** * configuration and processing of the task * * @param inputDataModelID/* w ww . j a va 2 s .com*/ * @param projectIDs * @param outputDataModelID * @return */ private String executeTask(final String inputDataModelID, final Collection<String> projectIDs, final String outputDataModelID, final String serviceName, final String engineDswarmAPI, final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly, final Optional<String> optionalExportMimeType, final Optional<String> optionalExportFileExtension) throws Exception { final JsonArray mappings = getMappingsFromProjects(projectIDs, serviceName, engineDswarmAPI); final JsonObject inputDataModel = getDataModel(inputDataModelID, serviceName, engineDswarmAPI); final JsonObject outputDataModel = getDataModel(outputDataModelID, serviceName, engineDswarmAPI); final Optional<JsonObject> optionalSkipFilter = getSkipFilter(serviceName, engineDswarmAPI); // erzeuge Task-JSON final String persistString = config.getProperty(TPUStatics.PERSIST_IN_DMP_IDENTIFIER); final boolean persist; if (persistString != null && !persistString.trim().isEmpty()) { persist = Boolean.valueOf(persistString); } else { // default is false persist = false; } final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DswarmBackendStatics.PERSIST_IDENTIFIER, persist); // default for now: true, i.e., no content will be returned jp.write(DswarmBackendStatics.DO_NOT_RETURN_DATA_IDENTIFIER, true); // default for now: true, i.e., if a schema is attached it will utilised (instead of being derived from the data resource) jp.write(DswarmBackendStatics.UTILISE_EXISTING_INPUT_IDENTIFIER, true); if (optionalDoIngestOnTheFly.isPresent()) { final Boolean doIngestOnTheFly = optionalDoIngestOnTheFly.get(); if (doIngestOnTheFly) { LOG.info(String.format("[%s][%d] do ingest on-the-fly", serviceName, cnt)); } jp.write(DswarmBackendStatics.DO_INGEST_ON_THE_FLY, doIngestOnTheFly); } if (optionalDoExportOnTheFly.isPresent()) { final Boolean doExportOnTheFly = optionalDoExportOnTheFly.get(); if (doExportOnTheFly) { LOG.info(String.format("[%s][%d] do export on-the-fly", serviceName, cnt)); } jp.write(DswarmBackendStatics.DO_EXPORT_ON_THE_FLY, doExportOnTheFly); } jp.write(DswarmBackendStatics.DO_VERSIONING_ON_RESULT_IDENTIFIER, false); // task jp.writeStartObject(DswarmBackendStatics.TASK_IDENTIFIER); jp.write(DswarmBackendStatics.NAME_IDENTIFIER, "Task Batch-Prozess 'CrossRef'"); jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, "Task Batch-Prozess 'CrossRef' zum InputDataModel 'inputDataModelID '"); // job jp.writeStartObject(DswarmBackendStatics.JOB_IDENTIFIER); jp.write(DswarmBackendStatics.UUID_IDENTIFIER, UUID.randomUUID().toString()); jp.write(DswarmBackendStatics.MAPPINGS_IDENTIFIER, mappings); if (optionalSkipFilter.isPresent()) { jp.write(DswarmBackendStatics.SKIP_FILTER_IDENTIFIER, optionalSkipFilter.get()); } jp.writeEnd(); jp.write(DswarmBackendStatics.INPUT_DATA_MODEL_IDENTIFIER, inputDataModel); jp.write(DswarmBackendStatics.OUTPUT_DATA_MODEL_IDENTIFIER, outputDataModel); // end task jp.writeEnd(); // end request jp.writeEnd(); jp.flush(); jp.close(); final String task = stringWriter.toString(); stringWriter.flush(); stringWriter.close(); LOG.debug(String.format("[%s][%d] task : %s", serviceName, cnt, task)); try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { // POST /dmp/tasks/ final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.TASKS_ENDPOINT); final StringEntity stringEntity = new StringEntity(task, ContentType.APPLICATION_JSON); stringEntity.setChunked(true); final String mimetype; if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) { if (optionalExportMimeType.isPresent()) { mimetype = optionalExportMimeType.get(); } else { // default export mime type is XML mimetype = APIStatics.APPLICATION_XML_MIMETYPE; } } else { mimetype = APIStatics.APPLICATION_JSON_MIMETYPE; } httpPost.setHeader(HttpHeaders.ACCEPT, mimetype); //httpPost.setHeader(HttpHeaders.TRANSFER_ENCODING, CHUNKED_TRANSFER_ENCODING); httpPost.setEntity(stringEntity); final Header[] requestHeaders = httpPost.getAllHeaders(); final String printedRequestHeaders = printHeaders(requestHeaders); LOG.info(String.format("[%s][%d] request : %s :: request headers : \n'%s' :: body : '%s'", serviceName, cnt, httpPost.getRequestLine(), printedRequestHeaders, stringEntity)); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final Header[] responseHeaders = httpResponse.getAllHeaders(); final String printedResponseHeaders = printHeaders(responseHeaders); LOG.info(String.format("[%s][%d] response headers : \n'%s'", serviceName, cnt, printedResponseHeaders)); final int statusCode = httpResponse.getStatusLine().getStatusCode(); switch (statusCode) { case 204: { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); EntityUtils.consume(httpResponse.getEntity()); return "success"; } case 200: { if (optionalDoExportOnTheFly.isPresent() && optionalDoExportOnTheFly.get()) { LOG.info(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); final String exportFileExtension; if (optionalExportFileExtension.isPresent()) { exportFileExtension = optionalExportFileExtension.get(); } else { // XML as default file ending exportFileExtension = TaskProcessingUnit.XML_FILE_ENDING; } // write result to file final String fileName = TPUUtil.writeResultToFile(httpResponse, config, outputDataModelID + "-" + inputDataModelID + "-" + cnt, exportFileExtension); return "success - exported XML to '" + fileName + "'"; } } default: { LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase())); final String response = TPUUtil.getResponseMessage(httpResponse); throw new Exception("something went wrong at task execution" + response); } } } } }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
public String call() { final String serviceName = config.getProperty(TPUStatics.SERVICE_NAME_IDENTIFIER); final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER); final Optional<Boolean> optionalEnhanceInputDataResource = TPUUtil .getBooleanConfigValue(TPUStatics.ENHANCE_INPUT_DATA_RESOURCE, config); LOG.info(String.format("[%s][%d] Starting 'Init (Task)' ...", serviceName, cnt)); try {//ww w. j a v a 2 s. c o m final boolean doIngest; final String doIngestString = config.getProperty(TPUStatics.DO_INITIAL_DATA_MODEL_INGEST_IDENTIFIER); if (doIngestString != null && !doIngestString.trim().isEmpty()) { doIngest = Boolean.valueOf(doIngestString); } else { // default = true doIngest = true; } if (doIngest) { LOG.debug("[{}][{}] do data model creation with data ingest", serviceName, cnt); TPUUtil.initSchemaIndices(serviceName, config); } final String configurationFileName = config.getProperty(TPUStatics.CONFIGURATION_NAME_IDENTIFIER); final String configurationJSONString = readFile(configurationFileName, Charsets.UTF_8); final JsonObject configurationJSON = TPUUtil.getJsonObject(configurationJSONString); final String finalInputResourceFile; if (optionalEnhanceInputDataResource.isPresent() && Boolean.TRUE.equals(optionalEnhanceInputDataResource.get())) { final Optional<String> optionalUpdatedInputResourceFile = enhanceInputDataResource(initResourceFile, configurationJSON); if (optionalUpdatedInputResourceFile.isPresent()) { finalInputResourceFile = optionalUpdatedInputResourceFile.get(); } else { finalInputResourceFile = initResourceFile; } } else { finalInputResourceFile = initResourceFile; } final String name = String.format("resource for project '%s'", initResourceFile); final String description = String.format("'resource does not belong to a project' - case %d", cnt); final String inputResourceJson = uploadFileAndCreateResource(finalInputResourceFile, name, description, serviceName, engineDswarmAPI); if (inputResourceJson == null) { final String message = "something went wrong at resource creation"; LOG.error(message); throw new RuntimeException(message); } final JsonObject inputResourceJSON = TPUUtil.getJsonObject(inputResourceJson); final String inputResourceID = inputResourceJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] input resource id = %s", serviceName, cnt, inputResourceID)); if (inputResourceID == null) { final String message = "something went wrong at resource creation, no resource uuid available"; LOG.error(message); throw new RuntimeException(message); } // TODO: refactor this, so that a configuration only needs to be create once per TPU task // create configuration final String finalConfigurationJSONString = createConfiguration(configurationJSONString, serviceName, engineDswarmAPI); if (finalConfigurationJSONString == null) { final String message = "something went wrong at configuration creation"; LOG.error(message); throw new RuntimeException(message); } final JsonObject finalConfigurationJSON = TPUUtil.getJsonObject(finalConfigurationJSONString); final String configurationID = finalConfigurationJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] configuration id = %s", serviceName, cnt, configurationID)); if (configurationID == null) { final String message = "something went wrong at configuration creation, no configuration uuid available"; LOG.error(message); throw new RuntimeException(message); } // check for existing input schema final Optional<JsonObject> optionalInputSchema = getInputSchema(serviceName, engineDswarmAPI); // create the datamodel (will use it's resource) final String dataModelName = String.format("data model %d", cnt); final String dataModelDescription = String.format("data model description %d", cnt); final String dataModelJSONString = createDataModel(inputResourceJSON, finalConfigurationJSON, optionalInputSchema, dataModelName, dataModelDescription, serviceName, engineDswarmAPI, doIngest); if (dataModelJSONString == null) { final String message = "something went wrong at data model creation"; LOG.error(message); throw new RuntimeException(message); } final JsonObject dataModelJSON = TPUUtil.getJsonObject(dataModelJSONString); final String dataModelID = dataModelJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER); LOG.info(String.format("[%s][%d] data model id = %s", serviceName, cnt, dataModelID)); if (dataModelID == null) { final String message = "something went wrong at data model creation, no data model uuid available"; LOG.error(message); throw new RuntimeException(message); } // we don't need to transform after each ingest of a slice of records, // so transform and export will be done separately LOG.info(String.format("[%s][%d] (Note: Only ingest, but no transformation or export done.)", serviceName, cnt)); final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DATA_MODEL_ID, dataModelID); jp.write(RESOURCE_ID, inputResourceID); jp.write(CONFIGURATION_ID, configurationID); jp.writeEnd(); jp.flush(); jp.close(); final String result = stringWriter.toString(); stringWriter.flush(); stringWriter.close(); return result; } catch (final Exception e) { final String message = String.format("[%s][%d] Processing resource '%s' failed with a %s", serviceName, cnt, initResourceFile, e.getClass().getSimpleName()); LOG.error(message, e); throw new RuntimeException(message, e); } }
From source file:org.kuali.student.myplan.course.controller.CourseSearchController.java
@RequestMapping(value = "/course/updateFacets") public void updateFacets(HttpServletResponse response, HttpServletRequest request) { String formKey = request.getParameter(FORM_KEY_PARAM); response.setHeader("content-type", "application/json"); response.setHeader("Cache-Control", "No-cache"); response.setHeader("Cache-Control", "No-store"); response.setHeader("Cache-Control", "max-age=0"); HashMap<String, Object> meetingResults = new HashMap<String, Object>(); String meetings = request.getParameter(MEETING_FACETS_PARAM); CourseSearchForm searchForm = null;//from w ww .j a v a2 s. c o m if (StringUtils.hasText(formKey)) { try { meetingResults = new ObjectMapper().readValue(meetings, HashMap.class); } catch (IOException e) { e.printStackTrace(); } searchForm = (CourseSearchForm) ((UifFormManager) request.getSession().getAttribute("formManager")) .getSessionForm(formKey); Map<String, List<String>> meetingfacets = searchForm.getMeetingFacets(); for (String meeting : meetingResults.keySet()) { List<String> values = new ArrayList<String>(); if (StringUtils.hasText((String) meetingResults.get(meeting))) { values = Arrays.asList(((String) meetingResults.get(meeting)).split(",")); } meetingfacets.put(meeting, values); } searchForm.setMeetingFacets(meetingfacets); } StringWriter stringWriter = new StringWriter(); JsonGenerator jsonString = Json.createGenerator(stringWriter); jsonString.writeStartObject(); try { jsonString.write("STATUS", "SUCCESS"); jsonString.writeEnd().flush(); response.getWriter().println(stringWriter.toString()); } catch (Exception e) { logger.error("Could not write the response", e); } }
From source file:iing.uabc.edu.mx.persistencia.util.JSON.java
public static void stringifyArray(JsonGenerator generator, CollectionManager manager) { //Get size of the array to start stringifying elements //Note that the elements of this array has to be of the same class Collection collection = manager.getCollection(); Class elementType = manager.getElementClass(); System.out.println("Coleccion de tamanio " + collection.size()); int i = 0;/*www . j a v a2 s . c om*/ //Read every element and transform it to a json array element string for (Iterator it = collection.iterator(); it.hasNext();) { Object element = it.next(); System.out.println("Elemento: [" + i + "], Valor: " + element); if (element == null) { //Set to null the property generator.writeNull(); continue; } //Is a String if (elementType == String.class) { generator.write(String.valueOf(element)); } //Is a Date else if (elementType == Date.class) { String date = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(element); generator.write(date); } //Is a integer else if (elementType == Integer.class || elementType == Integer.TYPE) { generator.write((int) element); } //Is a double else if (elementType == Double.class || elementType == Double.TYPE) { generator.write((double) element); } //Is boolean else if (elementType == Boolean.class || elementType == Boolean.TYPE) { generator.write((boolean) element); } //Is a collection (Not implemented) else if (element 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); // // generator.writeEnd(); } else { //Is a object... probably BeanManager objectManager = new BeanManager(element); System.out.println("Nuevo Objecto {}: " + element.getClass().getSimpleName()); generator.writeStartObject(); 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()); }//from www . java2 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; }