Search in sources :

Example 1 with PProcessor

use of net.morimekta.providence.PProcessor in project providence by morimekta.

the class SerializerTest method setUpData.

@BeforeClass
public static void setUpData() throws IOException, ExceptionFields {
    MessageGenerator gen = new MessageGenerator().addFactory(f -> {
        if (f.equals(Operand._Field.OPERATION)) {
            return () -> Operation.builder().setOperator(Operator.ADD).addToOperands(Operand.withNumber(123)).addToOperands(Operand.withNumber(321)).build();
        }
        return null;
    });
    if (operation == null) {
        operation = gen.generate(Operation.kDescriptor);
    }
    if (containers == null) {
        containers = new ArrayList<>();
        for (int i = 0; i < 1; ++i) {
            containers.add(gen.generate(Containers.kDescriptor));
        }
    }
    serviceCalls = new ArrayList<>();
    /**
     * Temporary setup needed to generate
     */
    ContainerService.Iface impl = pC -> {
        if (pC == null) {
            throw new PApplicationException("", PApplicationExceptionType.INTERNAL_ERROR);
        }
        if (pC.mutate().presentFields().isEmpty()) {
            throw gen.generate(ExceptionFields.kDescriptor);
        }
        return CompactFields.builder().setName("" + pC.hashCode()).setId(pC.hashCode()).build();
    };
    PProcessor processor = new ContainerService.Processor(impl);
    PServiceCallHandler handler = new PServiceCallHandler() {

        @Nullable
        @Override
        @SuppressWarnings("unchecked")
        public <Request extends PMessage<Request, RequestField>, Response extends PMessage<Response, ResponseField>, RequestField extends PField, ResponseField extends PField> PServiceCall<Response, ResponseField> handleCall(PServiceCall<Request, RequestField> call, PService service) throws IOException {
            serviceCalls.add(call);
            try {
                PServiceCall response = processor.handleCall(call, service);
                serviceCalls.add(response);
                return response;
            } catch (PApplicationException e) {
                PServiceCall ex = new PServiceCall(call.getMethod(), PServiceCallType.EXCEPTION, call.getSequence(), e);
                serviceCalls.add(ex);
                return ex;
            }
        }
    };
    ContainerService.Client client = new ContainerService.Client(handler);
    client.load(gen.generate(Containers.kDescriptor));
    try {
        client.load(Containers.builder().build());
    } catch (ExceptionFields e) {
    // ignore.
    }
    try {
        // NPE -> PApplicationException
        client.load(null);
    } catch (PApplicationException e) {
    // ignore.
    }
}
Also used : Operand(net.morimekta.test.providence.core.calculator.Operand) CoreMatchers.is(org.hamcrest.CoreMatchers.is) BeforeClass(org.junit.BeforeClass) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PApplicationException(net.morimekta.providence.PApplicationException) MessageCollectors(net.morimekta.providence.streams.MessageCollectors) EqualToMessage(net.morimekta.providence.util_internal.EqualToMessage) Binary(net.morimekta.util.Binary) PServiceCallType(net.morimekta.providence.PServiceCallType) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) PService(net.morimekta.providence.descriptor.PService) Containers(net.morimekta.test.providence.core.Containers) PProcessor(net.morimekta.providence.PProcessor) ByteArrayInputStream(java.io.ByteArrayInputStream) PApplicationExceptionType(net.morimekta.providence.PApplicationExceptionType) MessageGenerator(net.morimekta.providence.util_internal.MessageGenerator) Assert.fail(org.junit.Assert.fail) Nullable(javax.annotation.Nullable) ExtraMatchers.equalToLines(net.morimekta.testing.ExtraMatchers.equalToLines) Operation(net.morimekta.test.providence.core.calculator.Operation) UTF_8(java.nio.charset.StandardCharsets.UTF_8) PServiceCallHandler(net.morimekta.providence.PServiceCallHandler) Test(org.junit.Test) IOException(java.io.IOException) MessageStreams(net.morimekta.providence.streams.MessageStreams) ContainerService(net.morimekta.test.providence.core.ContainerService) Collectors(java.util.stream.Collectors) File(java.io.File) PMessage(net.morimekta.providence.PMessage) PField(net.morimekta.providence.descriptor.PField) CompactFields(net.morimekta.test.providence.core.CompactFields) List(java.util.List) Rule(org.junit.Rule) PServiceCall(net.morimekta.providence.PServiceCall) ExceptionFields(net.morimekta.test.providence.core.ExceptionFields) TokenizerException(net.morimekta.providence.serializer.pretty.TokenizerException) ConsumeAll(net.morimekta.test.providence.core.ConsumeAll) Assert.assertEquals(org.junit.Assert.assertEquals) Operator(net.morimekta.test.providence.core.calculator.Operator) InputStream(java.io.InputStream) PProcessor(net.morimekta.providence.PProcessor) MessageGenerator(net.morimekta.providence.util_internal.MessageGenerator) PField(net.morimekta.providence.descriptor.PField) PProcessor(net.morimekta.providence.PProcessor) ExceptionFields(net.morimekta.test.providence.core.ExceptionFields) PServiceCallHandler(net.morimekta.providence.PServiceCallHandler) PMessage(net.morimekta.providence.PMessage) PApplicationException(net.morimekta.providence.PApplicationException) PServiceCall(net.morimekta.providence.PServiceCall) ContainerService(net.morimekta.test.providence.core.ContainerService) PService(net.morimekta.providence.descriptor.PService) BeforeClass(org.junit.BeforeClass)

Example 2 with PProcessor

use of net.morimekta.providence.PProcessor in project providence by morimekta.

the class WrappedProcessorTest method testWrapper.

@Test
public void testWrapper() throws IOException {
    PProcessor processor = mock(PProcessor.class);
    WrappedProcessor wrap = new WrappedProcessor(processor, (call, p) -> {
        // before call
        PServiceCall reply = p.handleCall(call, p.getDescriptor());
        // after call
        return reply;
    });
    PApplicationException c = new PApplicationException("call", PApplicationExceptionType.INTERNAL_ERROR);
    PApplicationException r = new PApplicationException("call", PApplicationExceptionType.INTERNAL_ERROR);
    AtomicReference<PService> service = new AtomicReference<>();
    service.set(new PService("test", "Service", service::get, new PServiceMethod[] {}) {

        @Nullable
        @Override
        public PServiceMethod getMethod(String name) {
            for (PServiceMethod method : getMethods()) {
                if (method.getName().equals(name)) {
                    return method;
                }
            }
            return null;
        }
    });
    PServiceCall call = new PServiceCall<>("test", PServiceCallType.CALL, 44, c);
    PServiceCall reply = new PServiceCall<>("reply", PServiceCallType.REPLY, 44, r);
    when(processor.getDescriptor()).thenReturn(service.get());
    when(processor.handleCall(call, service.get())).thenReturn(reply);
    assertThat(wrap.handleCall(call), sameInstance(reply));
    verify(processor, atLeastOnce()).getDescriptor();
    verify(processor).handleCall(call, service.get());
    verifyNoMoreInteractions(processor);
}
Also used : PProcessor(net.morimekta.providence.PProcessor) PServiceCall(net.morimekta.providence.PServiceCall) PApplicationException(net.morimekta.providence.PApplicationException) AtomicReference(java.util.concurrent.atomic.AtomicReference) PServiceMethod(net.morimekta.providence.descriptor.PServiceMethod) Nullable(javax.annotation.Nullable) PService(net.morimekta.providence.descriptor.PService) Test(org.junit.Test)

Example 3 with PProcessor

use of net.morimekta.providence.PProcessor 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

PProcessor (net.morimekta.providence.PProcessor)3 PServiceCall (net.morimekta.providence.PServiceCall)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Nullable (javax.annotation.Nullable)2 PApplicationException (net.morimekta.providence.PApplicationException)2 PService (net.morimekta.providence.descriptor.PService)2 MediaType (com.google.common.net.MediaType)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 EOFException (java.io.EOFException)1 File (java.io.File)1 InputStream (java.io.InputStream)1 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 ServletException (javax.servlet.ServletException)1 PApplicationExceptionType (net.morimekta.providence.PApplicationExceptionType)1 PMessage (net.morimekta.providence.PMessage)1