Search in sources :

Example 31 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class SimpleDistributionQueueProvider method enableQueueProcessing.

public void enableQueueProcessing(@Nonnull DistributionQueueProcessor queueProcessor, String... queueNames) {
    if (checkpoint) {
        // recover from checkpoints
        log.debug("recovering from checkpoints if needed");
        for (final String queueName : queueNames) {
            log.debug("recovering for queue {}", queueName);
            DistributionQueue queue = getQueue(queueName);
            FilenameFilter filenameFilter = new FilenameFilter() {

                @Override
                public boolean accept(File file, String name) {
                    return name.equals(queueName + "-checkpoint");
                }
            };
            for (File qf : checkpointDirectory.listFiles(filenameFilter)) {
                log.info("recovering from checkpoint {}", qf);
                try {
                    LineIterator lineIterator = IOUtils.lineIterator(new FileReader(qf));
                    while (lineIterator.hasNext()) {
                        String s = lineIterator.nextLine();
                        String[] split = s.split(" ");
                        String id = split[0];
                        String infoString = split[1];
                        Map<String, Object> info = new HashMap<String, Object>();
                        JsonReader reader = Json.createReader(new StringReader(infoString));
                        JsonObject jsonObject = reader.readObject();
                        for (Map.Entry<String, JsonValue> entry : jsonObject.entrySet()) {
                            if (entry.getValue().getValueType().equals(JsonValue.ValueType.ARRAY)) {
                                JsonArray value = jsonObject.getJsonArray(entry.getKey());
                                String[] a = new String[value.size()];
                                for (int i = 0; i < a.length; i++) {
                                    a[i] = value.getString(i);
                                }
                                info.put(entry.getKey(), a);
                            } else if (JsonValue.NULL.equals(entry.getValue())) {
                                info.put(entry.getKey(), null);
                            } else {
                                info.put(entry.getKey(), ((JsonString) entry.getValue()).getString());
                            }
                        }
                        queue.add(new DistributionQueueItem(id, info));
                    }
                    log.info("recovered {} items from queue {}", queue.getStatus().getItemsCount(), queueName);
                } catch (FileNotFoundException e) {
                    log.warn("could not read checkpoint file {}", qf.getAbsolutePath());
                } catch (JsonException e) {
                    log.warn("could not parse info from checkpoint file {}", qf.getAbsolutePath());
                }
            }
        }
        // enable checkpointing
        for (String queueName : queueNames) {
            ScheduleOptions options = scheduler.NOW(-1, 15).canRunConcurrently(false).name(getJobName(queueName + "-checkpoint"));
            scheduler.schedule(new SimpleDistributionQueueCheckpoint(getQueue(queueName), checkpointDirectory), options);
        }
    }
    // enable processing
    for (String queueName : queueNames) {
        ScheduleOptions options = scheduler.NOW(-1, 1).canRunConcurrently(false).name(getJobName(queueName));
        scheduler.schedule(new SimpleDistributionQueueProcessor(getQueue(queueName), queueProcessor), options);
    }
}
Also used : JsonException(javax.json.JsonException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FileNotFoundException(java.io.FileNotFoundException) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) LineIterator(org.apache.commons.io.LineIterator) FilenameFilter(java.io.FilenameFilter) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) FileReader(java.io.FileReader) DistributionQueue(org.apache.sling.distribution.queue.DistributionQueue) JsonValue(javax.json.JsonValue) DistributionQueueItem(org.apache.sling.distribution.queue.DistributionQueueItem) JsonArray(javax.json.JsonArray) ScheduleOptions(org.apache.sling.commons.scheduler.ScheduleOptions) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 32 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class DistributionUtils method getQueues.

public static Map<String, Map<String, Object>> getQueues(SlingInstance instance, String agentName) throws IOException, JsonException {
    Map<String, Map<String, Object>> result = new HashMap<String, Map<String, Object>>();
    JsonObject json = getResource(instance, queueUrl(agentName) + ".infinity");
    JsonArray items = json.getJsonArray("items");
    for (int i = 0; i < items.size(); i++) {
        String queueName = items.getString(i);
        Map<String, Object> queueProperties = new HashMap<String, Object>();
        JsonObject queue = json.getJsonObject(queueName);
        queueProperties.put("empty", queue.getBoolean("empty"));
        queueProperties.put("itemsCount", queue.getInt("itemsCount"));
        result.put(queueName, queueProperties);
    }
    return result;
}
Also used : JsonArray(javax.json.JsonArray) HashMap(java.util.HashMap) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 33 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class JsonRenderer method prettyPrint.

/**
     * Make a prettyprinted JSON text of this JSONObject.
     * <p>
     * Warning: This method assumes that the data structure is acyclical.
     * @return a printable, displayable, transmittable
     *  representation of the object, beginning
     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
     *  with <code>}</code>&nbsp;<small>(right brace)</small>.
     * @throws IllegalArgumentException If the object contains an invalid number.
     */
public String prettyPrint(JsonObject jo, Options opt) {
    int n = jo.size();
    if (n == 0) {
        return "{}";
    }
    final JsonArrayBuilder children = Json.createArrayBuilder();
    Iterator<String> keys = jo.keySet().iterator();
    StringBuilder sb = new StringBuilder("{");
    int newindent = opt.initialIndent + opt.indent;
    String o;
    if (n == 1) {
        o = keys.next();
        final Object v = jo.get(o);
        if (!skipChildObject(children, opt, o, v)) {
            sb.append(quote(o));
            sb.append(": ");
            sb.append(valueToString(v, opt));
        }
    } else {
        while (keys.hasNext()) {
            o = keys.next();
            final Object v = jo.get(o);
            if (skipChildObject(children, opt, o, v)) {
                continue;
            }
            if (sb.length() > 1) {
                sb.append(",\n");
            } else {
                sb.append('\n');
            }
            indent(sb, newindent);
            sb.append(quote(o.toString()));
            sb.append(": ");
            sb.append(valueToString(v, options().withIndent(opt.indent).withInitialIndent(newindent)));
        }
        if (sb.length() > 1) {
            sb.append('\n');
            indent(sb, newindent);
        }
    }
    /** Render children if any were skipped (in "children in arrays" mode) */
    JsonArray childrenArray = children.build();
    if (childrenArray.size() > 0) {
        if (sb.length() > 1) {
            sb.append(",\n");
        } else {
            sb.append('\n');
        }
        final Options childOpt = new Options(opt);
        childOpt.withInitialIndent(childOpt.initialIndent + newindent);
        indent(sb, childOpt.initialIndent);
        sb.append(quote(opt.childrenKey)).append(":");
        sb.append(prettyPrint(childrenArray, childOpt));
    }
    sb.append('}');
    return sb.toString();
}
Also used : JsonArray(javax.json.JsonArray) JsonObject(javax.json.JsonObject) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonString(javax.json.JsonString)

Example 34 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class JsonResponseTest method testOnChange.

public void testOnChange() throws Exception {
    res.onChange("modified", "argument1", "argument2");
    Object prop = res.getProperty("changes");
    JsonArray changes = assertInstanceOf(prop, JsonArray.class);
    assertEquals(1, changes.size());
    Object obj = changes.getJsonObject(0);
    JsonObject change = assertInstanceOf(obj, JsonObject.class);
    assertProperty(change, JSONResponse.PROP_TYPE, "modified");
    JsonArray arguments = change.getJsonArray(JSONResponse.PROP_ARGUMENT);
    assertEquals(2, arguments.size());
}
Also used : JsonArray(javax.json.JsonArray) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject)

Example 35 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class FsMountHelper method getCurrentConfigurations.

/**
     * Return all file provider configs for this project
     * @param targetUrl The targetUrl of the webconsole
     * @return A map (may be empty) with the pids as keys and the configurations as values
     * @throws MojoExecutionException
     */
public Map<String, FsResourceConfiguration> getCurrentConfigurations(final String targetUrl) throws MojoExecutionException {
    log.debug("Getting current file provider configurations.");
    final Map<String, FsResourceConfiguration> result = new HashMap<>();
    final String getUrl = targetUrl + "/configMgr/(service.factoryPid=" + FS_FACTORY + ").json";
    final GetMethod get = new GetMethod(getUrl);
    try {
        final int status = httpClient.executeMethod(get);
        if (status == 200) {
            String contentType = get.getResponseHeader(HEADER_CONTENT_TYPE).getValue();
            int pos = contentType.indexOf(';');
            if (pos != -1) {
                contentType = contentType.substring(0, pos);
            }
            if (!JsonSupport.JSON_MIME_TYPE.equals(contentType)) {
                log.debug("Response type from web console is not JSON, but " + contentType);
                throw new MojoExecutionException("The Apache Felix Web Console is too old to mount " + "the initial content through file system provider configs. " + "Either upgrade the web console or disable this feature.");
            }
            final String jsonText;
            try (InputStream jsonResponse = get.getResponseBodyAsStream()) {
                jsonText = IOUtils.toString(jsonResponse, CharEncoding.UTF_8);
            }
            try {
                JsonArray array = JsonSupport.parseArray(jsonText);
                for (int i = 0; i < array.size(); i++) {
                    final JsonObject obj = array.getJsonObject(i);
                    final String pid = obj.getString("pid");
                    final JsonObject properties = obj.getJsonObject("properties");
                    final String fsmode = getConfigPropertyValue(properties, PROPERTY_FSMODE);
                    final String path = getConfigPropertyValue(properties, PROPERTY_PATH);
                    final String initialContentImportOptions = getConfigPropertyValue(properties, PROPERTY_INITIAL_CONTENT_IMPORT_OPTIONS);
                    final String fileVaultFilterXml = getConfigPropertyValue(properties, PROPERTY_FILEVAULT_FILTER_XML);
                    String root = getConfigPropertyValue(properties, PROPERTY_ROOTS);
                    if (root == null) {
                        root = getConfigPropertyValue(properties, PROPERTY_ROOT);
                    }
                    if (path != null && path.startsWith(this.project.getBasedir().getAbsolutePath()) && root != null) {
                        FsResourceConfiguration cfg = new FsResourceConfiguration().fsMode(fsmode).providerRootPath(path).contentRootDir(root).initialContentImportOptions(initialContentImportOptions).fileVaultFilterXml(fileVaultFilterXml);
                        log.debug("Found configuration with pid: " + pid + ", " + cfg);
                        result.put(pid, cfg);
                    }
                }
            } catch (JsonException ex) {
                throw new MojoExecutionException("Reading configuration from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
            }
        }
    } catch (HttpException ex) {
        throw new MojoExecutionException("Reading configuration from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Reading configuration from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
    } finally {
        get.releaseConnection();
    }
    return result;
}
Also used : JsonException(javax.json.JsonException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) JsonObject(javax.json.JsonObject) IOException(java.io.IOException) JsonArray(javax.json.JsonArray) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException)

Aggregations

JsonArray (javax.json.JsonArray)128 JsonObject (javax.json.JsonObject)97 Test (org.junit.Test)42 ArrayList (java.util.ArrayList)32 JsonReader (javax.json.JsonReader)31 HashMap (java.util.HashMap)29 JsonString (javax.json.JsonString)28 HashSet (java.util.HashSet)21 NameValuePair (org.apache.commons.httpclient.NameValuePair)20 Credentials (org.apache.commons.httpclient.Credentials)19 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)19 StringReader (java.io.StringReader)18 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)17 LinkedHashMap (java.util.LinkedHashMap)14 JsonValue (javax.json.JsonValue)11 Map (java.util.Map)10 JsonException (javax.json.JsonException)9 Response (javax.ws.rs.core.Response)9 IOException (java.io.IOException)7 JerseyTest (org.glassfish.jersey.test.JerseyTest)7