org.javatuples.Pair Java Examples

The following examples show how to use org.javatuples.Pair. 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
private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) {
    Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value");
    Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation");

    final String subject = criteria.getSubject();
    final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0));
    final String parameter = generateQueryParameter(subject);

    parameters.add(Pair.with(parameter, subjectValue));

    if (CriteriaType.isFunction(criteria.getType())) {
        return String.format("%s(r.%s, @%s)", criteria.getType().getSqlKeyword(), subject, parameter);
    } else {
        return String.format("r.%s %s @%s", subject, criteria.getType().getSqlKeyword(), parameter);
    }
}
 
Example #2
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 #3
Source File: MergeSingleImplTest.java    From business with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testToAggregateTuple() {
    Recipe recipe = new Recipe("customer1", "luke", "order1", "lightsaber");
    MergeSingleImpl<Recipe> underTest = new MergeSingleImpl<>(context, recipe);
    Pair<Order, Customer> pair = Pair.with(new Order(), new Customer("customer1"));
    underTest.into(pair);

    Assertions.assertThat(pair.getValue0())
            .isNotNull();
    Assertions.assertThat(pair.getValue0()
            .getProduct())
            .isEqualTo("lightsaber");
    Assertions.assertThat(pair.getValue1()
            .getId())
            .isEqualTo("customer1");
    Assertions.assertThat(pair.getValue1()
            .getName())
            .isEqualTo("luke");
}
 
Example #4
Source File: GremlinGroovyScriptEngineIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("This is not a test that needs to run on build - it's more for profiling the GremlinGroovyScriptEngine")
public void shouldTest() throws Exception {
    final Random r = new Random();
    final List<Pair<String, Integer>> scripts = new ArrayList<>();
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    for (int ix = 0; ix < 1000000; ix++) {
        final String script = "1 + " + ix;
        final int output = (int) engine.eval(script);
        assertEquals(1 + ix, output);

        if (ix % 1000 == 0) scripts.add(Pair.with(script, output));

        if (ix % 25 == 0) {
            final Pair<String,Integer> p = scripts.get(r.nextInt(scripts.size()));
            assertEquals(p.getValue1().intValue(), (int) engine.eval(p.getValue0()));
        }
    }
}
 
Example #5
Source File: StringFactory.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static String featureString(final Graph.Features features) {
    final StringBuilder sb = new StringBuilder("FEATURES");
    final Predicate<Method> supportMethods = (m) -> m.getModifiers() == Modifier.PUBLIC && m.getName().startsWith(featuresStartWith) && !m.getName().equals(featuresStartWith);
    sb.append(LINE_SEPARATOR);

    Stream.of(Pair.with(Graph.Features.GraphFeatures.class, features.graph()),
            Pair.with(Graph.Features.VariableFeatures.class, features.graph().variables()),
            Pair.with(Graph.Features.VertexFeatures.class, features.vertex()),
            Pair.with(Graph.Features.VertexPropertyFeatures.class, features.vertex().properties()),
            Pair.with(Graph.Features.EdgeFeatures.class, features.edge()),
            Pair.with(Graph.Features.EdgePropertyFeatures.class, features.edge().properties())).forEach(p -> {
        printFeatureTitle(p.getValue0(), sb);
        Stream.of(p.getValue0().getMethods())
                .filter(supportMethods)
                .map(createTransform(p.getValue1()))
                .forEach(sb::append);
    });

    return sb.toString();
}
 
Example #6
Source File: FluentAssemblerTupleMergeIT.java    From business with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void mergeFromRepositoryOrFactory() {
    Recipe recipe = new Recipe("customer1", "luke", "order1", "light saber");

    Pair<Order, Customer> orderCustomerPair = fluently.merge(recipe)
            .into(Order.class, Customer.class)
            .fromRepository()
            .orFromFactory();

    Assertions.assertThat(orderCustomerPair.getValue0())
            .isNotNull();
    Assertions.assertThat(orderCustomerPair.getValue0()
            .getId())
            .isEqualTo("order1");
    Assertions.assertThat(orderCustomerPair.getValue0()
            .getProduct())
            .isEqualTo("light saber");
    // the customer name is not part of the factory parameters, so it is set by the assembler
    Assertions.assertThat(orderCustomerPair.getValue1()
            .getId())
            .isEqualTo("customer1");
    Assertions.assertThat(orderCustomerPair.getValue1()
            .getName())
            .isEqualTo("luke");
}
 
Example #7
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 #8
Source File: DefaultTraversalMetrics.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private void addTopLevelMetrics(final Traversal.Admin traversal, final boolean onGraphComputer) {
    this.totalStepDuration = 0;

    final List<ProfileStep> profileSteps = TraversalHelper.getStepsOfClass(ProfileStep.class, traversal);
    final List<Pair<Integer, MutableMetrics>> tempMetrics = new ArrayList<>(profileSteps.size());

    for (int ii = 0; ii < profileSteps.size(); ii++) {
        // The index is necessary to ensure that step order is preserved after a merge.
        final ProfileStep step = profileSteps.get(ii);
        final MutableMetrics stepMetrics = onGraphComputer ? traversal.getSideEffects().get(step.getId()) : step.getMetrics();

        this.totalStepDuration += stepMetrics.getDuration(MutableMetrics.SOURCE_UNIT);
        tempMetrics.add(Pair.with(ii, stepMetrics.clone()));
    }

    tempMetrics.forEach(m -> {
        final double dur = m.getValue1().getDuration(TimeUnit.NANOSECONDS) * 100.d / this.totalStepDuration;
        m.getValue1().setAnnotation(PERCENT_DURATION_KEY, dur);
    });

    tempMetrics.forEach(p -> {
        this.stepIndexedMetrics.put(p.getValue1().getId(), p.getValue1().getImmutableClone());
        this.positionIndexedMetrics.put(p.getValue0(), p.getValue1().getImmutableClone());
    });
}
 
Example #9
Source File: IoRegistryTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFindRegisteredClassesByIoImplementationAndSerializer() {
    // note that this is a non-standard usage of IoRegistry strictly for testing purposes - refer to javadocs
    // for proper usage
    final FakeIoRegistry registry = new FakeIoRegistry();
    registry.register(GryoIo.class, Long.class, "test");
    registry.register(GryoIo.class, Integer.class, 1);
    registry.register(GryoIo.class, String.class, 1L);
    registry.register(GraphSONIo.class, Short.class, 100);

    final List<Pair<Class, Number>> foundGryo = registry.find(GryoIo.class, Number.class);
    assertEquals(2, foundGryo.size());
    assertEquals(String.class, foundGryo.get(1).getValue0());
    assertEquals(1L, foundGryo.get(1).getValue1());
    assertEquals(1, foundGryo.get(0).getValue1());
    assertEquals(Integer.class, foundGryo.get(0).getValue0());

    final List<Pair<Class, Date>> foundGraphSON = registry.find(GraphSONIo.class, Date.class);
    assertEquals(0, foundGraphSON.size());
}
 
Example #10
Source File: TraversalExplanationSerializer.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Map containing "original", "intermediate" and "final" keys.
 */
@Override
public Object transform(final TraversalExplanation value) {
    final Map<String, Object> result = new HashMap<>();
    result.put(ORIGINAL, getTraversalSteps(value.getOriginalTraversal()));

    final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = value.getStrategyTraversals();

    result.put(INTERMEDIATE,
            strategyTraversals.stream().map(pair -> {
                final Map<String, Object> item = new HashMap<>();
                item.put(STRATEGY, pair.getValue0().toString());
                item.put(CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName());
                item.put(TRAVERSAL, getTraversalSteps(pair.getValue1()));
                return item;
            }).collect(Collectors.toList()));

    result.put(FINAL, getTraversalSteps(strategyTraversals.isEmpty()
            ? value.getOriginalTraversal() : strategyTraversals.get(strategyTraversals.size() - 1).getValue1()));
    return result;
}
 
Example #11
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 #12
Source File: IoRegistryTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFindRegisteredClassesByIoImplementation() {
    // note that this is a non-standard usage of IoRegistry strictly for testing purposes - refer to javadocs
    // for proper usage
    final FakeIoRegistry registry = new FakeIoRegistry();
    registry.register(GryoIo.class, Long.class, "test");
    registry.register(GryoIo.class, Integer.class, 1);
    registry.register(GryoIo.class, String.class, 1L);
    registry.register(GraphSONIo.class, Short.class, 100);

    final List<Pair<Class, Object>> foundGryo = registry.find(GryoIo.class);
    assertEquals(3, foundGryo.size());
    assertEquals("test", foundGryo.get(0).getValue1());
    assertEquals(String.class, foundGryo.get(2).getValue0());
    assertEquals(1L, foundGryo.get(2).getValue1());
    assertEquals(Long.class, foundGryo.get(0).getValue0());
    assertEquals(1, foundGryo.get(1).getValue1());
    assertEquals(Integer.class, foundGryo.get(1).getValue0());

    final List<Pair<Class, Object>> foundGraphSON = registry.find(GraphSONIo.class);
    assertEquals(1, foundGraphSON.size());
    assertEquals(100, foundGraphSON.get(0).getValue1());
    assertEquals(Short.class, foundGraphSON.get(0).getValue0());
}
 
Example #13
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 #14
Source File: BranchStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void addGlobalChildOption(final M pickToken, final Traversal.Admin<S, E> traversalOption) {
    if (pickToken instanceof Pick) {
        if (this.traversalPickOptions.containsKey(pickToken))
            this.traversalPickOptions.get(pickToken).add(traversalOption);
        else
            this.traversalPickOptions.put((Pick) pickToken, new ArrayList<>(Collections.singletonList(traversalOption)));
    } else {
        final Traversal.Admin pickOptionTraversal;
        if (pickToken instanceof Traversal) {
            pickOptionTraversal = ((Traversal) pickToken).asAdmin();
        } else {
            pickOptionTraversal = new PredicateTraversal(pickToken);
        }
        this.traversalOptions.add(Pair.with(pickOptionTraversal, traversalOption));
    }
    // adding an IdentityStep acts as a placeholder when reducing barriers get in the way - see the
    // standardAlgorithm() method for more information.
    if (TraversalHelper.hasStepOfAssignableClass(ReducingBarrierStep.class, traversalOption))
        traversalOption.addStep(0, new IdentityStep(traversalOption));
    traversalOption.addStep(new EndStep(traversalOption));

    if (!this.hasBarrier && !TraversalHelper.getStepsOfAssignableClassRecursively(Barrier.class, traversalOption).isEmpty())
        this.hasBarrier = true;
    this.integrateChild(traversalOption);
}
 
Example #15
Source File: OpSelectorHandler.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(final ChannelHandlerContext ctx, final RequestMessage msg,
                      final List<Object> objects) throws Exception {
    final Context gremlinServerContext = new Context(msg, ctx, settings,
            graphManager, gremlinExecutor, this.scheduledExecutorService);
    try {
        // choose a processor to do the work based on the request message.
        final Optional<OpProcessor> processor = OpLoader.getProcessor(msg.getProcessor());

        if (processor.isPresent())
            // the processor is known so use it to evaluate the message
            objects.add(Pair.with(msg, processor.get().select(gremlinServerContext)));
        else {
            // invalid op processor selected so write back an error by way of OpProcessorException.
            final String errorMessage = String.format("Invalid OpProcessor requested [%s]", msg.getProcessor());
            throw new OpProcessorException(errorMessage, ResponseMessage.build(msg)
                    .code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS)
                    .statusMessage(errorMessage).create());
        }
    } catch (OpProcessorException ope) {
        logger.warn(ope.getMessage(), ope);
        gremlinServerContext.writeAndFlush(ope.getResponseMessage());
    }
}
 
Example #16
Source File: IndexMatchingIteratorTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void testFielded() throws Throwable {
    IndexMatchingIterator.Configuration conf = new IndexMatchingIterator.Configuration();
    conf.addPattern("onyx", "pokemon");
    conf.addPattern(".*r.*k", "bird");
    
    Set<Pair<String,String>> matches = Sets.newHashSet();
    IndexMatchingIterator itr = new IndexMatchingIterator();
    itr.init(new SortedMapIterator(data), ImmutableMap.of(CONF, gson().toJson(conf)), null);
    itr.seek(new Range(), new ArrayList<>(), false);
    while (itr.hasTop()) {
        matches.add(parse(itr.getTopKey()));
        itr.next();
    }
    assertEquals(ImmutableSet.of(Pair.with("onyx", "pokemon"), Pair.with("ruddy duck", "bird")), matches);
}
 
Example #17
Source File: ChainedComparator.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(final S objectA, final S objectB) {
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        final int comparison = this.traversers ?
                pair.getValue1().compare(TraversalUtil.apply((Traverser.Admin<S>) objectA, pair.getValue0()), TraversalUtil.apply((Traverser.Admin<S>) objectB, pair.getValue0())) :
                pair.getValue1().compare(TraversalUtil.apply(objectA, pair.getValue0()), TraversalUtil.apply(objectB, pair.getValue0()));
        if (comparison != 0)
            return comparison;
    }
    return 0;
}
 
Example #18
Source File: Tuples.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the tuple class corresponding to the specified cardinality.
 *
 * @param cardinality the cardinality (must be less or equal than 10).
 * @return the corresponding tuple class.
 */
public static Class<? extends Tuple> classOfTuple(int cardinality) {
    switch (cardinality) {
        case 1:
            return Unit.class;
        case 2:
            return Pair.class;
        case 3:
            return Triplet.class;
        case 4:
            return Quartet.class;
        case 5:
            return Quintet.class;
        case 6:
            return Sextet.class;
        case 7:
            return Septet.class;
        case 8:
            return Octet.class;
        case 9:
            return Ennead.class;
        case 10:
            return Decade.class;
        default:
            throw new IllegalArgumentException("Cannot create a tuple with " + cardinality + " element(s)");
    }
}
 
Example #19
Source File: AbstractQueryGenerator.java    From spring-data-cosmosdb with MIT License 5 votes vote down vote up
private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) {
    final CriteriaType type = criteria.getType();

    switch (type) {
        case ALL:
            return "";
        case IN:
        case NOT_IN:
            return generateInQuery(criteria);
        case BETWEEN:
            return generateBetween(criteria, parameters);
        case IS_NULL:
        case IS_NOT_NULL:
        case FALSE:
        case TRUE:
            return generateUnaryQuery(criteria);
        case IS_EQUAL:
        case NOT:
        case BEFORE:
        case AFTER:
        case LESS_THAN:
        case LESS_THAN_EQUAL:
        case GREATER_THAN:
        case GREATER_THAN_EQUAL:
        case CONTAINING:
        case ENDS_WITH:
        case STARTS_WITH:
            return generateBinaryQuery(criteria, parameters);
        case AND:
        case OR:
            Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria");

            final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters);
            final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters);

            return generateClosedQuery(left, right, type);
        default:
            throw new UnsupportedOperationException("unsupported Criteria type: " + type);
    }
}
 
Example #20
Source File: ResultQueue.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<List<Result>> await(final int items) {
    final CompletableFuture<List<Result>> result = new CompletableFuture<>();
    waiting.add(Pair.with(result, items));

    tryDrainNextWaiting(false);

    return result;
}
 
Example #21
Source File: IoIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private Pair<StarGraph, Integer> serializeDeserialize(final StarGraph starGraph) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        graph.io(IoCore.gryo()).writer().create().writeObject(outputStream, starGraph);
        return Pair.with(graph.io(IoCore.gryo()).reader().create().readObject(new ByteArrayInputStream(outputStream.toByteArray()), StarGraph.class), outputStream.size());
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example #22
Source File: GraphManager.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public void tryClearGraphs(){
    for(Pair<Graph, Configuration> p : openGraphs) {
        try {
            innerGraphProvider.clear(p.getValue0(), p.getValue1());
        }catch (Exception e){
            logger.warn(String.format("Automatic close of Graph instance [%s] and config [%s] generated failure.",
                    p.getValue0() != null ? p.getValue0().toString() : "null",
                    p.getValue1() != null ? p.getValue1().toString() : "null"), e);
        }
    }
}
 
Example #23
Source File: RecipeAssembler.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void mergeAggregateIntoDto(Pair<Order, Customer> sourceAggregate, Recipe targetDto) {
    targetDto.setOrderId(sourceAggregate.getValue0()
            .getId());
    targetDto.setCustomerId(sourceAggregate.getValue1()
            .getId());
    targetDto.setProduct(sourceAggregate.getValue0()
            .getProduct());
    targetDto.setCustomerName(sourceAggregate.getValue1()
            .getName());
}
 
Example #24
Source File: TestCypherQueryGraphHelper.java    From streams with Apache License 2.0 5 votes vote down vote up
@Test
public void createEdgeRequestTest() throws Exception {

  ActivityObject actor = new ActivityObject();
  actor.setId("actor");
  actor.setObjectType("type");
  actor.setContent("content");

  ActivityObject object = new ActivityObject();
  object.setId("object");
  object.setObjectType("type");
  object.setContent("content");

  ActivityObject target = new ActivityObject();
  object.setId("target");
  object.setObjectType("type");

  Activity activity = new Activity();
  activity.setId("activity");
  activity.setVerb("verb");
  activity.setContent("content");

  activity.setActor(actor);
  activity.setObject(object);
  activity.setObject(target);

  Pair<String, Map<String, Object>> queryAndParams = helper.createActorTargetEdge(activity);

  assert(queryAndParams != null);
  assert(queryAndParams.getValue0() != null);
  assert(queryAndParams.getValue1() != null);

}
 
Example #25
Source File: BranchStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private List<Traversal.Admin<S, E>> pickBranches(final Object choice) {
    final List<Traversal.Admin<S, E>> branches = new ArrayList<>();
    if (choice instanceof Pick) {
        if (this.traversalPickOptions.containsKey(choice)) {
            branches.addAll(this.traversalPickOptions.get(choice));
        }
    }
    for (final Pair<Traversal.Admin, Traversal.Admin<S, E>> p : this.traversalOptions) {
        if (TraversalUtil.test(choice, p.getValue0())) {
            branches.add(p.getValue1());
        }
    }
    return branches.isEmpty() ? this.traversalPickOptions.get(Pick.none) : branches;
}
 
Example #26
Source File: RecipeAssembler.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void mergeDtoIntoAggregate(Recipe sourceDto, Pair<Order, Customer> targetAggregate) {
    targetAggregate.getValue0()
            .setProduct(sourceDto.getProduct());
    targetAggregate.getValue1()
            .setName(sourceDto.getCustomerName());
}
 
Example #27
Source File: OrderGlobalStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private final ProjectedTraverser<S, Object> createProjectedTraverser(final Traverser.Admin<S> traverser) {
    // this was ProjectedTraverser<S, C> but the projection may not be C in the case of a lambda where a
    // Comparable may not be expected but rather an object that can be compared in any way given a lambda.
    // not sure why this is suddenly an issue but Intellij would not let certain tests pass without this
    // adjustment here.
    final List<Object> projections = new ArrayList<>(this.comparators.size());
    for (final Pair<Traversal.Admin<S, C>, Comparator<C>> pair : this.comparators) {
        projections.add(TraversalUtil.apply(traverser, pair.getValue0()));
    }
    return new ProjectedTraverser<>(traverser, projections);
}
 
Example #28
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 #29
Source File: LenientMultiSegmentationEvaluator.java    From bluima with Apache License 2.0 5 votes vote down vote up
private String getText(@SuppressWarnings("rawtypes") Sequence input,
        Pair<Integer, Integer> annot) {
    StringBuilder sb = new StringBuilder();
    for (int i = annot.getKey(); i < annot.getValue(); i++) {
        sb.append(getText(input, i) + " ");
    }
    return sb.toString();
}
 
Example #30
Source File: OrderDtoTupleAssembler.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void mergeDtoIntoAggregate(OrderDto sourceDto, Pair<Order, Customer> targetAggregate) {
    targetAggregate.getValue0()
            .setProduct(sourceDto.getProduct());
    targetAggregate.getValue0()
            .setPrice(sourceDto.getPrice());
    targetAggregate.getValue0()
            .setOrderDate(sourceDto.getOrderDate());
    targetAggregate.getValue1()
            .setName(sourceDto.getCustomerName());
}