List of usage examples for org.apache.commons.lang3.tuple Pair getRight
public abstract R getRight();
Gets the right element from this pair.
When treated as a key-value pair, this is the value.
From source file:de.tntinteractive.portalsammler.engine.SecureStore.java
private static void readSettings(final StorageLayer storage, final SecureRandom srand, final byte[] key, final SecureStore ret) throws IOException { final InputStream stream = storage.openInputStream("meta"); try {/*www . j a va2s. co m*/ final Pair<Integer, MapReader> saltAndReader = createMapReader(stream, srand, key); ret.settingSalt = saltAndReader.getLeft(); final MapReader r = saltAndReader.getRight(); Pair<String, Map<String, String>> p; while ((p = r.readNext()) != null) { final SourceSettings s = new SourceSettings(p.getRight()); ret.getSettings().putSettings(p.getLeft(), s); } r.close(); } finally { stream.close(); } }
From source file:android.databinding.tool.util.XmlEditor.java
public static String strip(File f, String newTag) throws IOException { ANTLRInputStream inputStream = new ANTLRInputStream(new FileReader(f)); XMLLexer lexer = new XMLLexer(inputStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); XMLParser parser = new XMLParser(tokenStream); XMLParser.DocumentContext expr = parser.document(); XMLParser.ElementContext root = expr.element(); if (root == null || !"layout".equals(nodeName(root))) { return null; // not a binding layout }/*w w w .j a v a2 s .co m*/ List<? extends ElementContext> childrenOfRoot = elements(root); List<? extends XMLParser.ElementContext> dataNodes = filterNodesByName("data", childrenOfRoot); if (dataNodes.size() > 1) { L.e("Multiple binding data tags in %s. Expecting a maximum of one.", f.getAbsolutePath()); } ArrayList<String> lines = new ArrayList<>(); lines.addAll(FileUtils.readLines(f, "utf-8")); for (android.databinding.parser.XMLParser.ElementContext it : dataNodes) { replace(lines, toPosition(it.getStart()), toEndPosition(it.getStop()), ""); } List<? extends XMLParser.ElementContext> layoutNodes = excludeNodesByName("data", childrenOfRoot); if (layoutNodes.size() != 1) { L.e("Only one layout element and one data element are allowed. %s has %d", f.getAbsolutePath(), layoutNodes.size()); } final XMLParser.ElementContext layoutNode = layoutNodes.get(0); ArrayList<Pair<String, android.databinding.parser.XMLParser.ElementContext>> noTag = new ArrayList<>(); recurseReplace(layoutNode, lines, noTag, newTag, 0); // Remove the <layout> Position rootStartTag = toPosition(root.getStart()); Position rootEndTag = toPosition(root.content().getStart()); replace(lines, rootStartTag, rootEndTag, ""); // Remove the </layout> ImmutablePair<Position, Position> endLayoutPositions = findTerminalPositions(root, lines); replace(lines, endLayoutPositions.left, endLayoutPositions.right, ""); StringBuilder rootAttributes = new StringBuilder(); for (AttributeContext attr : attributes(root)) { rootAttributes.append(' ').append(attr.getText()); } Pair<String, XMLParser.ElementContext> noTagRoot = null; for (Pair<String, XMLParser.ElementContext> pair : noTag) { if (pair.getRight() == layoutNode) { noTagRoot = pair; break; } } if (noTagRoot != null) { ImmutablePair<String, XMLParser.ElementContext> newRootTag = new ImmutablePair<>( noTagRoot.getLeft() + rootAttributes.toString(), layoutNode); int index = noTag.indexOf(noTagRoot); noTag.set(index, newRootTag); } else { ImmutablePair<String, XMLParser.ElementContext> newRootTag = new ImmutablePair<>( rootAttributes.toString(), layoutNode); noTag.add(newRootTag); } //noinspection NullableProblems Collections.sort(noTag, new Comparator<Pair<String, XMLParser.ElementContext>>() { @Override public int compare(Pair<String, XMLParser.ElementContext> o1, Pair<String, XMLParser.ElementContext> o2) { Position start1 = toPosition(o1.getRight().getStart()); Position start2 = toPosition(o2.getRight().getStart()); int lineCmp = Integer.compare(start2.line, start1.line); if (lineCmp != 0) { return lineCmp; } return Integer.compare(start2.charIndex, start1.charIndex); } }); for (Pair<String, android.databinding.parser.XMLParser.ElementContext> it : noTag) { XMLParser.ElementContext element = it.getRight(); String tag = it.getLeft(); Position endTagPosition = endTagPosition(element); fixPosition(lines, endTagPosition); String line = lines.get(endTagPosition.line); String newLine = line.substring(0, endTagPosition.charIndex) + " " + tag + line.substring(endTagPosition.charIndex); lines.set(endTagPosition.line, newLine); } return StringUtils.join(lines, System.getProperty("line.separator")); }
From source file:forge.card.BoosterGenerator.java
public static List<PaperCard> getBoosterPack(SealedProduct.Template template) { List<PaperCard> result = new ArrayList<>(); List<PrintSheet> sheetsUsed = new ArrayList<>(); CardEdition edition = StaticData.instance().getEditions().get(template.getEdition()); boolean hasFoil = edition != null && !template.getSlots().isEmpty() && MyRandom.getRandom().nextDouble() < edition.getFoilChanceInBooster() && edition.getFoilType() != FoilType.NOT_SUPPORTED; boolean foilAtEndOfPack = hasFoil && edition.getFoilAlwaysInCommonSlot(); String foilSlot = !hasFoil ? null : foilAtEndOfPack ? BoosterSlots.COMMON : Aggregates.random(template.getSlots()).getKey(); String extraFoilSheetKey = edition != null ? edition.getAdditionalSheetForFoils() : ""; for (Pair<String, Integer> slot : template.getSlots()) { String slotType = slot.getLeft(); // add expansion symbol here? int numCards = slot.getRight(); String[] sType = TextUtil.splitWithParenthesis(slotType, ' '); String setCode = sType.length == 1 && template.getEdition() != null ? template.getEdition() : null; String sheetKey = StaticData.instance().getEditions().contains(setCode) ? slotType.trim() + " " + setCode : slotType.trim();/*from ww w. j av a2 s .c o m*/ boolean foilInThisSlot = hasFoil && slotType.startsWith(foilSlot); if (foilInThisSlot) numCards--; PrintSheet ps = getPrintSheet(sheetKey); result.addAll(ps.random(numCards, true)); sheetsUsed.add(ps); if (foilInThisSlot && !foilAtEndOfPack) { if (!extraFoilSheetKey.isEmpty()) { // TODO: extra foil sheets are currently reliably supported only for boosters with FoilAlwaysInCommonSlot=True. // If FoilAlwaysInCommonSlot is false, a card from the extra sheet may still replace a card in any slot. List<PaperCard> foilCards = new ArrayList<>(); for (PaperCard card : ps.toFlatList()) { if (!foilCards.contains(card)) { foilCards.add(card); } } addCardsFromExtraSheet(foilCards, sheetKey); result.add(generateFoilCard(foilCards)); } else { result.add(generateFoilCard(ps)); } } } if (hasFoil && foilAtEndOfPack) { List<PaperCard> foilCards = new ArrayList<>(); for (PrintSheet printSheet : sheetsUsed) { for (PaperCard card : printSheet.toFlatList()) { if (!foilCards.contains(card)) { foilCards.add(card); } } } if (!extraFoilSheetKey.isEmpty()) { addCardsFromExtraSheet(foilCards, extraFoilSheetKey); } result.add(generateFoilCard(foilCards)); } return result; }
From source file:alfio.manager.CheckInManager.java
public static String encrypt(String key, String payload) { try {/* w w w. ja va 2s . com*/ Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key); Cipher cipher = cipherAndSecret.getKey(); cipher.init(Cipher.ENCRYPT_MODE, cipherAndSecret.getRight()); byte[] data = cipher.doFinal(payload.getBytes(StandardCharsets.UTF_8)); byte[] iv = cipher.getIV(); return Base64.encodeBase64URLSafeString(iv) + "|" + Base64.encodeBase64URLSafeString(data); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
From source file:com.act.lcms.db.model.ChemicalAssociatedWithPathway.java
public static List<Pair<Integer, DB.OPERATION_PERFORMED>> insertOrUpdateChemicalsAssociatedWithPathwayFromParser( DB db, ConstructAnalysisFileParser parser) throws SQLException, IOException, ClassNotFoundException { List<Pair<Integer, DB.OPERATION_PERFORMED>> operationsPerformed = new ArrayList<>(); List<Pair<String, List<ConstructAnalysisFileParser.ConstructAssociatedChemical>>> stepPairs = parser .getConstructProducts();//from w ww. j a v a2 s. co m for (Pair<String, List<ConstructAnalysisFileParser.ConstructAssociatedChemical>> stepPair : stepPairs) { String constructId = stepPair.getLeft(); for (ConstructAnalysisFileParser.ConstructAssociatedChemical step : stepPair.getRight()) { System.out.format("Processing entry %s %s %s %d\n", constructId, step.getChemical(), step.getKind(), step.getIndex()); ChemicalAssociatedWithPathway cp = INSTANCE .getChemicalAssociatedWithPathwayByConstructIdAndIndex(db, constructId, step.getIndex()); DB.OPERATION_PERFORMED op = null; if (cp == null) { cp = INSTANCE.insert(db, new ChemicalAssociatedWithPathway(null, constructId, step.getChemical(), step.getKind(), step.getIndex())); op = DB.OPERATION_PERFORMED.CREATE; } else { cp.setConstructId(constructId); cp.setChemical(step.getChemical()); cp.setKind(step.getKind()); cp.setIndex(step.getIndex()); INSTANCE.update(db, cp); op = DB.OPERATION_PERFORMED.UPDATE; } // Chem should only be null if we couldn't insert the row into the DB. if (cp == null) { operationsPerformed.add(Pair.of((Integer) null, DB.OPERATION_PERFORMED.ERROR)); } else { operationsPerformed.add(Pair.of(cp.getId(), op)); } } } return operationsPerformed; }
From source file:com.jkoolcloud.tnt4j.streams.utils.TimestampFormatter.java
/** * Parses the value into a timestamp with microsecond accuracy based on the specified units. * <p>// w w w.ja v a 2s. c o m * If {@code value} represents decimal number (as {@link Number} or {@link String}, fraction gets preserved by * scaling down {@code value} in {@code units} until numeric value expression gets with low (epsilon is * {@code 0.001}) or without fraction or {@code units} gets set to {@link TimeUnit#NANOSECONDS}. * * @param units * units that value is in * @param value * value to convert * @return microsecond timestamp * @throws ParseException * if an error parsing the specified value * * @see #scale(double, TimeUnit) */ public static UsecTimestamp parse(TimeUnit units, Object value) throws ParseException { UsecTimestamp ts; try { long time; if (value instanceof Date) { time = ((Date) value).getTime(); units = TimeUnit.MILLISECONDS; } else if (value instanceof Calendar) { time = ((Calendar) value).getTimeInMillis(); units = TimeUnit.MILLISECONDS; } else { if (units == null) { units = TimeUnit.MILLISECONDS; } double dTime = value instanceof Number ? ((Number) value).doubleValue() : Double.parseDouble(value.toString()); Pair<Double, TimeUnit> sTimePair = scale(dTime, units); dTime = sTimePair.getLeft(); units = sTimePair.getRight(); time = (long) dTime; } switch (units) { case NANOSECONDS: long scale = 1000000L; long mSecs = time / scale; long uSecs = (time - mSecs * scale) / 1000L; ts = new UsecTimestamp(mSecs, uSecs); break; case MICROSECONDS: scale = 1000L; mSecs = time / scale; uSecs = time - mSecs * scale; ts = new UsecTimestamp(mSecs, uSecs); break; default: ts = new UsecTimestamp(units.toMicros(time)); break; } } catch (NumberFormatException nfe) { ParseException pe = new ParseException( StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "TimestampFormatter.failed.parsing", value, nfe.getLocalizedMessage()), 0); pe.initCause(nfe); throw pe; } return ts; }
From source file:com.acmutv.ontoqa.core.parser.SimpleSltagParser.java
private static void solveConflicts(ParserState dashboard) throws LTAGException { List<String> words = dashboard.getWords(); WaitingList wlist = dashboard.getWaitingList(); Map<Integer, Triple<Variable, Variable, Set<Statement>>> missedMainVariables = dashboard .getMissedMainVariables();/*from w w w. j a v a2 s . co m*/ Sltag curr = dashboard.getCurr(); Iterator<ConflictElement> iter = wlist.iterator(); while (iter.hasNext()) { ConflictElement elements = iter.next(); boolean used = false; LOGGER.debug("Examining collissions: substitutions"); for (Pair<Sltag, Integer> elem : elements.getSubstitutions()) { Sltag other = elem.getLeft(); Integer start = elem.getRight(); String startLexicalEntry = (start != null) ? words.get(start) : null; LOGGER.debug("Collision examination : substitution starting at {} ({}):\n{}", start, startLexicalEntry, other.toPrettyString()); LtagNode target = curr.firstMatch(other.getRoot().getCategory(), startLexicalEntry, LtagNodeMarker.SUB); if (target != null && LtagNodeMarker.SUB.equals(target.getMarker())) { LOGGER.debug("Collision examination : substitution : eligible target found {}", target); try { curr.substitution(other, target); LOGGER.debug("Substituted (colliding element) {} with:\n{}", target, other.toPrettyString()); used = true; break; } catch (LTAGException exc) { LOGGER.warn(exc.getMessage()); } } } if (used) { iter.remove(); continue; } else { LOGGER.debug("Cannot find nodes eligible for substitution"); } LOGGER.debug("Examining collissions: adjunctions"); for (Pair<Sltag, Integer> elem : elements.getAdjunctions()) { Sltag toAdjunct = elem.getLeft(); Integer start = elem.getRight(); String startLexicalEntry = (start != null) ? words.get(start) : null; SyntaxCategory category = toAdjunct.getRoot().getCategory(); LOGGER.debug("Collision examination : adjunction starting at {} ({}):\n{}", start, startLexicalEntry, toAdjunct.toPrettyString()); LtagNode localTarget = curr.firstMatch(category, startLexicalEntry, null); if (localTarget != null) { /* CAN MAKE ADJUNCTION */ LOGGER.debug("isLeftAdj: {} | isRightAdj: {}", toAdjunct.isLeftAdj(), toAdjunct.isRightAdj()); LOGGER.debug("missedMainVariables: {}", missedMainVariables); if (curr.getSemantics().getMainVariable() == null && toAdjunct.isLeftAdj() && missedMainVariables.containsKey(start)) { /* INSPECT MAIN VARIABLE MISS */ int lookup = (start != null) ? start : 0; Variable missedMainVar = missedMainVariables.get(lookup).getMiddle(); LOGGER.warn("Found possible main variable miss at pos {}: {}", lookup, missedMainVar); curr.getSemantics().setMainVariable(missedMainVar); LOGGER.warn("Main variable temporarily set to: {}", missedMainVar); curr.adjunction(toAdjunct, localTarget); curr.getSemantics().setMainVariable(null); LOGGER.warn("Resetting main variable to NULL"); } else if (curr.getSemantics().getMainVariable() == null && toAdjunct.isRightAdj() && missedMainVariables.containsKey((start != null) ? start + 2 : 1)) { int lookup = (start != null) ? start + 2 : 1; Variable missedMainVar = missedMainVariables.get(lookup).getMiddle(); LOGGER.warn("Found possible main variable miss at pos {}: {}", lookup, missedMainVar); curr.getSemantics().setMainVariable(missedMainVar); LOGGER.warn("Main variable temporarily set to: {}", missedMainVar); curr.adjunction(toAdjunct, localTarget); curr.getSemantics().setMainVariable(null); LOGGER.warn("Resetting main variable to NULL"); } else { curr.adjunction(toAdjunct, localTarget); } } } } }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesCacheDataConverter.java
static void addSingleRelationship(Map<String, Collection<String>> relationships, String account, String namespace, String fullName) { Pair<KubernetesKind, String> triple = KubernetesManifest.fromFullResourceName(fullName); KubernetesKind kind = triple.getLeft(); String name = triple.getRight(); Collection<String> keys = relationships.get(kind.toString()); if (keys == null) { keys = new ArrayList<>(); }/*from www . j a v a 2 s. c o m*/ keys.add(Keys.infrastructure(kind, account, namespace, name)); relationships.put(kind.toString(), keys); }
From source file:forge.download.GuiDownloadService.java
protected static void addMissingItems(Map<String, String> list, String nameUrlFile, String dir) { for (Pair<String, String> nameUrlPair : FileUtil.readNameUrlFile(nameUrlFile)) { File f = new File(dir, nameUrlPair.getLeft()); //System.out.println(f.getAbsolutePath()); if (!f.exists()) { list.put(f.getAbsolutePath(), nameUrlPair.getRight()); }//w ww .ja v a 2 s . c o m } }
From source file:com.samsung.sjs.ExplanationsTest.java
private static String explainErrors(JSEnvironment env, String sourceCode) { AstRoot root = new Parser().parse(sourceCode, "", 1); SatSolver sat = new Sat4J(); SJSTypeTheory theory = new SJSTypeTheory(env, null, root); List<Integer> hard = new ArrayList<>(); List<Integer> soft = new ArrayList<>(); List<ITypeConstraint> constraints = theory.getConstraints(); for (int i = 0; i < constraints.size(); ++i) { (theory.hackyGenerator().hasExplanation(constraints.get(i)) ? soft : hard).add(i); }//from w w w. ja v a 2s . c om Pair<TypeAssignment, Collection<Integer>> result = TheorySolver.solve(theory, new SatFixingSetFinder<>(sat), hard, soft); ConstraintGenerator g = theory.hackyGenerator(); StringBuilder buf = new StringBuilder(); for (int broken : result.getRight()) { ITypeConstraint c = theory.hackyConstraintAccess().get(broken); ByteArrayOutputStream stream = new ByteArrayOutputStream(); g.explainFailure(c, result.getLeft()).prettyprint(new PrintStream(stream)); buf.append(stream.toString()); } return buf.toString(); }