Example usage for com.google.gson JsonObject add

List of usage examples for com.google.gson JsonObject add

Introduction

In this page you can find the example usage for com.google.gson JsonObject add.

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

From source file:co.com.konrad.interbolsa.ws.EmpresaFacadeREST.java

@POST
@Override/*from w  ww. j a v a2  s. com*/
@Path("create")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String create(Empresa entity) throws Exception {
    //VAriable json
    JsonObject res = new JsonObject();
    Gson gson = new Gson();
    try {
        super.create(entity);
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");

        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<Empresa> rt = cq.from(Empresa.class);
        cq.where(cb.equal(rt.get(Empresa_.empresaNit), entity.getEmpresaNit()));
        javax.persistence.TypedQuery<Empresa> q = getEntityManager().createQuery(cq);
        Empresa empresa = q.getSingleResult();
        res.add("data", gson.toJsonTree(empresa));

    } catch (Throwable ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Error guardando entidad", ex);
        res.addProperty("codigo", 400);
        res.addProperty("mensaje", "operacion fallida");
    }
    return res.toString();
}

From source file:co.com.konrad.interbolsa.ws.UsuarioFacadeREST.java

@POST
@Override//from www  .  j a va2 s  .  c om
@Path("create")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String create(Usuario entity) throws Exception {
    JsonObject res = new JsonObject();
    Gson gson = new Gson();
    try {
        super.create(entity);
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");

        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<Usuario> rt = cq.from(Usuario.class);
        cq.where(cb.equal(rt.get(Usuario_.usuarioCedula), entity.getUsuarioCedula()));
        javax.persistence.TypedQuery<Usuario> q = getEntityManager().createQuery(cq);
        Usuario usuario = q.getSingleResult();
        res.add("data", gson.toJsonTree(usuario));
    } catch (Throwable ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Erro guardando entidad", ex);
        res.addProperty("codigo", 400);
        res.addProperty("mensaje", "operacion fallida");
    }
    return res.toString();
}

From source file:co.com.konrad.interbolsa.ws.UsuarioFacadeREST.java

@POST
@Path("login")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String login(Usuario entity) {
    JsonObject res = new JsonObject();
    Gson gson = new Gson();
    System.out.println("Correo " + entity.getUsuarioCorreo());
    System.out.println("Clave " + entity.getUsuairoClave());
    try {//from   w  w w . j a v  a  2s.c om
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");
        /*
        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<Usuario> rt = cq.from(Usuario.class);
        cq.where(
            cb.equal(rt.get(Usuario_.usuarioCorreo), entity.getUsuarioCorreo()),
            cb.equal(rt.get(Usuario_.usuairoClave), entity.getUsuairoClave())
        );
        javax.persistence.TypedQuery<Usuario> q = getEntityManager().createQuery(cq);
        Usuario usuario = q.getSingleResult();*/
        //res.add("data", gson.toJsonTree(usuario));

        String nativeQuery = " SELECT * FROM usuario INNER JOIN empresa ON empresa_id = empresa_empresa_id WHERE usuario_correo = ? AND usuairo_clave = ?";
        Query query = getEntityManager().createNativeQuery(nativeQuery);
        query.setParameter(1, entity.getUsuarioCorreo());
        query.setParameter(2, entity.getUsuairoClave());
        Object usuario = query.getSingleResult();
        res.add("data", gson.toJsonTree(usuario));
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Erro guardando entidad", ex);
        res.addProperty("codigo", 300);
        res.addProperty("mensaje", "Error de autenticacin");
    }
    return res.toString();
}

From source file:color.GetColorMaster.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w . j ava 2  s.  com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final DBHelper helper = DBHelper.GetDBHelper();
    final Connection dataConnection = helper.getConnMpAdmin();
    final JsonObject jResultObj = new JsonObject();
    if (dataConnection != null) {
        try {
            String sql = "select COLOUR_CD,COLOUR_NAME,USER_ID from COLOURMST";
            PreparedStatement pstLocal = dataConnection.prepareStatement(sql);
            ResultSet rsLocal = pstLocal.executeQuery();
            JsonArray array = new JsonArray();
            while (rsLocal.next()) {
                JsonObject object = new JsonObject();
                object.addProperty("COLOUR_CD", rsLocal.getString("COLOUR_CD"));
                object.addProperty("COLOUR_NAME", rsLocal.getString("COLOUR_NAME"));
                object.addProperty("USER_ID", rsLocal.getInt("USER_ID"));
                array.add(object);
            }
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
            jResultObj.add("data", array);
        } catch (SQLNonTransientConnectionException ex1) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", "Server is down");
        } catch (SQLException ex) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", ex.getMessage());
        }
    }
    response.getWriter().print(jResultObj);
}

From source file:com.adobe.acs.commons.audit_log_search.impl.AuditLogSearchServlet.java

License:Apache License

@Override
@SuppressWarnings("squid:S1141")
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    log.trace("doGet");

    AuditLogSearchRequest req = null;/*  w ww.j  a  va  2  s.co m*/

    JsonObject result = new JsonObject();
    boolean succeeded = true;
    try {
        req = new AuditLogSearchRequest(request);
        log.debug("Loaded search request: {}", req);

        JsonArray results = new JsonArray();
        long count = 0;
        String whereClause = req.getQueryParameters();
        StringBuilder queryBuilder = new StringBuilder("SELECT * FROM [cq:AuditEvent] AS s");
        if (StringUtils.isNotEmpty(whereClause)) {
            queryBuilder.append(" WHERE ").append(whereClause);
        }
        String queryStr = queryBuilder.toString();
        log.debug("Finding audit events with: {}", queryStr);
        ResourceResolver resolver = request.getResourceResolver();
        QueryManager queryManager = resolver.adaptTo(Session.class).getWorkspace().getQueryManager();
        Query query = queryManager.createQuery(queryStr, Query.JCR_SQL2);

        int limit = -1;
        if (StringUtils.isNotEmpty(request.getParameter("limit"))) {
            limit = Integer.parseInt(request.getParameter("limit"), 10);
            if (limit > 0) {
                log.debug("Limiting to {} results", limit);
                query.setLimit(limit);
            }
        }

        NodeIterator nodes = query.execute().getNodes();
        log.debug("Query execution complete!");
        while (nodes.hasNext()) {
            results.add(serializeAuditEvent(resolver.getResource(nodes.nextNode().getPath()), req));
            count++;
        }
        result.addProperty("count", count);
        result.add("events", results);
        log.debug("Found {} audit events", count);
    } catch (ParseException e) {
        log.warn("Encountered exception parsing start / end date", e);
        succeeded = false;
    } catch (RepositoryException e) {
        log.warn("Encountered respository exception attempting to retrieve audit events", e);
        succeeded = false;
    } catch (ClassNotFoundException e) {
        log.warn("Encountered exception deserializing attributes", e);
        succeeded = false;
    }

    result.addProperty("succeeded", succeeded);

    response.setContentType("application/json");
    response.getWriter().write(result.toString());
}

From source file:com.adobe.acs.commons.audit_log_search.impl.AuditLogSearchServlet.java

License:Apache License

private JsonObject serializeAuditEvent(Resource auditEventResource, AuditLogSearchRequest request)
        throws RepositoryException, IOException, ClassNotFoundException {
    JsonObject auditEvent = new JsonObject();
    ValueMap properties = auditEventResource.getValueMap();
    auditEvent.addProperty("category", properties.get("cq:category", String.class));
    auditEvent.addProperty("eventPath", auditEventResource.getPath());
    auditEvent.addProperty("path", properties.get("cq:path", String.class));
    auditEvent.addProperty("type", properties.get("cq:type", String.class));
    String userId = properties.get("cq:userid", String.class);
    auditEvent.addProperty("userId", userId);
    auditEvent.addProperty("userName", request.getUserName(auditEventResource.getResourceResolver(), userId));
    auditEvent.addProperty("userPath", request.getUserPath(auditEventResource.getResourceResolver(), userId));
    auditEvent.addProperty("time", properties.get("cq:time", new Date()).getTime());

    JsonArray modified = getModifiedProperties(properties);
    if (properties.get("above", String.class) != null) {
        modified.add(new JsonPrimitive("above=" + properties.get("above", String.class)));
    }//from ww w. ja  v  a2 s.  co m
    if (properties.get("destination", String.class) != null) {
        modified.add(new JsonPrimitive("destination=" + properties.get("destination", String.class)));
    }
    if (properties.get("versionId", String.class) != null) {
        modified.add(new JsonPrimitive("versionId=" + properties.get("versionId", String.class)));
    }
    if (modified.size() != 0) {
        auditEvent.add("modified", modified);
    }

    return auditEvent;
}

From source file:com.adobe.acs.commons.exporters.impl.users.UsersInitServlet.java

License:Apache License

/**
 * Returns a JSON containing the options available to the form, and any prior saved data that should pre-populate the form.
 * @param request the Sling HTTP Request object
 * @param response the Sling HTTP Response object
 * @throws IOException/*from   w  w  w. ja  v  a2 s .c o  m*/
 * @throws ServletException
 */
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    final JsonObject json = new JsonObject();
    final JsonObject existing = new JsonObject();
    final JsonObject options = new JsonObject();

    try {
        options.add(GROUPS, getGroupOptions(request.getResourceResolver()));
        options.add(GROUP_FILTERS, getGroupFilterOptions());

        final Parameters parameters = new Parameters(request.getResource());
        existing.addProperty(GROUP_FILTER, parameters.getGroupFilter());
        existing.add(GROUPS, new Gson().toJsonTree(Arrays.asList(parameters.getGroups())));
        existing.add(CUSTOM_PROPERTIES, parameters.getCustomPropertiesAsJSON());

        json.add("options", options);
        json.add("form", existing);

    } catch (RepositoryException e) {
        throw new ServletException(e);
    }

    response.getWriter().write(json.toString());
    response.getWriter().flush();
}

From source file:com.adobe.acs.commons.forms.helpers.impl.PostRedirectGetFormHelperImpl.java

License:Apache License

protected final String getQueryParameterValue(Form form) {
    boolean hasData = false;
    final JsonObject jsonData = new JsonObject();

    form = this.clean(form);

    jsonData.addProperty(KEY_FORM_NAME, form.getName());

    Gson gson = new Gson();

    if (form.hasData()) {
        final JsonObject jsonForm = (JsonObject) gson.toJsonTree(form.getData());
        jsonData.add(KEY_FORM, jsonForm);
        hasData = true;//from   w w w.  j av a2  s .  c  o  m
    }

    if (form.hasErrors()) {
        final JsonObject jsonError = (JsonObject) gson.toJsonTree(form.getErrors());
        jsonData.add(KEY_ERRORS, jsonError);
        hasData = true;
    }

    return hasData ? this.encode(jsonData.toString()) : "";

}

From source file:com.adobe.acs.commons.packaging.impl.PackageHelperImpl.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  w w  .ja va2  s .co m*/
 */
public String getSuccessJSON(final JcrPackage jcrPackage) throws RepositoryException {
    final JsonObject json = new JsonObject();

    json.addProperty(KEY_STATUS, "success");
    json.addProperty(KEY_PATH, jcrPackage.getNode().getPath());
    JsonArray filterSetsArray = new JsonArray();
    json.add(KEY_FILTER_SETS, filterSetsArray);

    final List<PathFilterSet> filterSets = jcrPackage.getDefinition().getMetaInf().getFilter().getFilterSets();
    for (final PathFilterSet filterSet : filterSets) {
        final JsonObject jsonFilterSet = new JsonObject();
        jsonFilterSet.addProperty(KEY_IMPORT_MODE, filterSet.getImportMode().name());
        jsonFilterSet.addProperty(KEY_ROOT_PATH, filterSet.getRoot());

        filterSetsArray.add(jsonFilterSet);
    }

    return json.toString();
}

From source file:com.adobe.acs.commons.packaging.impl.PackageHelperImpl.java

License:Apache License

/**
 * {@inheritDoc}/*from w ww.  j av a2 s .c  om*/
 */
public String getPathFilterSetPreviewJSON(final Collection<PathFilterSet> pathFilterSets) {
    final JsonObject json = new JsonObject();

    json.addProperty(KEY_STATUS, "preview");
    json.addProperty(KEY_PATH, "Not applicable (Preview)");
    JsonArray filterSets = new JsonArray();
    json.add(KEY_FILTER_SETS, filterSets);

    for (final PathFilterSet pathFilterSet : pathFilterSets) {
        final JsonObject tmp = new JsonObject();
        tmp.addProperty(KEY_IMPORT_MODE, "Not applicable (Preview)");
        tmp.addProperty(KEY_ROOT_PATH, pathFilterSet.getRoot());

        filterSets.add(tmp);
    }

    return json.toString();
}