Search in sources :

Example 56 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project mu-server by 3redronin.

the class RequestBodyReaderStringTest method requestBodiesCanBeReadAsStringsWithLargeChunks.

@Test
public void requestBodiesCanBeReadAsStringsWithLargeChunks() throws IOException {
    server = ServerUtils.httpsServerForTest().addHandler((request, response) -> {
        String body = request.readBodyAsString();
        response.write(body);
        return true;
    }).start();
    String m1 = StringUtils.randomAsciiStringOfLength(100000);
    String m2 = StringUtils.randomAsciiStringOfLength(100000);
    Request.Builder request = request().url(server.uri().toString()).post(new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.get("text/plain");
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            bufferedSink.write(m1.getBytes(StandardCharsets.UTF_8)).flush();
            bufferedSink.write(m2.getBytes(StandardCharsets.UTF_8)).flush();
        }
    });
    try (Response resp = call(request)) {
        assertThat(resp.code(), equalTo(200));
        assertThat(resp.body().string(), equalTo(m1 + m2));
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) MediaType(okhttp3.MediaType) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 57 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project mu-server by 3redronin.

the class RequestBodyReaderInputStreamAdapterTest method hugeBodiesCanBeStreamed.

@Test
public void hugeBodiesCanBeStreamed() throws IOException {
    int chunkSize = 10000;
    int loops = 6400;
    server = ServerUtils.httpsServerForTest().withMaxRequestSize(loops * (long) chunkSize).addHandler((request, response) -> {
        response.contentType("application/octet-stream");
        try (InputStream is = request.inputStream().orElseThrow(() -> new MuException("No input stream"))) {
            byte[] buffer = new byte[chunkSize];
            int read;
            long received = 0;
            while ((read = is.read(buffer)) > -1) {
                received += read;
            }
            response.write("Got " + received + " bytes");
        }
        return true;
    }).start();
    Request.Builder request = request().url(server.uri().toString()).post(new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.get("application/octet-stream");
        }

        @Override
        public void writeTo(BufferedSink bufferedSink) throws IOException {
            byte[] ones = new byte[chunkSize];
            Arrays.fill(ones, (byte) 1);
            for (int i = 0; i < loops; i++) {
                ByteBuffer src = ByteBuffer.wrap(ones);
                bufferedSink.write(src);
            }
        }
    });
    try (Response resp = call(request)) {
        assertThat(resp.code(), is(200));
        assertThat(resp.body().string(), equalTo("Got " + ((long) chunkSize * (long) loops) + " bytes"));
    }
}
Also used : Request(okhttp3.Request) BufferedSink(okio.BufferedSink) ByteBuffer(java.nio.ByteBuffer) Response(okhttp3.Response) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 58 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project mu-server by 3redronin.

the class EntityProvidersTest method customConvertersCanBeUsedEvenWithGenerics.

@Test
public void customConvertersCanBeUsedEvenWithGenerics() throws Exception {
    class Dog {

        public final String breed;

        public final String name;

        Dog(String name, String breed) {
            this.name = name;
            this.breed = breed;
        }
    }
    @Path("dogs")
    class Sample {

        @POST
        public Dog get(String name) {
            return new Dog(name, "Unknown");
        }

        @GET
        @Path("all")
        public javax.ws.rs.core.Response all() {
            List<Dog> dogs = asList(new Dog("Little", "Chihuahua"), new Dog("Mangle", "Mongrel"));
            GenericEntity<List<Dog>> dogList = new GenericEntity<List<Dog>>(dogs) {
            };
            return javax.ws.rs.core.Response.ok(dogList).build();
        }
    }
    class DogWriter implements MessageBodyWriter<Dog> {

        public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) {
            return type.equals(Dog.class);
        }

        public void writeTo(Dog dog, Class<?> type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
            try (PrintStream stream = new PrintStream(entityStream)) {
                stream.print("Dog: " + dog.name + " (" + dog.breed + ")");
            }
        }
    }
    class DogListWriter implements MessageBodyWriter<List<Dog>> {

        public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) {
            return List.class.isAssignableFrom(type) && genericType instanceof ParameterizedType && ((ParameterizedType) genericType).getActualTypeArguments()[0].equals(Dog.class);
        }

        public void writeTo(List<Dog> dogs, Class<?> type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
            try (PrintStream stream = new PrintStream(entityStream)) {
                for (Dog dog : dogs) {
                    stream.println(dog.name + " (" + dog.breed + ")");
                }
            }
        }
    }
    this.server = httpsServerForTest().addHandler(restHandler(new Sample()).addCustomWriter(new DogWriter()).addCustomWriter(new DogListWriter()).build()).start();
    try (Response resp = call(request().post(RequestBody.create("Little", MediaType.parse("text/plain"))).url(server.uri().resolve("/dogs").toString()))) {
        assertThat(resp.body().string(), equalTo("Dog: Little (Unknown)"));
    }
    try (Response resp = call(request().url(server.uri().resolve("/dogs/all").toString()))) {
        assertThat(resp.body().string(), equalTo("Little (Chihuahua)" + NEWLINE + "Mangle (Mongrel)" + NEWLINE));
    }
}
Also used : Matchers(org.hamcrest.Matchers) Collectors(java.util.stream.Collectors) javax.ws.rs(javax.ws.rs) ParameterizedType(java.lang.reflect.ParameterizedType) Response(okhttp3.Response) MediaType(okhttp3.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) GenericEntity(javax.ws.rs.core.GenericEntity) MediaType(okhttp3.MediaType) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ServerUtils.httpsServerForTest(scaffolding.ServerUtils.httpsServerForTest) Test(org.junit.Test)

Example 59 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project mu-server by 3redronin.

the class AsynchronousProcessingTest method aCustomTimeoutHandlerCanBeUsed.

@Test
public void aCustomTimeoutHandlerCanBeUsed() throws Exception {
    class Hawk {

        String toHawker() {
            return "Oops, this is Hawkward";
        }
    }
    @Path("samples")
    class Sample {

        @GET
        public void go(@Suspended AsyncResponse ar) {
            ar.setTimeoutHandler(asyncResponse -> asyncResponse.resume(new Hawk()));
            ar.setTimeout(10, TimeUnit.MILLISECONDS);
        }
    }
    this.server = ServerUtils.httpsServerForTest().addHandler(restHandler(new Sample()).addCustomWriter(new MessageBodyWriter<Hawk>() {

        public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) {
            return type.equals(Hawk.class);
        }

        public void writeTo(Hawk hawk, Class<?> type, Type genericType, Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
            entityStream.write(hawk.toHawker().getBytes("UTF-8"));
        }
    })).start();
    try (Response resp = call(request().url(server.uri().resolve("/samples").toString()))) {
        assertThat(resp.code(), is(200));
        assertThat(resp.body().string(), equalTo("Oops, this is Hawkward"));
    }
}
Also used : Matchers(org.hamcrest.Matchers) javax.ws.rs(javax.ws.rs) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) Response(okhttp3.Response) AsyncResponse(javax.ws.rs.container.AsyncResponse) MediaType(okhttp3.MediaType) Type(java.lang.reflect.Type) MediaType(okhttp3.MediaType) Suspended(javax.ws.rs.container.Suspended) AsyncResponse(javax.ws.rs.container.AsyncResponse) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.junit.Test)

Example 60 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project Ethernity-Wallet-Android by kris-krytech.

the class AlphaWalletService method postRequest.

private Integer postRequest(StringBuilder sb, Map<String, String> args) throws Exception {
    MediaType mediaType = MediaType.parse("application/octet-stream");
    sb.append(formPrologData(args));
    Request request = new Request.Builder().url(sb.toString()).post(RequestBody.create(mediaType, "")).build();
    okhttp3.Response response = httpClient.newCall(request).execute();
    return response.code();
}
Also used : Request(okhttp3.Request) MediaType(okhttp3.MediaType)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21