Search in sources :

Example 6 with JSONArray

use of org.apache.sling.commons.json.JSONArray in project acs-aem-commons by Adobe-Consulting-Services.

the class JsonEventLogger method convertValue.

/**
 * Converts individual java objects to JSONObjects using reflection and recursion
 * @param val an untyped Java object to try to convert
 * @return {@code val} if not handled, or return a converted JSONObject, JSONArray, or String
 * @throws JSONException
 */
@SuppressWarnings({ "unchecked", "squid:S3776" })
protected static Object convertValue(Object val) throws JSONException {
    if (val.getClass().isArray()) {
        Object[] vals = (Object[]) val;
        JSONArray array = new JSONArray();
        for (Object arrayVal : vals) {
            Object converted = convertValue(arrayVal);
            array.put(converted == null ? arrayVal : converted);
        }
        return array;
    } else if (val instanceof Collection) {
        JSONArray array = new JSONArray();
        for (Object arrayVal : (Collection<?>) val) {
            Object converted = convertValue(arrayVal);
            array.put(converted == null ? arrayVal : converted);
        }
        return array;
    } else if (val instanceof Map) {
        Map<?, ?> valMap = (Map<?, ?>) val;
        JSONObject obj = new JSONObject();
        if (valMap.isEmpty()) {
            return obj;
        } else if (valMap.keySet().iterator().next() instanceof String) {
            for (Map.Entry<String, ?> entry : ((Map<String, ?>) valMap).entrySet()) {
                Object converted = convertValue(entry.getValue());
                obj.put(entry.getKey(), converted == null ? entry.getValue() : converted);
            }
        } else {
            for (Map.Entry<?, ?> entry : valMap.entrySet()) {
                Object converted = convertValue(entry.getValue());
                obj.put(entry.getKey().toString(), converted == null ? entry.getValue() : converted);
            }
        }
        return obj;
    } else if (val instanceof Calendar) {
        try {
            return ISO8601.format((Calendar) val);
        } catch (IllegalArgumentException e) {
            log.debug("[constructMessage] failed to convert Calendar to ISO8601 String: {}, {}", e.getMessage(), val);
        }
    } else if (val instanceof Date) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime((Date) val);
            return ISO8601.format(calendar);
        } catch (IllegalArgumentException e) {
            log.debug("[constructMessage] failed to convert Date to ISO8601 String: {}, {}", e.getMessage(), val);
        }
    }
    return val;
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) Calendar(java.util.Calendar) JSONArray(org.apache.sling.commons.json.JSONArray) Collection(java.util.Collection) JSONObject(org.apache.sling.commons.json.JSONObject) Map(java.util.Map) Date(java.util.Date)

Example 7 with JSONArray

use of org.apache.sling.commons.json.JSONArray in project acs-aem-commons by Adobe-Consulting-Services.

the class TranscriptionServiceImpl method getResult.

@Override
public Result getResult(String jobId) {
    log.debug("getting result for {}", jobId);
    Request request = httpClientFactory.get("/speech-to-text/api/v1/recognitions/" + jobId);
    try {
        JSONObject json = httpClientFactory.getExecutor().execute(request).handleResponse(HANDLER);
        log.trace("content: {}", json.toString(2));
        if (json.getString("status").equals("completed")) {
            JSONArray results = json.getJSONArray("results").getJSONObject(0).getJSONArray("results");
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < results.length(); i++) {
                JSONObject result = results.getJSONObject(i);
                if (result.getBoolean("final")) {
                    JSONObject firstAlternative = result.getJSONArray("alternatives").getJSONObject(0);
                    String line = firstAlternative.getString("transcript");
                    if (StringUtils.isNotBlank(line)) {
                        double firstTimestamp = firstAlternative.getJSONArray("timestamps").getJSONArray(0).getDouble(1);
                        builder.append("[").append(firstTimestamp).append("s]: ").append(line).append("\n");
                    }
                }
            }
            String concatenated = builder.toString();
            concatenated = concatenated.replace("%HESITATION ", "");
            return new ResultImpl(true, concatenated);
        } else {
            return new ResultImpl(false, null);
        }
    } catch (Exception e) {
        log.error("Unable to get result. assuming failure.", e);
        return new ResultImpl(true, "error");
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) Request(org.apache.http.client.fluent.Request) JSONArray(org.apache.sling.commons.json.JSONArray)

Example 8 with JSONArray

use of org.apache.sling.commons.json.JSONArray in project acs-aem-commons by Adobe-Consulting-Services.

the class QuicklyEngineImpl method getJSONResults.

private JSONObject getJSONResults(Command cmd, SlingHttpServletRequest request, final Collection<Result> results) throws JSONException {
    final JSONObject json = new JSONObject();
    json.put(KEY_RESULTS, new JSONArray());
    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) {
            json.accumulate(KEY_RESULTS, tmp);
        }
    }
    return json;
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) ValueMap(org.apache.sling.api.resource.ValueMap) JSONArray(org.apache.sling.commons.json.JSONArray) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) JSONObject(org.apache.sling.commons.json.JSONObject) AuthoringUIMode(com.day.cq.wcm.api.AuthoringUIMode) Result(com.adobe.acs.commons.quickly.results.Result)

Example 9 with JSONArray

use of org.apache.sling.commons.json.JSONArray in project acs-aem-commons by Adobe-Consulting-Services.

the class WorkflowModelFilterPageInfoProvider method filter.

@SuppressWarnings("squid:S3776")
private void filter(JSONObject typeObject, String resourcePath, ResourceResolver resourceResolver) throws JSONException {
    final JSONArray models = typeObject.getJSONArray(KEY_MODELS);
    final JSONArray newModels = new JSONArray();
    for (int i = 0; i < models.length(); i++) {
        final JSONObject modelObject = models.getJSONObject(i);
        final String path = modelObject.getString(KEY_MODEL_PATH);
        final Resource modelResource = resourceResolver.getResource(path);
        if (modelResource != null) {
            // we're looking for the appliesTo property on the jcr:content node, the wid value
            // is the path to the jcr:content/model node.
            final ValueMap properties = modelResource.getParent().getValueMap();
            final String[] allowedPaths = properties.get(PN_ALLOWED_PATHS, String[].class);
            if (allowedPaths == null) {
                newModels.put(modelObject);
            } else {
                for (final String allowedPath : allowedPaths) {
                    if (resourcePath.matches(allowedPath)) {
                        newModels.put(modelObject);
                        break;
                    }
                }
            }
        }
    }
    typeObject.put(KEY_MODELS, newModels);
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) ValueMap(org.apache.sling.api.resource.ValueMap) JSONArray(org.apache.sling.commons.json.JSONArray) Resource(org.apache.sling.api.resource.Resource)

Example 10 with JSONArray

use of org.apache.sling.commons.json.JSONArray in project acs-aem-commons by Adobe-Consulting-Services.

the class TagWidgetConfigurationServlet method writeConfigResource.

private void writeConfigResource(Resource resource, String propertyName, SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, JSONException, 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.put(params[i].getString());
                }
                widget.put(key, arr);
            } else if (params.length == 1) {
                widget.put(key, params[0].getString());
            }
        }
    }
    widget = underlay(widget, resource);
    JSONObject parent = new JSONObject();
    parent.put("xtype", "dialogfieldset");
    parent.put("border", false);
    parent.put("padding", 0);
    parent.put("style", "padding: 0px");
    parent.accumulate("items", widget);
    parent.write(response.getWriter());
}
Also used : RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) JSONObject(org.apache.sling.commons.json.JSONObject) RequestParameter(org.apache.sling.api.request.RequestParameter) JSONArray(org.apache.sling.commons.json.JSONArray) RequestParameterMap(org.apache.sling.api.request.RequestParameterMap) Map(java.util.Map)

Aggregations

JSONArray (org.apache.sling.commons.json.JSONArray)23 JSONObject (org.apache.sling.commons.json.JSONObject)22 Map (java.util.Map)4 ValueMap (org.apache.sling.api.resource.ValueMap)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 PathFilterSet (org.apache.jackrabbit.vault.fs.api.PathFilterSet)3 Resource (org.apache.sling.api.resource.Resource)3 Page (com.day.cq.wcm.api.Page)2 Calendar (java.util.Calendar)2 HashSet (java.util.HashSet)2 Session (javax.jcr.Session)2 ServletException (javax.servlet.ServletException)2 RequestParameter (org.apache.sling.api.request.RequestParameter)2 RequestParameterMap (org.apache.sling.api.request.RequestParameterMap)2 JSONException (org.apache.sling.commons.json.JSONException)2 Result (com.adobe.acs.commons.quickly.results.Result)1 WorkflowRemovalForceQuitException (com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalForceQuitException)1 ClientLibrary (com.adobe.granite.ui.clientlibs.ClientLibrary)1