List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeTree
public void writeTree(JsonGenerator jgen, JsonNode rootNode) throws IOException, JsonProcessingException
From source file:squash.tools.FakeBookingCreator.java
public static void main(String[] args) throws IOException { int numberOfDays = 21; int numberOfCourts = 5; int maxCourtSpan = 5; int numberOfSlots = 16; int maxSlotSpan = 3; int minSurnameLength = 2; int maxSurnameLength = 20; int minBookingsPerDay = 0; int maxBookingsPerDay = 8; LocalDate startDate = LocalDate.of(2016, 7, 5); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); List<Booking> bookings = new ArrayList<>(); for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) { int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1); List<Booking> daysBookings = new ArrayList<>(); for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) { String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic( ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1)); String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic( ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1)); Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>(); daysBookings.forEach((booking) -> { addBookingToSet(booking, bookedCourts); });/* w w w .j a va2 s . c o m*/ Booking booking; Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>(); do { // Loop until we create a booking of free courts int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1); int courtSpan = ThreadLocalRandom.current().nextInt(1, Math.min(maxCourtSpan + 1, numberOfCourts - court + 2)); int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1); int slotSpan = ThreadLocalRandom.current().nextInt(1, Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2)); booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2); booking.setDate(date.format(formatter)); courtsToBook.clear(); addBookingToSet(booking, courtsToBook); } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0)); daysBookings.add(booking); } bookings.addAll(daysBookings); } // Encode bookings as JSON // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // Create a json factory to write the treenode as json. JsonFactory jsonFactory = new JsonFactory(); ObjectNode rootNode = factory.objectNode(); ArrayNode bookingsNode = rootNode.putArray("bookings"); for (int i = 0; i < bookings.size(); i++) { Booking booking = bookings.get(i); ObjectNode bookingNode = factory.objectNode(); bookingNode.put("court", booking.getCourt()); bookingNode.put("courtSpan", booking.getCourtSpan()); bookingNode.put("slot", booking.getSlot()); bookingNode.put("slotSpan", booking.getSlotSpan()); bookingNode.put("name", booking.getName()); bookingNode.put("date", booking.getDate()); bookingsNode.add(bookingNode); } // Add empty booking rules array - just so restore works rootNode.putArray("bookingRules"); rootNode.put("clearBeforeRestore", true); try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"), JsonEncoding.UTF8)) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_EMPTY); mapper.setSerializationInclusion(Include.NON_NULL); mapper.writeTree(generator, rootNode); } }
From source file:org.apache.infra.reviewboard.ReviewBoard.java
public static void main(String... args) throws IOException { URL url = new URL(REVIEW_BOARD_URL); HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD) .authPreemptive(host);// w ww.j a va 2 s . c o m Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/"); Response response = executor.execute(request); request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/"); response = executor.execute(request); ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent()); JsonFactory factory = new JsonFactory(); JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out)); generator.setPrettyPrinter(new DefaultPrettyPrinter()); mapper.writeTree(generator, json); }
From source file:uk.ac.ucl.excites.sapelli.collector.SapColCmdLn.java
/** * @param sapFile/* w ww. j ava 2s . c o m*/ * @param project * @throws IOException * @see https://github.com/ExCiteS/geokey-sapelli */ static public void printProjectInfoForGeoKey(File sapFile, Project project) throws IOException { GeoKeyFormDescriber gkFormDescriber = new GeoKeyFormDescriber(); // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // create a json factory to write the treenode as json. for the example // we just write to console JsonFactory jsonFactory = new JsonFactory(); JsonGenerator generator = jsonFactory.createGenerator(System.out); ObjectMapper mapper = new ObjectMapper(); // the root node ObjectNode projectJSON = factory.objectNode(); // describe project: projectJSON.put("name", project.getName()); projectJSON.put("variant", project.getVariant()); projectJSON.put("version", project.getVersion()); projectJSON.put("display_name", project.toString(false)); projectJSON.put("sapelli_id", project.getID()); projectJSON.put("sapelli_fingerprint", project.getFingerPrint()); projectJSON.put("sapelli_model_id", project.getModel().id); projectJSON.put("installation_path", fsp.getProjectInstallationFolder(project, false).getAbsolutePath()); ArrayNode formsJSON = factory.arrayNode(); for (Form frm : project.getForms()) { ObjectNode formNode = gkFormDescriber.getFormJSON(frm); if (formNode != null) formsJSON.add(formNode); } projectJSON.set("forms", formsJSON); // Serialise: mapper.writeTree(generator, projectJSON); }
From source file:edu.usd.btl.REST.CategoriesResource.java
@Path("/test") @GET/*from w w w .j a va2 s.c o m*/ @Produces("application/json") public String getTestJson() throws Exception { // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // create a json factory to write the treenode as json. for the example // we just write to console JsonFactory jsonFactory = new JsonFactory(); JsonGenerator generator = jsonFactory.createGenerator(System.out); ObjectMapper mapper = new ObjectMapper(); // the root node - album JsonNode album = factory.objectNode(); mapper.writeTree(generator, album); return "null"; }
From source file:org.camunda.spin.impl.json.jackson.format.JacksonJsonDataFormatWriter.java
public void writeToWriter(Writer writer, Object input) { final ObjectMapper objectMapper = dataFormat.getObjectMapper(); final JsonFactory factory = objectMapper.getFactory(); try {//from w w w.ja va 2 s. c o m JsonGenerator generator = factory.createGenerator(writer); objectMapper.writeTree(generator, (JsonNode) input); } catch (IOException e) { throw LOG.unableToWriteJsonNode(e); } }
From source file:uk.ac.ucl.excites.sapelli.collector.SapColCmdLn.java
static public void printProjectInfoJSON(File sapFile, Project project) throws IOException { // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // create a json factory to write the treenode as json. for the example // we just write to console JsonFactory jsonFactory = new JsonFactory(); JsonGenerator generator = jsonFactory.createGenerator(System.out); ObjectMapper mapper = new ObjectMapper(); // the root node ObjectNode projectJSON = factory.objectNode(); // describe project: projectJSON.put("source", sapFile.getAbsolutePath()); projectJSON.put("id", project.getID()); projectJSON.put("fingerprint", project.getFingerPrint()); projectJSON.put("name", project.getName()); projectJSON.put("variant", project.getVariant()); projectJSON.put("version", project.getVersion()); projectJSON.put("display-name", project.toString(false)); projectJSON.put("model-id", project.getModel().id); projectJSON.put("install-path", fsp.getProjectInstallationFolder(project, false).getAbsolutePath()); ArrayNode formsJSON = factory.arrayNode(); for (Form frm : project.getForms()) { ObjectNode formJSON = factory.objectNode(); formJSON.put("id", frm.id); formJSON.put("produces-data", frm.isProducesRecords()); formJSON.put("model-schema-number", (frm.isProducesRecords() ? frm.getSchema().getModelSchemaNumber() : null)); formsJSON.add(formJSON);/*ww w .j a v a2 s . co m*/ } projectJSON.set("forms", formsJSON); // Serialise: mapper.writeTree(generator, projectJSON); }
From source file:org.forgerock.openig.migrate.Main.java
void execute(OutputStream stream) throws Exception { // Pre-parse the original files with JSON-Simple parser (which is more lenient than Jackson's one) File source = new File(sources.get(0)); JSONParser parser = new JSONParser(); JSONObject object = (JSONObject) parser.parse(new FileReader(source)); // Then serialize again the structure (should clean up the JSON) StringWriter writer = new StringWriter(); object.writeJSONString(writer);/*ww w.j a v a 2 s .c o m*/ // Load migration actions to apply in order List<Action> actions = loadActions(); // Parse the cleaned-up content with Jackson this time JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = (ObjectNode) mapper.readTree(writer.toString()); // Apply migration actions for (Action action : actions) { node = action.migrate(node); } // Serialize the migrated content on the given stream (with pretty printer) DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(); prettyPrinter.indentArraysWith(DefaultPrettyPrinter.Lf2SpacesIndenter.instance); mapper.writeTree(factory.createGenerator(stream).setPrettyPrinter(prettyPrinter), node); }
From source file:net.floodlightcontroller.configuration.ConfigurationManager.java
/** * Writes a configuration file based on information gathered from * the various configuration listeners./*from w w w .j a va2s. co m*/ * * @param file An optional configuration file name. */ private void writeJsonToFile(String fileName) throws IOException { String configFile = (fileName != null) ? fileName : this.fileName; ObjectMapper mapper = new ObjectMapper(); ObjectNode rootNode = createJsonRootNode(); JsonFactory f = new JsonFactory(); JsonGenerator g = null; try { g = f.createJsonGenerator(new File(configFile), JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); mapper.writeTree(g, rootNode); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error("Could not write the JSON configuration file."); } throw new IOException("Could not write the JSON configuration file"); } }
From source file:net.floodlightcontroller.configuration.ConfigurationManager.java
@Override public String showConfiguration(String fileName) { ObjectMapper mapper = new ObjectMapper(); ObjectNode rootNode = createJsonRootNode(); JsonFactory f = new JsonFactory(); OutputStream out = new ByteArrayOutputStream(); JsonGenerator g = null;// ww w . ja v a 2s .c om try { g = f.createGenerator(out, JsonEncoding.UTF8); g.useDefaultPrettyPrinter(); mapper.writeTree(g, rootNode); } catch (IOException e) { return "Error: Could not parse the JSON configuration file."; } return out.toString(); }
From source file:com.ikanow.aleph2.data_model.utils.TestCrudUtils.java
/** Create a DB object from a JsonNode * @param bean_template/* w ww . jav a 2s .com*/ * @return * @throws IOException * @throws JsonMappingException * @throws JsonGenerationException */ public static DBObject convertJsonBean(JsonNode json, ObjectMapper object_mapper) { try { final BsonObjectGenerator generator = new BsonObjectGenerator(); object_mapper.writeTree(generator, json); return generator.getDBObject(); } catch (Exception e) { throw new RuntimeException(e); } }