Search in sources :

Example 1 with JsonReader

use of jakarta.json.JsonReader in project openmq by eclipse-ee4j.

the class JSONWebSocket method processData.

@Override
protected void processData(String text) throws Exception {
    if (DEBUG) {
        logger.log(logger.INFO, toString() + ".processData(text=" + text + ")");
    }
    try {
        JsonReader jsonReader = Json.createReader(new StringReader(text));
        JsonObject jo = jsonReader.readObject();
        String command = jo.getString(JsonMessage.Key.COMMAND);
        JsonObject headers = jo.getJsonObject(JsonMessage.Key.HEADERS);
        JsonObject body = jo.getJsonObject(JsonMessage.Key.BODY);
        StompFrameMessage frame = StompFrameMessageImpl.getFactory().newStompFrameMessage(StompFrameMessage.Command.valueOf(command), logger);
        Iterator<String> itr = headers.keySet().iterator();
        String key;
        String val;
        while (itr.hasNext()) {
            key = itr.next();
            val = headers.getString(key);
            if (val != null) {
                frame.addHeader(key, val);
            }
        }
        if (body != null) {
            JsonString btype = body.getJsonString(JsonMessage.BodySubKey.TYPE);
            if (btype == null || btype.getString().equals(JsonMessage.BODY_TYPE_TEXT)) {
                JsonString msg = body.getJsonString(JsonMessage.BodySubKey.TEXT);
                if (msg != null) {
                    frame.setBody(msg.getString().getBytes("UTF-8"));
                }
            } else if (btype.getString().equals(JsonMessage.BODY_TYPE_BYTES)) {
                JsonString enc = body.getJsonString("encoder");
                if (enc == null || enc.getString().equals(JsonMessage.ENCODER_BASE64)) {
                    JsonString msg = body.getJsonString(JsonMessage.BodySubKey.TEXT);
                    if (msg != null) {
                        byte[] bytes = null;
                        if (base64Class == null) {
                            BASE64Decoder decoder = new BASE64Decoder();
                            bytes = decoder.decodeBuffer(msg.getString());
                        } else {
                            Method gm = base64Class.getMethod("getDecoder", (new Class[] {}));
                            Object o = gm.invoke(null);
                            Method dm = o.getClass().getMethod("decode", (new Class[] { String.class }));
                            bytes = (byte[]) dm.invoke(o, msg.getString());
                        }
                        frame.setBody(bytes);
                        frame.addHeader(StompFrameMessage.CommonHeader.CONTENTLENGTH, String.valueOf(bytes.length));
                    }
                } else {
                    throw new IOException("encoder " + enc + " not supported");
                }
            } else {
                throw new IOException("body type:" + btype + " not supported");
            }
        }
        dispatchMessage((StompFrameMessageImpl) frame);
    } catch (Exception e) {
        logger.logStack(logger.ERROR, e.getMessage(), e);
        sendFatalError(e);
    }
}
Also used : StompFrameMessage(com.sun.messaging.bridge.api.StompFrameMessage) StringReader(java.io.StringReader) JsonReader(jakarta.json.JsonReader) JsonObject(jakarta.json.JsonObject) JsonObject(jakarta.json.JsonObject) JsonString(jakarta.json.JsonString) JsonString(jakarta.json.JsonString) Method(java.lang.reflect.Method) IOException(java.io.IOException) BASE64Decoder(com.sun.messaging.jmq.util.BASE64Decoder) IOException(java.io.IOException)

Example 2 with JsonReader

use of jakarta.json.JsonReader in project core by weld.

the class ProbeJMXUtil method invokeMBeanOperation.

public static JsonObject invokeMBeanOperation(String name, Object[] params, String[] signature) throws Exception {
    try (JMXConnector connector = getConnector(JMX_CONNECTION_URL)) {
        MBeanServerConnection connection = connector.getMBeanServerConnection();
        ObjectInstance mBeanInstance = getProbeMBeanInstance(connection);
        Object o = connection.invoke(mBeanInstance.getObjectName(), name, params, signature);
        CharArrayReader arrayReader = new CharArrayReader(o.toString().toCharArray());
        JsonReader reader = Json.createReader(arrayReader);
        return reader.readObject();
    }
}
Also used : CharArrayReader(java.io.CharArrayReader) JMXConnector(javax.management.remote.JMXConnector) ObjectInstance(javax.management.ObjectInstance) JsonReader(jakarta.json.JsonReader) JsonObject(jakarta.json.JsonObject) MBeanServerConnection(javax.management.MBeanServerConnection)

Example 3 with JsonReader

use of jakarta.json.JsonReader in project dash-licenses by eclipse.

the class TestLicenseToolModule method getHttpClientService.

public IHttpClientService getHttpClientService() {
    return new IHttpClientService() {

        @Override
        public int post(String url, String contentType, String payload, Consumer<String> handler) {
            if (url.equals(settings.getClearlyDefinedDefinitionsUrl())) {
                // The file contains only the information for the one record; the
                // ClearlyDefined service expects a Json collection as the response,
                // so insert the file contents into an array and pass that value to
                // the handler.
                JsonReader reader = Json.createReader(new StringReader(payload));
                JsonArray items = (JsonArray) reader.read();
                var builder = new StringBuilder();
                builder.append("{");
                for (int index = 0; index < items.size(); index++) {
                    if (index > 0)
                        builder.append(",");
                    var id = items.getString(index);
                    builder.append("\"");
                    builder.append(id);
                    builder.append("\" :");
                    switch(id) {
                        case "npm/npmjs/-/write/1.0.3":
                        case "npm/npmjs/-/write/1.0.4":
                        case "npm/npmjs/-/write/1.0.5":
                        case "npm/npmjs/-/write/1.0.6":
                            builder.append(new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/write-1.0.3.json"), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n")));
                            break;
                        case "npm/npmjs/@yarnpkg/lockfile/1.1.0":
                        case "npm/npmjs/@yarnpkg/lockfile/1.1.1":
                        case "npm/npmjs/@yarnpkg/lockfile/1.1.2":
                        case "npm/npmjs/@yarnpkg/lockfile/1.1.3":
                            builder.append(new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/lockfile-1.1.0.json"), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n")));
                            break;
                        /*
						 * I've run into cases where the ClearlyDefined API throws an error because of
						 * one apparently well-formed and otherwise correct ID. When this situation is
						 * encountered, an error message and nothing else is returned, regardless of how
						 * many IDs were included in the request.
						 */
                        case "npm/npmjs/breaky/mcbreakyface/1.0.0":
                        case "npm/npmjs/breaky/mcbreakyface/1.0.1":
                            handler.accept("An error occurred when trying to fetch coordinates for one of the components");
                            return 200;
                        default:
                            builder.append("{}");
                    }
                }
                builder.append("}");
                handler.accept(builder.toString());
                return 200;
            }
            if (url.equals(settings.getLicenseCheckUrl())) {
                if (payload.startsWith("request=")) {
                    var json = URLDecoder.decode(payload.substring("request=".length()), StandardCharsets.UTF_8);
                    var approved = Json.createObjectBuilder();
                    var rejected = Json.createObjectBuilder();
                    var reader = Json.createReader(new StringReader(json));
                    var root = reader.readObject().asJsonObject();
                    root.getJsonArray("dependencies").forEach(key -> {
                        var id = ((JsonString) key).getString();
                        var item = Json.createObjectBuilder();
                        switch(id) {
                            case "npm/npmjs/-/write/0.2.0":
                                item.add("authority", "CQ7766");
                                item.add("confidence", 100);
                                item.add("id", id);
                                item.add("license", "Apache-2.0");
                                item.addNull("sourceUrl");
                                item.add("status", "approved");
                                approved.add(id, item);
                                break;
                            case "npm/npmjs/@yarnpkg/lockfile/1.1.0":
                                item.add("authority", "CQ7722");
                                item.add("confidence", 100);
                                item.add("id", id);
                                item.add("license", "GPL-2.0");
                                item.addNull("sourceUrl");
                                item.add("status", "rejected");
                                rejected.add(id, item);
                                break;
                        }
                    });
                    var parent = Json.createObjectBuilder();
                    parent.add("approved", approved);
                    parent.add("rejected", rejected);
                    handler.accept(parent.build().toString());
                    return 200;
                }
            }
            return 404;
        }

        @Override
        public int get(String url, String contentType, Consumer<InputStream> handler) {
            if (url.equals(settings.getApprovedLicensesUrl())) {
                handler.accept(this.getClass().getResourceAsStream("/licenses.json"));
                return 200;
            }
            switch(url) {
                case "https://registry.npmjs.org/chalk":
                    handler.accept(this.getClass().getResourceAsStream("/chalk.json"));
                    return 200;
                case "https://pypi.org/pypi/asn1crypto/json":
                    handler.accept(this.getClass().getResourceAsStream("/test_data_asn1crypto.json"));
                    return 200;
                case "https://raw.githubusercontent.com/clearlydefined/service/HEAD/schemas/curation-1.0.json":
                    handler.accept(this.getClass().getResourceAsStream("/test_data_curation-1.0.json"));
                    return 200;
            }
            return 404;
        }

        @Override
        public boolean remoteFileExists(String url) {
            switch(url) {
                case "https://search.maven.org/artifact/group.path/artifact/1.0/jar":
                case "https://search.maven.org/remotecontent?filepath=group/path/artifact/1.0/artifact-1.0-sources.jar":
                case "https://github.com/sindresorhus/chalk/archive/v0.1.0.zip":
                case "https://registry.npmjs.org/chalk/-/chalk-0.1.0.tgz":
                    return true;
            }
            return IHttpClientService.super.remoteFileExists(url);
        }
    };
}
Also used : JsonArray(jakarta.json.JsonArray) Consumer(java.util.function.Consumer) InputStreamReader(java.io.InputStreamReader) IHttpClientService(org.eclipse.dash.licenses.http.IHttpClientService) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) JsonReader(jakarta.json.JsonReader) JsonString(jakarta.json.JsonString) JsonString(jakarta.json.JsonString)

Example 4 with JsonReader

use of jakarta.json.JsonReader in project dash-licenses by eclipse.

the class LicenseSupport method getApprovedLicenses.

private static Map<String, String> getApprovedLicenses(Reader contentReader) {
    JsonReader reader = Json.createReader(contentReader);
    JsonObject read = (JsonObject) reader.read();
    Map<String, String> licenses = new HashMap<>();
    JsonObject approved = read.getJsonObject("approved");
    if (approved != null) {
        approved.forEach((key, name) -> licenses.put(key.toUpperCase(), name.toString()));
    }
    // Augment the official list with licenses that are acceptable, but
    // not explicitly included in our approved list.
    licenses.put("EPL-1.0", "Eclipse Public License, v1.0");
    licenses.put("EPL-2.0", "Eclipse Public License, v2.0");
    licenses.put("WTFPL", "WTFPL");
    licenses.put("MIT-0", "MIT-0");
    licenses.put("CC-BY-3.0", "CC-BY-3.0");
    licenses.put("CC-BY-4.0", "CC-BY-4.0");
    licenses.put("UNLICENSE", "Unlicense");
    licenses.put("ARTISTIC-2.0", "Artistic-2.0");
    licenses.put("BSD-2-Clause-FreeBSD", "BSD 2-Clause FreeBSD License");
    licenses.put("0BSD", "BSD Zero Clause License");
    return licenses;
}
Also used : HashMap(java.util.HashMap) JsonReader(jakarta.json.JsonReader) JsonObject(jakarta.json.JsonObject)

Example 5 with JsonReader

use of jakarta.json.JsonReader in project dash-licenses by eclipse.

the class EclipseFoundationSupport method queryLicenseData.

@Override
public void queryLicenseData(Collection<IContentId> ids, Consumer<IContentData> consumer) {
    if (ids.isEmpty())
        return;
    String url = settings.getLicenseCheckUrl();
    if (url.isBlank()) {
        logger.debug("Bypassing Eclipse Foundation.");
        return;
    }
    logger.info("Querying Eclipse Foundation for license data for {} items.", ids.size());
    String form = encodeRequestPayload(ids);
    int code = httpClientService.post(url, "application/x-www-form-urlencoded", form, response -> {
        AtomicInteger counter = new AtomicInteger();
        JsonReader reader = Json.createReader(new StringReader(response));
        JsonObject read = (JsonObject) reader.read();
        JsonObject approved = read.getJsonObject("approved");
        if (approved != null)
            approved.forEach((key, each) -> {
                FoundationData data = new FoundationData(each.asJsonObject());
                logger.debug("EF approved: {} ({}) score: {} {} {}", data.getId(), data.getRule(), data.getScore(), data.getLicense(), data.getAuthority());
                consumer.accept(data);
                counter.incrementAndGet();
            });
        JsonObject restricted = read.getJsonObject("restricted");
        if (restricted != null)
            restricted.forEach((key, each) -> {
                FoundationData data = new FoundationData(each.asJsonObject());
                logger.debug("EF restricted: {} score: {} {} {}", data.getId(), data.getScore(), data.getLicense(), data.getAuthority());
                consumer.accept(data);
                counter.incrementAndGet();
            });
        logger.info("Found {} items.", counter.get());
    });
    if (code != 200) {
        logger.error("Error response from the Eclipse Foundation {}", code);
        throw new RuntimeException("Received an error response from the Eclipse Foundation.");
    }
}
Also used : Logger(org.slf4j.Logger) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) IContentId(org.eclipse.dash.licenses.IContentId) ISettings(org.eclipse.dash.licenses.ISettings) StandardCharsets(java.nio.charset.StandardCharsets) Json(jakarta.json.Json) Consumer(java.util.function.Consumer) Inject(javax.inject.Inject) IContentData(org.eclipse.dash.licenses.IContentData) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) URLEncoder(java.net.URLEncoder) StringReader(java.io.StringReader) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JsonObject(jakarta.json.JsonObject) IHttpClientService(org.eclipse.dash.licenses.http.IHttpClientService) JsonReader(jakarta.json.JsonReader) JsonArray(jakarta.json.JsonArray) ILicenseDataProvider(org.eclipse.dash.licenses.ILicenseDataProvider) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StringReader(java.io.StringReader) JsonReader(jakarta.json.JsonReader) JsonObject(jakarta.json.JsonObject)

Aggregations

JsonReader (jakarta.json.JsonReader)9 JsonObject (jakarta.json.JsonObject)8 StringReader (java.io.StringReader)4 InputStreamReader (java.io.InputStreamReader)3 JsonArray (jakarta.json.JsonArray)2 JsonString (jakarta.json.JsonString)2 JsonValue (jakarta.json.JsonValue)2 InputStream (java.io.InputStream)2 Consumer (java.util.function.Consumer)2 ClearlyDefinedContentData (org.eclipse.dash.licenses.clearlydefined.ClearlyDefinedContentData)2 IHttpClientService (org.eclipse.dash.licenses.http.IHttpClientService)2 Test (org.junit.jupiter.api.Test)2 JsonObjectExt (com.linkedin.avroutil1.parser.jsonpext.JsonObjectExt)1 JsonReaderExt (com.linkedin.avroutil1.parser.jsonpext.JsonReaderExt)1 JsonReaderWithLocations (com.linkedin.avroutil1.parser.jsonpext.JsonReaderWithLocations)1 JsonValueExt (com.linkedin.avroutil1.parser.jsonpext.JsonValueExt)1 StompFrameMessage (com.sun.messaging.bridge.api.StompFrameMessage)1 BASE64Decoder (com.sun.messaging.jmq.util.BASE64Decoder)1 Json (jakarta.json.Json)1 JsonArrayBuilder (jakarta.json.JsonArrayBuilder)1