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

The following examples show how to use org.javatuples.Pair#getValue0() . 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: 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 2
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 3
Source File: HttpGremlinEndpointHandler.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private Pair<String,MessageTextSerializer> chooseSerializer(final String acceptString) {
    final List<Pair<String,Double>> ordered = Stream.of(acceptString.split(",")).map(mediaType -> {
        // parse out each mediaType with its params - keeping it simple and just looking for "quality".  if
        // that value isn't there, default it to 1.0.  not really validating here so users better get their
        // accept headers straight
        final Matcher matcher = pattern.matcher(mediaType);
        return (matcher.matches()) ? Pair.with(matcher.group(1), Double.parseDouble(matcher.group(2))) : Pair.with(mediaType, 1.0);
    }).sorted((o1, o2) -> o2.getValue0().compareTo(o1.getValue0())).collect(Collectors.toList());

    for (Pair<String,Double> p : ordered) {
        // this isn't perfect as it doesn't really account for wildcards.  that level of complexity doesn't seem
        // super useful for gremlin server really.
        final String accept = p.getValue0().equals("*/*") ? "application/json" : p.getValue0();
        if (serializers.containsKey(accept))
            return Pair.with(accept, (MessageTextSerializer) serializers.get(accept));
    }

    return null;
}
 
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: BaseStrategy.java    From sqlg with MIT License 6 votes vote down vote up
private boolean optimizableOrderGlobalStep(OrderGlobalStep step) {
        @SuppressWarnings("unchecked")
        List<Pair<Traversal.Admin<?, ?>, Comparator<?>>> comparators = step.getComparators();
        for (Pair<Traversal.Admin<?, ?>, Comparator<?>> comparator : comparators) {
            Traversal.Admin<?, ?> defaultGraphTraversal = comparator.getValue0();
            List<CountGlobalStep> countGlobalSteps = TraversalHelper.getStepsOfAssignableClassRecursively(CountGlobalStep.class, defaultGraphTraversal);
            if (!countGlobalSteps.isEmpty()) {
                return false;
            }
            List<LambdaMapStep> lambdaMapSteps = TraversalHelper.getStepsOfAssignableClassRecursively(LambdaMapStep.class, defaultGraphTraversal);
            if (!lambdaMapSteps.isEmpty()) {
                return false;
            }
//            if (comparator.getValue1().toString().contains("$Lambda")) {
//                return false;
//            }
        }
        return true;
    }
 
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: OrderLocalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void replaceLocalChild(final Traversal.Admin<?, ?> oldTraversal, final Traversal.Admin<?, ?> newTraversal) {
    int i = 0;
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        final Traversal.Admin<S, C> traversal = pair.getValue0();
        if (null != traversal && traversal.equals(oldTraversal)) {
            this.comparators.set(i, Pair.with(this.integrateChild(newTraversal), pair.getValue1()));
            break;
        }
        i++;
    }
}
 
Example 10
Source File: OrderGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void replaceLocalChild(final Traversal.Admin<?, ?> oldTraversal, final Traversal.Admin<?, ?> newTraversal) {
    int i = 0;
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        final Traversal.Admin<S, C> traversal = pair.getValue0();
        if (null != traversal && traversal.equals(oldTraversal)) {
            this.comparators.set(i, Pair.with(this.integrateChild(newTraversal), pair.getValue1()));
            break;
        }
        i++;
    }
}
 
Example 11
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 12
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 13
Source File: ReplacedStepTree.java    From sqlg with MIT License 5 votes vote down vote up
/**
 * This happens when a SqlgVertexStep has a SelectOne step where the label is for an element on the path
 * that is before the current optimized steps.
 * @return
 */
public boolean orderByHasSelectOneStepAndForLabelNotInTree() {
    Set<String> labels = new HashSet<>();
    for (ReplacedStep<?, ?> replacedStep : linearPathToLeafNode()) {
        for (String label : labels) {
            labels.add(SqlgUtil.originalLabel(label));
        }
        for (Pair<Traversal.Admin<?, ?>, Comparator<?>> objects : replacedStep.getSqlgComparatorHolder().getComparators()) {
            Traversal.Admin<?, ?> traversal = objects.getValue0();
            if (traversal.getSteps().size() == 1 && traversal.getSteps().get(0) instanceof SelectOneStep) {
                //xxxxx.select("a").order().by(select("a").by("name"), Order.decr)
                SelectOneStep selectOneStep = (SelectOneStep) traversal.getSteps().get(0);
                Preconditions.checkState(selectOneStep.getScopeKeys().size() == 1, "toOrderByClause expects the selectOneStep to have one scopeKey!");
                Preconditions.checkState(selectOneStep.getLocalChildren().size() == 1, "toOrderByClause expects the selectOneStep to have one traversal!");
                Preconditions.checkState(
                        selectOneStep.getLocalChildren().get(0) instanceof ElementValueTraversal ||
                                selectOneStep.getLocalChildren().get(0) instanceof TokenTraversal
                        ,
                        "toOrderByClause expects the selectOneStep's traversal to be a ElementValueTraversal or a TokenTraversal!");
                String selectKey = (String) selectOneStep.getScopeKeys().iterator().next();
                if (!labels.contains(selectKey)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 14
Source File: ResponseCacheImpl.java    From artemis-disruptor-miaosha with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseDto getAndRemove(String requestId) {
  Pair<ResponseDto, Long> pair = RESPONSE_MAP.remove(requestId);
  return pair == null ? null : pair.getValue0();
}
 
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()));
}