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.
}
}
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;
}
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);
}
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;
}
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'");
}
Aggregations