Search in sources :

Example 1 with JsonException

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

the class AdapterWebConsolePlugin method getJson.

private void getJson(final HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");
    try {
        Map<String, Map<String, List<String>>> values = new HashMap<>();
        for (final AdaptableDescription desc : allAdaptables) {
            final Map<String, List<String>> adaptableObj;
            if (values.containsKey(desc.adaptable)) {
                adaptableObj = values.get(desc.adaptable);
            } else {
                adaptableObj = new HashMap<>();
                values.put(desc.adaptable, adaptableObj);
            }
            for (final String adapter : desc.adapters) {
                List<String> conditions = adaptableObj.get(desc.condition == null ? "" : desc.condition);
                if (conditions == null) {
                    conditions = new ArrayList<>();
                    adaptableObj.put(desc.condition == null ? "" : desc.condition, conditions);
                }
                conditions.add(adapter);
            }
        }
        final JsonObjectBuilder obj = Json.createObjectBuilder();
        for (Map.Entry<String, Map<String, List<String>>> entry : values.entrySet()) {
            JsonObjectBuilder adaptable = Json.createObjectBuilder();
            for (Map.Entry<String, List<String>> subEnty : entry.getValue().entrySet()) {
                if (subEnty.getValue().size() > 1) {
                    JsonArrayBuilder array = Json.createArrayBuilder();
                    for (String condition : subEnty.getValue()) {
                        array.add(condition);
                    }
                    adaptable.add(subEnty.getKey(), array);
                } else {
                    adaptable.add(subEnty.getKey(), subEnty.getValue().get(0));
                }
            }
            obj.add(entry.getKey(), adaptable);
        }
        Json.createGenerator(resp.getWriter()).write(obj.build()).flush();
    } catch (final JsonException e) {
        throw new ServletException("Unable to produce JSON", e);
    }
}
Also used : JsonException(javax.json.JsonException) HashMap(java.util.HashMap) JsonString(javax.json.JsonString) ServletException(javax.servlet.ServletException) List(java.util.List) ArrayList(java.util.ArrayList) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with JsonException

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

the class AnnouncementRegistryImpl method listAnnouncementsInSameCluster.

@Override
public synchronized Collection<Announcement> listAnnouncementsInSameCluster(final ClusterView localClusterView) {
    logger.debug("listAnnouncementsInSameCluster: start. localClusterView: {}", localClusterView);
    if (localClusterView == null) {
        throw new IllegalArgumentException("clusterView must not be null");
    }
    ResourceResolver resourceResolver = null;
    final Collection<Announcement> incomingAnnouncements = new LinkedList<Announcement>();
    final InstanceDescription localInstance = getLocalInstanceDescription(localClusterView);
    try {
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
        Resource clusterInstancesResource = ResourceHelper.getOrCreateResource(resourceResolver, config.getClusterInstancesPath());
        Iterator<Resource> it0 = clusterInstancesResource.getChildren().iterator();
        while (it0.hasNext()) {
            Resource aClusterInstanceResource = it0.next();
            final String instanceId = aClusterInstanceResource.getName();
            logger.debug("listAnnouncementsInSameCluster: handling clusterInstance: {}", instanceId);
            if (localInstance != null && localInstance.getSlingId().equals(instanceId)) {
                // this is the local instance then - which we serve from the cache only
                logger.debug("listAnnouncementsInSameCluster: matched localInstance, filling with cache: {}", instanceId);
                fillWithCachedAnnouncements(incomingAnnouncements);
                continue;
            }
            //TODO: add ClusterView.contains(instanceSlingId) for convenience to next api change
            if (!contains(localClusterView, instanceId)) {
                logger.debug("listAnnouncementsInSameCluster: instance is not in my view, ignoring: {}", instanceId);
                // (corresponds to earlier expiry-handling)
                continue;
            }
            final Resource announcementsResource = aClusterInstanceResource.getChild("announcements");
            if (announcementsResource == null) {
                logger.debug("listAnnouncementsInSameCluster: instance has no announcements: {}", instanceId);
                continue;
            }
            logger.debug("listAnnouncementsInSameCluster: instance has announcements: {}", instanceId);
            Iterator<Resource> it = announcementsResource.getChildren().iterator();
            Announcement topologyAnnouncement;
            while (it.hasNext()) {
                Resource anAnnouncement = it.next();
                topologyAnnouncement = Announcement.fromJSON(anAnnouncement.adaptTo(ValueMap.class).get("topologyAnnouncement", String.class));
                logger.debug("listAnnouncementsInSameCluster: found announcement: {}", topologyAnnouncement);
                incomingAnnouncements.add(topologyAnnouncement);
            // SLING-3389: no longer check for expired announcements -
            // instead make use of the fact that this instance
            // has a clusterView and that every live instance
            // is responsible of cleaning up expired announcements
            // with the repository
            }
        }
    // since SLING-3389 this method does only read operations, hence
    // no commit necessary anymore - close happens in below finally block
    } catch (LoginException e) {
        logger.error("listAnnouncementsInSameCluster: could not log in administratively: " + e, e);
        throw new RuntimeException("Could not log in to repository (" + e + ")", e);
    } catch (PersistenceException e) {
        logger.error("listAnnouncementsInSameCluster: got a PersistenceException: " + e, e);
        throw new RuntimeException("Exception while talking to repository (" + e + ")", e);
    } catch (JsonException e) {
        logger.error("listAnnouncementsInSameCluster: got a JSONException: " + e, e);
        throw new RuntimeException("Exception while converting json (" + e + ")", e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("listAnnouncementsInSameCluster: result: " + incomingAnnouncements.size());
    }
    return incomingAnnouncements;
}
Also used : JsonException(javax.json.JsonException) ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) LinkedList(java.util.LinkedList) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) InstanceDescription(org.apache.sling.discovery.InstanceDescription)

Example 3 with JsonException

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

the class TopologyRequestValidator method encodeMessage.

/**
     * Encodes a request returning the encoded body
     *
     * @param body
     * @return the encoded body.
     * @throws IOException
     */
public String encodeMessage(String body) throws IOException {
    checkActive();
    if (encryptionEnabled) {
        try {
            JsonObjectBuilder json = Json.createObjectBuilder();
            JsonArrayBuilder array = Json.createArrayBuilder();
            for (String value : encrypt(body)) {
                array.add(value);
            }
            json.add("payload", array);
            StringWriter writer = new StringWriter();
            Json.createGenerator(writer).write(json.build()).close();
            return writer.toString();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (IllegalBlockSizeException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (BadPaddingException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (NoSuchPaddingException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (JsonException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (InvalidKeySpecException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        } catch (InvalidParameterSpecException e) {
            throw new IOException("Unable to Encrypt Message " + e.getMessage());
        }
    }
    return body;
}
Also used : JsonException(javax.json.JsonException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) StringWriter(java.io.StringWriter) JsonArrayBuilder(javax.json.JsonArrayBuilder) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) JsonObjectBuilder(javax.json.JsonObjectBuilder)

Example 4 with JsonException

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

the class ResultJsonSerializer method serialize.

public String serialize(final Result overallResult, final List<HealthCheckExecutionResult> executionResults, final String jsonpCallback, boolean includeDebug) {
    LOG.debug("Sending json response... ");
    JsonObjectBuilder result = Json.createObjectBuilder();
    try {
        result.add("overallResult", overallResult.getStatus().toString());
        JsonArrayBuilder resultsJsonArr = Json.createArrayBuilder();
        for (HealthCheckExecutionResult healthCheckResult : executionResults) {
            resultsJsonArr.add(getJsonForSimpleResult(healthCheckResult, includeDebug));
        }
        result.add("results", resultsJsonArr);
    } catch (JsonException e) {
        LOG.info("Could not serialize health check result: " + e, e);
    }
    StringWriter writer = new StringWriter();
    Json.createGenerator(writer).write(result.build()).close();
    String resultStr = writer.toString();
    if (StringUtils.isNotBlank(jsonpCallback)) {
        resultStr = jsonpCallback + "(" + resultStr + ");";
    }
    return resultStr;
}
Also used : JsonException(javax.json.JsonException) StringWriter(java.io.StringWriter) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) HealthCheckExecutionResult(org.apache.sling.hc.api.execution.HealthCheckExecutionResult)

Example 5 with JsonException

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

the class JsonReader method parse.

public void parse(InputStream ins, ContentCreator contentCreator) throws IOException, RepositoryException {
    try {
        String jsonString = toString(ins).trim();
        if (!jsonString.startsWith("{")) {
            jsonString = "{" + jsonString + "}";
        }
        Map<String, Object> config = new HashMap<>();
        config.put("org.apache.johnzon.supports-comments", true);
        JsonObject json = Json.createReaderFactory(config).createReader(new StringReader(tickToDoubleQuote(jsonString))).readObject();
        this.createNode(null, json, contentCreator);
    } catch (JsonException je) {
        throw (IOException) new IOException(je.getMessage()).initCause(je);
    }
}
Also used : JsonException(javax.json.JsonException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) IOException(java.io.IOException)

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