Search in sources :

Example 66 with JsonObject

use of jakarta.json.JsonObject in project JsonPath by json-path.

the class JakartaMappingProvider method mapImpl.

private Object mapImpl(Object source, final Type targetType) {
    if (source == null || source == JsonValue.NULL) {
        return null;
    }
    if (source == JsonValue.TRUE) {
        if (Boolean.class.equals(targetType)) {
            return Boolean.TRUE;
        } else {
            String className = targetType.toString();
            throw new MappingException("JSON boolean (true) cannot be mapped to " + className);
        }
    }
    if (source == JsonValue.FALSE) {
        if (Boolean.class.equals(targetType)) {
            return Boolean.FALSE;
        } else {
            String className = targetType.toString();
            throw new MappingException("JSON boolean (false) cannot be mapped to " + className);
        }
    } else if (source instanceof JsonString) {
        if (String.class.equals(targetType)) {
            return ((JsonString) source).getChars();
        } else {
            String className = targetType.toString();
            throw new MappingException("JSON string cannot be mapped to " + className);
        }
    } else if (source instanceof JsonNumber) {
        JsonNumber jsonNumber = (JsonNumber) source;
        if (jsonNumber.isIntegral()) {
            return mapIntegralJsonNumber(jsonNumber, getRawClass(targetType));
        } else {
            return mapDecimalJsonNumber(jsonNumber, getRawClass(targetType));
        }
    }
    if (source instanceof JsonArrayBuilder) {
        source = ((JsonArrayBuilder) source).build();
    } else if (source instanceof JsonObjectBuilder) {
        source = ((JsonObjectBuilder) source).build();
    }
    if (source instanceof Collection) {
        // this covers both List<JsonValue> and JsonArray from JSON-P spec
        Class<?> rawTargetType = getRawClass(targetType);
        Type targetTypeArg = getFirstTypeArgument(targetType);
        Collection<Object> result = newCollectionOfType(rawTargetType);
        for (Object srcValue : (Collection<?>) source) {
            if (srcValue instanceof JsonObject) {
                if (targetTypeArg != null) {
                    result.add(mapImpl(srcValue, targetTypeArg));
                } else {
                    result.add(srcValue);
                }
            } else {
                result.add(unwrapJsonValue(srcValue));
            }
        }
        return result;
    } else if (source instanceof JsonObject) {
        if (targetType instanceof Class) {
            if (jsonToClassMethod != null) {
                try {
                    JsonParser jsonParser = new JsonStructureToParserAdapter((JsonStructure) source);
                    return jsonToClassMethod.invoke(jsonb, jsonParser, (Class<?>) targetType);
                } catch (Exception e) {
                    throw new MappingException(e);
                }
            } else {
                try {
                    // Fallback databinding approach for JSON-B API implementations without
                    // explicit support for use of JsonParser in their public API. The approach
                    // is essentially first to serialize given value into JSON, and then bind
                    // it to data object of given class.
                    String json = source.toString();
                    return jsonb.fromJson(json, (Class<?>) targetType);
                } catch (JsonbException e) {
                    throw new MappingException(e);
                }
            }
        } else if (targetType instanceof ParameterizedType) {
            if (jsonToTypeMethod != null) {
                try {
                    JsonParser jsonParser = new JsonStructureToParserAdapter((JsonStructure) source);
                    return jsonToTypeMethod.invoke(jsonb, jsonParser, (Type) targetType);
                } catch (Exception e) {
                    throw new MappingException(e);
                }
            } else {
                try {
                    // Fallback databinding approach for JSON-B API implementations without
                    // explicit support for use of JsonParser in their public API. The approach
                    // is essentially first to serialize given value into JSON, and then bind
                    // the JSON string to data object of given type.
                    String json = source.toString();
                    return jsonb.fromJson(json, (Type) targetType);
                } catch (JsonbException e) {
                    throw new MappingException(e);
                }
            }
        } else {
            throw new MappingException("JSON object cannot be databind to " + targetType);
        }
    } else {
        return source;
    }
}
Also used : JsonObject(jakarta.json.JsonObject) JsonString(jakarta.json.JsonString) JsonbException(jakarta.json.bind.JsonbException) JsonException(jakarta.json.JsonException) NoSuchElementException(java.util.NoSuchElementException) ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) JsonNumber(jakarta.json.JsonNumber) JsonbException(jakarta.json.bind.JsonbException) Collection(java.util.Collection) JsonObject(jakarta.json.JsonObject) JsonString(jakarta.json.JsonString) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) JsonParser(jakarta.json.stream.JsonParser) JsonStructure(jakarta.json.JsonStructure)

Example 67 with JsonObject

use of jakarta.json.JsonObject 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 68 with JsonObject

use of jakarta.json.JsonObject 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 69 with JsonObject

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

the class ProbeJmxIntegrationTest method testReceiveObservers.

@Test
public void testReceiveObservers() throws Exception {
    try (WeldContainer container = new Weld().initialize()) {
        assertNotNull(container.select(ProbeExtension.class).get());
        Object[] params = new Object[] { 0, 50, "", "" };
        String[] signature = new String[] { int.class.getName(), int.class.getName(), String.class.getName(), String.class.getName() };
        JsonObject obj = invokeMBeanOperation("receiveObservers", params, signature);
        JsonArray beansDataArray = obj.getJsonArray(Strings.DATA);
        JsonObject omegaObserverJson = getJsonObjectByClass(beansDataArray, OmegaObserver.class);
        assertNotNull(omegaObserverJson);
        assertEquals(omegaObserverJson.getJsonString(Strings.OBSERVED_TYPE).getString(), Omega.class.getName());
        assertEquals(omegaObserverJson.getJsonString(Strings.RECEPTION).getString(), "ALWAYS");
        assertEquals(omegaObserverJson.getJsonString(Strings.PRIORITY_RANGE).getString(), Strings.APPLICATION.toUpperCase());
        assertEquals(omegaObserverJson.getInt(Strings.PRIORITY), jakarta.interceptor.Interceptor.Priority.APPLICATION + 500);
    }
}
Also used : JsonArray(jakarta.json.JsonArray) WeldContainer(org.jboss.weld.environment.se.WeldContainer) JsonObject(jakarta.json.JsonObject) JsonObject(jakarta.json.JsonObject) Weld(org.jboss.weld.environment.se.Weld) Test(org.junit.Test)

Example 70 with JsonObject

use of jakarta.json.JsonObject in project glassfish-hk2 by eclipse-ee4j.

the class JsonParser method marshal.

/* (non-Javadoc)
     * @see org.glassfish.hk2.xml.spi.XmlServiceParser#marshall(java.io.OutputStream, org.glassfish.hk2.xml.api.XmlRootHandle)
     */
@Override
public <T> void marshal(OutputStream outputStream, XmlRootHandle<T> rootHandle, Map<String, Object> options) throws IOException {
    JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
    T root = rootHandle.getRoot();
    JsonObject rootObject = createJsonObject((BaseHK2JAXBBean) root, objectBuilder);
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE);
    JsonWriterFactory writerFactory = Json.createWriterFactory(config);
    JsonWriter writer = writerFactory.createWriter(outputStream);
    try {
        writer.writeObject(rootObject);
    } finally {
        writer.close();
    }
}
Also used : HashMap(java.util.HashMap) JsonObject(jakarta.json.JsonObject) JsonObject(jakarta.json.JsonObject) JsonObjectBuilder(jakarta.json.JsonObjectBuilder) JsonWriter(jakarta.json.JsonWriter) JsonWriterFactory(jakarta.json.JsonWriterFactory)

Aggregations

JsonObject (jakarta.json.JsonObject)356 Test (org.junit.Test)125 Test (org.junit.jupiter.api.Test)92 JsonArray (jakarta.json.JsonArray)29 Response (jakarta.ws.rs.core.Response)29 JsonObjectBuilder (jakarta.json.JsonObjectBuilder)24 JsonString (jakarta.json.JsonString)24 JsonValue (jakarta.json.JsonValue)20 WebClientResponse (io.helidon.webclient.WebClientResponse)19 Client (jakarta.ws.rs.client.Client)18 StringReader (java.io.StringReader)17 HelidonTest (io.helidon.microprofile.tests.junit5.HelidonTest)15 JsonReader (jakarta.json.JsonReader)14 List (java.util.List)14 JsonException (jakarta.json.JsonException)13 Map (java.util.Map)13 Logger (java.util.logging.Logger)13 Routing (io.helidon.webserver.Routing)11 Json (jakarta.json.Json)11 Produces (jakarta.ws.rs.Produces)11