Search in sources :

Example 16 with PServiceCall

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

the class TProtocolSerializer method deserialize.

@Nonnull
@Override
@SuppressWarnings("unchecked")
public <Message extends PMessage<Message, Field>, Field extends PField> PServiceCall<Message, Field> deserialize(@Nonnull InputStream input, @Nonnull PService service) throws SerializerException {
    PServiceCallType type = null;
    TMessage tm = null;
    try {
        TTransport transport = new TIOStreamTransport(input);
        TProtocol protocol = protocolFactory.getProtocol(transport);
        tm = protocol.readMessageBegin();
        type = PServiceCallType.findById(tm.type);
        if (type == null) {
            throw new SerializerException("Unknown call type for id " + tm.type).setExceptionType(PApplicationExceptionType.INVALID_MESSAGE_TYPE);
        } else if (type == PServiceCallType.EXCEPTION) {
            PApplicationException exception = readMessage(protocol, PApplicationException.kDescriptor);
            return new PServiceCall(tm.name, type, tm.seqid, exception);
        }
        PServiceMethod method = service.getMethod(tm.name);
        if (method == null) {
            throw new SerializerException("No such method " + tm.name + " on " + service.getQualifiedName()).setExceptionType(PApplicationExceptionType.UNKNOWN_METHOD);
        }
        @SuppressWarnings("unchecked") PMessageDescriptor<Message, Field> descriptor = isRequestCallType(type) ? method.getRequestType() : method.getResponseType();
        Message message = readMessage(protocol, descriptor);
        protocol.readMessageEnd();
        return new PServiceCall<>(tm.name, type, tm.seqid, message);
    } catch (TTransportException e) {
        throw new SerializerException(e, e.getMessage()).setExceptionType(PApplicationExceptionType.findById(e.getType())).setCallType(type).setSequenceNo(tm != null ? tm.seqid : 0).setMethodName(tm != null ? tm.name : null);
    } catch (TException e) {
        throw new SerializerException(e, e.getMessage()).setExceptionType(PApplicationExceptionType.PROTOCOL_ERROR).setCallType(type).setSequenceNo(tm != null ? tm.seqid : 0).setMethodName(tm != null ? tm.name : null);
    } catch (SerializerException e) {
        e.setMethodName(tm.name).setSequenceNo(tm.seqid).setCallType(type);
        throw e;
    }
}
Also used : TException(org.apache.thrift.TException) PMessage(net.morimekta.providence.PMessage) TMessage(org.apache.thrift.protocol.TMessage) PServiceCallType(net.morimekta.providence.PServiceCallType) TTransportException(org.apache.thrift.transport.TTransportException) TIOStreamTransport(org.apache.thrift.transport.TIOStreamTransport) SerializerException(net.morimekta.providence.serializer.SerializerException) TField(org.apache.thrift.protocol.TField) PField(net.morimekta.providence.descriptor.PField) TMessage(org.apache.thrift.protocol.TMessage) TProtocol(org.apache.thrift.protocol.TProtocol) PApplicationException(net.morimekta.providence.PApplicationException) PServiceCall(net.morimekta.providence.PServiceCall) TTransport(org.apache.thrift.transport.TTransport) PServiceMethod(net.morimekta.providence.descriptor.PServiceMethod) Nonnull(javax.annotation.Nonnull)

Example 17 with PServiceCall

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

the class TTupleProtocolSerializer method deserialize.

@Nonnull
@Override
@SuppressWarnings("unchecked")
public <Message extends PMessage<Message, Field>, Field extends PField> PServiceCall<Message, Field> deserialize(@Nonnull InputStream input, @Nonnull PService service) throws SerializerException {
    TMessage tm = null;
    PServiceCallType type = null;
    try {
        TTransport transport = new TIOStreamTransport(input);
        TTupleProtocol protocol = (TTupleProtocol) protocolFactory.getProtocol(transport);
        tm = protocol.readMessageBegin();
        type = PServiceCallType.findById(tm.type);
        if (type == null) {
            throw new SerializerException("Unknown call type for id " + tm.type);
        } else if (type == PServiceCallType.EXCEPTION) {
            PApplicationException exception = readMessage(protocol, PApplicationException.kDescriptor);
            return new PServiceCall(tm.name, type, tm.seqid, exception);
        }
        PServiceMethod method = service.getMethod(tm.name);
        if (method == null) {
            throw new SerializerException("No such method " + tm.name + " on " + service.getQualifiedName());
        }
        PMessageDescriptor<Message, Field> descriptor = isRequestCallType(type) ? method.getRequestType() : method.getResponseType();
        Message message = readMessage(protocol, descriptor);
        protocol.readMessageEnd();
        return new PServiceCall<>(tm.name, type, tm.seqid, message);
    } catch (TTransportException e) {
        throw new SerializerException(e, "Unable to serialize into transport protocol").setExceptionType(PApplicationExceptionType.findById(e.getType())).setCallType(type).setMethodName(tm != null ? tm.name : "").setSequenceNo(tm != null ? tm.seqid : 0);
    } catch (TException e) {
        throw new SerializerException(e, "Transport exception in protocol").setExceptionType(PApplicationExceptionType.PROTOCOL_ERROR).setCallType(type).setMethodName(tm != null ? tm.name : "").setSequenceNo(tm != null ? tm.seqid : 0);
    }
}
Also used : TException(org.apache.thrift.TException) PMessage(net.morimekta.providence.PMessage) TMessage(org.apache.thrift.protocol.TMessage) PServiceCallType(net.morimekta.providence.PServiceCallType) TTransportException(org.apache.thrift.transport.TTransportException) TIOStreamTransport(org.apache.thrift.transport.TIOStreamTransport) SerializerException(net.morimekta.providence.serializer.SerializerException) TTupleProtocol(org.apache.thrift.protocol.TTupleProtocol) PField(net.morimekta.providence.descriptor.PField) TMessage(org.apache.thrift.protocol.TMessage) PApplicationException(net.morimekta.providence.PApplicationException) PServiceCall(net.morimekta.providence.PServiceCall) TTransport(org.apache.thrift.transport.TTransport) PServiceMethod(net.morimekta.providence.descriptor.PServiceMethod) Nonnull(javax.annotation.Nonnull)

Example 18 with PServiceCall

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

Example 19 with PServiceCall

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

the class Convert method run.

@SuppressWarnings("unchecked")
void run(String... args) {
    try {
        ArgumentParser cli = options.getArgumentParser("pvd", "Providence Converter");
        try {
            cli.parse(args);
            if (options.showHelp()) {
                System.out.println(cli.getProgramDescription());
                System.out.println("Usage: " + cli.getSingleLineUsage());
                System.out.println();
                System.out.println("Example code to run:");
                System.out.println("$ cat call.json | pvd -I thrift/ -S cal.Calculator");
                System.out.println("$ pvd -i binary,file:my.data -o json_protocol -I thrift/ cal.Operation");
                System.out.println();
                System.out.println("Note that when handling service calls, only 1 call can be converted.");
                System.out.println();
                cli.printUsage(System.out);
                System.out.println();
                System.out.println("Available formats are:");
                for (Format format : Format.values()) {
                    System.out.println(String.format(" - %-20s : %s", format.name(), format.desc));
                }
                return;
            }
            if (options.showVersion()) {
                System.out.println(cli.getProgramDescription());
                return;
            }
            if (options.listTypes) {
                ProgramRegistry registry = options.getProgramRegistry();
                for (ProgramTypeRegistry pr : registry.getLoadedRegistries()) {
                    CProgram program = pr.getProgram();
                    System.out.println(program.getProgramFilePath() + ":");
                    for (PDeclaredDescriptor dd : program.getDeclaredTypes()) {
                        if (dd instanceof CStructDescriptor) {
                            System.out.println("  struct    " + dd.getQualifiedName());
                        } else if (dd instanceof CUnionDescriptor) {
                            System.out.println("  union     " + dd.getQualifiedName());
                        } else if (dd instanceof CExceptionDescriptor) {
                            System.out.println("  exception " + dd.getQualifiedName());
                        }
                    }
                    for (PService s : program.getServices()) {
                        System.out.println("  service   " + s.getQualifiedName());
                    }
                }
                return;
            }
            cli.validate();
            if (options.getDefinition() == null) {
                MessageReader in = options.getServiceInput();
                MessageWriter out = options.getServiceOutput();
                PService service = options.getServiceDefinition();
                PServiceCall call = in.read(service);
                in.close();
                out.write(call);
                out.separator();
                out.close();
                // TODO: Validate we don't have garbage data after call.
                if (options.out.base64mime && options.out.file == null) {
                    System.out.println();
                }
            } else {
                AtomicInteger num = new AtomicInteger(0);
                int size = options.getInput().peek(m -> num.incrementAndGet()).collect(options.getOutput());
                if (num.get() == 0 || size == 0) {
                    throw new IOException("No data");
                }
                if (options.out.base64mime && options.out.file == null) {
                    System.out.println();
                }
            }
            return;
        } catch (ArgumentException e) {
            System.err.println(e.getMessage());
            System.out.println("Usage: " + cli.getSingleLineUsage());
            System.err.println();
            System.err.println("Run $ pvd --help # for available options.");
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        } catch (SerializerException e) {
            System.out.flush();
            System.err.println();
            System.err.println(e.asString());
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        } catch (UncheckedIOException | IOException e) {
            System.out.flush();
            System.err.println();
            System.err.println("I/O error: " + e.getMessage());
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        System.out.flush();
        System.err.println();
        System.err.println("Unchecked exception: " + e.getMessage());
        if (options.verbose()) {
            System.err.println();
            e.printStackTrace();
        }
    }
    exit(1);
}
Also used : ArgumentParser(net.morimekta.console.args.ArgumentParser) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) CProgram(net.morimekta.providence.reflect.contained.CProgram) IOException(java.io.IOException) PDeclaredDescriptor(net.morimekta.providence.descriptor.PDeclaredDescriptor) MessageWriter(net.morimekta.providence.mio.MessageWriter) ProgramRegistry(net.morimekta.providence.reflect.util.ProgramRegistry) ArgumentException(net.morimekta.console.args.ArgumentException) CUnionDescriptor(net.morimekta.providence.reflect.contained.CUnionDescriptor) UncheckedIOException(java.io.UncheckedIOException) PService(net.morimekta.providence.descriptor.PService) STTY(net.morimekta.console.util.STTY) PServiceCall(net.morimekta.providence.PServiceCall) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CExceptionDescriptor(net.morimekta.providence.reflect.contained.CExceptionDescriptor) CStructDescriptor(net.morimekta.providence.reflect.contained.CStructDescriptor) MessageReader(net.morimekta.providence.mio.MessageReader) Format(net.morimekta.providence.tools.common.formats.Format) SerializerException(net.morimekta.providence.serializer.SerializerException) ProgramRegistry(net.morimekta.providence.reflect.util.ProgramRegistry) CUnionDescriptor(net.morimekta.providence.reflect.contained.CUnionDescriptor) MessageReader(net.morimekta.providence.mio.MessageReader) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ArgumentParser(net.morimekta.console.args.ArgumentParser) SerializerException(net.morimekta.providence.serializer.SerializerException) IOException(java.io.IOException) ArgumentException(net.morimekta.console.args.ArgumentException) UncheckedIOException(java.io.UncheckedIOException) SerializerException(net.morimekta.providence.serializer.SerializerException) Format(net.morimekta.providence.tools.common.formats.Format) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CProgram(net.morimekta.providence.reflect.contained.CProgram) PServiceCall(net.morimekta.providence.PServiceCall) PDeclaredDescriptor(net.morimekta.providence.descriptor.PDeclaredDescriptor) MessageWriter(net.morimekta.providence.mio.MessageWriter) CStructDescriptor(net.morimekta.providence.reflect.contained.CStructDescriptor) ArgumentException(net.morimekta.console.args.ArgumentException) CExceptionDescriptor(net.morimekta.providence.reflect.contained.CExceptionDescriptor) PService(net.morimekta.providence.descriptor.PService)

Aggregations

PServiceCall (net.morimekta.providence.PServiceCall)19 IOException (java.io.IOException)13 PApplicationException (net.morimekta.providence.PApplicationException)12 PServiceCallType (net.morimekta.providence.PServiceCallType)7 PServiceMethod (net.morimekta.providence.descriptor.PServiceMethod)7 Nonnull (javax.annotation.Nonnull)6 PMessage (net.morimekta.providence.PMessage)6 SerializerException (net.morimekta.providence.serializer.SerializerException)6 UncheckedIOException (java.io.UncheckedIOException)5 PField (net.morimekta.providence.descriptor.PField)5 Test (org.junit.Test)5 PProcessor (net.morimekta.providence.PProcessor)4 PService (net.morimekta.providence.descriptor.PService)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 ExecutionException (java.util.concurrent.ExecutionException)2 ExecutorService (java.util.concurrent.ExecutorService)2 TimeoutException (java.util.concurrent.TimeoutException)2 Nullable (javax.annotation.Nullable)2 PServiceCallHandler (net.morimekta.providence.PServiceCallHandler)2