List of usage examples for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair
public ImmutablePair(final L left, final R right)
From source file:com.ottogroup.bi.streaming.operator.json.insert.JsonStaticContentInsertionTest.java
/** * Test case for {@link JsonStaticContentInsertion#JsonStaticContentInsertion(java.util.List)} being provided a * configuration which holds an element that shows an empty path (no elements) *//*from w ww. ja v a 2 s .co m*/ @Test(expected = IllegalArgumentException.class) public void testConstructor_withElementHoldingEmptyContentPath() throws Exception { List<Pair<JsonContentReference, Serializable>> values = new ArrayList<>(); values.add(new ImmutablePair<JsonContentReference, Serializable>( new JsonContentReference(new String[0], JsonContentType.STRING), "test")); new JsonStaticContentInsertion(values); }
From source file:com.streamsets.pipeline.stage.it.KeywordsInObjectNamesIT.java
@Test public void testKeywordInDbTableColumnName() throws Exception { executeUpdate(Utils.format("CREATE DATABASE IF NOT EXISTS `{}`", keyword)); HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().database(keyword).table(keyword) .build();/*from w w w . ja v a 2 s . com*/ HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build(); Map<String, Field> map = new LinkedHashMap<>(); map.put(keyword, Field.create("value")); Record record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); try { processRecords(processor, hiveTarget, ImmutableList.of(record)); } catch (StageException se) { LOG.error("Processing exception", se); Assert.fail("Processing testing record unexpectedly failed: " + se.getMessage()); throw se; } String fullTableName = Utils.format("`{}`.`{}`", keyword, keyword); assertTableExists(fullTableName); assertQueryResult(Utils.format("select * from {}", fullTableName), new QueryValidator() { @Override public void validateResultSet(ResultSet rs) throws Exception { assertResultSetStructure(rs, new ImmutablePair(Utils.format("{}.{}", keyword, keyword), Types.VARCHAR), new ImmutablePair(Utils.format("{}.dt", keyword), Types.VARCHAR)); Assert.assertTrue("Table tbl doesn't contain any rows", rs.next()); Assert.assertEquals("value", rs.getObject(1)); Assert.assertFalse("Table tbl contains more then one row", rs.next()); } }); }
From source file:com.sludev.commons.vfs2.provider.azure.AzFileObject.java
/** * Convenience method that returns the container and path from the current URL. * //from w w w.jav a 2s . co m * @return A tuple containing the container name and the path. */ protected Pair<String, String> getContainerAndPath() { Pair<String, String> res = null; try { URLFileName currName = (URLFileName) getName(); String currNameStr = currName.getPath(); currNameStr = StringUtils.stripStart(currNameStr, "/"); if (StringUtils.isBlank(currNameStr)) { log.warn(String.format("getContainerAndPath() : Path '%s' does not appear to be valid", currNameStr)); return null; } // Deal with the special case of the container root. if (StringUtils.contains(currNameStr, "/") == false) { // Container and root return new ImmutablePair<>(currNameStr, "/"); } String[] resArray = StringUtils.split(currNameStr, "/", 2); res = new ImmutablePair<>(resArray[0], resArray[1]); } catch (Exception ex) { log.error(String.format("getContainerAndPath() : Path does not appear to be valid"), ex); } return res; }
From source file:com.norconex.importer.handler.tagger.impl.TextBetweenTagger.java
@Override protected void tagStringContent(String reference, StringBuilder content, ImporterMetadata metadata, boolean parsed, boolean partialContent) { int flags = Pattern.DOTALL | Pattern.UNICODE_CASE; if (!caseSensitive) { flags = flags | Pattern.CASE_INSENSITIVE; }//from w ww. j av a 2 s.c o m for (TextBetween between : betweens) { List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>(); Pattern leftPattern = Pattern.compile(between.start, flags); Matcher leftMatch = leftPattern.matcher(content); while (leftMatch.find()) { Pattern rightPattern = Pattern.compile(between.end, flags); Matcher rightMatch = rightPattern.matcher(content); if (rightMatch.find(leftMatch.end())) { if (inclusive) { matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end())); } else { matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start())); } } else { break; } } for (int i = matches.size() - 1; i >= 0; i--) { Pair<Integer, Integer> matchPair = matches.get(i); String value = content.substring(matchPair.getLeft(), matchPair.getRight()); if (value != null) { metadata.addString(between.name, value); } } } }
From source file:com.jaspersoft.jasperserver.jrsh.completion.completer.RepositoryNameCompleter.java
@Override public int complete(String buffer, int cursor, List<CharSequence> candidates) { if (buffer != null && cursor < buffer.length()) { candidates.add(""); return buffer.length(); }//from ww w.j ava2 s . c o m if (uniqueId == 0) { uniqueId = hashCode(); } if (buffer == null) { candidates.add("/"); return 0; } else { if (uniqueId == hashCode()) { if (buffer.isEmpty()) { return 0; } List<Pair<String, Boolean>> resources; List<String> filteredResources; try { if (isResourceExist(buffer)) { resources = download(buffer); if (!resources.isEmpty() && !buffer.equals("/")) { return buffer.length() + 1; } fillResources(candidates, resources); } else { String root = getPreviousPath(buffer); if (isResourceExist(root)) { resources = download(root); List<Pair<String, Boolean>> temp = new ArrayList<>(); for (Pair<String, Boolean> pair : resources) { String resource = pair.getKey(); Boolean isFolder = pair.getRight(); if (startsWith(resource, buffer)) { ImmutablePair<String, Boolean> newPair = new ImmutablePair<>(resource, isFolder); temp.add(newPair); } } fillResources(candidates, temp); } else { String lastInput = getLastInput(buffer); if ("".equals(lastInput)) { List<Pair<String, Boolean>> temp = new ArrayList<>(); ImmutablePair<String, Boolean> newPair = new ImmutablePair<>("", false); temp.add(newPair); fillResources(candidates, temp); return buffer.length(); } } } } catch (AuthenticationFailedException e3) { SessionUtil.reopenSession(); complete(buffer, cursor, candidates); } if (candidates.size() == 1) { return buffer.lastIndexOf("/") + 1; } if (candidates.size() > 1) { String lastInput = getLastInput(buffer); if (compareCandidatesWithLastInput(lastInput, candidates)) { return buffer.length() - lastInput.length(); } } return buffer.length(); } else { candidates.addAll(bufCandidates); if (candidates.size() > 0) { String lastInput = getLastInput(buffer); if (compareCandidatesWithLastInput(lastInput, candidates)) { return buffer.length() - lastInput.length(); } } return buffer.length(); } } }
From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.MINLPSolver.MINLPDataFileBuilder.java
public void createDataFile(File dataFile) throws MatrixHugeHoleException, IOException { Matrix matrix = fullMatrix.removeFailedSimulations(); addHeader();/*from w w w. j a v a 2s .c o m*/ addScalarParameter("nAM", matrix.getNumRows()); addScalarParameter("N", data.getPrivateCloudParameters().getN()); addDoubleParameter("V", data.getPrivateCloudParameters().getV()); addDoubleParameter("M", data.getPrivateCloudParameters().getM()); final boolean tail = (matrix.getNumRows() > 1); @SuppressWarnings("unchecked") Pair<Iterable<Integer>, Iterable<Double>>[] costOrPenaltiesPairs = tail ? new Pair[matrix.getNumRows() - 1] : null; @SuppressWarnings("unchecked") Pair<Iterable<Integer>, Iterable<Double>>[] mTilde = tail ? new Pair[matrix.getNumRows() - 1] : null; @SuppressWarnings("unchecked") Pair<Iterable<Integer>, Iterable<Double>>[] vTilde = tail ? new Pair[matrix.getNumRows() - 1] : null; @SuppressWarnings("unchecked") Pair<Iterable<Integer>, Iterable<Integer>>[] nu = tail ? new Pair[matrix.getNumRows() - 1] : null; Pair<Iterable<Integer>, Iterable<Double>> costOrPenaltiesFirst = null; Pair<Iterable<Integer>, Iterable<Double>> mTildeFirst = null; Pair<Iterable<Integer>, Iterable<Double>> vTildeFirst = null; Pair<Iterable<Integer>, Iterable<Integer>> nuFirst = null; int i = 0; for (Entry<String, SolutionPerJob[]> row : matrix.entrySet()) { Iterable<Integer> rowH = matrix.getAllH(row.getKey()); Iterable<Double> rowCostOrPenalty = matrix.getAllCost(row.getKey()); Iterable<Double> rowMTilde = matrix.getAllMtilde(row.getKey(), data.getMapVMConfigurations()); Iterable<Double> rowVTilde = matrix.getAllVtilde(row.getKey(), data.getMapVMConfigurations()); Iterable<Integer> rowNu = matrix.getAllNu(row.getKey()); Pair<Iterable<Integer>, Iterable<Double>> costOrPenalty = new ImmutablePair<>(rowH, rowCostOrPenalty); Pair<Iterable<Integer>, Iterable<Double>> thisMTilde = new ImmutablePair<>(rowH, rowMTilde); Pair<Iterable<Integer>, Iterable<Double>> thisVTilde = new ImmutablePair<>(rowH, rowVTilde); Pair<Iterable<Integer>, Iterable<Integer>> thisNu = new ImmutablePair<>(rowH, rowNu); if (i == 0) { costOrPenaltiesFirst = costOrPenalty; mTildeFirst = thisMTilde; vTildeFirst = thisVTilde; nuFirst = thisNu; } else if (tail) { int idx = i - 1; costOrPenaltiesPairs[idx] = costOrPenalty; mTilde[idx] = thisMTilde; vTilde[idx] = thisVTilde; nu[idx] = thisNu; } int writtenIndex = ++i; addIndexedSet("H", writtenIndex, rowH); fullMatrix.addNotFailedRow(writtenIndex, row.getKey()); } final String parameterName = "bigC"; addIndexedArrayParameter(parameterName, costOrPenaltiesFirst, costOrPenaltiesPairs); addIndexedArrayParameter("Mtilde", mTildeFirst, mTilde); addIndexedArrayParameter("Vtilde", vTildeFirst, vTilde); addIndexedArrayParameter("nu", nuFirst, nu); if (fileUtility == null) throw new RuntimeException("fileUtility is null"); if (dataFile == null) throw new RuntimeException("dataFile is null"); fileUtility.writeContentToFile(build(), dataFile); }
From source file:blusunrize.immersiveengineering.client.models.smart.ConnModelReal.java
@Nonnull @Override/*from www . j ava2 s . co m*/ public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { if (side == null && state instanceof IExtendedBlockState) { IExtendedBlockState ext = (IExtendedBlockState) state; Object[] additional = null; if (ext.getUnlistedProperties().containsKey(IEProperties.TILEENTITY_PASSTHROUGH)) { TileEntity te = ext.getValue(IEProperties.TILEENTITY_PASSTHROUGH); if (te instanceof IEBlockInterfaces.ICacheData) additional = ((IEBlockInterfaces.ICacheData) te).getCacheData(); } int x = 0, z = 0; if (ext.getUnlistedProperties().containsKey(IEProperties.CONNECTIONS)) { Set<Connection> conns = ext.getValue(IEProperties.CONNECTIONS); if (conns != null && conns.size() > 0) { BlockPos tmp = conns.iterator().next().start; x = (tmp.getX() % 16 + 16) % 16; z = (tmp.getZ() % 16 + 16) % 16; } } ExtBlockstateAdapter ad = new ExtBlockstateAdapter(ext, null, ExtBlockstateAdapter.ONLY_OBJ_CALLBACK, additional); Pair<Byte, ExtBlockstateAdapter> key = new ImmutablePair<>((byte) ((x << 4) | z), ad); try { IBakedModel ret = cache.get(key, () -> new AssembledBakedModel(ext, textureAtlasSprite, base, layers)); return ret.getQuads(state, null, rand); } catch (ExecutionException e) { e.printStackTrace(); } } return getBaseQuads(MinecraftForgeClient.getRenderLayer(), state, side, rand); }
From source file:com.streamsets.pipeline.stage.it.DecimalTypeIT.java
@Test public void correctCases() throws Exception { executeUpdate("CREATE TABLE `tbl` (id int, dec decimal(4, 2)) PARTITIONED BY (dt string) STORED AS AVRO"); HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().decimalConfig(4, 2).build(); HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build(); List<Record> records = new LinkedList<>(); Map<String, Field> map = new LinkedHashMap<>(); map.put("id", Field.create(Field.Type.INTEGER, 1)); map.put("dec", Field.create(BigDecimal.valueOf(12.12))); Record record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record);/* w w w.j a v a 2s. co m*/ map = new LinkedHashMap<>(); map.put("id", Field.create(Field.Type.INTEGER, 2)); map.put("dec", Field.create(BigDecimal.valueOf(1.0))); record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record); map = new LinkedHashMap<>(); map.put("id", Field.create(Field.Type.INTEGER, 3)); map.put("dec", Field.create(BigDecimal.valueOf(12.0))); record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record); map = new LinkedHashMap<>(); map.put("id", Field.create(Field.Type.INTEGER, 4)); map.put("dec", Field.create(BigDecimal.valueOf(0.1))); record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record); map = new LinkedHashMap<>(); map.put("id", Field.create(Field.Type.INTEGER, 5)); map.put("dec", Field.create(BigDecimal.valueOf(0.12))); record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record); processRecords(processor, hiveTarget, records); assertQueryResult("select * from tbl order by id", new QueryValidator() { @Override public void validateResultSet(ResultSet rs) throws Exception { assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER), new ImmutablePair("tbl.dec", Types.DECIMAL), new ImmutablePair("tbl.dt", Types.VARCHAR)); Assert.assertTrue("Table tbl doesn't contain any rows", rs.next()); Assert.assertEquals(1, rs.getLong(1)); Assert.assertEquals(BigDecimal.valueOf(12.12), rs.getBigDecimal(2)); Assert.assertTrue("Unexpected number of rows", rs.next()); Assert.assertEquals(2, rs.getLong(1)); Assert.assertEquals(BigDecimal.valueOf(1), rs.getBigDecimal(2)); Assert.assertTrue("Unexpected number of rows", rs.next()); Assert.assertEquals(3, rs.getLong(1)); Assert.assertEquals(BigDecimal.valueOf(12), rs.getBigDecimal(2)); Assert.assertTrue("Unexpected number of rows", rs.next()); Assert.assertEquals(4, rs.getLong(1)); Assert.assertEquals(BigDecimal.valueOf(0.1), rs.getBigDecimal(2)); Assert.assertTrue("Unexpected number of rows", rs.next()); Assert.assertEquals(5, rs.getLong(1)); Assert.assertEquals(BigDecimal.valueOf(0.12), rs.getBigDecimal(2)); Assert.assertFalse("Unexpected number of rows", rs.next()); } }); }
From source file:com.norconex.importer.handler.transformer.impl.StripBetweenTransformer.java
@Override protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata, boolean parsed, boolean partialContent) { int flags = Pattern.DOTALL | Pattern.UNICODE_CASE; if (!caseSensitive) { flags = flags | Pattern.CASE_INSENSITIVE; }/*w ww . j a va2 s . c o m*/ for (Pair<String, String> pair : stripPairs) { List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>(); Pattern leftPattern = Pattern.compile(pair.getLeft(), flags); Matcher leftMatch = leftPattern.matcher(content); while (leftMatch.find()) { Pattern rightPattern = Pattern.compile(pair.getRight(), flags); Matcher rightMatch = rightPattern.matcher(content); if (rightMatch.find(leftMatch.end())) { if (inclusive) { matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end())); } else { matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start())); } } else { break; } } for (int i = matches.size() - 1; i >= 0; i--) { Pair<Integer, Integer> matchPair = matches.get(i); content.delete(matchPair.getLeft(), matchPair.getRight()); } } }
From source file:com.microsoft.tooling.msservices.serviceexplorer.azure.rediscache.RedisCacheModule.java
@Override protected void refreshItems() throws AzureCmdException { List<Pair<String, String>> failedSubscriptions = new ArrayList<>(); try {/*from www.ja v a 2s. c o m*/ AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager(); // not signed in if (azureManager == null) { return; } SubscriptionManager subscriptionManager = azureManager.getSubscriptionManager(); Set<String> sidList = subscriptionManager.getAccountSidList(); for (String sid : sidList) { try { Azure azure = azureManager.getAzure(sid); for (RedisCache cache : azure.redisCaches().list()) { addChildNode(new RedisCacheNode(this, sid, cache)); } } catch (Exception ex) { failedSubscriptions.add(new ImmutablePair<>(sid, ex.getMessage())); continue; } } } catch (Exception ex) { DefaultLoader.getUIHelper() .logError("An error occurred when trying to load Redis Caches\n\n" + ex.getMessage(), ex); } if (!failedSubscriptions.isEmpty()) { StringBuilder errorMessage = new StringBuilder( "An error occurred when trying to load Redis Caches for the subscriptions:\n\n"); for (Pair error : failedSubscriptions) { errorMessage.append(error.getKey()).append(": ").append(error.getValue()).append("\n"); } DefaultLoader.getUIHelper().logError( "An error occurred when trying to load Redis Caches\n\n" + errorMessage.toString(), null); } }