List of usage examples for org.apache.commons.lang3.tuple Pair getLeft
public abstract L getLeft();
Gets the left element from this pair.
When treated as a key-value pair, this is the key.
From source file:com.act.lcms.v2.MassChargeCalculator.java
protected static Double computeMass(MZSource mzSource) { Double mass;//from ww w. ja v a 2s. c o m String msg; switch (mzSource.getKind()) { case INCHI: Pair<Double, Integer> massAndCharge; try { massAndCharge = MassCalculator.calculateMassAndCharge(mzSource.getInchi()); } catch (Exception e) { LOGGER.error("Calculating mass for molecule %s failed: %s", mzSource.getInchi(), e.getMessage()); throw e; } if (massAndCharge.getRight() > 0) { LOGGER.warn( "(MZSrc %d) Molecule %s has a positive charge %d; ionization may not have the expected effect", mzSource.getId(), mzSource.getInchi(), massAndCharge.getRight()); } else if (massAndCharge.getRight() < 0) { LOGGER.warn("(MZSrc %d) Molecule %s has a negative charge %d; it may not fly in positive ion mode", mzSource.getId(), mzSource.getInchi(), massAndCharge.getRight()); } mass = massAndCharge.getLeft(); break; case ARBITRARY_MASS: mass = mzSource.getArbitraryMass(); break; case PRE_EXTRACTED_MASS: mass = mzSource.getPreExtractedMass().getRight(); break; case UNKNOWN: msg = String.format("mzSource with id %d has UNKNOWN kind, which is invalid", mzSource.getId()); LOGGER.error(msg); throw new RuntimeException(msg); default: msg = String.format("mzSource with id %d has unknown kind (should be impossible): %s", mzSource.getId(), mzSource.getKind()); LOGGER.error(msg); throw new RuntimeException(msg); } return mass; }
From source file:atg.tools.dynunit.internal.inject.ClassReflectionTest.java
@Test public void testGetElementForAnnotationDefault() throws Exception { final Pair<? extends AnnotatedElement, Default> annotatedElement = reflection .getAnnotatedElement(Default.class); assertNotNull(annotatedElement);//from w w w . j a v a2 s. c o m assertThat("The only element annotated @Default should be the method setReal", annotatedElement.getLeft(), is(instanceOf(Method.class))); final Method setReal = (Method) annotatedElement.getLeft(); assertThat(setReal.getName(), is(equalTo("setReal"))); }
From source file:com.streamsets.pipeline.stage.destination.kinesis.KinesisTarget.java
@Override public void write(Batch batch) throws StageException { Iterator<Record> batchIterator = batch.getRecords(); List<Pair<ListenableFuture<UserRecordResult>, String>> putFutures = new LinkedList<>(); int i = 0;/* w w w .j av a2s .co m*/ while (batchIterator.hasNext()) { Record record = batchIterator.next(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(ONE_MB); try { DataGenerator generator = generatorFactory.getGenerator(bytes); generator.write(record); generator.close(); ByteBuffer data = ByteBuffer.wrap(bytes.toByteArray()); Object partitionerKey; if (conf.partitionStrategy == PartitionStrategy.EXPRESSION) { RecordEL.setRecordInContext(partitionVars, record); try { partitionerKey = partitionEval.eval(partitionVars, conf.partitionExpression, Object.class); } catch (ELEvalException e) { throw new StageException(Errors.KINESIS_06, conf.partitionExpression, record.getHeader().getSourceId(), e.toString()); } } else { partitionerKey = i; } String partitionKey = partitioner.partition(partitionerKey, numShards); // To preserve ordering we flush after each record. if (conf.preserveOrdering) { Future<UserRecordResult> resultFuture = kinesisProducer.addUserRecord(conf.streamName, partitionKey, data); getAndCheck(resultFuture, partitionKey); kinesisProducer.flushSync(); } else { putFutures.add(Pair.of(kinesisProducer.addUserRecord(conf.streamName, partitionKey, data), partitionKey)); } ++i; } catch (IOException e) { LOG.error(Errors.KINESIS_05.getMessage(), record, e.toString(), e); handleFailedRecord(record, e.toString()); } } // This has no effect when preserveOrdering is true because the list is empty. for (Pair<ListenableFuture<UserRecordResult>, String> pair : putFutures) { getAndCheck(pair.getLeft(), pair.getRight()); } kinesisProducer.flushSync(); }
From source file:com.streamsets.pipeline.stage.processor.kv.redis.RedisStore.java
public LookupValue get(Pair<String, DataType> pair) { Jedis jedis = pool.getResource();/*from w ww .ja v a 2 s. c o m*/ LookupValue values; // check the type DataType type = pair.getRight(); String key = pair.getLeft(); switch (type) { case STRING: values = new LookupValue(jedis.get(key), type); break; case LIST: values = new LookupValue(jedis.lrange(key, 0, jedis.llen(key)), type); break; case HASH: values = new LookupValue(jedis.hgetAll(key), type); break; case SET: values = new LookupValue(jedis.smembers(key), type); break; default: values = null; } jedis.close(); return values; }
From source file:com.vmware.photon.controller.api.frontend.commands.steps.TenantPushSecurityGroupsStepCmd.java
@Override protected void execute() throws ExternalException { List<TenantEntity> tenantList = step.getTransientResourceEntities(null); checkArgument(tenantList.size() > 0); for (TenantEntity tenantEntity : tenantList) { logger.info("Propagating the security groups of tenant {}", tenantEntity.getId()); // Since this step might be called by deployment when propagating the security groups, // we need to refresh the tenantEntity to make sure it has the latest security groups. tenantEntity = tenantBackend.findById(tenantEntity.getId()); List<Project> projects = new ArrayList<>(); ResourceList<Project> resourceList = projectBackend.filter(tenantEntity.getId(), Optional.<String>absent(), Optional.of(PaginationConfig.DEFAULT_DEFAULT_PAGE_SIZE)); projects.addAll(resourceList.getItems()); while (StringUtils.isNotBlank(resourceList.getNextPageLink())) { resourceList = projectBackend.getProjectsPage(resourceList.getNextPageLink()); projects.addAll(resourceList.getItems()); }//ww w . j a v a2 s . co m List<String> tenantSecurityGroups = tenantEntity.getSecurityGroups().stream().map(g -> g.getName()) .collect(Collectors.toList()); for (Project project : projects) { logger.info("Updating the security groups of project {} using the ones from tenant {}", project.getId(), tenantEntity.getId()); List<SecurityGroup> currSecurityGroups = project.getSecurityGroups(); Pair<List<SecurityGroup>, List<String>> result = SecurityGroupUtils .mergeParentSecurityGroups(currSecurityGroups, tenantSecurityGroups); projectBackend.replaceSecurityGroups(project.getId(), result.getLeft()); if (result.getRight() != null && !result.getRight().isEmpty()) { step.addWarning(new SecurityGroupsAlreadyInheritedException(result.getRight())); } } } }
From source file:de.johni0702.minecraft.gui.layout.GridLayout.java
@Override public ReadableDimension calcMinSize(GuiContainer<?> container) { Preconditions.checkState(columns != 0, "Columns may not be 0."); int maxWidth = 0, maxHeight = 0; int elements = 0; for (Map.Entry<GuiElement, LayoutData> entry : container.getElements().entrySet()) { GuiElement element = entry.getKey(); ReadableDimension minSize = element.getMinSize(); int width = minSize.getWidth(); if (width > maxWidth) { maxWidth = width;//from w w w. jav a 2s . co m } int height = minSize.getHeight(); if (height > maxHeight) { maxHeight = height; } elements++; } int rows = (elements - 1 + columns) / columns; int totalWidth = maxWidth * columns; int totalHeight = maxHeight * rows; if (!cellsEqualSize) { Pair<int[], int[]> maxCellSize = calcNeededCellSize(container); totalWidth = 0; for (int w : maxCellSize.getLeft()) { totalWidth += w; } totalHeight = 0; for (int h : maxCellSize.getRight()) { totalHeight += h; } } if (elements > 0) { totalWidth += spacingX * (columns - 1); } if (elements > columns) { totalHeight += spacingY * (rows - 1); } return new Dimension(totalWidth, totalHeight); }
From source file:edu.uci.ics.hyracks.api.rewriter.runtime.SuperActivityOperatorNodePushable.java
@Override public void setOutputFrameWriter(int clusterOutputIndex, IFrameWriter writer, RecordDescriptor recordDesc) throws HyracksDataException { /**/*from w w w . j a va 2s.com*/ * set the right output frame writer */ Pair<ActivityId, Integer> activityIdOutputIndex = parent.getActivityIdOutputIndex(clusterOutputIndex); IOperatorNodePushable opPushable = operatorNodePushables.get(activityIdOutputIndex.getLeft()); opPushable.setOutputFrameWriter(activityIdOutputIndex.getRight(), writer, recordDesc); }
From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.AMPLSolver.AMPLSolver.java
protected Pair<Double, Boolean> run(@NotNull Pair<List<File>, List<File>> pFiles, String remoteName) throws JSchException, IOException { List<File> amplFiles = pFiles.getLeft(); boolean stillNotOk = true; for (int iteration = 0; stillNotOk && iteration < MAX_ITERATIONS; ++iteration) { File dataFile = amplFiles.get(0); String fullRemotePath = connSettings.getRemoteWorkDir() + REMOTEPATH_DATA_DAT; connector.sendFile(dataFile.getAbsolutePath(), fullRemotePath, getClass()); logger.info(remoteName + "-> AMPL .data file sent"); String remoteRelativeDataPath = ".." + REMOTEPATH_DATA_DAT; String remoteRelativeSolutionPath = ".." + RESULTS_SOLFILE; Matcher matcher = Pattern.compile("([\\w.-]*)(?:-\\d*)\\.dat").matcher(dataFile.getName()); if (!matcher.matches()) { throw new RuntimeException(String.format("problem matching %s", dataFile.getName())); }//from w w w .j a va 2 s.c o m String prefix = matcher.group(1); File runFile = fileUtility.provideTemporaryFile(prefix, ".run"); String runFileContent = new AMPLRunFileBuilder().setDataFile(remoteRelativeDataPath) .setSolverPath(connSettings.getSolverPath()).setSolutionFile(remoteRelativeSolutionPath) .build(); fileUtility.writeContentToFile(runFileContent, runFile); fullRemotePath = connSettings.getRemoteWorkDir() + REMOTE_SCRATCH + "/" + REMOTEPATH_DATA_RUN; connector.sendFile(runFile.getAbsolutePath(), fullRemotePath, getClass()); logger.info(remoteName + "-> AMPL .run file sent"); if (fileUtility.delete(runFile)) logger.debug(runFile + " deleted"); logger.debug(remoteName + "-> Cleaning result directory"); clearResultDir(); logger.info(remoteName + "-> Processing execution..."); String command = String.format("cd %s%s && %s %s", connSettings.getRemoteWorkDir(), REMOTE_SCRATCH, ((AMPLSettings) connSettings).getAmplDirectory(), REMOTEPATH_DATA_RUN); List<String> remoteMsg = connector.exec(command, getClass()); if (remoteMsg.contains("exit-status: 0")) { stillNotOk = false; logger.info(remoteName + "-> The remote optimization process completed correctly"); } else { logger.info("Remote exit status: " + remoteMsg); if (remoteMsg.get(0).contains("error processing param")) { iteration = MAX_ITERATIONS; logger.info(remoteName + "-> Wrong parameters. Aborting"); } else { logger.info(remoteName + "-> Restarted. Iteration " + iteration); } } } if (stillNotOk) { logger.info(remoteName + "-> Error in remote optimization"); throw new IOException("Error in the initial solution creation process"); } else { File solutionFile = amplFiles.get(1); String fullRemotePath = connSettings.getRemoteWorkDir() + RESULTS_SOLFILE; connector.receiveFile(solutionFile.getAbsolutePath(), fullRemotePath, getClass()); Double objFunctionValue = analyzeSolution(solutionFile, ((AMPLSettings) connSettings).isVerbose()); logger.info(remoteName + "-> The value of the objective function is: " + objFunctionValue); // TODO: this always returns false, should check if every error just throws return Pair.of(objFunctionValue, false); } }
From source file:com.minlia.cloud.framework.test.common.web.AbstractDiscoverabilityLiveTest.java
@Test public void whenConsumingSimillarResourceName_thenRedirectedToCorrectResourceName() { final String simillarUriOfResource = getUri().substring(0, getUri().length() - 1); final Pair<String, String> readCredentials = getApi().getReadCredentials(); final RequestSpecification givenAuthenticated = auth.givenBasicAuthenticated(readCredentials.getLeft(), readCredentials.getRight()); final RequestSpecification readReq = givenAuthenticated.header(HttpHeaders.ACCEPT, marshaller.getMime()); final RequestSpecification customRequest = readReq .config(new RestAssuredConfig().redirect(new RedirectConfig().followRedirects(false))); final Response responseOfSimillarUri = getApi().findOneByUriAsResponse(simillarUriOfResource, customRequest);//from w w w .j a v a 2s .c om assertThat(responseOfSimillarUri.getStatusCode(), is(301)); }
From source file:com.nttec.everychan.ui.FavoritesFragment.java
@Override public boolean onContextItemSelected(MenuItem item) { View v = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).targetView; Database.FavoritesEntry entry = (FavoritesEntry) v.getTag(); switch (item.getItemId()) { case R.id.context_menu_remove_favorites: MainApplication.getInstance().database.removeFavorite(entry.chan, entry.board, entry.boardPage, entry.thread);// ww w . j a v a 2 s.c o m for (Pair<ListView, String> p : listViews) ((FavoritesAdapter) p.getLeft().getAdapter()).remove(entry); return true; case R.id.context_menu_open_browser: UrlHandler.launchExternalBrowser(activity, entry.url); return true; } return false; }