List of usage examples for com.google.gson GsonBuilder registerTypeAdapter
@SuppressWarnings({ "unchecked", "rawtypes" }) public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
From source file:com.vaadin.addon.charts.model.AbstractConfigurationObject.java
/** * Returns default GSON builder for configuration serializer. */// w w w. ja va 2s .c om public static GsonBuilder createGsonBuilder() { GsonBuilder builder = new GsonBuilder(); // uncomment if you wish to debug generated json builder.setPrettyPrinting(); builder.registerTypeHierarchyAdapter(ChartEnum.class, new ChartEnumSerializer()); builder.registerTypeHierarchyAdapter(SolidColor.class, new SolidColorSerializer()); builder.registerTypeHierarchyAdapter(AxisList.class, new AxisListSerializer()); builder.registerTypeHierarchyAdapter(PaneList.class, new PaneListSerializer()); builder.registerTypeAdapter(ContainerDataSeries.class, new ContainerDataSeriesSerializer()); builder.registerTypeAdapterFactory(new DataSeriesItemTypeAdapterFactory()); builder.registerTypeAdapterFactory(new AbstractSeriesTypeAdapterFactory()); builder.registerTypeAdapterFactory(new TitleTypeAdapterFactory()); return builder; }
From source file:com.vmware.dcp.common.serialization.JsonMapper.java
License:Open Source License
private static void registerCommonGsonTypeAdapters(GsonBuilder bldr) { bldr.registerTypeAdapter(ObjectMapTypeConverter.TYPE, ObjectMapTypeConverter.INSTANCE); bldr.registerTypeAdapter(InstantConverter.TYPE, InstantConverter.INSTANCE); bldr.registerTypeAdapter(ZonedDateTimeConverter.TYPE, ZonedDateTimeConverter.INSTANCE); bldr.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()); bldr.registerTypeAdapter(RequestRouteConverter.TYPE, RequestRouteConverter.INSTANCE); }
From source file:com.vmware.vchs.api.samples.services.helper.HttpUtils.java
License:Open Source License
/** * This method will unmarshal the passed in entity using the passed in class type. It will check * the content-type to determine if the response is json or xml and use the appropriate * deserializer.//from w w w . j a va2s . co m * * @param entity * the entity to unmarshal * @param clazz * the class type to base the unmarshal from * @return unmarshal an instance of the provided class type */ public static <T> T unmarshal(HttpEntity entity, Class<T> clazz) { InputStream is = null; try { String s = EntityUtils.toString(entity); // Check if the response content-type contains the string json.. if so use GSON to // convert from json to the provided Class<T> type if (entity.getContentType().toString().toLowerCase().contains("json")) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new XMLGregorianClassConverter.Serializer()); gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new XMLGregorianClassConverter.Deserializer()); Gson g = gsonBuilder.create(); return g.fromJson(s, clazz); } is = new ByteArrayInputStream(s.getBytes("UTF-8")); return JAXB.unmarshal(is, clazz); } catch (ParseException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (null != is) { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:com.vmware.vchs.api.samples.services.IAM.java
License:Open Source License
/** * This method will create a new user from the provided User instance. * //from w w w .ja va 2 s. c o m * @param url * the url of the API to make requests to * @param token * the OAUTH2 authentication token from IAM * @param user * the instance of User to create the new user from * @param version * the version of the API to call * @return an instance of User if created successfully, null otherwise */ public static final User createUser(String url, String token, User user, String version) { StringBuilder sb = new StringBuilder(url); sb.append(SampleConstants.API_IAM_USERS); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new HttpUtils.XMLGregorianClassConverter.Serializer()); gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new HttpUtils.XMLGregorianClassConverter.Deserializer()); Gson g = gsonBuilder.create(); String userToSend = g.toJson(user); HttpResponse response = HttpUtils.httpPost(sb.toString(), token, SampleConstants.APPLICATION_JSON, SampleConstants.APPLICATION_JSON, SampleConstants.CLASS_IAM_USER, version, userToSend); if (null != response) { // If the response status is 400 - 599 if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_BAD_REQUEST) { // This is here to show when an error occurs, the response should always be // an Error instance Error error = HttpUtils.unmarshal(response.getEntity(), Error.class); // Do something with Error, possibly using Error.getCode() value to // determine the specific reason for the error. } else { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { try { String s = EntityUtils.toString(response.getEntity()); User createdUser = g.fromJson(s, User.class); return createdUser; } catch (JsonSyntaxException e1) { throw new RuntimeException("JSON Syntax Exception: " + e1.getMessage()); } catch (ParseException e1) { throw new RuntimeException("Response Parsing Exception: " + e1.getMessage()); } catch (IOException e1) { throw new RuntimeException(e1); } } } } return null; }
From source file:com.vmware.vchs.api.samples.services.IAM.java
License:Open Source License
/** * This method updates the passed in user by using the PUT method to the * /api/iam/Users/{user-id} url. The response should be a 204 if the update was successful. * /*from www . j ava 2 s . com*/ * @param url * the hostname url to send the update request to * @param token * the OAUTH token to authenticate the request with * @param user * the user instance to send as the entity to update with * @return true if the update was successful false otherwise */ public static boolean updateUser(String url, String token, User user, String version) { StringBuilder sb = new StringBuilder(url); sb.append(SampleConstants.API_IAM_USERS); sb.append("/"); sb.append(user.getId()); // Configure the GSON object GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new HttpUtils.XMLGregorianClassConverter.Serializer()); gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new HttpUtils.XMLGregorianClassConverter.Deserializer()); Gson g = gsonBuilder.create(); // Convert the object to JSON String userToSend = g.toJson(user); // Send the PUT request HttpResponse response = HttpUtils.httpPut(sb.toString(), token, SampleConstants.APPLICATION_JSON, SampleConstants.APPLICATION_JSON, SampleConstants.CLASS_IAM_USER, version, userToSend); if (null != response) { // If the response status is 400 - 599 if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_BAD_REQUEST) { // This is here to show when an error occurs, the response should always be // an Error instance Error error = HttpUtils.unmarshal(response.getEntity(), Error.class); // Do something with Error, possibly using Error.getCode() value to // determine the specific reason for the error. } else { return response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED; } } return false; }
From source file:com.vsthost.rnd.jpsolver.data.Value.java
License:Apache License
/** * Returns the JSON representation of the value. * * TODO: Implement a toJson (class, serializer) method for user-defined classes implementing Value interface. * * @return The JSON representation of the value. *//* ww w. j av a 2 s. c om*/ public default String toJson() { // Initialize the Json builder: GsonBuilder gsonBuilder = new GsonBuilder(); // Register serializers for scalar values: gsonBuilder.registerTypeAdapter(BooleanValue.class, new ScalarValueSerializer()); gsonBuilder.registerTypeAdapter(NumericValue.class, new ScalarValueSerializer()); gsonBuilder.registerTypeAdapter(TextValue.class, new ScalarValueSerializer()); // We want nulls to be serialized: gsonBuilder.serializeNulls(); // Done, get the JSON: return gsonBuilder.create().toJson(this.get()); }
From source file:com.xse.optstack.persconftool.base.persistence.PersConfExport.java
License:Open Source License
private boolean persistGroup(final File resourceFolder, final EApplicationGroup group) { final boolean persistStatus = true; final File groupFolder = new File( resourceFolder.getAbsolutePath() + File.separator + group.getType().getLiteral().toLowerCase()); try {/* ww w . j a v a 2 s. c om*/ groupFolder.mkdir(); } catch (final SecurityException e) { Logger.error(Activator.PLUGIN_ID, "Not allowed to create group folder: " + groupFolder.getAbsolutePath(), e); return false; } final Set<String> appNames = new HashSet<>(); // ################ Installation Rules final Gson installRulesJson = PersConfExport.createGsonBuilder().create(); final JsonObject installRulesObj = new JsonObject(); for (final EApplication eApplication : group.getApplications()) { if (eApplication.getInstallRule() != null) { installRulesObj.add(eApplication.getName(), new JsonPrimitive( PersConfDefinitions.INSTALL_RULE_PREFIX + eApplication.getInstallRule().getLiteral())); } } try (final FileWriter fileWriter = new FileWriter(new File( groupFolder.getAbsolutePath() + File.separator + PersConfDefinitions.INSTALL_RULES_FILE))) { fileWriter.write(installRulesJson.toJson(installRulesObj)); } catch (final IOException e) { Logger.error(Activator.PLUGIN_ID, "Error writing install rules configuration file!", e); } // ################ Ownership Configuration final Gson ownershipConfigurationJson = PersConfExport.createGsonBuilder().create(); final JsonObject ownershipConfigurationObj = new JsonObject(); for (final EApplication eApplication : group.getApplications()) { final JsonObject appElement = new JsonObject(); boolean saveApplication = false; if (eApplication.getUserName() == null || eApplication.getUserName().equals("")) appElement.add(PersConfDefinitions.USERNAME_KEY_NAME, new JsonPrimitive("")); else { appElement.add(PersConfDefinitions.USERNAME_KEY_NAME, new JsonPrimitive(eApplication.getUserName())); saveApplication = true; } if (eApplication.getGroupName() == null || eApplication.getGroupName().equals("")) appElement.add(PersConfDefinitions.GROUPNAME_KEY_NAME, new JsonPrimitive("")); else { appElement.add(PersConfDefinitions.GROUPNAME_KEY_NAME, new JsonPrimitive(eApplication.getGroupName())); saveApplication = true; } if (eApplication.getUserId() == null) appElement.add(PersConfDefinitions.USERID_KEY_NAME, new JsonPrimitive("")); else { appElement.add(PersConfDefinitions.USERID_KEY_NAME, new JsonPrimitive(String.valueOf(eApplication.getUserId()))); saveApplication = true; } if (eApplication.getGroupId() == null) appElement.add(PersConfDefinitions.GROUPID_KEY_NAME, new JsonPrimitive("")); else { appElement.add(PersConfDefinitions.GROUPID_KEY_NAME, new JsonPrimitive(String.valueOf(eApplication.getGroupId()))); saveApplication = true; } if (saveApplication) ownershipConfigurationObj.add(eApplication.getName(), appElement); } try (final FileWriter fileWriter = new FileWriter(new File(groupFolder.getAbsolutePath() + File.separator + PersConfDefinitions.OWNERSHIP_CONFIGURATION_FILE))) { fileWriter.write(ownershipConfigurationJson.toJson(ownershipConfigurationObj)); } catch (final IOException e) { Logger.error(Activator.PLUGIN_ID, "Error writing ownership configuration file!", e); } for (final EApplication eApplication : group.getApplications()) { final File applicationFolder = new File(groupFolder + File.separator + eApplication.getName()); applicationFolder.mkdir(); this.exportCHeader(eApplication); // ################ Resource Configuration final GsonBuilder resourceConfigJsonBuilder = PersConfExport.createGsonBuilder(); resourceConfigJsonBuilder.registerTypeAdapter(EApplicationImpl.class, new ResouceConfigurationApplicationTypeAdapter()); resourceConfigJsonBuilder.registerTypeAdapter(EConfigurationImpl.class, new ResourceConfigurationConfigurationTypeAdapter()); resourceConfigJsonBuilder.registerTypeAdapter(EPolicy.class, new ResouceConfigurationTypeAdapter()); resourceConfigJsonBuilder.registerTypeAdapter(EStorage.class, new ResouceConfigurationTypeAdapter()); resourceConfigJsonBuilder.registerTypeAdapter(EDefaultDataType.class, new ResouceConfigurationTypeAdapter()); resourceConfigJsonBuilder.setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(final FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(final Class<?> clazz) { return clazz.isAssignableFrom(EDefaultData.class); } }); final Gson gson = resourceConfigJsonBuilder.create(); try (final FileWriter fileWriter = new FileWriter(new File(applicationFolder.getAbsolutePath() + File.separator + PersConfDefinitions.RESOURCE_CONFIGURATION_FILE))) { fileWriter.write(gson.toJson(eApplication)); } catch (final IOException e) { Logger.error(Activator.PLUGIN_ID, "Error writing resource configuration file!", e); } // ################ Install Exceptions final Gson installExceptionsGson = PersConfExport.createGsonBuilder().create(); final JsonObject installExceptionsObj = new JsonObject(); for (final EResource resource : eApplication.getResources()) { if (resource.getInstallException() != null) { installExceptionsObj.add(resource.getName(), new JsonPrimitive(PersConfDefinitions.INSTALL_EXCEPTION_PREFIX + resource.getInstallException().getLiteral())); } } try (final FileWriter fileWriter = new FileWriter(new File(applicationFolder.getAbsolutePath() + File.separator + PersConfDefinitions.INSTALL_EXCEPTIONS_FILE))) { fileWriter.write(installExceptionsGson.toJson(installExceptionsObj)); } catch (final IOException e) { Logger.error(Activator.PLUGIN_ID, "Error writing install exceptions configuration file!", e); } final File fileFolder = new File(applicationFolder + File.separator + PersConfDefinitions.FILE_FOLDER); fileFolder.mkdir(); final File configDefaultFileFolder = new File( fileFolder + File.separator + PersConfDefinitions.CONFIGURABLE_DEFAULT_DATA_FOLDER); configDefaultFileFolder.mkdir(); final File defaultFileFolder = new File( fileFolder + File.separator + PersConfDefinitions.DEFAULT_DATA_FOLDER); defaultFileFolder.mkdir(); // ################ Default Data final File keyFolder = new File(applicationFolder + File.separator + PersConfDefinitions.KEY_FOLDER); keyFolder.mkdir(); // ################ Factory Default // boolean hasDefaultKeyData = false; // for (final EResource eResource : eApplication.getResources()) { // if (DefaultDataApplicationTypeAdapter.hasDefaultDataValue(eResource.getConfiguration().getFactoryDefault())) { // hasDefaultKeyData = true; // break; // } // } PersConfExport.copyDefaultDataFiles(defaultFileFolder, eApplication, EConfiguration::getFactoryDefault); final File factoryDefaultsFile = new File( keyFolder.getAbsolutePath() + File.separator + PersConfDefinitions.FACTORY_DEFAULTS_FILE); final GsonBuilder factoryDefaultGsonBuilder = PersConfExport.createGsonBuilder(); factoryDefaultGsonBuilder.registerTypeAdapter(EApplicationImpl.class, new DefaultDataApplicationTypeAdapter(true)); factoryDefaultGsonBuilder.registerTypeAdapter(EDefaultDataImpl.class, new DefaultDataTypeAdapter()); final Gson factoryDefaultGson = factoryDefaultGsonBuilder.create(); try (final FileWriter fileWriter = new FileWriter(factoryDefaultsFile)) { fileWriter.write(factoryDefaultGson.toJson(eApplication)); } catch (final IOException e) { e.printStackTrace(); } // ################ Configurable Default // hasDefaultKeyData = false; // for (final EResource eResource : eApplication.getResources()) { // if (DefaultDataApplicationTypeAdapter.hasDefaultDataValue(eResource.getConfiguration().getConfigDefault())) { // hasDefaultKeyData = true; // break; // } // } PersConfExport.copyDefaultDataFiles(configDefaultFileFolder, eApplication, EConfiguration::getConfigDefault); final File configDefaultsFile = new File( keyFolder.getAbsolutePath() + File.separator + PersConfDefinitions.CONFIGURABLE_DEFAULTS_FILE); final GsonBuilder configurableDefaultGsonBuilder = PersConfExport.createGsonBuilder(); configurableDefaultGsonBuilder.registerTypeAdapter(EApplicationImpl.class, new DefaultDataApplicationTypeAdapter(false)); configurableDefaultGsonBuilder.registerTypeAdapter(EDefaultDataImpl.class, new DefaultDataTypeAdapter()); final Gson configurableDefaultGson = configurableDefaultGsonBuilder.create(); try (final FileWriter fileWriter = new FileWriter(configDefaultsFile)) { fileWriter.write(configurableDefaultGson.toJson(eApplication)); } catch (final IOException e) { e.printStackTrace(); } appNames.add(eApplication.getName()); } final File[] groupFiles = groupFolder.listFiles((FileFilter) DirectoryFileFilter.INSTANCE); // remove all application folders not part of the current configuration anymore if (groupFiles != null) { for (final File appFolder : groupFiles) { if (!appNames.contains(appFolder.getName())) { try { FileUtils.deleteDirectory(appFolder); } catch (final IOException e) { Logger.error(Activator.PLUGIN_ID, "Unable to delete removed application directory: " + appFolder.getName(), e); } } } } return persistStatus; }
From source file:com.zonaAzulDigital.services.CartaoZonaAzulService.java
@POST @Path("/comprar") @Consumes(MediaType.APPLICATION_JSON)/*ww w . jav a2s .c o m*/ public Response comprarCartao(String json) { Response r = Response.serverError().build(); if (json != null && !json.isEmpty()) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Placa.class, new PlacaDeserializer()); gsonBuilder.registerTypeAdapter(Motorista.class, new MotoristaDeserializer()); Gson gson = gsonBuilder.create(); ModelCartaoZonaAzulInterface mcza = new ModelCartaoZonaAzul(new DaoMotoristaBD(), new DaoCartaoZonaAzulBD(), new DaoCompraCartaoZADB(), new DaoPlacaBD()); ModelMotoristaInterface mc = new ModelMotorista(new DaoMotoristaBD()); try { Motorista m = gson.fromJson(json, Motorista.class); Placa p = gson.fromJson(json, Placa.class); Motorista motorista = mc.login(m.getCpf(), m.getSenha()); mcza.comprar(motorista, p); Motorista motoristaRetorno = mc.login(m.getCpf(), m.getSenha()); motoristaRetorno.setSenha(""); String jsonRetorno = gson.toJson(motoristaRetorno); r = Response.ok(jsonRetorno).build(); } catch (PlacaException pe) { r = Response.status(403).build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, pe); } catch (MotoristaException me) { r = Response.status(406).build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, me); } catch (LoginException le) { r = Response.status(401).build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, le); } catch (Exception e) { r = Response.serverError().build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, e); } } return r; }
From source file:com.zonaAzulDigital.services.CartaoZonaAzulService.java
@GET @Path("/buscar") @Consumes(MediaType.APPLICATION_JSON)// www. ja va2 s. co m public Response consultarCartao(String json) { Response r = Response.serverError().build(); if (json != null || !json.isEmpty()) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Placa.class, new PlacaDeserializer()); Gson gson = gsonBuilder.create(); ModelCartaoZonaAzulInterface mcza = new ModelCartaoZonaAzul(new DaoMotoristaBD(), new DaoCartaoZonaAzulBD(), new DaoCompraCartaoZADB(), new DaoPlacaBD()); try { Placa p = gson.fromJson(json, Placa.class); CartaoZonaAzul cza = mcza.recuperaCartaoAtivo(p); String jsonRetorno = gson.toJson(cza); r = Response.ok(jsonRetorno).build(); } catch (DaoException de) { r = Response.status(417).build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, de); } catch (PlacaException pe) { r = Response.status(403).build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, pe); } catch (Exception e) { r = Response.serverError().build(); Logger.getLogger(CartaoZonaAzulService.class.getName()).log(Level.SEVERE, null, e); } } return r; }
From source file:com.zuoxiaolong.blog.sdk.BlogInterfaceHandler.java
License:Apache License
/** * ?????/* w ww . j a v a 2s .co m*/ * * @return */ public static List<ArticleRankResponseDto> getArticleRank() throws Exception { HttpRequest request = new HttpRequest(); String responseString = request.doGet(BlogSdkPropertiesUtil.getProperty("articleRankUrl")); System.out.println(responseString); // Creates the json object which will manage the information received GsonBuilder gsonBuilder = new GsonBuilder(); // Register an adapter to manage the date types as long values gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong()); } }); Gson gson = gsonBuilder.create(); Type articleRankResponseDtoListType = new TypeToken<List<ArticleRankResponseDto>>() { }.getType(); List<ArticleRankResponseDto> articleRankResponseDtos = gson.fromJson(responseString, articleRankResponseDtoListType); return articleRankResponseDtos; }