Search in sources :

Example 1 with IOMessageWriter

use of net.morimekta.providence.mio.IOMessageWriter in project providence by morimekta.

the class GeneratorWatcher method dumpGeneratedMessages.

/**
 * Dump all generated messages.
 *
 * @throws IOException If writing the messages failed.
 */
@SuppressWarnings("unchecked")
public void dumpGeneratedMessages() throws IOException {
    MessageWriter writer = this.writer;
    if (writer == null) {
        writer = new IOMessageWriter(System.err, outputSerializer);
    }
    for (PMessage message : generated) {
        writer.write(message);
        writer.separator();
    }
}
Also used : IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) PMessage(net.morimekta.providence.PMessage) MessageWriter(net.morimekta.providence.mio.MessageWriter) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter)

Example 2 with IOMessageWriter

use of net.morimekta.providence.mio.IOMessageWriter in project providence by morimekta.

the class SocketServer method process.

@SuppressWarnings("unchecked")
private void process(long startTime, Socket socket) {
    try (Socket ignore = socket;
        BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
        IOMessageReader reader = new IOMessageReader(in, serializer);
        IOMessageWriter writer = new IOMessageWriter(out, serializer)) {
        while (socket.isConnected()) {
            AtomicReference<PServiceCall> callRef = new AtomicReference<>();
            AtomicReference<PServiceCall> responseRef = new AtomicReference<>();
            try {
                DefaultProcessorHandler handler = new DefaultProcessorHandler(new WrappedProcessor(processor, (c, p) -> {
                    callRef.set(c);
                    responseRef.set(p.handleCall(c));
                    return responseRef.get();
                }));
                handler.process(reader, writer);
                out.flush();
                long endTime = System.nanoTime();
                double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
                try {
                    instrumentation.onComplete(duration, callRef.get(), responseRef.get());
                } catch (Throwable th) {
                    LOGGER.error("Exception in service instrumentation", th);
                }
            } catch (IOException e) {
                long endTime = System.nanoTime();
                double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
                try {
                    instrumentation.onTransportException(e, duration, callRef.get(), responseRef.get());
                } catch (Throwable th) {
                    LOGGER.error("Exception in service instrumentation", th);
                }
                throw new UncheckedIOException(e.getMessage(), e);
            }
            in.mark(1);
            if (in.read() < 0) {
                return;
            }
            in.reset();
            startTime = System.nanoTime();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e.getMessage(), e);
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Socket(java.net.Socket) BufferedInputStream(java.io.BufferedInputStream) DefaultProcessorHandler(net.morimekta.providence.server.DefaultProcessorHandler) LoggerFactory(org.slf4j.LoggerFactory) BinarySerializer(net.morimekta.providence.serializer.BinarySerializer) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) BufferedOutputStream(java.io.BufferedOutputStream) ServerSocket(java.net.ServerSocket) PProcessor(net.morimekta.providence.PProcessor) SocketTimeoutException(java.net.SocketTimeoutException) NS_IN_MILLIS(net.morimekta.providence.util.ServiceCallInstrumentation.NS_IN_MILLIS) WrappedProcessor(net.morimekta.providence.server.WrappedProcessor) ThreadFactory(java.util.concurrent.ThreadFactory) Nonnull(javax.annotation.Nonnull) ExecutorService(java.util.concurrent.ExecutorService) Serializer(net.morimekta.providence.serializer.Serializer) Logger(org.slf4j.Logger) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) ServiceCallInstrumentation(net.morimekta.providence.util.ServiceCallInstrumentation) Executors(java.util.concurrent.Executors) UncheckedIOException(java.io.UncheckedIOException) TimeUnit(java.util.concurrent.TimeUnit) PServiceCall(net.morimekta.providence.PServiceCall) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) DefaultProcessorHandler(net.morimekta.providence.server.DefaultProcessorHandler) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) AtomicReference(java.util.concurrent.atomic.AtomicReference) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) BufferedInputStream(java.io.BufferedInputStream) WrappedProcessor(net.morimekta.providence.server.WrappedProcessor) PServiceCall(net.morimekta.providence.PServiceCall) BufferedOutputStream(java.io.BufferedOutputStream) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 3 with IOMessageWriter

use of net.morimekta.providence.mio.IOMessageWriter in project providence by morimekta.

the class MessageGenerator method dumpGeneratedMessages.

/**
 * Dump all generated messages.
 *
 * @throws IOException If writing the messages failed.
 */
@SuppressWarnings("unchecked")
private void dumpGeneratedMessages() throws IOException {
    MessageWriter writer = this.writer;
    if (writer == null) {
        writer = new IOMessageWriter(System.err, outputSerializer);
    }
    for (PMessage message : generated) {
        writer.write(message);
        writer.separator();
    }
}
Also used : IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) PMessage(net.morimekta.providence.PMessage) MessageWriter(net.morimekta.providence.mio.MessageWriter) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter)

Example 4 with IOMessageWriter

use of net.morimekta.providence.mio.IOMessageWriter in project providence by morimekta.

the class GeneratorWatcherTest method testRandom_customWriter.

@Test
public void testRandom_customWriter() throws IOException {
    Fairy fairy = Fairy.create(Locale.ENGLISH);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GeneratorWatcher<SimpleGeneratorBase, SimpleGeneratorContext> generator = GeneratorWatcher.create().setMessageWriter(new IOMessageWriter(baos, new FastBinarySerializer())).setMaxCollectionItems(2).withGenerator(CompactFields.kDescriptor, gen -> {
        gen.setAlwaysPresent(CompactFields._Field.NAME);
        gen.setValueGenerator(CompactFields._Field.NAME, ctx -> fairy.textProducer().word(1));
    }).dumpOnFailure();
    generator.starting(Description.EMPTY);
    CompactFields compact = generator.generate(CompactFields.kDescriptor);
    assertThat(compact.getLabel(), is(notNullValue()));
    assertThat(compact.getName(), is(notNullValue()));
    assertThat(compact.getName(), not(containsString(" ")));
    assertThat(compact.hasId(), is(true));
    assertThat(generator.allGenerated(), hasItem(compact));
    generator.failed(new Throwable(), Description.EMPTY);
    assertThat(console.output(), is(""));
    assertThat(console.error(), is(""));
    IOMessageReader reader = new IOMessageReader(new ByteArrayInputStream(baos.toByteArray()), new FastBinarySerializer());
    assertThat(reader.read(CompactFields.kDescriptor), is(equalToMessage(compact)));
}
Also used : IntStream(java.util.stream.IntStream) CoreMatchers.is(org.hamcrest.CoreMatchers.is) ConsoleWatcher(net.morimekta.testing.rules.ConsoleWatcher) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CoreMatchers.not(org.hamcrest.CoreMatchers.not) Random(java.util.Random) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) ArrayList(java.util.ArrayList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) Assert.assertThat(org.junit.Assert.assertThat) ExtraStreams(net.morimekta.util.ExtraStreams) ByteArrayInputStream(java.io.ByteArrayInputStream) Locale(java.util.Locale) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) JsonSerializer(net.morimekta.providence.serializer.JsonSerializer) Test(org.junit.Test) Description(org.junit.runner.Description) IOException(java.io.IOException) StandardCharsets(java.nio.charset.StandardCharsets) PMessage(net.morimekta.providence.PMessage) PField(net.morimekta.providence.descriptor.PField) Rule(org.junit.Rule) FastBinarySerializer(net.morimekta.providence.serializer.FastBinarySerializer) MessageReader(net.morimekta.providence.mio.MessageReader) PrettySerializer(net.morimekta.providence.serializer.PrettySerializer) CompactFields(net.morimekta.test.android.CompactFields) ProvidenceMatchers.equalToMessage(net.morimekta.providence.testing.ProvidenceMatchers.equalToMessage) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) Fairy(io.codearte.jfairy.Fairy) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) FastBinarySerializer(net.morimekta.providence.serializer.FastBinarySerializer) ByteArrayInputStream(java.io.ByteArrayInputStream) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Fairy(io.codearte.jfairy.Fairy) CompactFields(net.morimekta.test.android.CompactFields) Test(org.junit.Test)

Example 5 with IOMessageWriter

use of net.morimekta.providence.mio.IOMessageWriter in project providence by morimekta.

the class ProvidenceServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    long startTime = System.nanoTime();
    AtomicReference<PServiceCall> callRef = new AtomicReference<>();
    AtomicReference<PServiceCall> responseRef = new AtomicReference<>();
    PProcessor processor = new WrappedProcessor(processorProvider.processorForRequest(req), (c, r) -> {
        callRef.set(c);
        responseRef.set(r.handleCall(c));
        return responseRef.get();
    });
    try {
        Serializer requestSerializer = serializerProvider.getDefault();
        if (req.getContentType() != null) {
            try {
                MediaType mediaType = MediaType.parse(req.getContentType());
                requestSerializer = serializerProvider.getSerializer(mediaType.withoutParameters().toString());
            } catch (IllegalArgumentException e) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown content-type: " + req.getContentType());
                LOGGER.warn("Unknown content type in request", e);
                return;
            }
        } else {
            LOGGER.debug("Request is missing content type.");
        }
        Serializer responseSerializer = requestSerializer;
        String acceptHeader = req.getHeader("Accept");
        if (acceptHeader != null) {
            String[] entries = acceptHeader.split("[,]");
            for (String entry : entries) {
                entry = entry.trim();
                if (entry.isEmpty()) {
                    continue;
                }
                if ("*/*".equals(entry)) {
                    // Then responding same as request is good.
                    break;
                }
                try {
                    MediaType mediaType = MediaType.parse(entry);
                    responseSerializer = serializerProvider.getSerializer(mediaType.withoutParameters().toString());
                    break;
                } catch (IllegalArgumentException ignore) {
                // Ignore. Bad header input is pretty common.
                }
            }
        }
        MessageReader reader = new IOMessageReader(req.getInputStream(), requestSerializer);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MessageWriter writer = new IOMessageWriter(baos, responseSerializer);
        getHandler(processor).process(reader, writer);
        resp.setStatus(HttpServletResponse.SC_OK);
        if (baos.size() > 0) {
            resp.setContentType(responseSerializer.mediaType());
            resp.setContentLength(baos.size());
            resp.getOutputStream().write(baos.toByteArray());
            resp.getOutputStream().flush();
        }
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onComplete(duration, callRef.get(), responseRef.get());
        } catch (Throwable th) {
            LOGGER.error("Exception in service instrumentation", th);
        }
    } catch (EOFException e) {
        // output stream closed before write is complete.
        // So we cannot even try to respond.
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onTransportException(e, duration, callRef.get(), responseRef.get());
        } catch (Throwable th) {
            LOGGER.error("Exception in service instrumentation", th);
        }
    } catch (Exception e) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error: " + e.getMessage());
        } catch (IOException ioEx) {
            e.addSuppressed(ioEx);
        }
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onTransportException(e, duration, callRef.get(), responseRef.get());
        } catch (Throwable th) {
            LOGGER.error("Exception in service instrumentation", th);
        }
    }
}
Also used : PProcessor(net.morimekta.providence.PProcessor) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageReader(net.morimekta.providence.mio.MessageReader) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) EOFException(java.io.EOFException) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) PServiceCall(net.morimekta.providence.PServiceCall) EOFException(java.io.EOFException) MediaType(com.google.common.net.MediaType) MessageWriter(net.morimekta.providence.mio.MessageWriter) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) Serializer(net.morimekta.providence.serializer.Serializer)

Aggregations

IOMessageWriter (net.morimekta.providence.mio.IOMessageWriter)5 IOException (java.io.IOException)3 PMessage (net.morimekta.providence.PMessage)3 IOMessageReader (net.morimekta.providence.mio.IOMessageReader)3 MessageWriter (net.morimekta.providence.mio.MessageWriter)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 PProcessor (net.morimekta.providence.PProcessor)2 PServiceCall (net.morimekta.providence.PServiceCall)2 MessageReader (net.morimekta.providence.mio.MessageReader)2 Serializer (net.morimekta.providence.serializer.Serializer)2 MediaType (com.google.common.net.MediaType)1 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 Fairy (io.codearte.jfairy.Fairy)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 EOFException (java.io.EOFException)1 UncheckedIOException (java.io.UncheckedIOException)1 InetSocketAddress (java.net.InetSocketAddress)1