use of org.javatuples.Quartet in project igloo-parent by igloo-project.
the class TestApachePoiExcelImporter method doImport.
public List<Quartet<Date, Boolean, String, Integer>> doImport(InputStream stream, String filename) throws TableImportException {
final List<Quartet<Date, Boolean, String, Integer>> results = Lists.newArrayList();
SCANNER.scan(stream, filename, SheetSelection.ALL, new IExcelImportFileVisitor<Workbook, Sheet, Row, Cell, CellReference>() {
@Override
public void visitSheet(ITableImportNavigator<Sheet, Row, Cell, CellReference> navigator, Workbook workbook, Sheet sheet) throws TableImportException {
ITableImportEventHandler eventHandler = new LoggerTableImportEventHandler(TableImportNonFatalErrorHandling.THROW_IMMEDIATELY, LOGGER);
Columns.TableContext sheetContext = COLUMNS.map(sheet, navigator, eventHandler);
assertTrue(sheetContext.column(COLUMNS.dateColumn).exists());
assertTrue(sheetContext.column(COLUMNS.integerColumn).exists());
assertTrue(sheetContext.column(COLUMNS.booleanColumn).exists());
assertFalse(sheetContext.column(COLUMNS.missingColumn).exists());
for (Columns.RowContext rowContext : Iterables.skip(sheetContext, 1)) {
Quartet<Date, Boolean, String, Integer> result = Quartet.with(rowContext.cell(COLUMNS.dateColumn).get(), rowContext.cell(COLUMNS.booleanColumn).get(), rowContext.cell(COLUMNS.stringColumn).get(), rowContext.cell(COLUMNS.integerColumn).get());
results.add(result);
}
}
});
return results;
}
use of org.javatuples.Quartet in project GraphScope by alibaba.
the class MaxGraphHttpGremlinEndpointHandler method channelRead.
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
if (msg instanceof FullHttpRequest) {
final FullHttpRequest req = (FullHttpRequest) msg;
if ("/favicon.ico".equals(req.uri())) {
sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico");
ReferenceCountUtil.release(msg);
return;
}
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
if (req.method() != GET && req.method() != POST && req.method() != HEAD) {
sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString());
ReferenceCountUtil.release(msg);
return;
}
final Quartet<String, Map<String, Object>, String, Map<String, String>> requestArguments;
try {
requestArguments = getRequestArguments(req);
} catch (IllegalArgumentException iae) {
sendError(ctx, BAD_REQUEST, iae.getMessage());
ReferenceCountUtil.release(msg);
return;
}
final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json");
final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString);
if (null == serializer) {
sendError(ctx, BAD_REQUEST, String.format("no serializer for requested Accept header: %s", acceptString));
ReferenceCountUtil.release(msg);
return;
}
final String origin = req.headers().get(ORIGIN);
final boolean keepAlive = HttpUtil.isKeepAlive(req);
// not using the req any where below here - assume it is safe to release at this point.
ReferenceCountUtil.release(msg);
try {
logger.debug("Processing request containing script [{}] and bindings of [{}] on {}", requestArguments.getValue0(), requestArguments.getValue1(), Thread.currentThread().getName());
if (settings.authentication.enableAuditLog) {
String address = ctx.channel().remoteAddress().toString();
if (address.startsWith("/") && address.length() > 1)
address = address.substring(1);
auditLogger.info("User with address {} requested: {}", address, requestArguments.getValue0());
}
final ChannelPromise promise = ctx.channel().newPromise();
final AtomicReference<Object> resultHolder = new AtomicReference<>();
promise.addListener(future -> {
// processing of the exception
if (future.isSuccess()) {
logger.debug("Preparing HTTP response for request with script [{}] and" + " bindings of [{}] with result of [{}] on [{}]", requestArguments.getValue0(), requestArguments.getValue1(), resultHolder.get(), Thread.currentThread().getName());
ByteBuf content = (ByteBuf) resultHolder.get();
final FullHttpResponse response = req.method() == GET ? new DefaultFullHttpResponse(HTTP_1_1, OK, content) : new DefaultFullHttpResponse(HTTP_1_1, OK);
response.headers().set(CONTENT_TYPE, serializer.getValue0());
response.headers().set(CONTENT_LENGTH, content.readableBytes());
// handle cors business
if (origin != null)
response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
if (!keepAlive) {
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.writeAndFlush(response);
}
}
});
final Timer.Context timerContext = evalOpTimer.time();
final Bindings bindings;
try {
bindings = createBindings(requestArguments.getValue1(), requestArguments.getValue3());
} catch (IllegalStateException iae) {
sendError(ctx, BAD_REQUEST, iae.getMessage());
ReferenceCountUtil.release(msg);
return;
}
// provide a transform function to serialize to message - this will force
// serialization to occur
// in the same thread as the eval. after the CompletableFuture is returned from the
// eval the result
// is ready to be written as a ByteBuf directly to the response. nothing should be
// blocking here.
String script = requestArguments.getValue0();
final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, requestArguments.getValue2(), bindings, FunctionUtils.wrapFunction(o -> {
// stopping the timer here is roughly equivalent to
// where the timer would have been stopped for
// this metric in other contexts. we just want to
// measure eval time not serialization time.
timerContext.stop();
logger.debug("Transforming result of request with script" + " [{}] and bindings of [{}] with result" + " of [{}] on [{}]", requestArguments.getValue0(), requestArguments.getValue1(), o, Thread.currentThread().getName());
List<Object> resultList = opProcessor.processHttpGraphTraversal(script, o, settings.evaluationTimeout, req);
final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID()).code(ResponseStatusCode.SUCCESS).result(resultList).create();
// http server is sessionless and must handle commit on
// transactions. the commit occurs
// before serialization to be consistent with how things
// work for websocket based
// communication. this means that failed serialization
// does not mean that you won't get
// a commit to the database
attemptCommit(requestArguments.getValue3(), graphManager, settings.strictTransactionManagement);
try {
return Unpooled.wrappedBuffer(serializer.getValue1().serializeResponseAsString(responseMessage).getBytes(UTF8));
} catch (Exception ex) {
logger.warn(String.format("Error during serialization for %s", responseMessage), ex);
throw ex;
}
}));
evalFuture.exceptionally(t -> {
if (t.getMessage() != null)
sendError(ctx, INTERNAL_SERVER_ERROR, t.getMessage(), Optional.of(t));
else
sendError(ctx, INTERNAL_SERVER_ERROR, String.format("Error encountered evaluating script: %s", requestArguments.getValue0()), Optional.of(t));
promise.setFailure(t);
return null;
});
evalFuture.thenAcceptAsync(r -> {
// now that the eval/serialization is done in the same thread - complete
// the promise so we can
// write back the HTTP response on the same thread as the original
// request
resultHolder.set(r);
promise.setSuccess();
}, gremlinExecutor.getExecutorService());
} catch (Exception ex) {
// tossed to exceptionCaught which delegates to sendError method
final Throwable t = ExceptionUtils.getRootCause(ex);
throw new RuntimeException(null == t ? ex : t);
}
}
}
use of org.javatuples.Quartet in project GraphScope by alibaba.
the class MaxGraphHttpGremlinEndpointHandler method getRequestArguments.
private static Quartet<String, Map<String, Object>, String, Map<String, String>> getRequestArguments(final FullHttpRequest request) {
if (request.method() == GET || request.method() == HEAD) {
final QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
final List<String> gremlinParms = decoder.parameters().get(Tokens.ARGS_GREMLIN);
if (null == gremlinParms || gremlinParms.size() == 0)
throw new IllegalArgumentException("no gremlin script supplied");
final String script = gremlinParms.get(0);
if (script.isEmpty())
throw new IllegalArgumentException("no gremlin script supplied");
// query string parameters - take the first instance of a key only - ignore the rest
final Map<String, Object> bindings = new HashMap<>();
decoder.parameters().entrySet().stream().filter(kv -> kv.getKey().startsWith(ARGS_BINDINGS_DOT)).forEach(kv -> bindings.put(kv.getKey().substring(ARGS_BINDINGS_DOT.length()), kv.getValue().get(0)));
final Map<String, String> aliases = new HashMap<>();
decoder.parameters().entrySet().stream().filter(kv -> kv.getKey().startsWith(ARGS_ALIASES_DOT)).forEach(kv -> aliases.put(kv.getKey().substring(ARGS_ALIASES_DOT.length()), kv.getValue().get(0)));
final List<String> languageParms = decoder.parameters().get(Tokens.ARGS_LANGUAGE);
final String language = (null == languageParms || languageParms.size() == 0) ? null : languageParms.get(0);
return Quartet.with(script, bindings, language, aliases);
} else {
final JsonNode body;
try {
body = mapper.readTree(request.content().toString(CharsetUtil.UTF_8));
} catch (IOException ioe) {
throw new IllegalArgumentException("body could not be parsed", ioe);
}
final JsonNode scriptNode = body.get(Tokens.ARGS_GREMLIN);
if (null == scriptNode)
throw new IllegalArgumentException("no gremlin script supplied");
final JsonNode bindingsNode = body.get(Tokens.ARGS_BINDINGS);
if (bindingsNode != null && !bindingsNode.isObject())
throw new IllegalArgumentException("bindings must be a Map");
final Map<String, Object> bindings = new HashMap<>();
if (bindingsNode != null)
bindingsNode.fields().forEachRemaining(kv -> bindings.put(kv.getKey(), kv.getValue()));
final JsonNode aliasesNode = body.get(Tokens.ARGS_ALIASES);
if (aliasesNode != null && !aliasesNode.isObject())
throw new IllegalArgumentException("aliases must be a Map");
final Map<String, String> aliases = new HashMap<>();
if (aliasesNode != null)
aliasesNode.fields().forEachRemaining(kv -> aliases.put(kv.getKey(), kv.getValue().asText()));
final JsonNode languageNode = body.get(Tokens.ARGS_LANGUAGE);
final String language = null == languageNode ? null : languageNode.asText();
return Quartet.with(scriptNode.asText(), bindings, language, aliases);
}
}
use of org.javatuples.Quartet in project GradleCenturion by Ultraviolet-Ninja.
the class Hexamaze method solve.
@NotNull
public static Quartet<@NotNull Grid, @Nullable String, @Nullable Integer, @Nullable List<Coordinates>> solve(@NotNull List<HexNode> nodeList) throws IllegalArgumentException, IllegalStateException {
Maze maze = new Maze();
Grid original = new Grid(new HexagonalPlane(nodeList));
Grid found = MazeSearch.search(maze, original).orElseThrow(() -> {
throw new IllegalArgumentException("Could not find maze from given shapes");
});
int colorValue = copyPegLocation(original, found);
Optional<Pair<String, List<Coordinates>>> exitInfoOptional = ExitChecker.findPossibleExits(found);
if (exitInfoOptional.isEmpty())
return new Quartet<>(found, null, null, null);
Pair<String, List<Coordinates>> exitInfo = exitInfoOptional.get();
return new Quartet<>(found, exitInfo.getValue0(), colorValue, MazeRunner.runMaze(found, exitInfo.getValue1()));
}
use of org.javatuples.Quartet in project igloo-parent by igloo-project.
the class ApachePoiExcelImportTest method testSuccess.
@Test
public void testSuccess() throws TableImportException {
InputStream stream = ApachePoiExcelImportTest.class.getResourceAsStream("/wellFormattedFile.xlsx");
TestApachePoiExcelImporter importer = new TestApachePoiExcelImporter();
List<Quartet<Date, Boolean, String, Integer>> results = importer.doImport(stream, "wellFormattedFile.xlsx");
Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.FEBRUARY, 14);
Date firstDate = DateUtils.truncate(calendar.getTime(), Calendar.DATE);
calendar.set(2014, Calendar.FEBRUARY, 15);
Date secondDate = DateUtils.truncate(calendar.getTime(), Calendar.DATE);
List<Quartet<Date, Boolean, String, Integer>> expectedResults = ImmutableList.of(newResult(firstDate, true, "String 3", 123), newResult(null, false, "string 4", 123), newResult(null, false, null, 9723), newResult(secondDate, false, "4244.12", null));
assertEquals(expectedResults.size(), results.size());
int index = 0;
for (Quartet<Date, Boolean, String, Integer> expectedResult : expectedResults) {
Quartet<Date, Boolean, String, Integer> actualResult = results.get(index);
assertValueEquals(index, 0, "date", expectedResult, actualResult);
assertValueEquals(index, 1, "boolean", expectedResult, actualResult);
assertValueEquals(index, 2, "string", expectedResult, actualResult);
assertValueEquals(index, 3, "integer", expectedResult, actualResult);
++index;
}
}
Aggregations