Search in sources :

Example 1 with Rfc3339DateJsonAdapter

use of com.squareup.moshi.adapters.Rfc3339DateJsonAdapter in project ApplicationInsights-Java by microsoft.

the class ServiceProfilerSettingsClient method toServiceProfilerConfiguration.

private static ProfilerConfiguration toServiceProfilerConfiguration(String config) throws IOException {
    Moshi moshi = new Moshi.Builder().add(Date.class, new Rfc3339DateJsonAdapter()).build();
    JsonAdapter<ProfilerConfiguration> jsonAdapter = moshi.adapter(ProfilerConfiguration.class);
    return jsonAdapter.fromJson(config);
}
Also used : Moshi(com.squareup.moshi.Moshi) ProfilerConfiguration(com.microsoft.applicationinsights.profiler.ProfilerConfiguration) Rfc3339DateJsonAdapter(com.squareup.moshi.adapters.Rfc3339DateJsonAdapter) Date(java.util.Date)

Example 2 with Rfc3339DateJsonAdapter

use of com.squareup.moshi.adapters.Rfc3339DateJsonAdapter in project axis-axis2-java-core by apache.

the class JsonFormatterTest method testWriteToJSON.

@Test
public void testWriteToJSON() throws Exception {
    Person person = new Person();
    person.setName("Leo");
    person.setAge(27);
    person.setGender("Male");
    person.setSingle(true);
    outMsgContext.setProperty(JsonConstant.RETURN_OBJECT, person);
    outMsgContext.setProperty(JsonConstant.RETURN_TYPE, Person.class);
    Moshi moshi = new Moshi.Builder().add(Date.class, new Rfc3339DateJsonAdapter()).build();
    JsonAdapter<Person> adapter = moshi.adapter(Person.class);
    String response = adapter.toJson(person);
    jsonString = "{\"" + JsonConstant.RESPONSE + "\":" + response + "}";
    JsonFormatter jsonFormatter = new JsonFormatter();
    jsonFormatter.writeTo(outMsgContext, outputFormat, outputStream, false);
    String personString = outputStream.toString();
    Assert.assertEquals(jsonString, personString);
}
Also used : Moshi(com.squareup.moshi.Moshi) Rfc3339DateJsonAdapter(com.squareup.moshi.adapters.Rfc3339DateJsonAdapter) Date(java.util.Date) Test(org.junit.Test)

Example 3 with Rfc3339DateJsonAdapter

use of com.squareup.moshi.adapters.Rfc3339DateJsonAdapter in project moshi by square.

the class ReadAndWriteRfc3339Dates method run.

public void run() throws Exception {
    Moshi moshi = new Moshi.Builder().add(Date.class, new Rfc3339DateJsonAdapter()).build();
    JsonAdapter<Tournament> jsonAdapter = moshi.adapter(Tournament.class);
    // The RFC3339 JSON adapter can read dates with a timezone offset like '-05:00'.
    String lastTournament = "" + "{" + "  \"location\":\"Chainsaw\"," + "  \"name\":\"21 for 21\"," + "  \"start\":\"2015-09-01T20:00:00-05:00\"" + "}";
    System.out.println("Last tournament: " + jsonAdapter.fromJson(lastTournament));
    // The RFC3339 JSON adapter always writes dates with UTC, using a 'Z' suffix.
    Tournament nextTournament = new Tournament("Waterloo Classic", "Bauer Kitchen", newDate(2015, 10, 1, 20, -5));
    System.out.println("Next tournament JSON: " + jsonAdapter.toJson(nextTournament));
}
Also used : Moshi(com.squareup.moshi.Moshi) Rfc3339DateJsonAdapter(com.squareup.moshi.adapters.Rfc3339DateJsonAdapter) Tournament(com.squareup.moshi.recipes.models.Tournament) Date(java.util.Date)

Example 4 with Rfc3339DateJsonAdapter

use of com.squareup.moshi.adapters.Rfc3339DateJsonAdapter in project axis-axis2-java-core by apache.

the class JsonUtils method invokeServiceClass.

public static Object invokeServiceClass(JsonReader jsonReader, Object service, Method operation, Class[] paramClasses, int paramCount) throws InvocationTargetException, IllegalAccessException, IOException {
    Object[] methodParam = new Object[paramCount];
    try {
        // define custom Moshi adapter so Json numbers become Java Long and Double
        JsonAdapter.Factory objectFactory = new JsonAdapter.Factory() {

            @Override
            @Nullable
            public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
                if (type != Object.class)
                    return null;
                final JsonAdapter<Object> delegate = moshi.nextAdapter(this, Object.class, annotations);
                return new JsonAdapter<Object>() {

                    @Override
                    @Nullable
                    public Object fromJson(JsonReader reader) throws IOException {
                        if (reader.peek() != JsonReader.Token.NUMBER) {
                            return delegate.fromJson(reader);
                        } else {
                            String n = reader.nextString();
                            if (n.indexOf('.') != -1) {
                                return Double.parseDouble(n);
                            }
                            try {
                                Long longValue = Long.parseLong(n);
                                return longValue;
                            } catch (Exception e) {
                            }
                            // if exception parsing long, try double again
                            return Double.parseDouble(n);
                        }
                    }

                    @Override
                    public void toJson(JsonWriter writer, @Nullable Object value) {
                        try {
                            delegate.toJson(writer, value);
                        } catch (Exception ex) {
                            log.error(ex.getMessage(), ex);
                        }
                    }
                };
            }
        };
        Moshi moshiFrom = new Moshi.Builder().add(objectFactory).add(Date.class, new Rfc3339DateJsonAdapter()).build();
        String[] argNames = new String[paramCount];
        jsonReader.beginObject();
        // get message name from input json stream
        String messageName = jsonReader.nextName();
        if (messageName == null || !messageName.equals(operation.getName())) {
            log.error("JsonUtils.invokeServiceClass() throwing IOException, messageName: " + messageName + " is unknown, it does not match the axis2 operation, the method name: " + operation.getName());
            throw new IOException("Bad Request");
        }
        jsonReader.beginArray();
        int i = 0;
        for (Class paramType : paramClasses) {
            JsonAdapter<Map> moshiFromJsonAdapter = null;
            moshiFromJsonAdapter = moshiFrom.adapter(paramType);
            jsonReader.beginObject();
            argNames[i] = jsonReader.nextName();
            // moshi handles all types well and returns an object from it
            methodParam[i] = moshiFromJsonAdapter.fromJson(jsonReader);
            log.trace("JsonUtils.invokeServiceClass() completed processing on messageName: " + messageName + " , arg name: " + argNames[i] + " , methodParam: " + methodParam[i].getClass().getName() + " , from argNames.length: " + argNames.length);
            jsonReader.endObject();
            i++;
        }
        jsonReader.endArray();
        jsonReader.endObject();
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new IOException("Bad Request");
    }
    return operation.invoke(service, methodParam);
}
Also used : Set(java.util.Set) Moshi(com.squareup.moshi.Moshi) Rfc3339DateJsonAdapter(com.squareup.moshi.adapters.Rfc3339DateJsonAdapter) LogFactory(org.apache.commons.logging.LogFactory) JsonAdapter(com.squareup.moshi.JsonAdapter) Rfc3339DateJsonAdapter(com.squareup.moshi.adapters.Rfc3339DateJsonAdapter) JsonReader(com.squareup.moshi.JsonReader) IOException(java.io.IOException) JsonWriter(com.squareup.moshi.JsonWriter) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Date(java.util.Date) Type(java.lang.reflect.Type) Map(java.util.Map) Nullable(javax.annotation.Nullable)

Example 5 with Rfc3339DateJsonAdapter

use of com.squareup.moshi.adapters.Rfc3339DateJsonAdapter in project axis-axis2-java-core by apache.

the class JsonFormatter method writeTo.

public void writeTo(MessageContext outMsgCtxt, OMOutputFormat omOutputFormat, OutputStream outputStream, boolean preserve) throws AxisFault {
    String charSetEncoding = (String) outMsgCtxt.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
    JsonWriter jsonWriter;
    String msg;
    try {
        Moshi moshi = new Moshi.Builder().add(String.class, new JsonHtmlEncoder()).add(Date.class, new Rfc3339DateJsonAdapter()).build();
        JsonAdapter<Object> adapter = moshi.adapter(Object.class);
        BufferedSink sink = Okio.buffer(Okio.sink(outputStream));
        jsonWriter = JsonWriter.of(sink);
        Object retObj = outMsgCtxt.getProperty(JsonConstant.RETURN_OBJECT);
        if (outMsgCtxt.isProcessingFault()) {
            OMElement element = outMsgCtxt.getEnvelope().getBody().getFirstElement();
            try {
                jsonWriter.beginObject();
                jsonWriter.name(element.getLocalName());
                jsonWriter.beginObject();
                Iterator childrenIterator = element.getChildElements();
                while (childrenIterator.hasNext()) {
                    Object next = childrenIterator.next();
                    OMElement omElement = (OMElement) next;
                    jsonWriter.name(omElement.getLocalName());
                    jsonWriter.value(omElement.getText());
                }
                jsonWriter.endObject();
                jsonWriter.endObject();
                jsonWriter.flush();
                jsonWriter.close();
            } catch (IOException e) {
                throw new AxisFault("Error while processing fault code in JsonWriter");
            }
        } else if (retObj == null) {
            OMElement element = outMsgCtxt.getEnvelope().getBody().getFirstElement();
            QName elementQname = outMsgCtxt.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE).getElementQName();
            ArrayList<XmlSchema> schemas = outMsgCtxt.getAxisService().getSchema();
            MoshiXMLStreamWriter xmlsw = new MoshiXMLStreamWriter(jsonWriter, elementQname, schemas, outMsgCtxt.getConfigurationContext());
            try {
                xmlsw.writeStartDocument();
                element.serialize(xmlsw, preserve);
                xmlsw.writeEndDocument();
            } catch (XMLStreamException e) {
                throw new AxisFault("Error while writing to the output stream using JsonWriter", e);
            }
        } else {
            try {
                jsonWriter.beginObject();
                jsonWriter.name(JsonConstant.RESPONSE);
                Type returnType = (Type) outMsgCtxt.getProperty(JsonConstant.RETURN_TYPE);
                adapter.toJson(jsonWriter, retObj);
                jsonWriter.endObject();
                jsonWriter.flush();
            } catch (IOException e) {
                msg = "Exception occurred while writting to JsonWriter at the JsonFormatter ";
                log.error(msg, e);
                throw AxisFault.makeFault(e);
            }
        }
        log.debug("JsonFormatter.writeTo() has completed");
    } catch (Exception e) {
        msg = "Exception occurred when try to encode output stream using  " + Constants.Configuration.CHARACTER_SET_ENCODING + " charset";
        log.error(msg, e);
        throw AxisFault.makeFault(e);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Moshi(com.squareup.moshi.Moshi) QName(javax.xml.namespace.QName) Rfc3339DateJsonAdapter(com.squareup.moshi.adapters.Rfc3339DateJsonAdapter) ArrayList(java.util.ArrayList) BufferedSink(okio.BufferedSink) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) JsonWriter(com.squareup.moshi.JsonWriter) Date(java.util.Date) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Type(java.lang.reflect.Type) XMLStreamException(javax.xml.stream.XMLStreamException) Iterator(java.util.Iterator)

Aggregations

Moshi (com.squareup.moshi.Moshi)7 Rfc3339DateJsonAdapter (com.squareup.moshi.adapters.Rfc3339DateJsonAdapter)7 Date (java.util.Date)6 JsonWriter (com.squareup.moshi.JsonWriter)3 Tournament (com.squareup.moshi.recipes.models.Tournament)2 IOException (java.io.IOException)2 Type (java.lang.reflect.Type)2 ArrayList (java.util.ArrayList)2 QName (javax.xml.namespace.QName)2 BufferedSink (okio.BufferedSink)2 OMElement (org.apache.axiom.om.OMElement)2 Test (org.junit.Test)2 ProfilerConfiguration (com.microsoft.applicationinsights.profiler.ProfilerConfiguration)1 JsonAdapter (com.squareup.moshi.JsonAdapter)1 JsonReader (com.squareup.moshi.JsonReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Annotation (java.lang.annotation.Annotation)1