use of net.morimekta.providence.mio.IOMessageReader 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);
}
}
use of net.morimekta.providence.mio.IOMessageReader 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)));
}
use of net.morimekta.providence.mio.IOMessageReader in project providence by morimekta.
the class GeneratorWatcherTest method testRandom_withReader.
@Test
public void testRandom_withReader() {
ByteArrayInputStream bais = new ByteArrayInputStream(("{\n" + " name = \"villa\"\n" + " id = 123\n" + " label = \"Sjampanjebrus\"\n" + "}\n").getBytes(StandardCharsets.UTF_8));
MessageReader reader = new IOMessageReader(bais, new PrettySerializer());
CompactFields compact = CompactFields.builder().setId(123).setName("villa").setLabel("Sjampanjebrus").build();
GeneratorWatcher<SimpleGeneratorBase, SimpleGeneratorContext> generator = GeneratorWatcher.create().dumpOnFailure().setMessageReader(reader);
generator.starting(Description.EMPTY);
CompactFields gen = generator.generate(CompactFields.kDescriptor);
assertThat(gen, is(equalToMessage(compact)));
assertThat(generator.allGenerated(), hasItem(compact));
generator.failed(new Throwable(), Description.EMPTY);
assertThat(console.output(), is(""));
assertThat(console.error(), is("android.CompactFields {\n" + " name = \"villa\"\n" + " id = 123\n" + " label = \"Sjampanjebrus\"\n" + "}\n"));
}
use of net.morimekta.providence.mio.IOMessageReader 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);
}
}
}
Aggregations