Example usage for com.google.gson GsonBuilder setPrettyPrinting

List of usage examples for com.google.gson GsonBuilder setPrettyPrinting

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder setPrettyPrinting.

Prototype

public GsonBuilder setPrettyPrinting() 

Source Link

Document

Configures Gson to output Json that fits in a page for pretty printing.

Usage

From source file:com.xse.optstack.persconftool.base.persistence.PersConfExport.java

License:Open Source License

private static GsonBuilder createGsonBuilder() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setExclusionStrategies(new EmfExclusionStrategy());
    gsonBuilder.setPrettyPrinting();

    return gsonBuilder;
}

From source file:de.adorsys.beanval2json.BeanvalAnnotationProcessor.java

License:Apache License

private String toJson(Map<String, Constraints> constraints) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    return gsonBuilder.create().toJson(constraints);
}

From source file:de.dentrassi.pm.maven.ChannelData.java

License:Open Source License

/**
 * Make an appropriate Gson parser to processing ChannelData instances
 *
 * @param pretty//from  w  ww .ja v a  2 s .  com
 *            if the gson output should be "pretty printed"
 * @return the new gson instance
 */
public static Gson makeGson(final boolean pretty) {
    final GsonBuilder gb = new GsonBuilder();

    if (pretty) {
        gb.setPrettyPrinting();
    }

    gb.registerTypeAdapter(Node.class, new NodeAdapter());
    gb.registerTypeAdapter(byte[].class, new ByteArrayAdapter());

    return gb.create();
}

From source file:de.dentrassi.pm.npm.ModuleHandler.java

License:Open Source License

public void process(final OutputStream stream) throws IOException {
    final String sitePrefix = this.service.getDefaultSitePrefix();

    final GsonBuilder builder = new GsonBuilder();
    if (this.pretty) {
        builder.setPrettyPrinting();
    }//w w w . j  ava2s  . c  o m

    builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    final Gson gson = builder.create();

    final JsonParser parser = new JsonParser();

    final TreeMap<String, PackageEntry> versions = new TreeMap<>();

    for (final Artifact art : this.channel.getArtifacts()) {
        final String pkg = art.getInformation().getMetaData()
                .get(new MetaKey(NpmChannelAspectFactory.ID, "package.json"));
        if (pkg == null) {
            continue;
        }

        try {
            final JsonElement pkgEle = parser.parse(pkg);
            final PackageInfo pi = gson.fromJson(pkgEle, PackageInfo.class);

            if (!this.moduleName.equals(pi.getName())) {
                continue;
            }

            versions.put(pi.getVersion(), new PackageEntry(pi, pkgEle, art));
        } catch (final Exception e) {
            logger.info("Failed to parse package.json of " + art.getId(), e);
            continue;
        }
    }

    // now build the main file

    final JsonObject main = new JsonObject();

    // pull in meta data from most recent version

    main.addProperty("name", this.moduleName);

    if (!versions.isEmpty()) {
        final Entry<String, PackageEntry> mostRecent = versions.lastEntry();
        final PackageInfo pi = mostRecent.getValue().getInfo();
        main.addProperty("license", pi.getLicense());

        final JsonObject distTags = new JsonObject();
        main.add("dist-tags", distTags);

        distTags.addProperty("latest", pi.getVersion());
    }

    final JsonObject times = new JsonObject();
    main.add("time", times);

    final JsonObject versionsEle = new JsonObject();
    main.add("versions", versionsEle);

    for (final Map.Entry<String, PackageEntry> entry : versions.entrySet()) {
        final PackageInfo pi = entry.getValue().getInfo();
        final Artifact art = entry.getValue().getArtifact();

        times.add(pi.getVersion(), gson.toJsonTree(art.getInformation().getCreationTimestamp()));

        final JsonObject ele = (JsonObject) entry.getValue().getElement();

        final JsonObject dist = new JsonObject();
        dist.addProperty("shasum", art.getInformation().getMetaData().get(new MetaKey("hasher", "sha1")));
        dist.addProperty("tarball", String.format("%s/artifact/%s/dump", sitePrefix, art.getId()));

        ele.add("dist", dist);

        versionsEle.add(pi.getVersion(), ele);
    }

    // render

    try (OutputStreamWriter out = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
        gson.toJson(main, out);
    }
}

From source file:de.dentrassi.pm.usage.UsageController.java

License:Open Source License

private String makeJson(final Statistics stats) {
    final GsonBuilder gb = new GsonBuilder();
    gb.setPrettyPrinting();
    final Gson g = gb.create();
    return g.toJson(stats);
}

From source file:de.fraunhofer.fokus.eject.ObjectInstantiation.java

License:Apache License

/**
 * Read the file. If no file was found, the default constructor should be used.
 *
 * @param fileHandle The file to read.//from www.j a v  a2s.  c o  m
 * @return The created object.
 * @throws InstantiationException The object could not be instantiated.
 */
public T readFile(File fileHandle) throws InstantiationException {
    if (!state.equals(InstantiationState.Initialized)) {
        throw new IllegalStateException("The state is not the Initialized state.");
    }

    T obj = null;
    final Gson gson = new Gson();

    if (fileHandle.exists()) {
        if (fileHandle.canRead()) {
            try {
                final BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(fileHandle)));
                obj = gson.fromJson(reader, clazz);
            } catch (FileNotFoundException e) {
                logFileNotExist(fileHandle);
            }
        } else {
            appendLog(LogMessages.FILE_CAN_NOT_READ);
        }
    } else {
        logFileNotExist(fileHandle);
    }

    if (obj != null) {
        state = state.transition(InstantiationState.ReadFileSuccessful);
        appendLog(LogMessages.FILE_FOUND);
        appendLog(LogMessages.NEWLINE);
    } else {
        state = state.transition(InstantiationState.ErrorReadingFile);
    }

    if (state.equals(InstantiationState.ErrorReadingFile)) {
        if (tryDefaultConstructor) {
            appendLog(LogMessages.NEWLINE);
            appendLog(LogMessages.TRY_DEFAULT_CONSTRUCTOR);
            appendLog(LogMessages.NEWLINE);
            try {
                obj = clazz.newInstance();
                state = state.transition(InstantiationState.DefaultConstructorSuccessful);
                appendLog(LogMessages.DEFAULT_CONSTRUCTOR_USED);
                appendLog(LogMessages.NEWLINE);
            } catch (InstantiationException | IllegalAccessException e) {
                state = state.transition(InstantiationState.ErrorUsingDefaultConstructor);
            }
        } else {
            state = state.transition(InstantiationState.NoDefaultConstructor);
        }
    }

    if (obj == null && !allowNull) {
        appendLog(LogMessages.ERROR);
        appendLog(LogMessages.NEWLINE);
        throw new InstantiationException(LogMessages.ERROR.toString());
    }

    if (createLog) {
        final GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        final Gson gsonPretty = builder.create();

        String normalString = gson.toJson(obj);
        String prettyString = gsonPretty.toJson(obj);

        appendLog(LogMessages.DIFFER);
        appendLog(LogMessages.NEWLINE);

        appendLog(LogMessages.NORMAL_STRING);
        appendLog(LogMessages.NEWLINE);
        appendLog(normalString);
        appendLog(LogMessages.NEWLINE);

        appendLog(LogMessages.PRETTY_STRING);
        appendLog(LogMessages.NEWLINE);
        appendLog(prettyString);
    }
    return obj;
}

From source file:de.iteratec.iteraplan.presentation.rest.RestUtils.java

License:Open Source License

public static String formatToJson(JsonElement element) {
    GsonBuilder builer = new GsonBuilder();
    builer.setPrettyPrinting();
    Gson gson = builer.create();/*from   www  . ja  va  2s.  co m*/

    return gson.toJson(element);
}

From source file:de.skubware.opentraining.activity.create_workout.upload_exercise.UploadExerciseAsyncTask.java

License:Open Source License

public static RestAdapter getRestAdapter(Context c, JsonSerializer serializer) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ExerciseType.class, serializer);
    gsonBuilder.setPrettyPrinting();

    Gson gson = gsonBuilder.create();/*  w w  w .j av  a2  s .  c  o m*/

    GsonConverter converter = new GsonConverter(gson);

    RestAdapter.Builder builder = new RestAdapter.Builder().setConverter(converter)
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade requestFacade) {
                    requestFacade.addHeader("Authorization", "Token ba1ce753f54ba3b8ee4af301f07c58628a1c01bf");
                }
            });

    String baseURL;
    if (BuildConfig.DEBUG) {
        // set different API-Endpoint for debugging
        baseURL = "http://preview.wger.de";
        // only log if debug-build
        // (otherwise auth-token appears in log)
        builder.setLog(new AndroidLog("WgerRestService")).setLogLevel(LogLevel.FULL);
    } else {
        // get the URL from preferences
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c);
        baseURL = settings.getString("exercise_sync_url", c.getString(R.string.pref_default_exercise_sync_url));
    }
    builder.setEndpoint(baseURL + "/api/v2/");

    return builder.build();
}

From source file:edu.oregonstate.eecs.mcplan.search.fsss.experiments.FsssJairExperiments.java

License:Open Source License

public static void main(final String[] args) throws Exception {
    final String experiment_file = args[0];
    final File root_directory;
    if (args.length > 1) {
        root_directory = new File(args[1]);
    } else {//w  w  w.  j ava 2s.  c  o m
        root_directory = new File(".");
    }
    final CsvConfigurationParser csv_config = new CsvConfigurationParser(new FileReader(experiment_file));
    final String experiment_name = FilenameUtils.getBaseName(experiment_file);

    final File expr_directory = new File(root_directory, experiment_name);
    expr_directory.mkdirs();

    for (int expr = 0; expr < csv_config.size(); ++expr) {
        final KeyValueStore expr_config = csv_config.get(expr);
        final Configuration config = new Configuration(root_directory.getPath(), experiment_name, expr_config);

        LoggerManager.getLogger("log.domain").setLevel(Level.valueOf(config.get("log.domain")));
        LoggerManager.getLogger("log.search").setLevel(Level.valueOf(config.get("log.search")));

        final GsonBuilder gson_builder = new GsonBuilder();
        if (config.getBoolean("log.history.pretty")) {
            gson_builder.setPrettyPrinting();
        }

        if ("advising".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final int max_grade = config.getInt("advising.max_grade");
            final int passing_grade = config.getInt("advising.passing_grade");
            final AdvisingParameters params = AdvisingRddlParser.parse(max_grade, passing_grade, domain,
                    instance);
            final AdvisingFsssModel model = new AdvisingFsssModel(config.rng_world, params);
            runGames(config, model, expr);
        }
        //         else if( "cliffworld".equals( config.domain ) ) {
        //            final CliffWorld.FsssModel model = new CliffWorld.FsssModel( config.rng_world, config );
        //            runGames( config, model, expr );
        //         }
        else if ("crossing".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final IpcCrossingState s0 = IpcCrossingDomains.parse(domain, instance);
            final IpcCrossingFsssModel model = new IpcCrossingFsssModel(config.rng_world, s0);
            runGames(config, model, expr);
        } else if ("elevators".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final IpcElevatorsState s0 = IpcElevatorsDomains.parse(domain, instance);
            final IpcElevatorsFsssModel model = new IpcElevatorsFsssModel(config.rng_world, s0);
            runGames(config, model, expr);
        }
        //         else if( "firegirl".equals( config.domain ) ) {
        //            final int T = config.getInt( "firegirl.T" );
        //            final double discount = config.getDouble( "discount" );
        //            final FactoredRepresenter<FireGirlState, ? extends FactoredRepresentation<FireGirlState>> base_repr;
        //            if( "local".equals( config.get( "firegirl.repr" ) ) ) {
        //               base_repr = new FireGirlLocalFeatureRepresenter();
        //            }
        //            else {
        //               throw new IllegalArgumentException( "firegirl.repr" );
        //            }
        //            final FireGirlParameters params = new FireGirlParameters( T, discount, base_repr );
        //            final FireGirlFsssModel model = new FireGirlFsssModel( params, config.rng_world );
        //            runGames( config, model, expr );
        //         }
        //         else if( "inventory".equals( config.domain ) ) {
        //            final String problem_name = config.get( "inventory.problem" );
        //            final InventoryProblem problem;
        //            if( "Dependent".equals( problem_name ) ) {
        //               problem = InventoryProblem.Dependent();
        //            }
        //            else if( "Geometric".equals( problem_name ) ) {
        //               problem = InventoryProblem.Geometric();
        //            }
        //            else if( "Geometric2".equals( problem_name ) ) {
        //               problem = InventoryProblem.Geometric2();
        //            }
        //            else if( "TwoProducts".equals( problem_name ) ) {
        //               problem = InventoryProblem.TwoProducts();
        //            }
        //            else {
        //               throw new IllegalArgumentException( "inventory.problem" );
        //            }
        //            final InventoryFsssModel model = new InventoryFsssModel( config.rng_world, problem );
        //            runGames( config, model, expr );
        //         }
        else if ("racegrid".equals(config.domain)) {
            final String circuit = config.get("racegrid.circuit");
            final int scale = config.getInt("racegrid.scale");
            final int T = config.getInt("racegrid.T");
            final RacegridState ex;
            if ("bbs_small".equals(circuit)) {
                ex = RacegridCircuits.barto_bradtke_singh_SmallTrack(config.rng_world, T, scale);
            } else if ("bbs_large".equals(circuit)) {
                ex = RacegridCircuits.barto_bradtke_singh_LargeTrack(config.rng_world, T, scale);
            } else {
                throw new IllegalArgumentException("racegrid.circuit");
            }
            final double slip = config.getDouble("racegrid.slip");
            final RacegridFsssModel model = new RacegridFsssModel(config.rng_world, ex, slip);
            runGames(config, model, expr);
        }
        //         else if( "rally".equals( config.domain ) ) {
        //            final RallyWorld.Parameters params = new RallyWorld.Parameters( config.rng_world, config );
        //            final RallyWorld.FsssModel model = new RallyWorld.FsssModel( params );
        //            runGames( config, model, expr );
        //         }
        else if ("relevant_irrelevant".equals(config.domain)) {
            final RelevantIrrelevant.Parameters params = new RelevantIrrelevant.Parameters(config);
            final RelevantIrrelevant.FsssModel model = new RelevantIrrelevant.FsssModel(config.rng_world,
                    params);
            runGames(config, model, expr);
        } else if ("sailing".equals(config.domain)) {
            final String world = config.get("sailing.world");
            final int V = config.getInt("sailing.V");
            final int T = config.getInt("sailing.T");
            final int dim = config.getInt("sailing.dim");
            final SailingState.Factory state_factory;
            if ("empty".equals(world)) {
                state_factory = new SailingWorlds.EmptyRectangleFactory(V, T, dim, dim);
            } else if ("island".equals(world)) {
                state_factory = new SailingWorlds.SquareIslandFactory(V, T, dim, dim / 3);
            } else if ("random".equals(world)) {
                final double p = config.getDouble("sailing.p");
                state_factory = new SailingWorlds.RandomObstaclesFactory(p, V, T, dim);
            } else {
                throw new IllegalArgumentException("sailing.world");
            }
            final SailingFsssModel model = new SailingFsssModel(config.rng_world, state_factory);
            runGames(config, model, expr);
        } else if ("saving".equals(config.domain)) {
            final SavingProblem.Parameters params = new SavingProblem.Parameters(config);
            final SavingProblem.FsssModel model = new SavingProblem.FsssModel(config.rng_world, params);
            runGames(config, model, expr);
        } else if ("spbj".equals(config.domain)) {
            final SpBjFsssModel model = new SpBjFsssModel(config.rng_world);
            runGames(config, model, expr);
        } else if ("tamarisk".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final IpcTamariskState s0 = IpcTamariskDomains.parse(domain, instance);
            // TODO: Make this a parameter
            final IpcTamariskReachRepresenter base_repr = new IpcTamariskReachRepresenter(s0.params);
            final IpcTamariskFsssModel model = new IpcTamariskFsssModel(config.rng_world, s0.params, s0,
                    base_repr);
            runGames(config, model, expr);
        } else if ("tetris".equals(config.domain)) {
            final int T = config.getInt("tetris.T");
            final int Nrows = config.getInt("tetris.Nrows");
            final TetrisParameters params = new TetrisParameters(T, Nrows);
            final FactoredRepresenter<TetrisState, ? extends FactoredRepresentation<TetrisState>> base_repr;
            if ("ground".equals(config.get("tetris.repr"))) {
                base_repr = new TetrisGroundRepresenter(params);
            } else if ("bertsekas".equals(config.get("tetris.repr"))) {
                base_repr = new TetrisBertsekasRepresenter(params);
            } else {
                throw new IllegalArgumentException("tetris.repr");
            }
            final TetrisFsssModel model = new TetrisFsssModel(config.rng_world, params, base_repr);

            gson_builder.registerTypeAdapter(TetrisState.class, new TetrisState.GsonSerializer());
            gson_builder.registerTypeAdapter(TetrisAction.class, new TetrisAction.GsonSerializer());
            gson = gson_builder.create();

            runGames(config, model, expr);
        } else if ("weinstein_littman".equals(config.domain)) {
            final WeinsteinLittman.Parameters params = new WeinsteinLittman.Parameters(config);
            final WeinsteinLittman.FsssModel model = new WeinsteinLittman.FsssModel(config.rng_world, params);
            runGames(config, model, expr);
        } else {
            throw new IllegalArgumentException("domain = " + config.domain);
        }
    }

    System.out.println("Alles gut!");
}

From source file:es.alrocar.poiproxy.fiware.poidp.schema.POISet.java

License:Apache License

protected Gson gson() {
    if (gson == null) {
        GsonBuilder lObjJson = new GsonBuilder();
        lObjJson.setDateFormat("yyyy/MM/dd HH:mm:ss");
        lObjJson.registerTypeAdapter(Date.class, new DateTypeAdapter());
        lObjJson.setPrettyPrinting();
        gson = lObjJson.create();/*  www .j  a  v  a  2 s . c  o m*/
    }
    return gson;
}