Example usage for com.google.gson FieldAttributes getDeclaringClass

List of usage examples for com.google.gson FieldAttributes getDeclaringClass

Introduction

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

Prototype

public Class<?> getDeclaringClass() 

Source Link

Usage

From source file:com.jd.survey.web.settings.NowwebmanagerController.java

License:Open Source License

@Override
public boolean shouldSkipField(FieldAttributes fieldattributes) {
    Class<?> owner = fieldattributes.getDeclaringClass();
    Class<?> c = fieldattributes.getDeclaredClass();
    String f = fieldattributes.getName();
    boolean isSkip = false;

    if (owner == target) {
        if (ArrayUtils.contains(fields, f)) {
            log.debug("fitler field:{} for class:{}", f, owner);
            isSkip = true;//from w  w  w  .  ja  va  2 s.c o  m
        }
        if (ArrayUtils.contains(clazz, c)) {
            log.debug("fitler class:{} for class:{}", c, owner);
            isSkip = true;
        }
        if (reverse) {
            isSkip = !isSkip;
        }
    }

    return isSkip;
}

From source file:de.chaosfisch.services.ExportPostProcessor.java

License:Open Source License

@Override
public Upload process(final Upload upload) {
    if (!config.getBoolean(ExportPostProcessor.JSON_LOGFILES, false)) {
        return upload;
    }/*from w  w  w .  j a va 2 s.  c o  m*/

    LOGGER.info("Running export postprocessor");
    final Gson gson = new GsonBuilder().setPrettyPrinting()
            .addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(final FieldAttributes f) {
                    return f.getDeclaringClass().isAssignableFrom(Account.class);
                }

                @Override
                public boolean shouldSkipClass(final Class<?> clazz) {
                    return clazz.isAssignableFrom(Account.class);
                }
            }).registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).serializeNulls().create();

    try {
        final Upload copy = gson.fromJson(gson.toJson(upload), Upload.class);

        try {
            Files.createDirectories(Paths.get(ApplicationData.DATA_DIR + "/uploads/"));
            Files.write(
                    Paths.get(String.format("%s/uploads/%s.json", ApplicationData.DATA_DIR, copy.getVideoid())),
                    gson.toJson(copy).getBytes(Charsets.UTF_8));
        } catch (final IOException e) {
            LOGGER.warn("Couldn't write json log.", e);
        }
        LOGGER.info("Finished export postprocessor");
    } catch (final Exception e) {
        e.printStackTrace();
    }

    return upload;
}

From source file:dtu.ds.warnme.ws.rest.json.gson.exclusionStrategies.PasswordExclusionStrategy.java

License:Open Source License

@Override
public boolean shouldSkipField(FieldAttributes f) {
    return f.getDeclaringClass().equals(clazz) && f.getName().equals(field.getName());
}

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;/*from w w w  .  ja v  a 2  s .c om*/
    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 ww.ja  va 2  s.c o 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.j a  v  a  2  s .c  om
        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.realm.examples.realmgridview.GridViewExampleActivity.java

License:Apache License

private List<City> loadCities() {
    // In this case we're loading from local assets.
    // NOTE: could alternatively easily load from network
    InputStream stream = null;//from w w  w . j  a  va 2 s . co m
    try {
        stream = getAssets().open("cities.json");
    } catch (IOException e) {
        return null;
    }

    // GSON can parse the data.
    // Note there is a bug in GSON 2.3.1 that can cause it to StackOverflow when working with RealmObjects.
    // To work around this, use the ExclusionStrategy below or downgrade to 1.7.1
    // See more here: https://code.google.com/p/google-gson/issues/detail?id=440
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }).create();

    JsonElement json = new JsonParser().parse(new InputStreamReader(stream));
    List<City> cities = gson.fromJson(json, new TypeToken<List<City>>() {
    }.getType());

    // Open a transaction to store items into the realm
    // Use copyToRealm() to convert the objects into proper RealmObjects managed by Realm.
    realm.beginTransaction();
    Collection<City> realmCities = realm.copyToRealm(cities);
    realm.commitTransaction();

    return new ArrayList<City>(realmCities);
}

From source file:io.realm.examples.realmrecyclerview.RecyclerViewExampleActivity.java

License:Apache License

private void initGson() {
    gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override/*from ww  w.  j  ava2  s.  co  m*/
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }).create();
}

From source file:managedbeans.MyExclusionStrategy.java

public boolean shouldSkipField(FieldAttributes f) {
    return (f.getDeclaringClass() == paciente.class && f.getName().equals("CLAPS"))
            || (f.getDeclaringClass() == clap.class && f.getName().equals("paciente"))
            || (f.getDeclaringClass() == region.class && f.getName().equals("comunas"))
            || (f.getDeclaringClass() == comuna.class && f.getName().equals("region"))
            || (f.getDeclaringClass() == cesfam.class && f.getName().equals("comuna"))
            || (f.getDeclaringClass() == Crafft.class && f.getName().equals("clap"))
            || (f.getDeclaringClass() == audit.class && f.getName().equals("clap")) || f.getName().equals("row")
            || f.getName().startsWith("_");

}

From source file:me.drakeet.meizhi.other.ActiveAndroidStrategy.java

License:Open Source License

@Override
public boolean shouldSkipField(FieldAttributes attributes) {
    return attributes.getDeclaringClass().equals(excludedThisClassFields);
}