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:com.adobe.acs.commons.quickly.impl.QuicklyEngineImpl.java

License:Apache License

private JsonObject getJSONResults(Command cmd, SlingHttpServletRequest request,
        final Collection<Result> results) {
    final JsonObject json = new JsonObject();

    JsonArray resultArray = new JsonArray();
    json.add(KEY_RESULTS, resultArray);

    final ValueMap requestConfig = new ValueMapDecorator(new HashMap<String, Object>());

    // Collect all items collected from OSGi Properties
    requestConfig.putAll(this.config);

    // Add Request specific configurations
    requestConfig.put(AuthoringUIMode.class.getName(), authoringUIModeService.getAuthoringUIMode(request));

    for (final Result result : results) {
        final JsonObject tmp = resultBuilder.toJSON(cmd, result, requestConfig);

        if (tmp != null) {
            resultArray.add(tmp);/*  w  w w.  java  2 s .  c  om*/
        }
    }

    return json;
}

From source file:com.adobe.acs.commons.quickly.results.impl.serializers.AbstractResultSerializer.java

License:Apache License

public JsonObject toJSON(final Result result) {
    final JsonObject json = new JsonObject();

    json.addProperty("title", result.getTitle());
    json.addProperty("type", result.getResultType());
    json.addProperty("description", result.getDescription());
    json.addProperty("path", result.getPath());

    json.add("action", this.toJSON(result.getAction()));
    json.add("secondaryAction", this.toJSON(result.getSecondaryAction()));

    return json;/*from   w  ww .  j  a va 2 s  .  c o m*/
}

From source file:com.adobe.acs.commons.quickly.results.impl.serializers.AbstractResultSerializer.java

License:Apache License

public JsonObject toJSON(final Action action) {

    final JsonObject json = new JsonObject();

    if (action != null) {
        Gson gson = new Gson();
        json.addProperty("uri", action.getUri());
        json.addProperty("method", action.getMethod().name());
        json.addProperty("target", action.getTarget().name());
        json.addProperty("xhr", false);
        json.addProperty("script", action.getScript());
        json.add("params", gson.toJsonTree(action.getParams()));
    }/*from   w  w w. j a v a2 s  . co  m*/

    return json;
}

From source file:com.adobe.acs.commons.redirectmaps.impl.RedirectEntriesUtils.java

License:Apache License

protected static final void writeEntriesToResponse(SlingHttpServletRequest request,
        SlingHttpServletResponse response, String message) throws IOException {
    log.trace("writeEntriesToResponse");

    log.debug("Requesting redirect maps from {}", request.getResource());
    RedirectMapModel redirectMap = request.getResource().adaptTo(RedirectMapModel.class);

    response.setContentType(MediaType.JSON_UTF_8.toString());

    JsonObject res = new JsonObject();
    res.addProperty("message", message);

    if (redirectMap != null) {
        JsonElement entries = gson.toJsonTree(redirectMap.getEntries(), new TypeToken<List<MapEntry>>() {
        }.getType());//from ww  w.j  ava 2s .c  o  m
        res.add("entries", entries);
        res.add("invalidEntries",
                gson.toJsonTree(redirectMap.getInvalidEntries(), new TypeToken<List<MapEntry>>() {
                }.getType()));
    } else {
        throw new IOException("Failed to get redirect map from " + request.getResource());
    }

    IOUtils.write(res.toString(), response.getOutputStream(), StandardCharsets.UTF_8);
}

From source file:com.adobe.acs.commons.replication.impl.ReplicateVersionServlet.java

License:Apache License

@Override
public final void doPost(SlingHttpServletRequest req, SlingHttpServletResponse res)
        throws ServletException, IOException {

    log.debug("Entering ReplicatePageVersionServlet.doPost(..)");

    String[] rootPaths = req.getParameterValues("rootPaths");
    Date date = getDate(req.getParameter("datetimecal"));
    String[] agents = req.getParameterValues("cmbAgent");

    JsonObject obj = validate(rootPaths, agents, date);

    if (!obj.has(KEY_ERROR)) {
        log.debug("Initiating version replication");

        List<ReplicationResult> response = replicateVersion.replicate(req.getResourceResolver(), rootPaths,
                agents, date);/*from w w  w.j a va  2  s  .  co m*/

        if (log.isDebugEnabled()) {
            for (final ReplicationResult replicationResult : response) {
                log.debug("Replication result: {} -- {}", replicationResult.getPath(),
                        replicationResult.getStatus());
            }
        }

        JsonArray arr = convertResponseToJson(response);
        obj = new JsonObject();
        obj.add(KEY_RESULT, arr);

    } else {
        log.debug("Did not attempt to replicate version due to issue with input params");

        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        obj.addProperty(KEY_STATUS, KEY_ERROR);
    }

    res.setContentType("application/json");
    res.getWriter().print(obj.toString());
}

From source file:com.adobe.acs.commons.synth.children.ChildrenAsPropertyResource.java

License:Apache License

/**
 * Serializes all children data as JSON to the resource's propertyName.
 *
 * @throws InvalidDataFormatException//from   w ww  .  j a v  a  2s.co m
 */
private void serialize() throws InvalidDataFormatException {
    final long start = System.currentTimeMillis();

    final ModifiableValueMap modifiableValueMap = this.resource.adaptTo(ModifiableValueMap.class);
    JsonObject childrenJSON = new JsonObject();

    try {
        // Add the new entries to the JSON
        for (Resource childResource : this.orderedCache) {
            childrenJSON.add(childResource.getName(), this.serializeToJSON(childResource));
        }

        if (childrenJSON.entrySet().size() > 0) {
            // Persist the JSON back to the Node
            modifiableValueMap.put(this.propertyName, childrenJSON.toString());
        } else {
            // Nothing to persist; delete the property
            modifiableValueMap.remove(this.propertyName);
        }

        log.debug("Persist operation for [ {} ] in [ {} ms ]",
                this.resource.getPath() + "/" + this.propertyName, System.currentTimeMillis() - start);

    } catch (NoSuchMethodException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    } catch (IllegalAccessException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    } catch (InvocationTargetException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    }
}

From source file:com.adobe.acs.commons.wcm.impl.AbstractWidgetConfigurationServlet.java

License:Apache License

/**
 * Load the base configuration and "underlay" it under the provided
 * configuration so that the provided configuration overwrites the default
 * configuration./*from   w w w.  j  a  v  a 2 s .c o  m*/
 *
 * @param config the configuration to underlay
 * @param resource the resource to underlay
 * @return the underlayed configuration
 * @throws JSONException
 * @throws ServletException
 */
protected final JsonObject underlay(JsonObject config, Resource resource) throws ServletException {
    JsonObject baseStructure = JsonObjectUtil.toJsonObject(resource);
    if (baseStructure != null) {
        config.entrySet().forEach(e -> baseStructure.add(e.getKey(), e.getValue()));
        return baseStructure;
    } else {
        return config;
    }
}

From source file:com.adobe.acs.commons.wcm.impl.CustomPollingImporterListServlet.java

License:Apache License

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    XSSAPI xssApi = request.adaptTo(XSSAPI.class);
    JsonObject result = new JsonObject();
    JsonArray list = new JsonArray();
    result.add("list", list);

    ServiceReference[] services = tracker.getServiceReferences();
    if (services != null) {
        for (ServiceReference service : services) {
            String displayName = PropertiesUtil.toString(service.getProperty("displayName"), null);
            String[] schemes = PropertiesUtil.toStringArray(service.getProperty(Importer.SCHEME_PROPERTY));
            if (displayName != null && schemes != null) {
                for (String scheme : schemes) {
                    JsonObject obj = new JsonObject();
                    obj.addProperty("qtip", "");
                    obj.addProperty("text", displayName);
                    obj.addProperty("text_xss", xssApi.encodeForJSString(displayName));
                    obj.addProperty("value", scheme);
                    list.add(obj);//from w ww  . j  a v  a 2 s  .c  o  m
                }
            }
        }
    }

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    Gson gson = new Gson();
    gson.toJson(result, response.getWriter());
}

From source file:com.adobe.acs.commons.wcm.impl.RTEConfigurationServlet.java

License:Apache License

private void writeConfigResource(Resource resource, String rteName, SlingHttpServletRequest request,
        SlingHttpServletResponse response) throws IOException, ServletException {
    JsonObject widget = createEmptyWidget(rteName);

    // these two size properties seem to be necessary to get the size correct
    // in a component dialog
    widget.addProperty("width", RTE_WIDTH);
    widget.addProperty("height", RTE_HEIGHT);

    RequestParameterMap map = request.getRequestParameterMap();
    for (Map.Entry<String, RequestParameter[]> entry : map.entrySet()) {
        String key = entry.getKey();
        RequestParameter[] params = entry.getValue();
        if (params != null && (params.length > 1 || EXTERNAL_STYLESHEETS_PROPERTY.equals(key))) {
            JsonArray arr = new JsonArray();
            for (int i = 0; i < params.length; i++) {
                arr.add(new JsonPrimitive(params[i].getString()));
            }//from  www.ja v  a2 s.  c o m
            widget.add(key, arr);
        } else if (params != null && params.length == 1) {
            widget.addProperty(key, params[0].getString());
        }
    }

    if (widget.has("fieldLabel")) {
        widget.remove("hideLabel");
    }

    JsonObject config = toJsonObject(resource);

    if (config == null) {
        config = new JsonObject();
    }

    if (config.has("includeDefault") && config.get("includeDefault").getAsBoolean()) {
        config = underlay(config, resource.getResourceResolver().getResource(DEFAULT_CONFIG));
    }

    widget.add("rtePlugins", config);

    JsonObject parent = new JsonObject();
    parent.addProperty("xtype", "dialogfieldset");
    parent.addProperty("border", false);
    parent.addProperty("padding", 0);
    parent.add("items", widget);
    Gson gson = new Gson();
    gson.toJson(parent, response.getWriter());
}

From source file:com.adobe.acs.commons.wcm.impl.TagWidgetConfigurationServlet.java

License:Apache License

private void writeConfigResource(Resource resource, String propertyName, SlingHttpServletRequest request,
        SlingHttpServletResponse response) throws IOException, ServletException {
    JsonObject widget = createEmptyWidget(propertyName);

    RequestParameterMap map = request.getRequestParameterMap();
    for (Map.Entry<String, RequestParameter[]> entry : map.entrySet()) {
        String key = entry.getKey();
        RequestParameter[] params = entry.getValue();
        if (params != null) {
            if (params.length > 1) {
                JsonArray arr = new JsonArray();
                for (int i = 0; i < params.length; i++) {
                    arr.add(new JsonPrimitive(params[i].getString()));
                }//  w  w w .  j a  v  a 2  s . co m
                widget.add(key, arr);
            } else if (params.length == 1) {
                widget.addProperty(key, params[0].getString());
            }
        }
    }

    widget = underlay(widget, resource);

    JsonObject parent = new JsonObject();
    parent.addProperty("xtype", "dialogfieldset");
    parent.addProperty("border", false);
    parent.addProperty("padding", 0);
    parent.addProperty("style", "padding: 0px");
    parent.add("items", widget);
    Gson gson = new Gson();
    gson.toJson(parent, response.getWriter());
}