Search in sources :

Example 11 with JSONObject

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

the class PackageHelperImpl method getSuccessJSON.

/**
 * {@inheritDoc}
 */
public String getSuccessJSON(final JcrPackage jcrPackage) throws JSONException, RepositoryException {
    final JSONObject json = new JSONObject();
    json.put(KEY_STATUS, "success");
    json.put(KEY_PATH, jcrPackage.getNode().getPath());
    json.put(KEY_FILTER_SETS, new JSONArray());
    final List<PathFilterSet> filterSets = jcrPackage.getDefinition().getMetaInf().getFilter().getFilterSets();
    for (final PathFilterSet filterSet : filterSets) {
        final JSONObject jsonFilterSet = new JSONObject();
        jsonFilterSet.put(KEY_IMPORT_MODE, filterSet.getImportMode().name());
        jsonFilterSet.put(KEY_ROOT_PATH, filterSet.getRoot());
        json.accumulate(KEY_FILTER_SETS, jsonFilterSet);
    }
    return json.toString();
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) PathFilterSet(org.apache.jackrabbit.vault.fs.api.PathFilterSet) JSONArray(org.apache.sling.commons.json.JSONArray)

Example 12 with JSONObject

use of org.apache.sling.commons.json.JSONObject 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 13 with JSONObject

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

the class InitServlet method doGet.

@Override
public final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    final JSONObject json = new JSONObject();
    try {
        // Only populate the form if removal is not running.
        json.put("form", this.getFormJSONObject(request.getResourceResolver()));
        response.getWriter().write(json.toString());
    } catch (Exception e) {
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(e.getMessage());
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) WorkflowException(com.day.cq.workflow.WorkflowException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) JSONException(org.apache.sling.commons.json.JSONException)

Example 14 with JSONObject

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

the class Failure method toJSON.

public JSONObject toJSON() throws JSONException {
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss aaa");
    JSONObject json = new JSONObject();
    json.put(PN_PATH, getPath());
    json.put(PN_PAYLOAD_PATH, getPayloadPath());
    json.put(PN_FAILED_AT, sdf.format(getFailedAt().getTime()));
    return json;
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat)

Example 15 with JSONObject

use of org.apache.sling.commons.json.JSONObject 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)

Aggregations

JSONObject (org.apache.sling.commons.json.JSONObject)74 JSONArray (org.apache.sling.commons.json.JSONArray)22 Test (org.junit.Test)20 JSONException (org.apache.sling.commons.json.JSONException)16 HashMap (java.util.HashMap)15 ValueMap (org.apache.sling.api.resource.ValueMap)9 Map (java.util.Map)8 ArrayList (java.util.ArrayList)6 ServletException (javax.servlet.ServletException)6 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)6 Resource (org.apache.sling.api.resource.Resource)6 RepositoryException (javax.jcr.RepositoryException)5 Calendar (java.util.Calendar)4 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)4 Config (com.adobe.acs.commons.workflow.bulk.execution.model.Config)3 IOException (java.io.IOException)3 LinkedHashMap (java.util.LinkedHashMap)3 Session (javax.jcr.Session)3 ModifiableValueMapDecorator (org.apache.sling.api.wrappers.ModifiableValueMapDecorator)3 Form (com.adobe.acs.commons.forms.Form)2