Example usage for com.google.gson JsonObject addProperty

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

Introduction

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

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

License:Apache License

/**
 * This method performs the Adobe I/O action
 *
 * @param payload//from  w w w .  j  a  va 2 s  .c o  m
 *            Payload of the call
 * @return JsonObject containing the result
 */
private JsonObject handleAdobeIO_Action(@NotNull final JsonObject payload) {
    // initialize jsonobject
    JsonObject processResponse = new JsonObject();

    // perform action, if the action is defined in the configuration
    try {
        LOGGER.debug("ActionUrl = {} . method = {}", url, method);
        // process the Adobe I/O action
        processResponse = process(url, Collections.emptyMap(), method, null, payload);
    } catch (Exception e) {
        processResponse.addProperty(RESULT_ERROR, "Problem processing");
        LOGGER.error("Problem processing action {} in handleAdobeIO_Action", url);
    }

    return processResponse;
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

License:Apache License

private JsonObject responseAsJson(@NotNull final HttpResponse response) throws IOException {
    String result = IOUtils.toString(response.getEntity().getContent(), CharEncoding.UTF_8);
    JsonParser parser = new JsonParser();
    JsonObject resultJson = new JsonObject();
    try {//from   w  w w.j  a va 2 s  .  co m
        LOGGER.debug("Call result = {}", result);
        resultJson = parser.parse(result).getAsJsonObject();
    } catch (Exception e) {
        resultJson.addProperty(RESULT_ERROR, result);
    }

    LOGGER.debug("JSON result from Service: {}", resultJson);
    return resultJson;
}

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;/*from   w  w  w  .  j  a  v a2  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   w ww .ja  v a 2s .c om
    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.dam.impl.CustomComponentActivatorListServlet.java

License:Apache License

@Activate
protected void activate(Config conf) {
    Map<String, String> components = ParameterUtil
            .toMap(PropertiesUtil.toStringArray(conf.components(), DEFAULT_COMPONENTS), "=");
    JsonArray array = new JsonArray();
    for (Map.Entry<String, String> entry : components.entrySet()) {
        JsonObject obj = new JsonObject();
        obj.addProperty("propertyName", entry.getKey());
        obj.addProperty("componentPath", entry.getValue());
        array.add(obj);/*w  ww.  ja v a2 s  . c o m*/
    }
    this.json = new JsonObject();
    json.add("components", array);
}

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

License:Apache License

protected JsonArray getCustomPropertiesAsJSON() {
    final JsonArray jsonArray = new JsonArray();

    for (String customProperty : customProperties) {
        final JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(RELATIVE_PROPERTY_PATH, customProperty);
        jsonArray.add(jsonObject);//from   w w w  .j  a va 2s. co  m
    }

    return jsonArray;
}

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 .  j a v  a  2 s.  co  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.exporters.impl.users.UsersInitServlet.java

License:Apache License

/**
 * Creates a list of options for the Group Filter list.
 * @return a JSON Array of the available group filter options.
 * @throws JSONException// w  ww.j  av a  2s.  c  o  m
 */
private JsonArray getGroupFilterOptions() {
    JsonObject both = new JsonObject();
    both.addProperty(KEY_TEXT, "Direct or Indirect Membership");
    both.addProperty(KEY_VALUE, GROUP_FILTER_BOTH);

    JsonObject direct = new JsonObject();
    direct.addProperty(KEY_TEXT, "Direct Membership");
    direct.addProperty(KEY_VALUE, GROUP_FILTER_DIRECT);

    JsonObject indirect = new JsonObject();
    indirect.addProperty(KEY_TEXT, "Indirect Membership");
    indirect.addProperty(KEY_VALUE, GROUP_FILTER_INDIRECT);

    JsonArray jsonArray = new JsonArray();
    jsonArray.add(direct);
    jsonArray.add(indirect);
    jsonArray.add(both);

    return jsonArray;
}

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. jav  a 2 s  .co  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.oak.sql2scorer.impl.servlets.ExplainScoreServlet.java

License:Apache License

@Override
protected void doPost(@Nonnull final SlingHttpServletRequest request,
        @Nonnull final SlingHttpServletResponse response) throws ServletException, IOException {

    response.setContentType("application/json;charset=utf-8");

    final long limit = ofNullable(request.getParameter(P_LIMIT)).map(Long::valueOf).orElse(10L);
    final long offset = ofNullable(request.getParameter(P_OFFSET)).map(Long::valueOf).orElse(0L);

    // require a query statement
    final String rawStatement = request.getParameter(P_STATEMENT);
    if (rawStatement == null) {
        JsonObject obj = new JsonObject();
        obj.addProperty(KEY_ERROR, "please submit a valid JCR-SQL2 query in the `statement` parameter.");
        response.getWriter().write(obj.toString());
        return;// w  w w .  j a  v  a  2s. c  o m
    }

    try {
        final Session session = request.getResourceResolver().adaptTo(Session.class);
        if (session == null || !session.isLive()) {
            throw new RepositoryException("failed to get a live JCR session from the request");
        }

        final QueryManager qm = session.getWorkspace().getQueryManager();

        // validate the syntax of the raw statement.
        Query rawQuery = qm.createQuery(rawStatement, Query.JCR_SQL2);
        rawQuery.setLimit(1L);
        rawQuery.execute();

        // we can then expect the first SELECT to exist and be the instance we want to replace. (case-insensitive)
        final String statement = rawStatement.replaceFirst("(?i)SELECT", "SELECT [oak:scoreExplanation],");

        // create a new query using our enhanced statement
        final Query query = qm.createQuery(statement, Query.JCR_SQL2);

        // set limit and offset
        query.setLimit(limit);
        query.setOffset(offset);

        // prepare Gson with QueryExecutingTypeAdapter
        Gson json = new GsonBuilder()
                .registerTypeHierarchyAdapter(Query.class, new QueryExecutingTypeAdapter(qm)).create();

        // execute the query and write the response.
        response.getWriter().write(json.toJson(query));
    } catch (final InvalidQueryException e) {
        JsonObject obj = new JsonObject();
        obj.addProperty(KEY_ERROR,
                "please submit a valid JCR-SQL2 query in the `statement` parameter: " + e.getMessage());
        response.getWriter().write(obj.toString());
    } catch (final RepositoryException e) {
        JsonObject obj = new JsonObject();
        obj.addProperty(KEY_ERROR, e.getMessage());
        response.getWriter().write(obj.toString());
    }
}