List of usage examples for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair
public ImmutablePair(final L left, final R right)
From source file:com.pinterest.terrapin.base.FutureUtil.java
/** * Run speculative execution for a set of futures. This is especially useful for improving latency * and surviving failures. The provided BackupFutureRetryPolicy will decide whether the backup * future should be fired or not. The 1st future which returns successfully is returned. * * @param originalFuture The original future which has already been issued. * @param functionBackupFuture A function which can issue the backup future once @waitTimeMillis * has expired. * @param waitTimeMillis The time to wait in milliseconds before issuing the backup future. * @param statsPrefix The stats prefix to be prefixed with recorded stats such as "won", "lost" * and "backup-fired". * @param retryPolicy decides whether the backup future should be fired if the original future * fails//from w w w . ja v a2 s .c om * @param <T> * @return Returns a future which encapsulates the speculative execution strategy. */ public static <T> Future<T> getSpeculativeFuture(final Future<T> originalFuture, final Function0<Future<T>> functionBackupFuture, long waitTimeMillis, final String statsPrefix, final BackupFutureRetryPolicy retryPolicy) { return originalFuture.within(Duration.fromMilliseconds(waitTimeMillis), timer) .rescue(new Function<Throwable, Future<T>>() { public Future<T> apply(Throwable t) { if (retryPolicy.isRetriable(t)) { final Future<T> backupFuture = functionBackupFuture.apply(); Stats.incr(statsPrefix + "-backup-fired"); // Build information into each future as to whether this is the original // future or the backup future. final Future<Pair<Boolean, T>> originalFutureWithInfo = originalFuture .map(new Function<T, Pair<Boolean, T>>() { public Pair<Boolean, T> apply(T t) { return new ImmutablePair(true, t); } }); final Future<Pair<Boolean, T>> backupFutureWithInfo = backupFuture .map(new Function<T, Pair<Boolean, T>>() { public Pair<Boolean, T> apply(T t) { return new ImmutablePair(false, t); } }); // If there is an exception, the first future throwing the exception will // return. Instead we want the 1st future which is successful. Future<Pair<Boolean, T>> origFutureSuccessful = originalFutureWithInfo .rescue(new Function<Throwable, Future<Pair<Boolean, T>>>() { public Future<Pair<Boolean, T>> apply(Throwable t) { // Fall back to back up future which may also fail in which case we bubble // up the exception. return backupFutureWithInfo; } }); Future<Pair<Boolean, T>> backupFutureSuccessful = backupFutureWithInfo .rescue(new Function<Throwable, Future<Pair<Boolean, T>>>() { public Future<Pair<Boolean, T>> apply(Throwable t) { // Fall back to original Future which may also fail in which case we bubble // up the exception. return originalFutureWithInfo; } }); return origFutureSuccessful.select(backupFutureSuccessful) .map(new Function<Pair<Boolean, T>, T>() { public T apply(Pair<Boolean, T> tuple) { if (tuple.getLeft()) { Stats.incr(statsPrefix + "-won"); } else { Stats.incr(statsPrefix + "-lost"); } return tuple.getRight(); } }); } else { return Future.exception(t); } } }); }
From source file:com.lyncode.jtwig.functions.repository.FunctionResolver.java
public CallableFunction get(String name, GivenParameters givenParameters) throws FunctionNotFoundException, ResolveException { if (!functions.containsKey(name)) throw new FunctionNotFoundException("Function with name '" + name + "' not found."); if (!cachedFunctions.containsKey(name)) cachedFunctions.put(name, new HashMap<Class[], Pair<FunctionReference, Boolean>>()); if (cachedFunctions.get(name).containsKey(givenParameters.types())) { Pair<FunctionReference, Boolean> pair = cachedFunctions.get(name).get(givenParameters.types()); Object[] arguments = pair.getRight() ? parameterResolver.resolveParameters(pair.getLeft(), givenParameters, parameterConverter) : parameterResolver.resolveParameters(pair.getLeft(), givenParameters, emptyConverter()); return new CallableFunction(pair.getLeft(), arguments); }//from w w w.j a v a 2s .c o m List<FunctionReference> functionList = functions.get(name); for (FunctionReference function : functionList) { Object[] arguments = parameterResolver.resolveParameters(function, givenParameters, emptyConverter()); if (arguments != null) { cachedFunctions.get(name).put(givenParameters.types(), new ImmutablePair<>(function, false)); return new CallableFunction(function, arguments); } } for (FunctionReference function : functionList) { Object[] arguments = parameterResolver.resolveParameters(function, givenParameters, parameterConverter); if (arguments != null) { cachedFunctions.get(name).put(givenParameters.types(), new ImmutablePair<>(function, true)); return new CallableFunction(function, arguments); } } throw new FunctionNotFoundException("Function with name '" + name + "' and given parameters not found. Available:\n" + listAvailable(name, functions.get(name))); }
From source file:it.polimi.diceH2020.SPACE4CloudWS.fineGrainedLogicForOptimization.ReactorConsumer.java
private Pair<Boolean, Long> runSolver(SolutionPerJob solPerJob) { Pair<Optional<Double>, Long> solverResult = solverCache.evaluate(solPerJob); Optional<Double> solverMetric = solverResult.getLeft(); long runtime = solverResult.getRight(); if (solverMetric.isPresent()) { PerformanceSolver solver = solverCache.getPerformanceSolver(); Technology technology = dataService.getScenario().getTechnology(); Double mainMetric = solver.transformationFromSolverResult(solPerJob, technology) .apply(solverMetric.get()); solver.metricUpdater(solPerJob, technology).accept(mainMetric); boolean feasible = solver.feasibilityCheck(solPerJob, technology).test(mainMetric); solPerJob.setFeasible(feasible); return new ImmutablePair<>(true, runtime); }//from w w w . j av a 2 s . c o m solverCache.invalidate(solPerJob); return new ImmutablePair<>(false, runtime); }
From source file:com.galenframework.speclang2.reader.pagespec.ForLoop.java
private static Pair<String, String> parseExtraMapping(StringCharReader reader) { String type = reader.readWord(); String as = reader.readWord(); String varName = reader.readWord(); if (type.isEmpty()) { throw new SyntaxException("Missing type. Expected 'prev' or 'next'"); }//from w w w . j av a 2s . c om if (!"as".equals(as)) { throw new SyntaxException("Incorrect statement. Use 'as'"); } if (varName.isEmpty()) { throw new SyntaxException("Missing mapping name for '" + type + "'"); } String theRest = reader.getTheRest().trim(); if (!theRest.isEmpty()) { throw new SyntaxException("Cannot process: " + theRest); } return new ImmutablePair<String, String>(type, varName); }
From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessorTest.java
@Test(timeout = 10000) public void scaleTest() { CompletableFuture<Void> result = new CompletableFuture<>(); CompletableFuture<Void> result2 = new CompletableFuture<>(); CompletableFuture<Void> result3 = new CompletableFuture<>(); EventStreamWriter<AutoScaleEvent> writer = createWriter(event -> { if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM1) && event.getDirection() == AutoScaleEvent.UP) { result.complete(null);/*from w w w. j a va2 s. co m*/ } if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM2) && event.getDirection() == AutoScaleEvent.DOWN) { result2.complete(null); } if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM3) && event.getDirection() == AutoScaleEvent.DOWN) { result3.complete(null); } }); AutoScaleProcessor monitor = new AutoScaleProcessor(writer, AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0) .with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0) .with(AutoScalerConfig.CACHE_CLEANUP_IN_SECONDS, 1) .with(AutoScalerConfig.CACHE_EXPIRY_IN_SECONDS, 1).build(), executor, maintenanceExecutor); String streamSegmentName1 = Segment.getScopedName(SCOPE, STREAM1, 0); String streamSegmentName2 = Segment.getScopedName(SCOPE, STREAM2, 0); String streamSegmentName3 = Segment.getScopedName(SCOPE, STREAM3, 0); monitor.notifyCreated(streamSegmentName1, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); monitor.notifyCreated(streamSegmentName2, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); monitor.notifyCreated(streamSegmentName3, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); long twentyminutesback = System.currentTimeMillis() - Duration.ofMinutes(20).toMillis(); monitor.put(streamSegmentName1, new ImmutablePair<>(twentyminutesback, twentyminutesback)); monitor.put(streamSegmentName3, new ImmutablePair<>(twentyminutesback, twentyminutesback)); monitor.report(streamSegmentName1, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 1001, 500, 200, 200); monitor.report(streamSegmentName3, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 0.0, 0.0, 0.0, 0.0); monitor.notifySealed(streamSegmentName1); assertTrue(FutureHelpers.await(result)); assertTrue(FutureHelpers.await(result)); assertTrue(FutureHelpers.await(result3)); }
From source file:io.pravega.service.server.host.stat.AutoScaleProcessorTest.java
@Test(timeout = 10000) public void scaleTest() { CompletableFuture<Void> result = new CompletableFuture<>(); CompletableFuture<Void> result2 = new CompletableFuture<>(); CompletableFuture<Void> result3 = new CompletableFuture<>(); EventStreamWriter<ScaleEvent> writer = createWriter(event -> { if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM1) && event.getDirection() == ScaleEvent.UP) { result.complete(null);/* ww w . j a va 2s. c om*/ } if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM2) && event.getDirection() == ScaleEvent.DOWN) { result2.complete(null); } if (event.getScope().equals(SCOPE) && event.getStream().equals(STREAM3) && event.getDirection() == ScaleEvent.DOWN) { result3.complete(null); } }); AutoScaleProcessor monitor = new AutoScaleProcessor(writer, AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0) .with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0) .with(AutoScalerConfig.CACHE_CLEANUP_IN_SECONDS, 1) .with(AutoScalerConfig.CACHE_EXPIRY_IN_SECONDS, 1).build(), executor, maintenanceExecutor); String streamSegmentName1 = Segment.getScopedName(SCOPE, STREAM1, 0); String streamSegmentName2 = Segment.getScopedName(SCOPE, STREAM2, 0); String streamSegmentName3 = Segment.getScopedName(SCOPE, STREAM3, 0); monitor.notifyCreated(streamSegmentName1, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); monitor.notifyCreated(streamSegmentName2, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); monitor.notifyCreated(streamSegmentName3, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, 10); long twentyminutesback = System.currentTimeMillis() - Duration.ofMinutes(20).toMillis(); monitor.put(streamSegmentName1, new ImmutablePair<>(twentyminutesback, twentyminutesback)); monitor.put(streamSegmentName3, new ImmutablePair<>(twentyminutesback, twentyminutesback)); monitor.report(streamSegmentName1, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 1001, 500, 200, 200); monitor.report(streamSegmentName3, 10, WireCommands.CreateSegment.IN_EVENTS_PER_SEC, twentyminutesback, 0.0, 0.0, 0.0, 0.0); monitor.notifySealed(streamSegmentName1); assertTrue(FutureHelpers.await(result)); assertTrue(FutureHelpers.await(result)); assertTrue(FutureHelpers.await(result3)); }
From source file:com.streamsets.pipeline.stage.executor.jdbc.TestJdbcQueryExecutor.java
@Test public void testEL() throws Exception { JdbcQueryExecutor queryExecutor = createExecutor( "CREATE TABLE ${record:value('/table')} AS SELECT * FROM origin"); ExecutorRunner runner = new ExecutorRunner.Builder(JdbcQueryDExecutor.class, queryExecutor) .setOnRecordError(OnRecordError.STOP_PIPELINE).build(); runner.runInit();// ww w . j a v a 2s . c o m Map<String, Field> map = new HashMap<>(); map.put("table", Field.create("el")); Record record = RecordCreator.create(); record.set(Field.create(map)); runner.runWrite(ImmutableList.of(record)); runner.runDestroy(); assertTableStructure("el", new ImmutablePair("ID", Types.INTEGER), new ImmutablePair("NAME", Types.VARCHAR)); }
From source file:com.pinterest.terrapin.server.ResourcePartitionMap.java
public Reader getReader(String resource, String partition) throws TerrapinGetException { Pair<String, String> readerMapKey = new ImmutablePair(resource, partition); Reader r = readerMap.get(readerMapKey); if (r == null) { Integer partitionCount = partitionCountMap.get(resource); if (partitionCount == null || partitionCount < 1) { throw new TerrapinGetException("Resource " + resource + " not found.", TerrapinGetErrorCode.NOT_SERVING_RESOURCE); } else {//from w w w . j a v a 2 s. c o m throw new TerrapinGetException("Resource " + resource + " Partition " + partition + " not found.", TerrapinGetErrorCode.NOT_SERVING_PARTITION); } } return r; }
From source file:com.galenframework.speclang2.pagespec.ForLoop.java
private static Pair<String, String> parseExtraMapping(StringCharReader reader) { String type = reader.readWord(); String as = reader.readWord(); String varName = reader.readWord(); if (type.isEmpty()) { throw new SyntaxException("Missing type. Expected 'prev' or 'next'"); }// w w w . j av a 2s . c om if (!"as".equals(as)) { throw new SyntaxException("Incorrect statement. Use 'as'"); } if (varName.isEmpty()) { throw new SyntaxException("Missing mapping name for '" + type + "'"); } String theRest = reader.getTheRest().trim(); if (!theRest.isEmpty()) { throw new SyntaxException("Cannot process: " + theRest); } return new ImmutablePair<>(type, varName); }
From source file:com.romeikat.datamessie.core.base.util.CollectionUtil.java
public <T> Collection<Pair<T, T>> getPairsAsymmetric(final Collection<T> elements, final boolean addSelfPairs) { final List<T> elementsList = new ArrayList<T>(elements); final List<Pair<T, T>> pairs = new LinkedList<Pair<T, T>>(); final int numberOfElements = elementsList.size(); if (elementsList == null || numberOfElements < 1) { return pairs; }//ww w .j a va 2s .c o m for (int i = 0; i < numberOfElements; i++) { final T element1 = elementsList.get(i); if (addSelfPairs) { pairs.add(new ImmutablePair<T, T>(element1, element1)); } for (int j = i + 1; j < numberOfElements; j++) { final T element2 = elementsList.get(j); pairs.add(new ImmutablePair<T, T>(element1, element2)); } } return pairs; }