Example usage for com.google.gson GsonBuilder excludeFieldsWithoutExposeAnnotation

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

Introduction

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

Prototype

public GsonBuilder excludeFieldsWithoutExposeAnnotation() 

Source Link

Document

Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the com.google.gson.annotations.Expose annotation.

Usage

From source file:net.daw.service.generic.implementation.ViewServiceGenImpl.java

License:Open Source License

@Override
public String get(Integer id) throws Exception {
    String data = null;/*from   w  ww  .  j  a  v a2  s  .c o  m*/
    try {
        oConnection.setAutoCommit(false);
        BeanGenImpl oGenericBean = (BeanGenImpl) Class
                .forName("net.daw.bean.generic.specific.implementation." + strPojo + "BeanGenSpImpl")
                .newInstance();
        Constructor c = Class.forName("net.daw.dao.generic.specific.implementation." + strPojo + "DaoGenSpImpl")
                .getConstructor(String.class, Connection.class);
        TableDaoGenImpl oGenericDao = (TableDaoGenImpl) c.newInstance(strObjectName, oConnection);
        oGenericBean.setId(id);
        oGenericBean = (BeanGenImpl) (BeanInterface) oGenericDao.get(oGenericBean,
                AppConfigurationHelper.getJsonDepth());
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("dd/MM/yyyy");
        Gson gson = gsonBuilder.excludeFieldsWithoutExposeAnnotation().create();
        data = gson.toJson(oGenericBean);
    } catch (Exception ex) {
        oConnection.rollback();
        ExceptionBooster.boost(new Exception(this.getClass().getName() + ":get ERROR: " + ex.getMessage()));
    } finally {
        oConnection.commit();
    }
    return data;
}

From source file:net.daw.service.generic.implementation.ViewServiceGenImpl.java

License:Open Source License

@Override
public String getPage(int intRegsPerPag, int intPage, ArrayList<FilterBeanHelper> alFilter,
        HashMap<String, String> hmOrder) throws Exception {
    String data = null;// w  w w.j a  v a 2 s  .  c  om
    try {
        oConnection.setAutoCommit(false);
        BeanGenImpl oGenericBean = (BeanGenImpl) Class
                .forName("net.daw.bean.generic.specific.implementation." + strPojo + "BeanGenSpImpl")
                .newInstance();
        Constructor c = Class.forName("net.daw.dao.generic.specific.implementation." + strPojo + "DaoGenSpImpl")
                .getConstructor(String.class, Connection.class);
        TableDaoGenImpl oGenericDao = (TableDaoGenImpl) c.newInstance(strObjectName, oConnection);
        List<BeanInterface> loGenericBean = oGenericDao.getPage(intRegsPerPag, intPage, alFilter, hmOrder);
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("dd/MM/yyyy");
        Gson gson = gsonBuilder.excludeFieldsWithoutExposeAnnotation().create();
        data = gson.toJson(loGenericBean);
        data = "{\"list\":" + data + "}";
    } catch (Exception ex) {
        oConnection.rollback();
        ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getPage ERROR: " + ex.getMessage()));
    } finally {
        oConnection.commit();
    }
    return data;
}

From source file:net.oneandone.stool.util.BuildStats.java

License:Apache License

public static Gson gson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    return gsonBuilder.create();
}

From source file:net.onrc.openvirtex.api.service.handlers.monitoring.GetPhysicalTopology.java

License:Apache License

@SuppressWarnings("unchecked")
@Override// w w  w  .  j  a  v  a2s  .co m
public JSONRPC2Response process(final Object params) {
    Map<String, Object> result;
    JSONRPC2Response resp = null;
    // TODO: gson objects can be shared with other methods
    final GsonBuilder gsonBuilder = new GsonBuilder();
    //gsonBuilder.setPrettyPrinting();
    gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    gsonBuilder.registerTypeAdapter(PhysicalSwitch.class, new PhysicalSwitchSerializer());
    gsonBuilder.registerTypeAdapter(PhysicalPort.class, new PhysicalPortSerializer());
    /*gsonBuilder.registerTypeAdapter(PhysicalLink.class,
    new PhysicalLinkSerializer());*/

    final Gson gson = gsonBuilder.create();

    result = gson.fromJson(gson.toJson(PhysicalNetwork.getInstance()), Map.class);
    resp = new JSONRPC2Response(result, 0);
    return resp;
}

From source file:net.onrc.openvirtex.api.service.handlers.monitoring.GetVirtualTopology.java

License:Apache License

@SuppressWarnings("unchecked")
@Override// www .j  a  v a  2  s .c  o  m
public JSONRPC2Response process(final Map<String, Object> params) {
    Map<String, Object> result;
    JSONRPC2Response resp = null;
    Number tid = null;
    try {
        tid = HandlerUtils.<Number>fetchField(MonitoringHandler.TENANT, params, true, null);
        OVXNetwork vnet = OVXMap.getInstance().getVirtualNetwork(tid.intValue());
        // TODO: gson objects can be shared with other methods
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        gsonBuilder.registerTypeAdapter(OVXSwitch.class, new OVXSwitchSerializer());
        gsonBuilder.registerTypeAdapter(OVXPort.class, new OVXPortSerializer());
        /*gsonBuilder.registerTypeAdapter(OVXLink.class,
              new OVXLinkSerializer());*/

        final Gson gson = gsonBuilder.create();
        result = gson.fromJson(gson.toJson(vnet), Map.class);
        resp = new JSONRPC2Response(result, 0);
        return resp;
    } catch (ClassCastException | MissingRequiredField e) {
        resp = new JSONRPC2Response(new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
                this.cmdName() + ": Unable to fetch virtual topology : " + e.getMessage()), 0);
    } catch (NetworkMappingException e) {
        resp = new JSONRPC2Response(new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(),
                this.cmdName() + ": Invalid tenantId : " + tid), 0);
    }
    return resp;
}

From source file:org.foxbpm.web.common.util.JSONUtil.java

License:Apache License

private static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();/*from  ww w.  j  a  va  2  s  .  c o m*/
    if (version != null)
        builder.setVersion(version.doubleValue());
    // if (StringUtil.isEmpty(datePattern))
    // datePattern = DEFAULT_DATE_PATTERN;
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    String result = null;
    Gson gson = builder.create();
    try {
        if (targetType != null) {
            result = gson.toJson(target, targetType);
        } else {
            result = gson.toJson(target);
        }
    } catch (Exception ex) {
        if (target instanceof Collection || target instanceof Iterator || target instanceof Enumeration
                || target.getClass().isArray()) {
            result = EMPTY_JSON_ARRAY;
        } else
            result = EMPTY_JSON;
    }
    return result;
}

From source file:org.iti.agrimarket.service.OfferProductRestController.java

/**
 * is responsible to Get all offers/*from w  ww .  j  a v  a2  s .  c  om*/
 *
 * @author Muhammad
 * @param param to get all offers associated with an id
 * @return JSON list of all offers on a product
 */
@RequestMapping(value = GET_OFFERS_URL, method = RequestMethod.POST)
public Response getOffers(@RequestBody String param) {

    GetOffersParam parsedParam = paramExtractor.getParam(param, GetOffersParam.class);

    if (parsedParam == null || parsedParam.getProductId() == 0) {
        logger.trace(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }

    int productId = parsedParam.getProductId();

    GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    Gson gson = builder.create();

    Product product = null;
    if (productId != 0) {
        //check if product existed 
        product = productServiceInterface.getProduct(productId);
        List<UserOfferProductFixed> offers = offerService.getOffers(product);
        if (!offers.isEmpty()) {
            return Response.ok("{\"" + Constants.OFFERS + "\":" + gson.toJson(offers) + "}",
                    MediaType.APPLICATION_JSON).build();
        } else {
            return Response.status(Response.Status.NO_CONTENT).build();
        }
    } else {
        logger.trace(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();

    }

}

From source file:org.iti.agrimarket.service.OfferProductRestController.java

/**
 * is responsible to Get all offers associated with an user
 *
 * @author Muhammad/*from   w  ww . ja  v  a 2s.com*/
 * @param userId to get all offers associated with an user
 * @param user is user name for the service
 * @param key is the encrypted key
 * @return JSON list of all user's offers
 */
@RequestMapping(value = GET_USER_OFFERS_URL, method = RequestMethod.POST)
public Response getUserOffers(@RequestBody String param) {

    GetUserOffersParam parsedParam = paramExtractor.getParam(param, GetUserOffersParam.class);

    if (parsedParam == null || parsedParam.getUserId() == 0) {
        logger.trace(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }

    int userId = parsedParam.getUserId();
    GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    Gson gson = builder.create();
    User userObj;
    if (userId != 0) {
        userObj = userService.getUser(userId);
        List<UserOfferProductFixed> offers = offerService.getUserOffers(userObj);
        if (!offers.isEmpty()) {
            return Response.ok("{\"" + Constants.OFFERS + "\":" + gson.toJson(offers) + "}",
                    MediaType.APPLICATION_JSON).build();
        } else {
            return Response.status(Response.Status.NO_CONTENT).build();
        }
    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

}

From source file:org.iti.agrimarket.service.SearchRestController.java

@RequestMapping(value = SEARCH_LIMITED_OFFERS_URL, method = RequestMethod.POST)
public Response getLimitedOffersByProductName(@RequestBody String param) {

    SearchLimitedOffersByProductNameParam parsedParam = paramExtractor.getParam(param,
            SearchLimitedOffersByProductNameParam.class);

    if (parsedParam == null || parsedParam.getProductName() == null || parsedParam.getProductName().isEmpty()
            || parsedParam.getPageNo() <= 0) {
        logger.trace(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }/*from  w ww.  ja  va  2  s . co  m*/

    String productName = parsedParam.getProductName();

    GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    Gson gson = builder.create();

    //        GroupedOffers offers = offerService.searchGroupedLimitedOffers(productName, parsedParam.getPageNo(), parsedParam.getSortType());
    List<UserOfferProductFixed> offers = offerService.searchLimitedOffers(productName, parsedParam.getPageNo(),
            parsedParam.getSortType());
    if (offers != null) {

        List<UserOfferProductFixed> newOffers = new ArrayList<>();
        for (UserOfferProductFixed userOffer : offers) {
            UserOfferProductFixed newOffer = new UserOfferProductFixed();
            newOffer.setId(userOffer.getId());
            newOffer.setDescription(userOffer.getDescription());
            newOffer.setImageUrl(userOffer.getImageUrl());
            newOffer.setPrice(userOffer.getPrice());
            newOffer.setQuantity(userOffer.getQuantity());
            newOffer.setRecommended(userOffer.getRecommended());
            newOffer.setStartDate(userOffer.getStartDate());
            newOffer.setUserLocation(userOffer.getUserLocation());
            newOffer.setUserPhone(userOffer.getUserPhone());
            User user = new User();
            user.setId(userOffer.getUser().getId());
            user.setFullName(userOffer.getUser().getFullName());
            newOffer.setUser(user);
            Product newProduct = new Product();
            newProduct.setId(userOffer.getProduct().getId());
            newProduct.setNameAr(userOffer.getProduct().getNameAr());
            newProduct.setNameEn(userOffer.getProduct().getNameEn());
            newOffer.setProduct(newProduct);
            Unit newUnitQuantity = new Unit();
            newUnitQuantity.setId(userOffer.getUnitByUnitId().getId());
            newUnitQuantity.setNameAr(userOffer.getUnitByUnitId().getNameAr());
            newUnitQuantity.setNameEn(userOffer.getUnitByUnitId().getNameEn());
            newOffer.setUnitByUnitId(newUnitQuantity);
            Unit newUnitPrice = new Unit();
            newUnitPrice.setId(userOffer.getUnitByPricePerUnitId().getId());
            newUnitPrice.setNameAr(userOffer.getUnitByPricePerUnitId().getNameAr());
            newUnitPrice.setNameEn(userOffer.getUnitByPricePerUnitId().getNameEn());
            newOffer.setUnitByPricePerUnitId(newUnitPrice);

            newOffers.add(newOffer);
        }
        return Response.ok(getCustomAdaptedGson().toJson(newOffers), MediaType.APPLICATION_JSON).build();
    } else {
        return Response.status(Constants.DB_ERROR).build();
    }

}

From source file:org.iti.agrimarket.service.UserRestController.java

@RequestMapping(value = Constants.GET_USER_URL, method = RequestMethod.POST)
public Response getUser(@RequestBody String paramJson) {

    //parse getUnit String to Json object
    GetUserParam userParam = paramExtractor.getParam(paramJson, GetUserParam.class);
    User user = null;/*from w  w w.  j av  a2 s .co  m*/
    // validate  propertise of userParam object 
    if (userParam != null && userParam.getId() != null) {
        // Get unit object from DB by id
        user = userServiceInterface.getUser(userParam.getId());
        GsonBuilder builder = new GsonBuilder();
        builder.excludeFieldsWithoutExposeAnnotation();
        Gson gson = builder.create();
        if (user != null) {
            return Response.ok(gson.toJson(user), MediaType.APPLICATION_JSON).build();
        } else {
            // return missing parameter error 

            logger.trace(Constants.INVALID_PARAM);
            return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
        }
    } else {
        // return missing parameter error 

        logger.trace(Constants.INVALID_PARAM);
        return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build();
    }
}