Example usage for com.google.gson GsonBuilder GsonBuilder

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

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java

License:Apache License

/**
 * Saves the {@link SessionInfo} to the filesystem.
 *
 * @param info to be saved.//from  w  w w.j a v a 2  s. c om
 * @return true if and only if successful; false otherwise.
 */
private boolean save(SessionInfo info, String accountId) {
    try {
        Gson gson = new GsonBuilder().registerTypeAdapter(Location.class, new LocationCodec(locationFactory))
                .create();
        Location outputDir = locationFactory.create(archiveDir + "/" + accountId);
        if (!outputDir.exists()) {
            return false;
        }
        final Location sessionInfoFile = outputDir.append("session.json");
        OutputSupplier<Writer> writer = new OutputSupplier<Writer>() {
            @Override
            public Writer getOutput() throws IOException {
                return new OutputStreamWriter(sessionInfoFile.getOutputStream(), "UTF-8");
            }
        };

        Writer w = writer.getOutput();
        try {
            gson.toJson(info, w);
        } finally {
            Closeables.closeQuietly(w);
        }
    } catch (IOException e) {
        LOG.warn(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:co.cask.cdap.gateway.handlers.ProgramLifecycleHttpHandler.java

License:Apache License

/**
 * Relays job-level and task-level information about a particular MapReduce program run.
 *///from   ww w.j  a  v  a 2 s. c  o  m
@GET
@Path("/apps/{app-id}/mapreduce/{mapreduce-id}/runs/{run-id}/info")
public void getMapReduceInfo(HttpRequest request, HttpResponder responder,
        @PathParam("namespace-id") String namespaceId, @PathParam("app-id") String appId,
        @PathParam("mapreduce-id") String mapreduceId, @PathParam("run-id") String runId)
        throws IOException, NotFoundException {
    Id.Program programId = Id.Program.from(namespaceId, appId, ProgramType.MAPREDUCE, mapreduceId);
    Id.Run run = new Id.Run(programId, runId);
    ApplicationSpecification appSpec = store.getApplication(programId.getApplication());
    if (appSpec == null) {
        throw new NotFoundException(programId.getApplication());
    }
    if (!appSpec.getMapReduce().containsKey(mapreduceId)) {
        throw new NotFoundException(programId);
    }
    RunRecordMeta runRecordMeta = store.getRun(programId, runId);
    if (runRecordMeta == null) {
        throw new NotFoundException(run);
    }

    MRJobInfo mrJobInfo = mrJobInfoFetcher.getMRJobInfo(run);

    mrJobInfo.setState(runRecordMeta.getStatus().name());
    // Multiple startTs / endTs by 1000, to be consistent with Task-level start/stop times returned by JobClient
    // in milliseconds. RunRecord returns seconds value.
    mrJobInfo.setStartTime(TimeUnit.SECONDS.toMillis(runRecordMeta.getStartTs()));
    Long stopTs = runRecordMeta.getStopTs();
    if (stopTs != null) {
        mrJobInfo.setStopTime(TimeUnit.SECONDS.toMillis(stopTs));
    }

    // JobClient (in DistributedMRJobInfoFetcher) can return NaN as some of the values, and GSON otherwise fails
    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
    responder.sendJson(HttpResponseStatus.OK, mrJobInfo, mrJobInfo.getClass(), gson);
}

From source file:co.cask.cdap.internal.app.ApplicationSpecificationAdapter.java

License:Apache License

public static ApplicationSpecificationAdapter create(SchemaGenerator generator) {
    return new ApplicationSpecificationAdapter(generator, addTypeAdapters(new GsonBuilder()).create());
}

From source file:co.cask.cdap.internal.app.deploy.InMemoryConfigurator.java

License:Apache License

private <T extends Config> String getSpecJson(Application<T> app, final String configString)
        throws IllegalAccessException, InstantiationException, IOException {

    File tempDir = DirUtils.createTempDir(baseUnpackDir);
    // This Gson cannot be static since it is used to deserialize user class.
    // Gson will keep a static map to class, hence will leak the classloader
    Gson gson = new GsonBuilder().registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory())
            .create();//w w w .j  av  a  2 s.co  m
    // Now, we call configure, which returns application specification.
    DefaultAppConfigurer configurer;
    try (PluginInstantiator pluginInstantiator = new PluginInstantiator(cConf, app.getClass().getClassLoader(),
            tempDir)) {
        configurer = new DefaultAppConfigurer(appNamespace, artifactId, app, configString, artifactRepository,
                pluginInstantiator);
        T appConfig;
        Type configType = Artifacts.getConfigType(app.getClass());
        if (Strings.isNullOrEmpty(configString)) {
            //noinspection unchecked
            appConfig = ((Class<T>) configType).newInstance();
        } else {
            try {
                appConfig = gson.fromJson(configString, configType);
            } catch (JsonSyntaxException e) {
                throw new IllegalArgumentException(
                        "Invalid JSON configuration was provided. Please check the syntax.", e);
            }
        }

        app.configure(configurer, new DefaultApplicationContext<>(appConfig));
    } finally {
        try {
            DirUtils.deleteDirectoryContents(tempDir);
        } catch (IOException e) {
            LOG.warn("Exception raised when deleting directory {}", tempDir, e);
        }
    }
    ApplicationSpecification specification = configurer.createSpecification();

    // Convert the specification to JSON.
    // We write the Application specification to output file in JSON format.
    // TODO: The SchemaGenerator should be injected
    return ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(specification);
}

From source file:co.cask.cdap.internal.app.runtime.artifact.ArtifactStore.java

License:Apache License

@Inject
ArtifactStore(final DatasetFramework datasetFramework, NamespacedLocationFactory namespacedLocationFactory,
        LocationFactory locationFactory, TransactionExecutorFactory txExecutorFactory) {
    this.locationFactory = locationFactory;
    this.namespacedLocationFactory = namespacedLocationFactory;
    this.gson = new GsonBuilder().registerTypeAdapter(Schema.class, new SchemaTypeAdapter())
            .registerTypeAdapter(ArtifactRange.class, new ArtifactRangeCodec()).create();
    this.metaTable = Transactional.of(txExecutorFactory, new Supplier<DatasetContext<Table>>() {
        @Override/*ww w  .  j  av a2s  .co m*/
        public DatasetContext<Table> get() {
            try {
                return DatasetContext.of((Table) DatasetsUtil.getOrCreateDataset(datasetFramework, META_ID,
                        Table.class.getName(), META_PROPERTIES, DatasetDefinition.NO_ARGUMENTS, null));
            } catch (Exception e) {
                // there's nothing much we can do here
                throw Throwables.propagate(e);
            }
        }
    });
}

From source file:co.cask.cdap.notifications.service.AbstractNotificationService.java

License:Apache License

protected Gson createGson() {
    return new GsonBuilder().enableComplexMapKeySerialization().create();
}

From source file:co.cask.cdap.passport.http.client.PassportClient.java

License:Apache License

/**
 * Get List of VPC for the apiKey./*  ww w .j av  a2s .co  m*/
 * @return Instance of {@code AccountProvider}
 * */
public AccountProvider<Account> getAccount(String apiKey) {
    Preconditions.checkNotNull(apiKey, "ApiKey cannot be null");

    try {
        Account account = accountCache.getIfPresent(apiKey);
        if (account == null) {
            String data = httpGet(API_BASE + "whois", apiKey);
            if (data != null) {
                Gson gson = new GsonBuilder()
                        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                account = gson.fromJson(data, Account.class);
                accountCache.put(apiKey, account);
                return new AccountProvider<Account>(account);
            }
        } else {
            return new AccountProvider<Account>(account);
        }
        // This is a hack for overriding accountId type to String.
        // Ideally Account should use String type for account id instead
        return new AccountProvider<Account>(null);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:co.cask.cdap.passport.meta.Account.java

License:Apache License

/**
 * Deserialize Account from jsonString.// w w  w  . ja  va  2s .co  m
 * @param jsonString json string containing account info
 * @return {@code Account}
 */
public static Account fromString(String jsonString) {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    return gson.fromJson(jsonString, Account.class);
}

From source file:co.cask.cdap.passport.meta.Account.java

License:Apache License

/**
 * Serialize account into json string. The field names will be lowercase with underscores where captialized.
 * @return Json serialized String representing account
 *///w  ww  . j  a  v a  2 s  .  co  m
@Override
public String toString() {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    return gson.toJson(this);

}

From source file:co.cask.cdap.ui.ConfigurationJsonTool.java

License:Apache License

public static void exportToJson(Configuration configuration, Appendable output) {
    // Set the log-level of the Configuration logger to ERROR. We don't want warning of deprecated key.
    Level oldLevel = setConfigurationLogLevel(Level.ERROR);

    Map<String, String> map = Maps.newHashMapWithExpectedSize(configuration.size());
    for (Map.Entry<String, String> entry : configuration) {
        map.put(entry.getKey(), entry.getValue());
    }/* w  w w .  j  a v a  2  s .com*/
    new GsonBuilder().setPrettyPrinting().create().toJson(map, output);

    // Restore the log level
    setConfigurationLogLevel(oldLevel);
}