List of usage examples for com.google.gson GsonBuilder setPrettyPrinting
public GsonBuilder setPrettyPrinting()
From source file:org.apache.zeppelin.user.Credentials.java
License:Apache License
/** * Wrapper fro user credentials. It can load credentials from a file if credentialsPath is * supplied, and will encrypt the file if an encryptKey is supplied. * * @param credentialsPersist/*from w w w. ja v a2 s. c o m*/ * @param credentialsPath * @param encryptKey */ public Credentials(Boolean credentialsPersist, String credentialsPath, String encryptKey) { if (encryptKey != null) { this.encryptor = new Encryptor(encryptKey); } this.credentialsPersist = credentialsPersist; if (credentialsPath != null) { credentialsFile = new File(credentialsPath); } credentialsMap = new HashMap<>(); if (credentialsPersist) { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); gson = builder.create(); loadFromFile(); } }
From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java
License:Open Source License
private void jsonTheDirectory(OutputStream outputStream, File writeDirectory) throws UnsupportedEncodingException, IOException { // Create a root object. JsonObject root = new JsonObject(); // Put the individual files into a JSON file. for (File f : writeDirectory.listFiles(ignoreDAEFilter)) addFileToJSON(root, f);/* w w w. j av a2s . c o m*/ // Configure the builder. GsonBuilder builder = new GsonBuilder(); builder.disableHtmlEscaping(); if (wantJSONPrettyPrint) builder.setPrettyPrinting(); Gson gson = builder.create(); // Get the JSON string. String output = gson.toJson(root); // Push the data into the parent stream (gets returned to the server). outputStream.write(output.getBytes()); }
From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java
License:Open Source License
private boolean writeFileUsingJsonElement(File expectedOutputFile, JsonElement root) { boolean success = false; // Write the file back out. try (Writer writer = new FileWriter(expectedOutputFile)) { GsonBuilder builder = new GsonBuilder(); if (wantJSONPrettyPrint) builder.setPrettyPrinting(); Gson gson = builder.create();/*w w w . j av a2 s . c o m*/ gson.toJson(root, writer); success = true; } catch (IOException e) { e.printStackTrace(); } return success; }
From source file:org.chililog.server.common.JsonTranslator.java
License:Apache License
/** * <p>/*from ww w . java2 s . c o m*/ * Singleton constructor that creates our reusable GSON object. * </p> * * <p> * If there are any errors, the JVM is terminated. Without valid application properties, we will fall over elsewhere * so might as well terminate here. * </p> */ private JsonTranslator() { try { GsonBuilder builder = new GsonBuilder(); if (AppProperties.getInstance().getJsonPretty()) { builder.setPrettyPrinting(); } builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); builder.setFieldNamingStrategy(new ChiliLogFieldNamingStrategy()); builder.disableHtmlEscaping(); _gson = builder.create(); } catch (Exception e) { _logger.error("Error initializing JSON translator: " + e.getMessage(), e); System.exit(1); } }
From source file:org.cloudfoundry.community.servicebroker.vrealize.DefaultConfig.java
License:Open Source License
@Bean Gson gson() {// w ww . j a va 2 s. c om GsonBuilder builder = new GsonBuilder(); CatalogTranslator catalogTranslator = new CatalogTranslator(); ServiceDefinitionTranslator serviceDefinitionTranslator = new ServiceDefinitionTranslator(); PlanTranslator planTranslator = new PlanTranslator(); builder.registerTypeAdapter(Catalog.class, catalogTranslator); builder.registerTypeAdapter(ServiceDefinition.class, serviceDefinitionTranslator); builder.registerTypeAdapter(Plan.class, planTranslator); builder.setPrettyPrinting(); Gson gson = builder.create(); catalogTranslator.setGson(gson); serviceDefinitionTranslator.setGson(gson); return gson; }
From source file:org.commonjava.freeki.model.io.PrettyPrintingAdapter.java
License:Open Source License
@Override public void register(final GsonBuilder gsonBuilder) { gsonBuilder.setPrettyPrinting(); }
From source file:org.couchbase.mock.control.handlers.MockHelpCommandHandler.java
License:Apache License
public static String getIndentedHelp() { StringWriter sw = new StringWriter(0); JsonWriter writer = new JsonWriter(sw); writer.setIndent(" "); GsonBuilder gsB = new GsonBuilder(); return gsB.setPrettyPrinting().create().toJson(helpInfo); }
From source file:org.eclim.command.Main.java
License:Open Source License
/** * Main method for executing the client. * * @param context The nailgun context.//from w w w . jav a2s.c om */ public static final void nailMain(final NGContext context) { try { logger.debug("args: " + Arrays.toString(context.getArgs())); ArrayList<String> arguments = new ArrayList<String>(); for (String arg : context.getArgs()) { if (arg.startsWith("-D")) { String[] prop = StringUtils.split(arg.substring(2), '='); System.setProperty(prop[0], prop[1]); } else { arguments.add(arg); } } if (arguments.isEmpty() || arguments.contains("-?")) { int index = arguments.indexOf("-?"); String cmd = arguments.size() > index + 1 ? arguments.get(index + 1) : null; usage(cmd, context.out); System.exit(arguments.isEmpty() ? 1 : 0); } Options options = new Options(); final CommandLine commandLine = options .parse((String[]) arguments.toArray(new String[arguments.size()])); String commandName = commandLine.getValue(Options.COMMAND_OPTION); logger.debug("Main - command: {}", commandName); final Command command = commandLine.getCommand(); command.setContext(context); final Object[] results = new Object[1]; Display.getDefault().syncExec(new Runnable() { public void run() { try { results[0] = command.execute(commandLine); } catch (Exception e) { results[0] = e; logger.error("Command failed", e); } finally { command.cleanup(commandLine); } } }); Object result = results[0]; if (result != null) { if (result instanceof Throwable) { throw (Throwable) result; } GsonBuilder builder = new GsonBuilder(); if (commandLine.hasOption(Options.PRETTY_OPTION)) { builder = builder.setPrettyPrinting(); } if (commandLine.hasOption(Options.EDITOR_OPTION) && commandLine.getValue(Options.EDITOR_OPTION).equals("vim")) { builder = builder.registerTypeAdapter(Boolean.TYPE, new BooleanSerializer()) .registerTypeAdapter(Boolean.class, new BooleanSerializer()); } context.out.println(builder.create().toJson(result)); } } catch (ParseException e) { context.out.println(Services.getMessage(e.getClass().getName(), e.getMessage())); logger.debug("Main - exit on error"); System.exit(1); } catch (Throwable e) { logger.debug("Command triggered exception: " + Arrays.toString(context.getArgs()), e); e.printStackTrace(context.err); logger.debug("Main - exit on error"); System.exit(1); } }
From source file:org.eclipse.californium.extplugtests.ReceivetestClient.java
License:Open Source License
/** * Process JSON response.//from w ww .j a v a2 s .c o m * * @param payload JSON payload as string * @param errors request ID of previously failed request. * @param verbose {@code true} to interpret the string, either pretty JSON, * or pretty application, if data complies the assumed request * statistic information. * @return payload as application text, pretty JSON, or just as provided * text. */ public static String processJSON(String payload, String errors, boolean verbose) { StringBuilder statistic = new StringBuilder(); JsonElement element = null; try { JsonParser parser = new JsonParser(); element = parser.parse(payload); if (verbose && element.isJsonArray()) { // expected JSON data SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy"); try { for (JsonElement item : element.getAsJsonArray()) { if (!item.isJsonObject()) { // unexpected => // stop application pretty printing statistic.setLength(0); break; } JsonObject object = item.getAsJsonObject(); if (object.has("rid")) { String rid = object.get("rid").getAsString(); long time = object.get("time").getAsLong(); if (rid.startsWith(REQUEST_ID_PREFIX)) { boolean hit = errors.contains(rid); rid = rid.substring(REQUEST_ID_PREFIX.length()); long requestTime = Long.parseLong(rid); statistic.append("Request: ").append(format.format(requestTime)); long diff = time - requestTime; if (-MAX_DIFF_TIME_IN_MILLIS < diff && diff < MAX_DIFF_TIME_IN_MILLIS) { statistic.append(", received: ").append(diff).append(" ms"); } else { statistic.append(", received: ").append(format.format(time)); } if (hit) { statistic.append(" * lost response!"); } } else { statistic.append("Request: ").append(rid); statistic.append(", received: ").append(format.format(time)); } if (object.has("ep")) { String endpoint = object.get("ep").getAsString(); if (endpoint.contains(":")) { endpoint = "[" + endpoint + "]"; } int port = object.get("port").getAsInt(); statistic.append(System.lineSeparator()); statistic.append(" (").append(endpoint).append(":").append(port).append(")"); } statistic.append(System.lineSeparator()); } else { long time = object.get("systemstart").getAsLong(); statistic.append("Server's system start: ").append(format.format(time)); statistic.append(System.lineSeparator()); } } } catch (Throwable e) { // unexpected => stop application pretty printing statistic.setLength(0); } } if (statistic.length() == 0) { // JSON plain pretty printing GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create(); gson.toJson(element, statistic); } } catch (JsonSyntaxException e) { // plain payload e.printStackTrace(); statistic.setLength(0); statistic.append(payload); } return statistic.toString(); }
From source file:org.eclipse.californium.plugtests.util.JsonDecoder.java
License:Open Source License
@Override public String decode(byte[] payload) { try {// w w w .jav a 2s . c o m JsonParser parser = new JsonParser(); JsonElement element = parser.parse(new String(payload, CoAP.UTF8_CHARSET)); GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); Gson gson = builder.create(); return gson.toJson(element); } catch (JsonSyntaxException ex) { ex.printStackTrace(); throw ex; } }