public void addTask(Datum datum, ApplyAction action) { if (services.containsKey(datum.key) && action == ApplyAction.CHANGE) { return; } if (action == ApplyAction.CHANGE) { services.put(datum.key, StringUtils.EMPTY); } tasks.add(Pair.with(datum, action)); }
/** * Add a "serializer" for the {@code Mapper}. Note that what is accepted as a "serializer" is implementation * specific. An {@link Io} implementation will consult this registry for "serializer" classes * it expects so refer to the {@link Io} implementation to understand what is expected for these values. * * @param clazz usually this is the class that is to be serialized - may be {@code null} * @param serializer a serializer implementation */ protected void register(final Class<? extends Io> ioClass, final Class clazz, final Object serializer) { if (!registeredSerializers.containsKey(ioClass)) registeredSerializers.put(ioClass, new ArrayList<>()); registeredSerializers.get(ioClass).add(Pair.with(clazz, serializer)); }
/** * Convert a set of key values to a list of Pair objects. Assumes that validations have already taken place to * assure that key positions contain strings and that there are an even number of elements. */ public static List<Pair<String, Object>> asPairs(final Object... keyValues) { final List list = Arrays.asList(keyValues); return IntStream.range(1, list.size()) .filter(i -> i % 2 != 0) .mapToObj(i -> Pair.with(list.get(i - 1).toString(), list.get(i))) .collect(Collectors.toList()); }
@Override public Graph openTestGraph(final Configuration config) { final Graph graph = innerGraphProvider.openTestGraph(config); openGraphs.add(Pair.with(graph, config)); return graph; }
public static <S> Pair<Double, S> clockWithResult(final int loops, final Supplier<S> supplier) { final S result = supplier.get(); // warm up return Pair.with(IntStream.range(0, loops).mapToDouble(i -> { long t = System.nanoTime(); supplier.get(); return (System.nanoTime() - t) * 0.000001; }).sum() / loops, result); } }
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; }
/** * A helper method that generates a {@link Map} of the memory key/values. * * @return the map representation of the memory key/values */ public default Map<String, Object> asMap() { final Map<String, Object> map = keys().stream() .map(key -> Pair.with(key, get(key))) .collect(Collectors.toMap(Pair::getValue0, Pair::getValue1)); return Collections.unmodifiableMap(map); }
/** * Gets the variables of the {@link Graph} as a {@code Map}. */ public default Map<String, Object> asMap() { final Map<String, Object> map = keys().stream() .map(key -> Pair.with(key, get(key).get())) .collect(Collectors.toMap(Pair::getValue0, Pair::getValue1)); return Collections.unmodifiableMap(map); }
/** * {@inheritDoc} */ @Override public <S> List<Pair<Class,S>> find(final Class<? extends Io> builderClass, final Class<S> serializerType) { if (!registeredSerializers.containsKey(builderClass)) return Collections.emptyList(); return Collections.unmodifiableList(registeredSerializers.get(builderClass).stream() .filter(p -> serializerType.isAssignableFrom(p.getValue1().getClass())) .map(p -> Pair.with(p.getValue0(), (S) p.getValue1())) .collect(Collectors.toList())); } }
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; }
/** * Filters to unique method names on each class. */ private static Stream<Method> uniqueMethods(final Class<?> clazz) { final Set<String> unique = new LinkedHashSet<>(); return Stream.of(clazz.getMethods()) .filter(m -> Modifier.isStatic(m.getModifiers())) .map(m -> Pair.with(generateMethodDescriptor(m), m)) .filter(p -> { final boolean exists = unique.contains(p.getValue0()); if (!exists) unique.add(p.getValue0()); return !exists; }) .map(Pair::getValue1); }
public default Stream<Pair<Object, Set<String>>> stream() { final List<Set<String>> labels = this.labels(); final List<Object> objects = this.objects(); return IntStream.range(0, this.size()).mapToObj(i -> Pair.with(objects.get(i), labels.get(i))); }
public static Pair<Class<? extends GraphProvider>, Class<? extends Graph>> getGraphProviderClass(final Class<?> klass) throws InitializationError { final GraphProviderClass annotation = klass.getAnnotation(GraphProviderClass.class); if (null == annotation) throw new InitializationError(String.format("class '%s' must have a GraphProviderClass annotation", klass.getName())); return Pair.with(annotation.provider(), annotation.graph()); }
@Override public <I extends InputShim> Pair read(final KryoShim<I, ?> kryo, final I input, final Class<Pair> pairClass) { return Pair.with(kryo.readClassAndObject(input), kryo.readClassAndObject(input)); } }
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(); }
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); } }
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); } } }
@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); ctx.writeAndFlush(ope.getResponseMessage()); } }
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()); }); }
public TraversalExplanation(final Traversal.Admin<?, ?> traversal) { this.traversal = traversal.clone(); TraversalStrategies mutatingStrategies = new DefaultTraversalStrategies(); for (final TraversalStrategy strategy : this.traversal.getStrategies().toList()) { final Traversal.Admin<?, ?> mutatingTraversal = this.traversal.clone(); mutatingStrategies.addStrategies(strategy); mutatingTraversal.setStrategies(mutatingStrategies); mutatingTraversal.applyStrategies(); this.strategyTraversals.add(Pair.with(strategy, mutatingTraversal)); } }