List of usage examples for org.apache.commons.lang3.tuple ImmutablePair getRight
@Override
public R getRight()
From source file:com.hortonworks.registries.schemaregistry.SchemaVersionLifecycleManager.java
public void disableSchemaVersion(Long schemaVersionId) throws SchemaNotFoundException, SchemaLifecycleException { ImmutablePair<SchemaVersionLifecycleContext, SchemaVersionLifecycleState> pair = createSchemaVersionLifeCycleContextAndState( schemaVersionId);/*from w w w.j a v a 2 s . c o m*/ ((InbuiltSchemaVersionLifecycleState) pair.getRight()).disable(pair.getLeft()); }
From source file:com.hortonworks.registries.schemaregistry.SchemaVersionLifecycleManager.java
public void startSchemaVersionReview(Long schemaVersionId) throws SchemaNotFoundException, SchemaLifecycleException { ImmutablePair<SchemaVersionLifecycleContext, SchemaVersionLifecycleState> pair = createSchemaVersionLifeCycleContextAndState( schemaVersionId);//from w w w. ja v a2 s.c om ((InbuiltSchemaVersionLifecycleState) pair.getRight()).startReview(pair.getLeft()); }
From source file:com.hortonworks.registries.schemaregistry.SchemaVersionLifecycleManager.java
public void executeState(Long schemaVersionId, Byte targetState, byte[] transitionDetails) throws SchemaLifecycleException, SchemaNotFoundException { ImmutablePair<SchemaVersionLifecycleContext, SchemaVersionLifecycleState> schemaLifeCycleContextAndState = createSchemaVersionLifeCycleContextAndState( schemaVersionId);/*from ww w . ja va 2 s .c om*/ SchemaVersionLifecycleContext schemaVersionLifecycleContext = schemaLifeCycleContextAndState.getLeft(); SchemaVersionLifecycleState currentState = schemaLifeCycleContextAndState.getRight(); schemaVersionLifecycleContext.setState(currentState); schemaVersionLifecycleContext.setDetails(transitionDetails); SchemaVersionLifecycleStateTransition transition = new SchemaVersionLifecycleStateTransition( currentState.getId(), targetState); SchemaVersionLifecycleStateAction action = schemaVersionLifecycleContext.getSchemaLifeCycleStatesMachine() .getTransitions().get(transition); try { List<SchemaVersionLifecycleStateTransitionListener> listeners = schemaVersionLifecycleContext .getSchemaLifeCycleStatesMachine().getListeners().getOrDefault(transition, DEFAULT_LISTENERS); listeners.stream().forEach(listener -> listener.preStateTransition(schemaVersionLifecycleContext)); action.execute(schemaVersionLifecycleContext); listeners.stream().forEach(listener -> listener.postStateTransition(schemaVersionLifecycleContext)); } catch (SchemaLifecycleException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof SchemaNotFoundException) { throw (SchemaNotFoundException) cause; } throw e; } }
From source file:com.telefonica.iot.cygnus.sinks.NGSICartoDBSink.java
private void persistDistanceEvent(NGSIEvent event) throws CygnusBadConfiguration, CygnusPersistenceError { // Get some values String schema = buildSchemaName(event.getServiceForNaming(enableNameMappings)); String service = event.getServiceForData(); String servicePath = event.getServicePathForData(); String entityId = event.getContextElement().getId(); String entityType = event.getContextElement().getType(); // Iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = event.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return;//from w ww .j av a2 s.co m } // if ((CartoDBBackendImpl) backends.get(schema)).startTransaction(); for (ContextAttribute contextAttribute : contextAttributes) { long recvTimeTs = event.getRecvTimeTs(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); ImmutablePair<String, Boolean> location = NGSIUtils.getGeometry(attrValue, attrType, attrMetadata, swapCoordinates); String tableName = buildTableName(event.getServicePathForNaming(enableGrouping, enableNameMappings), event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding), event.getAttributeForNaming(enableNameMappings)) + CommonConstants.CONCATENATOR + "distance"; if (location.getRight()) { // Try creating the table... the cost of checking if it exists and creating it is higher than directly // attempting to create it. If existing, nothing will be re-created and the new values will be inserted try { String typedFields = "(recvTimeMs bigint, fiwareServicePath text, entityId text, entityType text, " + "stageDistance float, stageTime float, stageSpeed float, sumDistance float, " + "sumTime float, sumSpeed float, sum2Distance float, sum2Time float, sum2Speed float, " + "maxDistance float, minDistance float, maxTime float, minTime float, maxSpeed float, " + "minSpeed float, numSamples bigint)"; backends.get(schema).createTable(schema, tableName, typedFields); // Once created, insert the first row String withs = ""; String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance," + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time," + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)"; String rows = "(" + recvTimeTs + ",'" + servicePath + "','" + entityId + "','" + entityType + "'," + location.getLeft() + ",0,0,0,0,0,0,0,0,0," + Float.MIN_VALUE + "," + Float.MAX_VALUE + "," + Float.MIN_VALUE + "," + Float.MAX_VALUE + "," + Float.MIN_VALUE + "," + Float.MAX_VALUE + ",1)"; LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema + "), Table (" + tableName + "), Data (" + rows + ")"); backends.get(schema).insert(schema, tableName, withs, fields, rows); } catch (Exception e1) { String withs = "" + "WITH geom AS (" + " SELECT " + location.getLeft() + " AS point" + "), calcs AS (" + " SELECT" + " cartodb_id," + " ST_Distance(the_geom::geography, geom.point::geography) AS stage_distance," + " (" + recvTimeTs + " - recvTimeMs) AS stage_time" + " FROM " + tableName + ", geom" + " ORDER BY cartodb_id DESC" + " LIMIT 1" + "), speed AS (" + " SELECT" + " (calcs.stage_distance / NULLIF(calcs.stage_time, 0)) AS stage_speed" + " FROM calcs" + "), inserts AS (" + " SELECT" + " (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum_dist," + " (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum_time," + " (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum_speed," + " (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) " + " * (-1 * ((-1 * t1.sumDistance) - calcs.stage_distance)) AS sum2_dist," + " (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) " + " * (-1 * ((-1 * t1.sumTime) - calcs.stage_time)) AS sum2_time," + " (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) " + " * (-1 * ((-1 * t1.sumSpeed) - speed.stage_speed)) AS sum2_speed," + " t1.max_distance," + " t1.min_distance," + " t1.max_time," + " t1.min_time," + " t1.max_speed," + " t1.min_speed," + " t2.num_samples" + " FROM" + " (" + " SELECT" + " GREATEST(calcs.stage_distance, maxDistance) AS max_distance," + " LEAST(calcs.stage_distance, minDistance) AS min_distance," + " GREATEST(calcs.stage_time, maxTime) AS max_time," + " LEAST(calcs.stage_time, minTime) AS min_time," + " GREATEST(speed.stage_speed, maxSpeed) AS max_speed," + " LEAST(speed.stage_speed, minSpeed) AS min_speed," + " sumDistance," + " sumTime," + " sumSpeed" + " FROM " + tableName + ", speed, calcs" + " ORDER BY " + tableName + ".cartodb_id DESC" + " LIMIT 1" + " ) AS t1," + " (" + " SELECT (-1 * ((-1 * COUNT(*)) - 1)) AS num_samples" + " FROM " + tableName + " ) AS t2," + " speed," + " calcs" + ")"; String fields = "(recvTimeMs, fiwareServicePath, entityId, entityType, the_geom, stageDistance," + "stageTime, stageSpeed, sumDistance, sumTime, sumSpeed, sum2Distance, sum2Time," + "sum2Speed, maxDistance, minDistance, maxTime, mintime, maxSpeed, minSpeed, numSamples)"; String rows = "(" + recvTimeTs + ",'" + servicePath + "','" + entityId + "','" + entityType + "'," + "(SELECT point FROM geom),(SELECT stage_distance FROM calcs)," + "(SELECT stage_time FROM calcs),(SELECT stage_speed FROM speed)," + "(SELECT sum_dist FROM inserts),(SELECT sum_time FROM inserts)," + "(SELECT sum_speed FROM inserts),(SELECT sum2_dist FROM inserts)," + "(SELECT sum2_time FROM inserts),(SELECT sum2_speed FROM inserts)," + "(SELECT max_distance FROM inserts),(SELECT min_distance FROM inserts)," + "(SELECT max_time FROM inserts),(SELECT min_time FROM inserts)," + "(SELECT max_speed FROM inserts),(SELECT min_speed FROM inserts)," + "(SELECT num_samples FROM inserts))"; LOGGER.info("[" + this.getName() + "] Persisting data at NGSICartoDBSink. Schema (" + schema + "), Table (" + tableName + "), Data (" + rows + ")"); try { backends.get(schema).insert(schema, tableName, withs, fields, rows); } catch (Exception e2) { ImmutablePair<Long, Long> bytes = ((CartoDBBackendImpl) backends.get(schema)) .finishTransaction(); serviceMetrics.add(service, servicePath, 0, 0, 0, 0, 0, 0, bytes.left, bytes.right, 0); throw new CygnusPersistenceError("-, " + e2.getMessage()); } // try catch } // try catch } // if } // for ImmutablePair<Long, Long> bytes = ((CartoDBBackendImpl) backends.get(schema)).finishTransaction(); serviceMetrics.add(service, servicePath, 0, 0, 0, 0, 0, 0, bytes.left, bytes.right, 0); }
From source file:forge.game.player.Player.java
public void scry(final int numScry) { final CardCollection topN = new CardCollection(); final PlayerZone library = getZone(ZoneType.Library); final int actualNumScry = Math.min(numScry, library.size()); if (actualNumScry == 0) { return;/* w w w.j av a 2s. c o m*/ } for (int i = 0; i < actualNumScry; i++) { topN.add(library.get(i)); } final ImmutablePair<CardCollection, CardCollection> lists = getController().arrangeForScry(topN); final CardCollection toTop = lists.getLeft(); final CardCollection toBottom = lists.getRight(); int numToBottom = 0; int numToTop = 0; if (toBottom != null) { for (Card c : toBottom) { getGame().getAction().moveToBottomOfLibrary(c); numToBottom++; } } if (toTop != null) { Collections.reverse(toTop); // the last card in list will become topmost in library, have to revert thus. for (Card c : toTop) { getGame().getAction().moveToLibrary(c); numToTop++; } } getGame().fireEvent(new GameEventScry(this, numToTop, numToBottom)); final HashMap<String, Object> runParams = new HashMap<String, Object>(); runParams.put("Player", this); getGame().getTriggerHandler().runTrigger(TriggerType.Scry, runParams, false); }
From source file:org.apache.drill.exec.server.options.SessionOptionManager.java
private boolean withinRange(final OptionValue value) { final int queryNumber = session.getQueryCount(); final ImmutablePair<Integer, Integer> pair = shortLivedOptions.get(value.name); final int start = pair.getLeft(); final int end = pair.getRight(); return start <= queryNumber && queryNumber < end; }
From source file:org.apache.drill.exec.server.rest.profile.OperatorWrapper.java
public String getContent() { TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS); for (ImmutablePair<OperatorProfile, Integer> ip : ops) { int minor = ip.getRight(); OperatorProfile op = ip.getLeft(); String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build(); builder.appendCell(path, null);//from w w w . j av a 2 s. c o m builder.appendNanos(op.getSetupNanos(), null); builder.appendNanos(op.getProcessNanos(), null); builder.appendNanos(op.getWaitNanos(), null); long maxBatches = Long.MIN_VALUE; long maxRecords = Long.MIN_VALUE; for (StreamProfile sp : op.getInputProfileList()) { maxBatches = Math.max(sp.getBatches(), maxBatches); maxRecords = Math.max(sp.getRecords(), maxRecords); } builder.appendFormattedInteger(maxBatches, null); builder.appendFormattedInteger(maxRecords, null); builder.appendBytes(op.getPeakLocalMemoryAllocated(), null); } return builder.build(); }
From source file:org.apache.drill.exec.server.rest.profile.OperatorWrapper.java
public void addSummary(TableBuilder tb) { String path = new OperatorPathBuilder().setMajor(major).setOperator(firstProfile).build(); tb.appendCell(path, null);/*from www . jav a2 s . c o m*/ tb.appendCell(operatorType == null ? "UNKNOWN_OPERATOR" : operatorType.toString(), null); double setupSum = 0.0; double processSum = 0.0; double waitSum = 0.0; double memSum = 0.0; for (ImmutablePair<OperatorProfile, Integer> ip : ops) { OperatorProfile profile = ip.getLeft(); setupSum += profile.getSetupNanos(); processSum += profile.getProcessNanos(); waitSum += profile.getWaitNanos(); memSum += profile.getPeakLocalMemoryAllocated(); } final ImmutablePair<OperatorProfile, Integer> shortSetup = Collections.min(ops, Comparators.setupTime); final ImmutablePair<OperatorProfile, Integer> longSetup = Collections.max(ops, Comparators.setupTime); tb.appendNanos(shortSetup.getLeft().getSetupNanos(), String.format(format, shortSetup.getRight())); tb.appendNanos(Math.round(setupSum / size), null); tb.appendNanos(longSetup.getLeft().getSetupNanos(), String.format(format, longSetup.getRight())); final ImmutablePair<OperatorProfile, Integer> shortProcess = Collections.min(ops, Comparators.processTime); final ImmutablePair<OperatorProfile, Integer> longProcess = Collections.max(ops, Comparators.processTime); tb.appendNanos(shortProcess.getLeft().getProcessNanos(), String.format(format, shortProcess.getRight())); tb.appendNanos(Math.round(processSum / size), null); tb.appendNanos(longProcess.getLeft().getProcessNanos(), String.format(format, longProcess.getRight())); final ImmutablePair<OperatorProfile, Integer> shortWait = Collections.min(ops, Comparators.waitTime); final ImmutablePair<OperatorProfile, Integer> longWait = Collections.max(ops, Comparators.waitTime); tb.appendNanos(shortWait.getLeft().getWaitNanos(), String.format(format, shortWait.getRight())); tb.appendNanos(Math.round(waitSum / size), null); tb.appendNanos(longWait.getLeft().getWaitNanos(), String.format(format, longWait.getRight())); final ImmutablePair<OperatorProfile, Integer> peakMem = Collections.max(ops, Comparators.operatorPeakMemory); tb.appendBytes(Math.round(memSum / size), null); tb.appendBytes(peakMem.getLeft().getPeakLocalMemoryAllocated(), null); }
From source file:org.ballerinalang.langserver.command.executors.CreateTestExecutor.java
private static ImmutablePair<Path, Path> createTestFolderIfNotExists(Path sourceFilePath) { Path projectRoot = Paths.get(LSCompilerUtil.getSourceRoot(sourceFilePath)); ImmutablePair<Path, Path> testsDirPath = getTestsDirPath(sourceFilePath, projectRoot); //Check for tests folder, if not exists create a new folder testsDirPath.getRight().toFile().mkdirs(); return testsDirPath; }
From source file:org.ballerinalang.langserver.command.executors.CreateTestExecutor.java
/** * {@inheritDoc}//from w w w . java 2 s . c o m */ @Override public Object execute(LSContext context) throws LSCommandExecutorException { String docUri = null; int line = -1; int column = -1; for (Object arg : context.get(ExecuteCommandKeys.COMMAND_ARGUMENTS_KEY)) { String argKey = ((JsonObject) arg).get(ARG_KEY).getAsString(); String argVal = ((JsonObject) arg).get(ARG_VALUE).getAsString(); switch (argKey) { case CommandConstants.ARG_KEY_DOC_URI: docUri = argVal; context.put(DocumentServiceKeys.FILE_URI_KEY, docUri); break; case CommandConstants.ARG_KEY_NODE_LINE: line = Integer.parseInt(argVal); break; case CommandConstants.ARG_KEY_NODE_COLUMN: column = Integer.parseInt(argVal); break; default: } } if (line == -1 || column == -1 || docUri == null) { throw new LSCommandExecutorException("Invalid parameters received for the create test command!"); } WorkspaceDocumentManager docManager = context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY); LSCompiler lsCompiler = context.get(ExecuteCommandKeys.LS_COMPILER_KEY); // Compile the source file BLangPackage builtSourceFile = null; try { builtSourceFile = lsCompiler.getBLangPackage(context, docManager, false, null, false); } catch (LSCompilerException e) { throw new LSCommandExecutorException("Couldn't compile the source", e); } // Generate test file and notify Client BallerinaLanguageServer ballerinaLanguageServer = context.get(ExecuteCommandKeys.LANGUAGE_SERVER_KEY); ExtendedLanguageClient client = ballerinaLanguageServer.getClient(); BallerinaWorkspaceService workspace = (BallerinaWorkspaceService) ballerinaLanguageServer .getWorkspaceService(); try { if (builtSourceFile == null || builtSourceFile.diagCollector.hasErrors()) { String message = "Test generation failed due to compilation errors!"; if (client != null) { client.showMessage(new MessageParams(MessageType.Error, message)); } throw new LSCommandExecutorException(message); } // Check for tests folder, if not exists create a new folder Path filePath = Paths.get(URI.create(docUri)); ImmutablePair<Path, Path> testDirs = createTestFolderIfNotExists(filePath); File testsDir = testDirs.getRight().toFile(); // Generate a unique name for the tests file File testFile = testsDir.toPath().resolve(generateTestFileName(filePath)).toFile(); // Generate test content edits String pkgRelativeSourceFilePath = testDirs.getLeft().relativize(filePath).toString(); Pair<BLangNode, Object> bLangNodePair = getBLangNode(line, column, docUri, docManager, lsCompiler, context); Position position = new Position(0, 0); Range focus = new Range(position, position); BiConsumer<Integer, Integer> focusLineAcceptor = (focusLine, incrementer) -> { if (focusLine != null) { position.setLine(focusLine); } position.setLine(position.getLine() + incrementer); }; List<TextEdit> content = TestGenerator.generate(docManager, bLangNodePair, focusLineAcceptor, builtSourceFile, pkgRelativeSourceFilePath, testFile); // Send edits List<Either<TextDocumentEdit, ResourceOperation>> edits = new ArrayList<>(); VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(); identifier.setUri(testFile.toPath().toUri().toString()); edits.add(Either.forRight(new CreateFile(testFile.toPath().toUri().toString()))); TextDocumentEdit textEdit = new TextDocumentEdit(identifier, content); edits.add(Either.forLeft(textEdit)); WorkspaceEdit workspaceEdit = new WorkspaceEdit(edits); ApplyWorkspaceEditParams editParams = new ApplyWorkspaceEditParams(workspaceEdit); if (client != null) { client.applyEdit(editParams); String message = "Tests generated into the file:" + testFile.toString(); client.showMessage(new MessageParams(MessageType.Info, message)); if (workspace.getExperimentalClientCapabilities().get(SHOW_TEXT_DOCUMENT.getValue())) { Location location = new Location(identifier.getUri(), focus); client.showTextDocument(location); } } return editParams; } catch (TestGeneratorException e) { String message = "Test generation failed!: " + e.getMessage(); if (client != null) { client.showMessage(new MessageParams(MessageType.Error, message)); } throw new LSCommandExecutorException(message, e); } }