Search in sources :

Example 1 with PService

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

use of net.morimekta.providence.descriptor.PService in project providence by morimekta.

the class ConvertOptions method getServiceDefinition.

public PService getServiceDefinition() throws ParseException, IOException {
    ProgramRegistry registry = getProgramRegistry();
    PService srv = registry.getService(type, null);
    if (srv == null) {
        String programName = type.substring(0, type.lastIndexOf("."));
        programName = programName.replaceAll("[-.]", "_");
        Map<String, File> includeMap = FormatUtils.getIncludeMap(getRc(), includes);
        String filePath = includeMap.get(programName).toString();
        CProgram document = registry.registryForPath(filePath).getProgram();
        Set<String> services = new TreeSet<>(document.getServices().stream().map(s -> s.getQualifiedName()).collect(Collectors.toSet()));
        throw new ArgumentException("Unknown service %s in %s.\n" + "Found %s", type, ReflectionUtils.programNameFromPath(type), services.size() == 0 ? "none" : Strings.join(", ", services));
    }
    return srv;
}
Also used : ProgramRegistry(net.morimekta.providence.reflect.util.ProgramRegistry) TreeSet(java.util.TreeSet) CProgram(net.morimekta.providence.reflect.contained.CProgram) ArgumentException(net.morimekta.console.args.ArgumentException) File(java.io.File) PService(net.morimekta.providence.descriptor.PService)

Example 3 with PService

use of net.morimekta.providence.descriptor.PService in project providence by morimekta.

the class RPC method run.

@SuppressWarnings("unchecked")
void run(String... args) {
    try {
        ArgumentParser cli = options.getArgumentParser("pvdrpc", "Providence RPC Tool");
        try {
            cli.parse(args);
            if (options.showHelp()) {
                System.out.println("Providence RPC Tool - " + getVersionString());
                System.out.println("Usage: " + cli.getSingleLineUsage());
                System.out.println();
                System.out.println("Example code to run:");
                System.out.println("$ cat call.json | pvdrpc -I thrift/ -s cal.Calculator http://localhost:8080/service");
                System.out.println("$ pvdrpc -i binary,file:my.data -f json_protocol -I thrift/ -s cal.Calculator http://localhost:8080/service");
                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;
            } else if (options.showVersion()) {
                System.out.println("Providence RPC Tool - " + getVersionString());
                return;
            }
            cli.validate();
            MessageReader in = options.getInput();
            MessageWriter out = options.getOutput();
            PService service = options.getDefinition();
            PServiceCallHandler handler = options.getHandler();
            PServiceCall call = in.read(service);
            in.close();
            PServiceCall resp = handler.handleCall(call, service);
            out.write(resp);
            out.separator();
            out.close();
            if (options.out.base64mime && options.out.file == null) {
                System.out.println();
            }
            return;
        } catch (ConnectException e) {
            System.out.flush();
            System.err.format("Unable to connect to %s: %s%n", options.endpoint, e.getMessage());
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        } catch (HttpResponseException e) {
            System.out.flush();
            System.err.println("Received " + e.getStatusCode() + " " + e.getStatusMessage());
            System.err.println(" - from: " + options.endpoint);
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        } catch (ArgumentException e) {
            System.out.flush();
            System.err.println(e.getMessage());
            System.err.println("Usage: " + cli.getSingleLineUsage());
            System.err.println();
            System.err.println("Run $ pvdrpc --help # for available options.");
        } catch (SerializerException e) {
            System.out.flush();
            System.err.println("Serializer error: " + e.asString());
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        } catch (UncheckedIOException | IOException e) {
            System.out.flush();
            System.err.println("I/O error: " + e.getMessage());
            if (options.verbose()) {
                System.out.flush();
                e.printStackTrace();
            }
        } catch (IllegalArgumentException e) {
            System.out.flush();
            System.err.println("Internal Error: " + e.getMessage());
            if (options.verbose()) {
                System.err.println();
                e.printStackTrace();
            }
        }
    } catch (RuntimeException | IOException e) {
        System.out.flush();
        System.err.println("Unchecked exception: " + e.getMessage());
        if (options.verbose()) {
            System.out.flush();
            e.printStackTrace();
        }
    }
    System.err.flush();
    exit(1);
}
Also used : MessageReader(net.morimekta.providence.mio.MessageReader) HttpResponseException(com.google.api.client.http.HttpResponseException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ArgumentParser(net.morimekta.console.args.ArgumentParser) SerializerException(net.morimekta.providence.serializer.SerializerException) Format(net.morimekta.providence.tools.common.formats.Format) PServiceCallHandler(net.morimekta.providence.PServiceCallHandler) PServiceCall(net.morimekta.providence.PServiceCall) MessageWriter(net.morimekta.providence.mio.MessageWriter) ArgumentException(net.morimekta.console.args.ArgumentException) PService(net.morimekta.providence.descriptor.PService) ConnectException(java.net.ConnectException)

Example 4 with PService

use of net.morimekta.providence.descriptor.PService in project providence by morimekta.

the class RPCOptions method getDefinition.

public PService getDefinition() throws ParseException, IOException {
    Map<String, File> includeMap = FormatUtils.getIncludeMap(getRc(), includes);
    if (service.isEmpty()) {
        throw new ArgumentException("Missing service type name");
    }
    Set<File> rootSet = new TreeSet<File>();
    for (File file : includeMap.values()) {
        rootSet.add(file.getParentFile());
    }
    String programName = service.substring(0, service.lastIndexOf("."));
    TypeLoader loader = new TypeLoader(rootSet, new ThriftProgramParser());
    try {
        if (!includeMap.containsKey(programName)) {
            throw new ArgumentException("No program " + programName + " found in include path.\n" + "Found: " + Strings.join(", ", new TreeSet<Object>(includeMap.keySet())));
        }
        loader.load(includeMap.get(programName));
    } catch (IOException e) {
        throw new ArgumentException(e.getLocalizedMessage());
    }
    String filePath = includeMap.get(programName).getCanonicalFile().getAbsolutePath();
    PService srv = loader.getProgramRegistry().getService(service, null);
    if (srv == null) {
        CProgram document = loader.getProgramRegistry().registryForPath(filePath).getProgram();
        Set<String> services = new TreeSet<>(document.getServices().stream().map(s -> s.getQualifiedName()).collect(Collectors.toSet()));
        throw new ArgumentException("Unknown service %s in %s.\n" + "Found %s", service, programName, services.size() == 0 ? "none" : Strings.join(", ", services));
    }
    return srv;
}
Also used : TypeLoader(net.morimekta.providence.reflect.TypeLoader) IOException(java.io.IOException) TreeSet(java.util.TreeSet) CProgram(net.morimekta.providence.reflect.contained.CProgram) ArgumentException(net.morimekta.console.args.ArgumentException) File(java.io.File) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) PService(net.morimekta.providence.descriptor.PService)

Example 5 with PService

use of net.morimekta.providence.descriptor.PService in project providence by morimekta.

the class JsonSerializerTest method testDeserialize_simpleFails.

@Test
public void testDeserialize_simpleFails() {
    PMessageDescriptor<?, ?> opt = OptionalFields.kDescriptor;
    PMessageDescriptor<?, ?> cnt = Containers.kDescriptor;
    PService calc = Calculator.kDescriptor;
    assertFail(opt, compact, "", "Empty json body");
    assertFail(opt, compact, "[false, 123, 54321]", "OptionalFields is not compatible for compact struct notation.");
    assertFail(cnt, compact, "{\"optionalFields\":[false,123,54321]}", "OptionalFields is not compatible for compact struct notation.");
    assertFail(opt, compact, "null", "Null value as body.");
    assertFail(opt, compact, "\"not a message\"", "expected message start, found: '\"not a message\"'");
    assertFail(opt, compact, "{\"booleanValue\":\"str\"}", "No boolean value for token: '\"str\"'");
    assertFail(opt, compact, "{\"booleanValue\":{}}", "No boolean value for token: '{'");
    assertFail(opt, compact, "{\"byteValue\":\"str\"}", "Not a valid byte value: '\"str\"'");
    assertFail(opt, compact, "{\"shortValue\":\"str\"}", "Not a valid short value: '\"str\"'");
    assertFail(opt, compact, "{\"integerValue\":\"str\"}", "Not a valid int value: '\"str\"'");
    assertFail(opt, compact, "{\"longValue\":\"str\"}", "Not a valid long value: '\"str\"'");
    assertFail(opt, compact, "{\"doubleValue\":\"str\"}", "Not a valid double value: '\"str\"'");
    assertFail(opt, compact, "{\"stringValue\":55}", "Not a valid string value: '55'");
    assertFail(opt, compact, "{\"binaryValue\":55}", "Not a valid binary value: 55");
    assertFail(opt, compact, "{\"binaryValue\":\"g./ar,bl'e\"}", "Unable to parse Base64 data: \"g./ar,bl'e\"");
    assertFail(calc, lenient, "{}", "Expected service call start ('['): but found '{'");
    assertFail(calc, lenient, "[123]", "Expected method name (string literal): but found '123'");
    assertFail(calc, lenient, "[\"iamalive\", 77]", "Service call type 77 is not valid");
    assertFail(calc, lenient, "[\"iamalive\", 1, -55]", "Expected entry sep (','): but found ']'");
    assertFail(calc, lenient, "[\"iamalive\", 2, -55, {\"0\": 6}]", "No response type for calculator.Calculator.iamalive()");
    assertFail(calc, lenient, "[\"iamalive\", \"boo\", -55, {\"0\": 6}]", "Service call type \"boo\" is not valid");
    assertFail(calc, lenient, "[\"iamalive\", false, -55, {\"0\": 6}]", "Invalid service call type token false");
    assertFail(calc, compact, "[\"calculate\", \"reply\", 55, {}]", "No union field set in calculator.Calculator.calculate.response");
    assertFail(calc, compact, "[\"ping\", \"reply\", 55, {\"0\": 3}]", "Not a void token value: '3'");
    assertFail(opt, compact, "{\"binaryValue\",\"AAss\"}", "Expected field KV sep (':'): but found ','");
    assertFail(opt, compact, "{\"enumValue\":false}", "false is not a enum value type");
    assertFail(Containers.kDescriptor, compact, "{\"enumMap\":[]}", "Invalid start of map '['");
    assertFail(Containers.kDescriptor, compact, "{\"enumSet\":{}}", "Invalid start of set '{'");
    assertFail(Containers.kDescriptor, compact, "{\"enumList\":{}}", "Invalid start of list '{'");
    assertFail(Containers.kDescriptor, compact, "{\"booleanMap\":{\"fleece\":false}}", "Invalid boolean value: \"fleece\"");
    assertFail(Containers.kDescriptor, compact, "{\"byteMap\":{\"5boo\":55}}", "Unable to parse numeric value 5boo");
    assertFail(Containers.kDescriptor, compact, "{\"shortMap\":{\"5boo\":55}}", "Unable to parse numeric value 5boo");
    assertFail(Containers.kDescriptor, compact, "{\"integerMap\":{\"5boo\":55}}", "Unable to parse numeric value 5boo");
    assertFail(Containers.kDescriptor, compact, "{\"longMap\":{\"5boo\":4}}", "Unable to parse numeric value 5boo");
    assertFail(Containers.kDescriptor, compact, "{\"doubleMap\":{\"5.5boo\":4.4}}", "Unable to parse double from key \"5.5boo\"");
    assertFail(Containers.kDescriptor, compact, "{\"doubleMap\":{\"5.5 boo\":4.4}}", "Garbage after double: \"5.5 boo\"");
    assertFail(Containers.kDescriptor, compact, "{\"doubleMap\":{\"boo 2\":4.4}}", "Unable to parse double from key \"boo 2\"");
    assertFail(Containers.kDescriptor, compact, "{\"binaryMap\":{\"\\_(^.^)_/\":\"\"}}", "Unable to parse Base64 data");
    assertFail(Containers.kDescriptor, compact, "{\"enumMap\":{\"1\":\"BOO\"}}", "\"BOO\" is not a known enum value for providence.Value");
    assertFail(Containers.kDescriptor, compact, "{\"enumMap\":{\"BOO\":\"1\"}}", "\"BOO\" is not a known enum value for providence.Value");
    assertFail(Containers.kDescriptor, compact, "{\"messageKeyMap\":{\"{\\\"1\\\":55}\":\"str\"}}", "Error parsing message key: Not a valid string value: '55'");
}
Also used : PService(net.morimekta.providence.descriptor.PService) Test(org.junit.Test)

Aggregations

PService (net.morimekta.providence.descriptor.PService)7 IOException (java.io.IOException)4 ArgumentException (net.morimekta.console.args.ArgumentException)4 PServiceCall (net.morimekta.providence.PServiceCall)4 File (java.io.File)3 CProgram (net.morimekta.providence.reflect.contained.CProgram)3 UncheckedIOException (java.io.UncheckedIOException)2 TreeSet (java.util.TreeSet)2 Nullable (javax.annotation.Nullable)2 ArgumentParser (net.morimekta.console.args.ArgumentParser)2 PApplicationException (net.morimekta.providence.PApplicationException)2 PProcessor (net.morimekta.providence.PProcessor)2 PServiceCallHandler (net.morimekta.providence.PServiceCallHandler)2 MessageReader (net.morimekta.providence.mio.MessageReader)2 MessageWriter (net.morimekta.providence.mio.MessageWriter)2 ProgramRegistry (net.morimekta.providence.reflect.util.ProgramRegistry)2 SerializerException (net.morimekta.providence.serializer.SerializerException)2 Format (net.morimekta.providence.tools.common.formats.Format)2 Test (org.junit.Test)2 HttpResponseException (com.google.api.client.http.HttpResponseException)1