Search in sources :

Example 6 with JsonException

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

the class OrderedJsonReader method writeChildren.

@Override
protected void writeChildren(JsonObject obj, ContentCreator contentCreator) throws RepositoryException {
    if (!obj.containsKey(PN_ORDEREDCHILDREN)) {
        super.writeChildren(obj, contentCreator);
    } else {
        for (Map.Entry<String, JsonValue> entry : obj.entrySet()) {
            final String n = entry.getKey();
            // skip well known objects
            if (!ignoredNames.contains(n)) {
                Object o = entry.getValue();
                if (!handleSecurity(n, o, contentCreator)) {
                    if (n.equals(PN_ORDEREDCHILDREN)) {
                        if (o instanceof JsonArray) {
                            JsonArray children = (JsonArray) o;
                            for (int childIndex = 0; childIndex < children.size(); childIndex++) {
                                Object oc = children.get(childIndex);
                                if (oc instanceof JsonObject) {
                                    JsonObject child = (JsonObject) oc;
                                    String childName = child.getString(PN_ORDEREDCHILDNAME, null);
                                    if (StringUtils.isNotBlank(childName)) {
                                        JsonObjectBuilder builder = Json.createObjectBuilder();
                                        for (Map.Entry<String, JsonValue> e : child.entrySet()) {
                                            if (!PN_ORDEREDCHILDNAME.equals(e.getKey())) {
                                                builder.add(e.getKey(), e.getValue());
                                            }
                                        }
                                        child = builder.build();
                                        this.createNode(childName, child, contentCreator);
                                    } else {
                                        throw new JsonException(PN_ORDEREDCHILDREN + " children must have a name whose key is " + PN_ORDEREDCHILDNAME);
                                    }
                                } else {
                                    throw new JsonException(PN_ORDEREDCHILDREN + " array must only have JSONObject items");
                                }
                            }
                        } else {
                            throw new JsonException(PN_ORDEREDCHILDREN + " value must be a JSON array");
                        }
                    }
                } else {
                    this.createProperty(n, o, contentCreator);
                }
            }
        }
    }
}
Also used : JsonArray(javax.json.JsonArray) JsonException(javax.json.JsonException) JsonValue(javax.json.JsonValue) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonObjectBuilder(javax.json.JsonObjectBuilder) Map(java.util.Map)

Example 7 with JsonException

use of javax.json.JsonException 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 8 with JsonException

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

the class DistributionUtils method getQueueItems.

public static List<Map<String, Object>> getQueueItems(SlingInstance instance, String queueUrl) throws IOException, JsonException {
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    JsonObject json = getResource(instance, queueUrl + ".infinity");
    Iterator<String> keys = json.keySet().iterator();
    while (keys.hasNext()) {
        String key = keys.next();
        JsonObject queueItem;
        Object item = json.get(key);
        if (item instanceof JsonObject) {
            queueItem = (JsonObject) item;
        } else if (item instanceof JsonString) {
            try {
                queueItem = Json.createReader(new StringReader(((JsonString) item).getString())).readObject();
            } catch (JsonException ex) {
                queueItem = null;
            }
        } else {
            queueItem = null;
        }
        if (queueItem != null && queueItem.containsKey("id")) {
            Map<String, Object> itemProperties = new HashMap<String, Object>();
            itemProperties.put("id", queueItem.getString("id"));
            itemProperties.put("paths", JsonUtil.unbox(queueItem.get("paths")));
            itemProperties.put("action", JsonUtil.unbox(queueItem.get("action")));
            itemProperties.put("userid", JsonUtil.unbox(queueItem.get("userid")));
            itemProperties.put("attempts", JsonUtil.unbox(queueItem.get("attempts")));
            itemProperties.put("time", JsonUtil.unbox(queueItem.get("time")));
            itemProperties.put("state", JsonUtil.unbox(queueItem.get("state")));
            result.add(itemProperties);
        }
    }
    return result;
}
Also used : JsonException(javax.json.JsonException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) JsonString(javax.json.JsonString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with JsonException

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

the class GenerateAdapterMetadataMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        final Map<String, Object> descriptor = new HashMap<>();
        final AnnotationDB annotationDb = new AnnotationDB();
        annotationDb.scanArchives(buildOutputDirectory.toURI().toURL());
        final Set<String> annotatedClassNames = new HashSet<String>();
        addAnnotatedClasses(annotationDb, annotatedClassNames, Adaptable.class);
        addAnnotatedClasses(annotationDb, annotatedClassNames, Adaptables.class);
        for (final String annotatedClassName : annotatedClassNames) {
            getLog().info(String.format("found adaptable annotation on %s", annotatedClassName));
            final String pathToClassFile = annotatedClassName.replace('.', '/') + ".class";
            final File classFile = new File(buildOutputDirectory, pathToClassFile);
            final FileInputStream input = new FileInputStream(classFile);
            final ClassReader classReader;
            try {
                classReader = new ClassReader(input);
            } finally {
                input.close();
            }
            final ClassNode classNode = new ClassNode();
            classReader.accept(classNode, SKIP_CODE | SKIP_DEBUG | SKIP_FRAMES);
            @SuppressWarnings("unchecked") final List<AnnotationNode> annotations = classNode.invisibleAnnotations;
            for (final AnnotationNode annotation : annotations) {
                if (ADAPTABLE_DESC.equals(annotation.desc)) {
                    parseAdaptableAnnotation(annotation, classNode, descriptor);
                } else if (ADAPTABLES_DESC.equals(annotation.desc)) {
                    parseAdaptablesAnnotation(annotation, classNode, descriptor);
                }
            }
        }
        final File outputFile = new File(outputDirectory, fileName);
        outputFile.getParentFile().mkdirs();
        try (FileWriter writer = new FileWriter(outputFile);
            JsonWriter jsonWriter = Json.createWriter(writer)) {
            jsonWriter.writeObject(JsonSupport.toJson(descriptor));
        }
        addResource();
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to generate metadata", e);
    } catch (JsonException e) {
        throw new MojoExecutionException("Unable to generate metadata", e);
    }
}
Also used : AnnotationDB(org.scannotation.AnnotationDB) JsonException(javax.json.JsonException) ClassNode(org.objectweb.asm.tree.ClassNode) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) FileWriter(java.io.FileWriter) IOException(java.io.IOException) JsonWriter(javax.json.JsonWriter) FileInputStream(java.io.FileInputStream) AnnotationNode(org.objectweb.asm.tree.AnnotationNode) ClassReader(org.objectweb.asm.ClassReader) File(java.io.File) HashSet(java.util.HashSet)

Example 10 with JsonException

use of javax.json.JsonException 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

JsonException (javax.json.JsonException)27 IOException (java.io.IOException)11 JsonObject (javax.json.JsonObject)11 HashMap (java.util.HashMap)9 JsonString (javax.json.JsonString)7 Map (java.util.Map)6 JsonArray (javax.json.JsonArray)6 JsonObjectBuilder (javax.json.JsonObjectBuilder)6 StringReader (java.io.StringReader)5 Resource (org.apache.sling.api.resource.Resource)5 InputStream (java.io.InputStream)4 ArrayList (java.util.ArrayList)4 JsonArrayBuilder (javax.json.JsonArrayBuilder)4 LoginException (org.apache.sling.api.resource.LoginException)4 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)4 File (java.io.File)3 StringWriter (java.io.StringWriter)3 JsonValue (javax.json.JsonValue)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 FileInputStream (java.io.FileInputStream)2