Java Code Examples for org.javatuples.Pair#getValue1()

The following examples show how to use org.javatuples.Pair#getValue1() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractQueryGenerator.java    From spring-data-cosmosdb with MIT License 6 votes vote down vote up
protected SqlQuerySpec generateCosmosQuery(@NonNull DocumentQuery query,
                                                                        @NonNull String queryHead) {
    final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query);
    final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query));
    final List<Pair<String, Object>> parameters = queryBody.getValue1();
    final SqlParameterList sqlParameters =
            new SqlParameterList();

    sqlParameters.addAll(
            parameters.stream()
                    .map(p -> new com.azure.data.cosmos.SqlParameter("@" + p.getValue0(),
                            toCosmosDbValue(p.getValue1())))
                    .collect(Collectors.toList())
    );

    return new SqlQuerySpec(queryString, sqlParameters);
}
 
Example 2
Source File: HasStepFolder.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
static boolean validJanusGraphOrder(OrderGlobalStep orderGlobalStep, Traversal rootTraversal, boolean isVertexOrder) {
    List<Pair<Traversal.Admin, Object>> comparators = orderGlobalStep.getComparators();
    for (Pair<Traversal.Admin, Object> comp : comparators) {
        String key;
        if (comp.getValue0() instanceof ElementValueTraversal &&
                comp.getValue1() instanceof Order) {
            key = ((ElementValueTraversal) comp.getValue0()).getPropertyKey();
        } else if (comp.getValue1() instanceof ElementValueComparator) {
            ElementValueComparator evc = (ElementValueComparator) comp.getValue1();
            if (!(evc.getValueComparator() instanceof Order)) return false;
            key = evc.getPropertyKey();
        } else {
            // do not fold comparators that include nested traversals that are not simple ElementValues
            return false;
        }
        JanusGraphTransaction tx = JanusGraphTraversalUtil.getTx(rootTraversal.asAdmin());
        PropertyKey pKey = tx.getPropertyKey(key);
        if (pKey == null
                || !(Comparable.class.isAssignableFrom(pKey.dataType()))
                || (isVertexOrder && pKey.cardinality() != Cardinality.SINGLE)) {
            return false;
        }
    }
    return true;
}
 
Example 3
Source File: ResultQueue.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Completes the next waiting future if there is one.
 */
private synchronized void tryDrainNextWaiting(final boolean force) {
    // need to peek because the number of available items needs to be >= the expected size for that future. if not
    // it needs to keep waiting
    final Pair<CompletableFuture<List<Result>>, Integer> nextWaiting = waiting.peek();
    if (nextWaiting != null && (force || (resultLinkedBlockingQueue.size() >= nextWaiting.getValue1() || readComplete.isDone()))) {
        final int items = nextWaiting.getValue1();
        final CompletableFuture<List<Result>> future = nextWaiting.getValue0();
        final List<Result> results = new ArrayList<>(items);
        resultLinkedBlockingQueue.drainTo(results, items);

        // it's important to check for error here because a future may have already been queued in "waiting" prior
        // to the first response back from the server. if that happens, any "waiting" futures should be completed
        // exceptionally otherwise it will look like success.
        if (null == error.get())
            future.complete(results);
        else
            future.completeExceptionally(error.get());

        waiting.remove(nextWaiting);
    }
}
 
Example 4
Source File: OpExecutorHandler.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Pair<RequestMessage, ThrowingConsumer<Context>> objects) throws Exception {
    final RequestMessage msg = objects.getValue0();
    final ThrowingConsumer<Context> op = objects.getValue1();
    final Context gremlinServerContext = new Context(msg, ctx,
            settings, graphManager, gremlinExecutor, scheduledExecutorService);
    try {
        op.accept(gremlinServerContext);
    } catch (OpProcessorException ope) {
        // Ops may choose to throw OpProcessorException or write the error ResponseMessage down the line
        // themselves
        logger.warn(ope.getMessage(), ope);
        gremlinServerContext.writeAndFlush(ope.getResponseMessage());
    } catch (Exception ex) {
        // It is possible that an unplanned exception might raise out of an OpProcessor execution. Build a general
        // error to send back to the client
        logger.warn(ex.getMessage(), ex);
        gremlinServerContext.writeAndFlush(ResponseMessage.build(msg)
                .code(ResponseStatusCode.SERVER_ERROR)
                .statusAttributeException(ex)
                .statusMessage(ex.getMessage()).create());
    } finally {
        ReferenceCountUtil.release(objects);
    }
}
 
Example 5
Source File: PermissionSystem.java    From LoboBrowser with MIT License 6 votes vote down vote up
public PermissionRow(final String requestHost, final Pair<Permission, Permission[]> initialRequestPermissions,
    final Optional<PermissionRow> headerRowOpt,
    final Optional<PermissionRow> fallbackRowOpt, final boolean hostCanBeUndecidable) {
  this.requestHost = requestHost;
  final List<PermissionCell> hostParentList = streamOpt(headerRowOpt.map(r -> r.hostCell)).collect(Collectors.toList());
  final Permission hostPermission = initialRequestPermissions.getValue0();
  final Permission[] kindPermissions = initialRequestPermissions.getValue1();
  hostCell = new PermissionCell(Optional.empty(), hostPermission, hostParentList, fallbackRowOpt.map(r -> r.hostCell),
      Optional.empty(), hostCanBeUndecidable);
  IntStream.range(0, requestCells.length).forEach(i -> {
    final LinkedList<PermissionCell> parentCells = makeParentCells(headerRowOpt, i);
    final Optional<PermissionCell> grandParentCellOpt = headerRowOpt.map(r -> r.hostCell);
    final Optional<PermissionCell> fallbackCellOpt = fallbackRowOpt.map(r -> r.requestCells[i]);
    final Optional<RequestKind> kindOpt = Optional.of(RequestKind.forOrdinal(i));
    requestCells[i] = new PermissionCell(kindOpt, kindPermissions[i], parentCells, fallbackCellOpt, grandParentCellOpt, true);
  });
}
 
Example 6
Source File: Neo4jHttpGraphHelper.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * writeDataStatement neo4j rest json write data payload.
 *
 * @param queryPlusParameters (query, parameter map)
 * @return ObjectNode
 */
public ObjectNode writeData(Pair<String, Map<String, Object>> queryPlusParameters) {

  LOGGER.debug("writeData: ", queryPlusParameters);

  Objects.requireNonNull(queryPlusParameters);
  Objects.requireNonNull(queryPlusParameters.getValue0());

  ObjectNode request = MAPPER.createObjectNode();

  request.put(statementKey, queryPlusParameters.getValue0());

  if( queryPlusParameters.getValue1() != null && queryPlusParameters.getValue1().size() > 0) {
    ObjectNode params = MAPPER.convertValue(queryPlusParameters.getValue1(), ObjectNode.class);
    request.put(paramsKey, params);
  } else {
    request.put(paramsKey, MAPPER.createObjectNode());
  }

  LOGGER.debug("writeData: ", request);

  return request;
}
 
Example 7
Source File: DefaultParser.java    From kbear with Apache License 2.0 5 votes vote down vote up
@Override
public CrrlStatement parse(String rule) {
    rule = rule.trim();

    rule = trimClause(rule, "use");

    Pair<String, String> pair = parseValue(rule, "cluster", "clusterId");
    String clusterId = pair.getValue0();
    rule = pair.getValue1();

    Route.Builder routeBuilder = Route.newBuilder().setClusterId(clusterId);

    Pair<String, Boolean> result = tryTrimComma(rule);
    rule = result.getValue0();
    if (result.getValue1()) {
        pair = parseValue(rule, "topic", "topicId");
        String topicId = pair.getValue0();
        routeBuilder.setTopicId(topicId);
        rule = pair.getValue1();
    }

    CrrlCriteria criteria;
    if (StringExtension.isBlank(rule))
        criteria = new NullCriteria();
    else {
        String criteriaString = trimClause(rule, "when");
        criteria = parseCriteria(criteriaString);
    }

    return new DefaultStatement(routeBuilder.build(), criteria);
}
 
Example 8
Source File: Fields.java    From gremlin-ogm with Apache License 2.0 5 votes vote down vote up
private static <E extends Element> Map<String, Field> fieldsByName(Pair<Class, Predicate<Field>>
    predicatedType) {
  Class<E> elementType = predicatedType.getValue0();
  Predicate<Field> predicate = predicatedType.getValue1();
  List<Field> allFields = Arrays.asList(getAllFields(elementType));
  allFields.forEach(field -> {
    field.setAccessible(true);
  });
  Map<String, Field> fieldMap = allFields.stream()
      .filter(field -> predicate.test(field) && !isHiddenField(field))
      .collect(Collectors.toMap(Field::getName, Function.identity()));
  return fieldMap;
}
 
Example 9
Source File: ShortestPathVertexProgram.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Move any valid path into the VP's memory.
 * @param vertex The current vertex.
 * @param memory The VertexProgram's memory.
 */
private void collectShortestPaths(final Vertex vertex, final Memory memory) {

    final VertexProperty<Map<Vertex, Pair<Number, Set<Path>>>> pathProperty = vertex.property(PATHS);

    if (pathProperty.isPresent()) {

        final Map<Vertex, Pair<Number, Set<Path>>> paths = pathProperty.value();
        final List<Path> result = new ArrayList<>();

        for (final Pair<Number, Set<Path>> pair : paths.values()) {
            for (final Path path : pair.getValue1()) {
                if (isEndVertex(vertex)) {
                    if (this.distanceEqualsNumberOfHops ||
                            this.maxDistance == null ||
                            NumberHelper.compare(pair.getValue0(), this.maxDistance) <= 0) {
                        result.add(path);
                    }
                }
            }
        }

        pathProperty.remove();

        memory.add(SHORTEST_PATHS, result);
    }
}
 
Example 10
Source File: MongoDbSafeKey.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes a string to be safe for use as a MongoDB field name.
 * @param key the unencoded key.
 * @return the encoded key.
 */
public static String encodeKey(final String key) {
    String encodedKey = key;
    for (final Pair<String, String> pair : ESCAPE_CHARACTERS) {
        final String unescapedCharacter = pair.getValue0();
        final String escapedCharacter = pair.getValue1();
        encodedKey = encodedKey.replace(unescapedCharacter, escapedCharacter);
    }

    return encodedKey;
}
 
Example 11
Source File: MongoDbSafeKey.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes a MongoDB safe field name to an unencoded string.
 * @param key the encoded key.
 * @return the unencoded key.
 */
public static String decodeKey(final String key) {
    String decodedKey = key;
    for (final Pair<String, String> pair : UNESCAPE_CHARACTERS) {
        final String unescapedCharacter = pair.getValue0();
        final String escapedCharacter = pair.getValue1();
        decodedKey = decodedKey.replace(escapedCharacter, unescapedCharacter);
    }

    return decodedKey;
}
 
Example 12
Source File: ReplacedStepTree.java    From sqlg with MIT License 5 votes vote down vote up
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean orderByIsOrder() {
    for (ReplacedStep<?, ?> replacedStep : linearPathToLeafNode()) {
        for (Pair<Traversal.Admin<?, ?>, Comparator<?>> objects : replacedStep.getSqlgComparatorHolder().getComparators()) {
            if (!(objects.getValue1() instanceof Order && objects.getValue1() != Order.shuffle)) {
                return false;
            }
        }
    }
    return true;
}
 
Example 13
Source File: IoIntegrateTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY)
public void shouldHaveSizeOfStarGraphLessThanDetached() throws Exception {
    final Random random = TestHelper.RANDOM;
    final Vertex vertex = graph.addVertex("person");
    for (int i = 0; i < 100; i++) { // vertex properties and meta properties
        vertex.property(VertexProperty.Cardinality.list, UUID.randomUUID().toString(), random.nextDouble(),
                "acl", random.nextBoolean() ? "public" : "private",
                "created", random.nextLong());
    }
    for (int i = 0; i < 50000; i++) {  // edges and edge properties
        vertex.addEdge("knows", graph.addVertex("person"), "since", random.nextLong(), "acl", random.nextBoolean() ? "public" : "private");
        graph.addVertex("software").addEdge("createdBy", vertex, "date", random.nextLong());
        graph.addVertex("group").addEdge("hasMember", vertex);
    }
    ///////////////
    Pair<StarGraph, Integer> pair = serializeDeserialize(StarGraph.of(vertex));
    int starGraphSize = pair.getValue1();
    TestHelper.validateEquality(vertex, pair.getValue0().getStarVertex());
    ///
    pair = serializeDeserialize(pair.getValue0());
    assertEquals(starGraphSize, pair.getValue1().intValue());
    starGraphSize = pair.getValue1();
    TestHelper.validateEquality(vertex, pair.getValue0().getStarVertex());
    ///
    pair = serializeDeserialize(pair.getValue0());
    assertEquals(starGraphSize, pair.getValue1().intValue());
    starGraphSize = pair.getValue1();
    TestHelper.validateEquality(vertex, pair.getValue0().getStarVertex());
    ///
    // this is a rough approximation of "detached" serialization of all vertices and edges.
    // now that writeVertex in gryo writes StarGraph that approach can't be used anymore to test
    // serialization size of detached.
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final GryoWriter writer = graph.io(IoCore.gryo()).writer().create();
    writer.writeObject(outputStream, DetachedFactory.detach(vertex, true));
    vertex.edges(Direction.BOTH).forEachRemaining(e -> writer.writeObject(outputStream, DetachedFactory.detach(e, true)));
    final int detachedVertexSize = outputStream.size();
    assertTrue(starGraphSize < detachedVertexSize);

    logger.info("Size of star graph:        {}", starGraphSize);
    logger.info("Size of detached vertex:   {}", detachedVertexSize);
    logger.info("Size reduction:            {}", (float) detachedVertexSize / (float) starGraphSize);
}
 
Example 14
Source File: Neo4jHttpGraphHelper.java    From streams with Apache License 2.0 4 votes vote down vote up
/**
 * readDataStatement neo4j rest json read data payload.
 *
 * @param queryPlusParameters (query, parameter map)
 * @return ObjectNode
 */
public ObjectNode readData(Pair<String, Map<String, Object>> queryPlusParameters) {

  LOGGER.debug("readData: ", queryPlusParameters);

  Objects.requireNonNull(queryPlusParameters);
  Objects.requireNonNull(queryPlusParameters.getValue0());

  ObjectNode request = MAPPER.createObjectNode();

  request.put(queryKey, queryPlusParameters.getValue0());

  if( queryPlusParameters.getValue1() != null && queryPlusParameters.getValue1().size() > 0) {
    ObjectNode params = MAPPER.convertValue(queryPlusParameters.getValue1(), ObjectNode.class);
    request.put(paramsKey, params);
  }

  LOGGER.debug("readData: ", request);

  return request;
}
 
Example 15
Source File: PersonFactory.java    From business with Mozilla Public License 2.0 4 votes vote down vote up
public PersonId createPersonId(Pair<String, String> name) {
    return new PersonId(new NameVO(name.getValue0(), name.getValue1()));
}