List of usage examples for com.google.gson ExclusionStrategy ExclusionStrategy
ExclusionStrategy
From source file:edu.utd.cs6301.shas.controller.DetectorServlet.java
public void init() throws ServletException { gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { return false; }/* w w w . j a va 2s . c om*/ /** * Custom field exclusion goes here */ public boolean shouldSkipField(FieldAttributes f) { return false; } }) /** * Use serializeNulls method if you want To serialize null * values By default, Gson does not serialize null values */ .serializeNulls().create(); }
From source file:edu.utd.cs6301.shas.controller.SprinklerServlet.java
public void init() throws ServletException { gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { return (clazz == Sprinklersetting.class); }// ww w . j a va2 s . c o m /** * Custom field exclusion goes here */ public boolean shouldSkipField(FieldAttributes f) { return false; } }) /** * Use serializeNulls method if you want To serialize null * values By default, Gson does not serialize null values */ .serializeNulls().create(); }
From source file:edu.utd.cs6301.shas.controller.SprinklerSettingServlet.java
public void init() throws ServletException { gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { return (clazz == Sprinkler.class); }//from w w w . j a va 2 s . co m /** * Custom field exclusion goes here */ public boolean shouldSkipField(FieldAttributes f) { return false; } }) /** * Use serializeNulls method if you want To serialize null * values By default, Gson does not serialize null values */ .serializeNulls().create(); }
From source file:ee.ria.xroad.common.util.JsonUtils.java
License:Open Source License
/** * Get Gson with custom serializer./*from ww w. jav a2s . c om*/ * @return Gson instance with custom serializer. */ public static Gson getSerializer() { GsonBuilder builder = new GsonBuilder(); builder.disableHtmlEscaping(); builder.registerTypeAdapter(ClientId.class, new ClientIdSerializer()); builder.setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(Exclude.class) != null; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); return builder.create(); }
From source file:fi.vm.sade.organisaatio.business.impl.OrganisaatioTarjonta.java
License:EUPL
private void initGson() { GsonBuilder gsonBuilder = new GsonBuilder(); // Jtetn oid pois sill KoulutusHakutulosV1RDTO sislt kaksi oid kentt gsonBuilder.setExclusionStrategies(new ExclusionStrategy() { @Override// w ww . jav a 2s . c o m public boolean shouldSkipField(FieldAttributes fieldAttributes) { return "oid".equals(fieldAttributes.getName()); } @Override public boolean shouldSkipClass(Class<?> arg0) { return false; } }); // Rekisteridn adapteri, jolla hoidetaan date tyyppi long arvona gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong()); } }); gson = gsonBuilder.create(); }
From source file:fr.gael.dhus.service.UserService.java
License:Open Source License
/** * Facility method to easily provide user content with resolved lazy fields * to be able to serialize. The method takes care of the possible cycles * such as "users->pref->filescanners->collections->users" ... * It also removes possible huge product list from collections. * * @param u the user to resolve.//from w ww. j av a 2s .c o m * @return the resolved user. */ @Transactional(readOnly = true, propagation = Propagation.REQUIRED) @Cacheable(value = "json_user", key = "#u") public User resolveUser(User u) { u = userDao.read(u.getUUID()); Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { // Avoid huge number of products in collection return clazz == Product.class; } /** * Custom field exclusion goes here */ public boolean shouldSkipField(FieldAttributes f) { // Avoid cycles caused by collection tree and user/auth users... return f.getName().equals("authorizedUsers") || f.getName().equals("parent") || f.getName().equals("subCollections"); } }).serializeNulls().create(); String users_string = gson.toJson(u); return gson.fromJson(users_string, User.class); }
From source file:info.raack.appliancedetection.evaluation.web.EvaluationController.java
License:Open Source License
@RequestMapping(value = "/evaluation/{id}", method = RequestMethod.GET) public void getEvaluationData(@PathVariable("id") String simulationId, @RequestParam("algorithmId") int algorithmId, @RequestParam(value = "start", required = false) Double startMillis, @RequestParam(value = "end", required = false) Double endMillis, @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO - for now, just use the naive algorithm's energy measurements. Date start = null;/* w w w. ja v a 2 s . c o m*/ Date end = null; if (startMillis != null && endMillis != null) { start = new Date(startMillis.longValue()); end = new Date(endMillis.longValue()); } else if (startMillis != null && endMillis == null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(startMillis.longValue()); start = c.getTime(); } else if (startMillis == null && endMillis != null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(endMillis.longValue()); end = c.getTime(); } if (ticks == null) { ticks = 300; } Evaluation evaluation = simulationService.getEvaluation(algorithmId, simulationId, start, end, true); if (evaluation == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } EvaluationWrapper wrapper = new EvaluationWrapper(evaluation); JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() { // serialize date to milliseconds since epoch public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) { JsonArray object = new JsonArray(); object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime())); object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed())); return object; } }; String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer) .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() { // skip logger public boolean shouldSkipClass(Class<?> clazz) { return clazz.equals(Logger.class); } public boolean shouldSkipField(FieldAttributes fieldAttributes) { // skip simulation of simulated appliance return (fieldAttributes.getName().equals("simulation") && fieldAttributes.getDeclaringClass() == SimulatedAppliance.class) || // skip simulation second data (fieldAttributes.getName().equals("secondData") && fieldAttributes.getDeclaringClass() == Simulation.class) || // skip endTime of energytimestep (fieldAttributes.getName().equals("endTime") && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) || // skip userAppliance, detectionAlgorithmId of appliance state transition ((fieldAttributes.getName().equals("userAppliance") || fieldAttributes.getName().equals("detectionAlgorithmId")) && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class); } }).create().toJson(wrapper); response.getWriter().write(dataJS); response.setContentType("application/json"); }
From source file:info.raack.appliancedetection.evaluation.web.EvaluationController.java
License:Open Source License
@RequestMapping(value = "/evaluationgroup/{id}", method = RequestMethod.GET) public void getEvaluationGroupData(@PathVariable("id") int simulationGroupId, HttpServletRequest request, HttpServletResponse response) throws IOException { EvaluationGroup evaluationGroup = simulationService.getEvaluationGroup(simulationGroupId); if (evaluationGroup == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return;//from w w w. j av a2 s .co m } String dataJS = new GsonBuilder().excludeFieldsWithModifiers(Modifier.STATIC) .setExclusionStrategies(new ExclusionStrategy() { // skip logger public boolean shouldSkipClass(Class<?> clazz) { return clazz.equals(Logger.class); } public boolean shouldSkipField(FieldAttributes fieldAttributes) { // skip everything in evaluation except overallEnergyError or simulation return (!(fieldAttributes.getName().equals("stateTransitionPrecision") || fieldAttributes.getName().equals("stateTransitionRecall") || fieldAttributes.getName().equals("stateTransitionAccuracy") || fieldAttributes.getName().equals("overallAccuracy") || fieldAttributes.getName().equals("overallEnergyError") || fieldAttributes.getName().equals("simulation")) && fieldAttributes.getDeclaringClass() == Evaluation.class) || // skip everything in simulation except id and durationInSeconds (!(fieldAttributes.getName().equals("id") || fieldAttributes.getName().equals("durationInSeconds")) && fieldAttributes.getDeclaringClass() == Simulation.class); } }).create().toJson(evaluationGroup); response.getWriter().write(dataJS); response.setContentType("application/json"); }
From source file:info.raack.appliancelabeler.web.MainController.java
License:Open Source License
@RequestMapping(value = "/energy/{frequency}", method = RequestMethod.GET) public void getEnergyData(@PathVariable("frequency") String frequency, @RequestParam(value = "start", required = false) Double startMillis, @RequestParam(value = "end", required = false) Double endMillis, @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request, HttpServletResponse response) throws IOException { // need to get latest values from stepgreen service EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response); Date start = new Date(); Date end = new Date(); if (startMillis != null && endMillis != null) { start = new Date(startMillis.longValue()); end = new Date(endMillis.longValue()); } else if (startMillis != null && endMillis == null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(startMillis.longValue()); start = new Date(); start.setTime(startMillis.longValue()); c.add(Calendar.DATE, 1);/*from ww w .java 2s. c o m*/ end = c.getTime(); } else if (startMillis == null && endMillis != null) { // if only start or end are provided, create a one day span Calendar c = new GregorianCalendar(); c.setTimeInMillis(endMillis.longValue()); end = new Date(); end.setTime(endMillis.longValue()); c.add(Calendar.DATE, -1); start = c.getTime(); } else { createOneDaySpan(energyMonitor, start, end); } if (ticks == null) { ticks = 300; } Date queryStart = null; Date queryEnd = null; // if the time window is less than 5 minutes, then just take the window as is; otherwise, enlarge the window to the 5 minute interval requested if (end.getTime() - start.getTime() > (5 * 60 * 1000)) { Calendar cal = new GregorianCalendar(); cal.setTime(start); queryStart = dateUtils.getPreviousFiveMinuteIncrement(cal).getTime(); cal = new GregorianCalendar(); cal.setTime(end); queryEnd = dateUtils.getNextFiveMinuteIncrement(cal).getTime(); } else { queryStart = start; queryEnd = end; } List<SecondData> data = getEnergyDataWithLimits(energyMonitor, DataService.DataFrequency.valueOf(frequency.toUpperCase()), queryStart, queryEnd, ticks); Map<UserAppliance, List<EnergyTimestep>> predictedEnergyUsage = dataService .getApplianceEnergyConsumptionForMonitor(energyMonitor, algorithm.getId(), queryStart, queryEnd); Map<UserAppliance, List<ApplianceStateTransition>> predictedApplianceStateTransitions = dataService .getPredictedApplianceStateTransitionsForMonitor(energyMonitor, algorithm.getId(), queryStart, queryEnd); JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() { // serialize date to milliseconds since epoch public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) { JsonArray object = new JsonArray(); object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime())); object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed())); return object; } }; EnergyWrapper energyWrapper = new EnergyWrapper(data, predictedEnergyUsage, predictedApplianceStateTransitions, database.getEnergyCost(energyMonitor)); String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer) .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() { // skip logger public boolean shouldSkipClass(Class<?> clazz) { return clazz.equals(Logger.class); } public boolean shouldSkipField(FieldAttributes fieldAttributes) { // skip endTime of energytimestep return (fieldAttributes.getName().equals("endTime") && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) || // skip userAppliance, detectionAlgorithmId of appliance state transition ((fieldAttributes.getName().equals("userAppliance") || fieldAttributes.getName().equals("detectionAlgorithmId")) && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class); } }).create().toJson(energyWrapper); response.getWriter().write(dataJS); // set appropriate JSON response type response.setContentType("application/json"); }
From source file:io.barracks.ota.client.Utils.java
License:Apache License
public static Gson getRobolectricGson(GsonBuilder builder) { return builder.setExclusionStrategies(new ExclusionStrategy() { @Override//from www.j a v a2s . co m public boolean shouldSkipField(FieldAttributes f) { return "__robo_data__".equals(f.getName()); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }).create(); }