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:apim.restful.exportimport.APIService.java

License:Open Source License

@GET
@Path("/export-api/{id}")
@Consumes(MediaType.APPLICATION_JSON)//from w ww  .j  a va2  s.c o m
@Produces(MediaType.MULTIPART_FORM_DATA)
public Response getAPI(@PathParam("id") String id) throws APIExportException {

    //initializing provider
    setProvider();

    log.info("Retrieving API for API-Id : " + id);
    String name = id.substring(0, id.indexOf("-"));
    String version = id.substring(id.indexOf("-") + 1, id.lastIndexOf("-"));
    String providerName = id.substring(id.lastIndexOf("-") + 1, id.length());
    apiIdentifier = new APIIdentifier(providerName, name, version);
    API apiToReturn = null;
    String swagger = "";
    String tempAPIName = name + "-" + version;
    //registry for the current user
    getRegistry();
    try {
        //directory creation
        baseAPIArchivePath = "/Users/thilinicooray/Desktop/" + tempAPIName;
        //where
        // should
        // archive save?
        createDirectory(baseAPIArchivePath);

        apiToReturn = provider.getAPI(apiIdentifier);

        //retrieving thumbnail
        if (getAPIIcon()) {
            apiToReturn.setThumbnailUrl(null);
        }

        //retrieving documents
        List<Documentation> docList = provider.getAllDocumentation(apiIdentifier);
        getAPIDocumentation(docList);

        //retrieving wsdl - error when manually adding
        String wsdlUrl = apiToReturn.getWsdlUrl();
        if (wsdlUrl != null) {
            if (getWSDL()) {
                apiToReturn.setWsdlUrl(null);
            }
        }

        //retrieving sequences
        Map<String, String> sequences = new HashMap<String, String>();
        sequences.put("in", apiToReturn.getInSequence());
        sequences.put("out", apiToReturn.getOutSequence());
        sequences.put("fault", apiToReturn.getFaultSequence());
        getSequences(sequences);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        // convert java object to JSON format,
        // and return as JSON formatted string
        String json = gson.toJson(apiToReturn);

        createDirectory(baseAPIArchivePath + "/Meta-information");

        //write converted json data to a file named "file.json"
        FileWriter writer = new FileWriter(
                baseAPIArchivePath + "/Meta-information/" + name + "-" + version + ".json");
        writer.write(json);
        writer.close();

        ArchiveGenerator.zipIt(baseAPIArchivePath + ".zip", baseAPIArchivePath);

    } catch (APIManagementException e) {
        log.error("Error while getting API" + e.toString());
        throw new APIExportException("Error while getting API", e);
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new APIExportException("I/O error while writing API Meta information to file :"
                + baseAPIArchivePath + "/Meta-information/" + name + "-" + version + ".json", e);
    }

    return Response.ok(swagger).build(); //?
}

From source file:apim.restful.exportimport.APIService.java

License:Open Source License

/**
 * Retrieve documentation for the exporting API and store it in the archive directory
 * FILE, INLINE and URL documentations are handled
 *
 * @param docList  documentation list of the exporting API
 * @throws APIExportException  If an error occurs while retrieving documents from the
 * registry or storing in the archive directory
 *///from  w w w.j  a va2 s  .c  o m
private void getAPIDocumentation(List<Documentation> docList) throws APIExportException {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    createDirectory(baseAPIArchivePath + "/Docs");

    try {
        for (Documentation doc : docList) {
            String sourceType = doc.getSourceType().name();

            if (sourceType.equalsIgnoreCase(Documentation.DocumentSourceType.FILE.toString())) {
                String fileName = doc.getFilePath().substring(doc.getFilePath().lastIndexOf("/") + 1);
                String filePath = APIUtil.getDocumentationFilePath(apiIdentifier, fileName);

                //check whether resource exists in the registry
                Resource docFile = registry.get(filePath);
                String localFilePath = "/Docs/" + fileName;
                OutputStream os = new FileOutputStream(baseAPIArchivePath + localFilePath);
                InputStream fileInputStream = docFile.getContentStream();
                byte[] b = new byte[2048];
                int length;

                while ((length = fileInputStream.read(b)) != -1) {
                    os.write(b, 0, length);
                }

                fileInputStream.close();
                os.close();
                doc.setFilePath(localFilePath);
            }
        }

        String json = gson.toJson(docList);
        FileWriter writer = new FileWriter(baseAPIArchivePath + "/Docs/docs.json");
        writer.write(json);
        writer.close();

    } catch (IOException e) {
        log.error("I/O error while writing API documentation to file" + e.toString());
        throw new APIExportException("I/O error while writing API documentation to file", e);
    } catch (RegistryException e) {
        log.error("Error while retrieving documentation " + e.toString());
        throw new APIExportException("Error while retrieving documentation", e);
    }
}

From source file:apim.restful.importexport.utils.APIExportUtil.java

License:Open Source License

/**
 * Retrieve documentation for the exporting API and store it in the archive directory
 * FILE, INLINE and URL documentations are handled
 *
 * @param apiIdentifier ID of the requesting API
 * @param registry      Current tenant registry
 * @param docList       documentation list of the exporting API
 * @throws APIExportException If an error occurs while retrieving documents from the
 *                            registry or storing in the archive directory
 */// ww  w  .  ja v  a  2s.  c  om
public static void exportAPIDocumentation(List<Documentation> docList, APIIdentifier apiIdentifier,
        Registry registry) throws APIExportException {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String archivePath = archiveBasePath
            .concat(File.separator + apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion());
    createDirectory(archivePath + File.separator + "Docs");
    InputStream fileInputStream = null;
    OutputStream outputStream = null;
    try {
        for (Documentation doc : docList) {
            String sourceType = doc.getSourceType().name();
            if (Documentation.DocumentSourceType.FILE.toString().equalsIgnoreCase(sourceType)) {
                String fileName = doc.getFilePath()
                        .substring(doc.getFilePath().lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
                String filePath = APIUtil.getDocumentationFilePath(apiIdentifier, fileName);

                //check whether resource exists in the registry
                Resource docFile = registry.get(filePath);
                String localFilePath = File.separator + "Docs" + File.separator + fileName;
                outputStream = new FileOutputStream(archivePath + localFilePath);
                fileInputStream = docFile.getContentStream();

                IOUtils.copy(fileInputStream, outputStream);

                doc.setFilePath(localFilePath);

                if (log.isDebugEnabled()) {
                    log.debug(fileName + " retrieved successfully");
                }
            }
        }

        String json = gson.toJson(docList);
        writeFile(archivePath + File.separator + "Docs" + File.separator + "docs.json", json);

        if (log.isDebugEnabled()) {
            log.debug("API Documentation retrieved successfully");
        }

    } catch (IOException e) {
        log.error("I/O error while writing API documentation to file" + e.getMessage());
        throw new APIExportException("I/O error while writing API documentation to file", e);
    } catch (RegistryException e) {
        log.error("Error while retrieving documentation " + e.getMessage());
        throw new APIExportException("Error while retrieving documentation", e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:apim.restful.importexport.utils.APIExportUtil.java

License:Open Source License

/**
 * Retrieve meta information of the API to export
 * URL template information are stored in swagger.json definition while rest of the required
 * data are in api.json/*from  ww w  .  ja v  a2s.  c o  m*/
 *
 * @param apiToReturn API to be exported
 * @param registry    Current tenant registry
 * @throws APIExportException If an error occurs while exporting meta information
 */
private static void exportMetaInformation(API apiToReturn, Registry registry) throws APIExportException {
    APIDefinition definitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String archivePath = archiveBasePath
            .concat(File.separator + apiToReturn.getId().getApiName() + "-" + apiToReturn.getId().getVersion());

    createDirectory(archivePath + File.separator + "Meta-information");
    //Remove unnecessary data from exported Api
    cleanApiDataToExport(apiToReturn);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String apiInJson = gson.toJson(apiToReturn);
    writeFile(archivePath + File.separator + "Meta-information" + File.separator + "api.json", apiInJson);

    try {
        String swaggerDefinition = definitionFromSwagger20.getAPIDefinition(apiToReturn.getId(), registry);
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(swaggerDefinition).getAsJsonObject();
        String formattedSwaggerJson = gson.toJson(json);
        writeFile(archivePath + File.separator + "Meta-information" + File.separator + "swagger.json",
                formattedSwaggerJson);

        if (log.isDebugEnabled()) {
            log.debug("Meta information retrieved successfully");
        }

    } catch (APIManagementException e) {
        log.error("Error while retrieving Swagger definition" + e.getMessage());
        throw new APIExportException("Error while retrieving Swagger definition", e);
    }
}

From source file:app.config.AppBootstrap.java

License:Apache License

public void init(AppContext context) {
    setInjector(Guice.createInjector(new GreeterModule()));
    Configuration.setUseDefaultLayoutForErrors(true);
    GsonBuilder jsonBuilder = new GsonBuilder();
    jsonBuilder.registerTypeAdapter(BaseCard.class, new BaseCardAdapter());
    context.set("json", jsonBuilder.create());
}

From source file:app.data.foundation.net.ApiModule.java

License:Apache License

@Inject
public ApiModule() {
    Gson gson = new GsonBuilder().registerTypeAdapterFactory(GsonAdapterFactory.create()).create();

    this.retrofit = new Retrofit.Builder().baseUrl("https://api.github.com")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson)).build();
}

From source file:app.domain.foundation.gcm.GcmNotification.java

License:Apache License

public static <T> GcmNotification<List<T>> getMessageArrayListFromGcmNotification(Class<T> classData,
        Message message) {//www.ja va 2  s.c  o  m
    String payload = message.payload().getString("payload");
    String title = message.payload().getString("title");
    String body = message.payload().getString("body");

    Type typeCollection = $Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, classData);

    List<T> data = new GsonBuilder().create().fromJson(payload, typeCollection);
    return new GcmNotification(data, title, body);
}

From source file:appdev.letsmeet.control.utils.messgeBodyHandlers.GsonMessageBodyHandler.java

private Gson getGson() {
    if (gson == null) {
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.serializeNulls().create();
    }//from  ww  w  .j a  v a2s .  c  om
    return gson;
}

From source file:apprenda.clientservices.tasks.ApprendaDeployTask.java

License:Apache License

@NotNull
private Gson getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    return builder.create();
}

From source file:ar.com.wolox.wolmo.networking.di.modules.GsonModule.java

License:Open Source License

@Provides
@Named("newInstance")
static GsonBuilder provideNewGsonBuilder() {
    return new GsonBuilder();
}