Java Code Examples for java.util.Set#add()
The following examples show how to use
java.util.Set#add() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StatisticsResource.java From open-rmbt with Apache License 2.0 | 6 votes |
private static Set<String> getCountries(Connection conn) throws SQLException { Set<String> countries = new TreeSet<>(); String sql = "WITH RECURSIVE t(n) AS ( " + "SELECT MIN(mobile_network_id) FROM test" + " UNION" + " SELECT (SELECT mobile_network_id FROM test WHERE mobile_network_id > n" + " ORDER BY mobile_network_id LIMIT 1)" + " FROM t WHERE n IS NOT NULL" + " )" + "SELECT upper(mccmnc2name.country) FROM t LEFT JOIN mccmnc2name ON n=mccmnc2name.uid WHERE NOT mccmnc2name.country IS NULL GROUP BY mccmnc2name.country;"; try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while(rs.next()) countries.add(rs.getString(1)); return countries; } }
Example 2
Source File: PCToken.java From pcgen with GNU Lesser General Public License v2.1 | 6 votes |
@Override public String[] unparse(LoadContext context, CDOMObject obj) { Changes<BonusObj> changes = context.getObjectContext().getListChanges(obj, ListKey.BONUS_PC); Collection<BonusObj> added = changes.getAdded(); if (added == null || added.isEmpty()) { // Zero indicates no Token (and no global clear, so nothing to do) return null; } Set<String> bonusSet = new TreeSet<>(); for (BonusObj bonus : added) { bonusSet.add(bonus.getLSTformat()); } return bonusSet.toArray(new String[0]); }
Example 3
Source File: TraceEventHelper.java From ironjacamar with Eclipse Public License 1.0 | 6 votes |
/** * Pool to Managed Connection Pools mapping * @param data The data * @return The mapping * @exception Exception If an error occurs */ public static Map<String, Set<String>> poolManagedConnectionPools(List<TraceEvent> data) throws Exception { Map<String, Set<String>> result = new TreeMap<String, Set<String>>(); for (TraceEvent te : data) { if (te.getType() == TraceEvent.GET_CONNECTION_LISTENER || te.getType() == TraceEvent.GET_CONNECTION_LISTENER_NEW || te.getType() == TraceEvent.GET_INTERLEAVING_CONNECTION_LISTENER || te.getType() == TraceEvent.GET_INTERLEAVING_CONNECTION_LISTENER_NEW) { Set<String> s = result.get(te.getPool()); if (s == null) s = new TreeSet<String>(); s.add(te.getManagedConnectionPool()); result.put(te.getPool(), s); } } return result; }
Example 4
Source File: GroovyCollections.java From groovy with Apache License 2.0 | 6 votes |
/** * Finds all non-null subsequences of a list. * E.g. <code>subsequences([1, 2, 3])</code> would be: * [[1, 2, 3], [1, 3], [2, 3], [1, 2], [1], [2], [3]] * * @param items the List of items * @return the subsequences from items */ public static <T> Set<List<T>> subsequences(List<T> items) { // items.inject([]){ ss, h -> ss.collect { it + [h] } + ss + [[h]] } Set<List<T>> ans = new HashSet<List<T>>(); for (T h : items) { Set<List<T>> next = new HashSet<List<T>>(); for (List<T> it : ans) { List<T> sublist = new ArrayList<T>(it); sublist.add(h); next.add(sublist); } next.addAll(ans); List<T> hlist = new ArrayList<T>(); hlist.add(h); next.add(hlist); ans = next; } return ans; }
Example 5
Source File: SocketServer.java From FuzzDroid with Apache License 2.0 | 5 votes |
private void handleDexFileReceived(DexFileTransferTraceItem dexFileRequest) { byte[] dexFile = dexFileRequest.getDexFile(); try{ // Write the received dex file to disk for debugging long timestamp = System.currentTimeMillis(); String dirPath = String.format("%s/dexFiles/", UtilInstrumenter.SOOT_OUTPUT); File dir = new File(dirPath); if(!dir.exists()) dir.mkdir(); String filePath = String.format("%s/dexFiles/%d_dexfile.dex", UtilInstrumenter.SOOT_OUTPUT, timestamp); System.out.println(String.format("Dex-File: %s (code position: %d)", filePath, dexFileRequest.getLastExecutedStatement())); LoggerHelper.logEvent(MyLevel.DEXFILE, String.format("Received dex-file %s/dexFiles/%d_dexfile.dex", UtilInstrumenter.SOOT_OUTPUT, timestamp)); Files.write(Paths.get(filePath), dexFile); // We need to remove the statements that load the external code, // because we merge it into a single app. We must not take the // last executed statement, but the current one -> +1. CodePosition codePos = decisionMaker.getCodePositionManager() .getCodePositionByID(dexFileRequest .getLastExecutedStatement()); Unit codePosUnit = decisionMaker.getCodePositionManager().getUnitForCodePosition(codePos); Set<InstanceIndependentCodePosition> statementsToRemove = new HashSet<>(); statementsToRemove.add(new InstanceIndependentCodePosition(codePos.getEnclosingMethod(), codePos.getLineNumber(), codePosUnit.toString())); // Register the new dex file and spawn an analysis task for it DexFile dexFileObj = decisionMaker.getDexFileManager().add(new DexFile( dexFileRequest.getFileName(), filePath, dexFile)); AnalysisTaskManager taskManager = decisionMaker.getAnalysisTaskManager(); taskManager.enqueueAnalysisTask(taskManager.getCurrentTask().deriveNewTask(dexFileObj, statementsToRemove)); }catch(Exception ex) { ex.printStackTrace(); } System.out.println("received dex file"); }
Example 6
Source File: XMLUtils.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * @param signatureElement * @param inputSet * @return nodes with the constrain */ public static Set<Node> excludeNodeFromSet(Node signatureElement, Set<Node> inputSet) { Set<Node> resultSet = new HashSet<Node>(); Iterator<Node> iterator = inputSet.iterator(); while (iterator.hasNext()) { Node inputNode = iterator.next(); if (!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)) { resultSet.add(inputNode); } } return resultSet; }
Example 7
Source File: DefaultConfigurator.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override public Set<String> getDeclaredIdentifiers() { if (_attributes != null) { final Set<String> identifiers = new TreeSet<String>(); for (final Entry<String, Object> entry : _attributes.entrySet()) { final String attributeName = entry.getKey(); final int indexOfDot = attributeName.indexOf("."); if (indexOfDot != -1) { identifiers.add(attributeName.substring(0, indexOfDot)); } } return identifiers; } throw new IllegalStateException("Method called before configuration initialisation."); }
Example 8
Source File: LocalCacheFactoryGenerator.java From caffeine with Apache License 2.0 | 5 votes |
private Set<Feature> getFeatures(List<Object> combination) { Set<Feature> features = new LinkedHashSet<>(); features.add(((Boolean) combination.get(0)) ? Feature.STRONG_KEYS : Feature.WEAK_KEYS); features.add(((Boolean) combination.get(1)) ? Feature.STRONG_VALUES : Feature.INFIRM_VALUES); for (int i = 2; i < combination.size(); i++) { if ((Boolean) combination.get(i)) { features.add(featureByIndex[i]); } } if (features.contains(Feature.MAXIMUM_WEIGHT)) { features.remove(Feature.MAXIMUM_SIZE); } return features; }
Example 9
Source File: PlannerOptions.java From pegasus with Apache License 2.0 | 5 votes |
/** * Set the input directory. * * @param input the input directory for the workflow */ public void setInputDirectories(String input) { Set<String> dirs = new HashSet(); for (String dir : input.split(",")) { dirs.add(dir); } this.setInputDirectories(dirs); }
Example 10
Source File: ThesisServiceWithMailNotification.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 5 votes |
protected static Set<Person> personSet(Person... persons) { Set<Person> result = new HashSet<>(); for (Person person : persons) { if (person != null) { result.add(person); } } return result; }
Example 11
Source File: DirectMapper.java From anno4j with Apache License 2.0 | 5 votes |
public void recordRole(Class<?> role, URI rdfType) { Set<URI> set = directTypes.get(role); if (set == null) directTypes.put(role, set = new HashSet<URI>()); if (rdfType != null) set.add(rdfType); if (rdfType != null) { Set<Class<?>> set1 = directRoles.get(rdfType); if (set1 == null) directRoles.put(rdfType, set1 = new HashSet<Class<?>>()); if (role != null) set1.add(role); } }
Example 12
Source File: ProfileSyncService.java From delion with Apache License 2.0 | 5 votes |
private static Set<Integer> modelTypeArrayToSet(int[] modelTypeArray) { Set<Integer> modelTypeSet = new HashSet<Integer>(); for (int i = 0; i < modelTypeArray.length; i++) { modelTypeSet.add(modelTypeArray[i]); } return modelTypeSet; }
Example 13
Source File: CompoundSearchInfoTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testOneItemList() throws IOException { FileSystem fs = FileUtil.createMemoryFileSystem(); FileObject fsRoot = fs.getRoot(); FileObject dir = fsRoot.createFolder("dir"); dir.createData("a", DummyDataLoader.dummyExt); dir.createData("b", DummyDataLoader.dummyExt); dir.createData("c", DummyDataLoader.dummyExt); DataFolder folder = DataFolder.findFolder(dir); SearchInfo refSearchInfo; SearchInfo testSearchInfo; Iterator refIt; Iterator testIt; Set testSet = new HashSet(); refSearchInfo = new SimpleSearchInfo(folder, false, null); testSearchInfo = new CompoundSearchInfo(new SearchInfo[] {refSearchInfo}); assertTrue(testSearchInfo.canSearch()); for(testIt = testSearchInfo.objectsToSearch(); testIt.hasNext();){ testSet.add(testIt.next()); } refIt = refSearchInfo.objectsToSearch(); while (refIt.hasNext()) { assertTrue(testSet.remove(refIt.next())); } assertTrue(testSet.isEmpty()); refSearchInfo = new SimpleSearchInfo(folder, false, null) { public boolean canSearch() { return false; } }; testSearchInfo = new CompoundSearchInfo(new SearchInfo[] {refSearchInfo}); assertEquals(refSearchInfo.canSearch(), testSearchInfo.canSearch()); }
Example 14
Source File: SchemaConfig.java From Mycat2 with GNU General Public License v3.0 | 5 votes |
/** * 取得该schema的所有数据节点 */ private Set<String> buildAllDataNodes() { Set<String> set = new HashSet<String>(); if (!isEmpty(dataNode)) { set.add(dataNode); } if (!noSharding) { for (TableConfig tc : tables.values()) { set.addAll(tc.getDataNodes()); } } return set; }
Example 15
Source File: DDWRTGenericBindingProvider.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
@Override public String[] getItemNamesForType(String eventType) { Set<String> itemNames = new HashSet<>(); for (Entry<String, BindingConfig> entry : bindingConfigs.entrySet()) { DDWRTBindingConfig fbConfig = (DDWRTBindingConfig) entry.getValue(); if (fbConfig.getType().equals(eventType)) { itemNames.add(entry.getKey()); } } return itemNames.toArray(new String[itemNames.size()]); }
Example 16
Source File: CreateDiskStoreTest.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
public void testDiskStoreConfig1() throws Exception { Connection conn = getConnection(); Statement s = conn.createStatement(); File f1 = new File("dir1"); f1.mkdir(); File f2 = new File("dir2"); f2.mkdir(); File f3 = new File("dir3"); f3.mkdir(); s .execute("create DiskStore testDiskStore2 maxlogsize 448 autocompact false " + " allowforcecompaction true compactionthreshold 80 TimeInterval 23344 " + "Writebuffersize 192923 queuesize 1734 ('dir1' 456, 'dir2', 'dir3' 55556 )"); DiskStore ds = Misc.getGemFireCache().findDiskStore("TESTDISKSTORE2"); assertNotNull(ds); assertEquals(ds.getAllowForceCompaction(), true); assertEquals(ds.getAutoCompact(), false); assertEquals(ds.getCompactionThreshold(), 80); assertEquals(448, ds.getMaxOplogSize()); assertEquals(ds.getQueueSize(), 1734); assertEquals(ds.getTimeInterval(), 23344); assertEquals(ds.getWriteBufferSize(), 192923); assertEquals(ds.getDiskDirs().length, 3); Set<String> files = new HashSet<String>(); files.add(new File(".", "dir1").getAbsolutePath()); files.add(new File(".", "dir2").getAbsolutePath()); files.add(new File(".", "dir3").getAbsolutePath()); assertEquals(ds.getDiskDirs().length, 3); for (File file : ds.getDiskDirs()) { assertTrue(files.remove(file.getAbsolutePath())); } assertTrue(files.isEmpty()); List<Long> sizes = new ArrayList<Long>(); int i = 0; sizes.add(456l); sizes.add(0l); sizes.add(55556l); for (long size : ds.getDiskDirSizes()) { assertEquals(size, sizes.get(i++).longValue()); } //cleanUpDirs(new File[] { f1, f2, f3 }); s.execute("drop DiskStore testDiskStore2"); }
Example 17
Source File: TSentryPrivilegeMap.java From incubator-sentry with Apache License 2.0 | 4 votes |
public void read(org.apache.thrift.protocol.TProtocol iprot, TSentryPrivilegeMap struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PRIVILEGE_MAP if (schemeField.type == org.apache.thrift.protocol.TType.MAP) { { org.apache.thrift.protocol.TMap _map88 = iprot.readMapBegin(); struct.privilegeMap = new HashMap<String,Set<TSentryPrivilege>>(2*_map88.size); for (int _i89 = 0; _i89 < _map88.size; ++_i89) { String _key90; // required Set<TSentryPrivilege> _val91; // required _key90 = iprot.readString(); { org.apache.thrift.protocol.TSet _set92 = iprot.readSetBegin(); _val91 = new HashSet<TSentryPrivilege>(2*_set92.size); for (int _i93 = 0; _i93 < _set92.size; ++_i93) { TSentryPrivilege _elem94; // required _elem94 = new TSentryPrivilege(); _elem94.read(iprot); _val91.add(_elem94); } iprot.readSetEnd(); } struct.privilegeMap.put(_key90, _val91); } iprot.readMapEnd(); } struct.setPrivilegeMapIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); }
Example 18
Source File: AStar.java From java-algorithms-implementation with Apache License 2.0 | 4 votes |
/** * Find the path using the A* algorithm from start vertex to end vertex or NULL if no path exists. * * @param graph * Graph to search. * @param start * Start vertex. * @param goal * Goal vertex. * * @return * List of Edges to get from start to end or NULL if no path exists. */ public List<Graph.Edge<T>> aStar(Graph<T> graph, Graph.Vertex<T> start, Graph.Vertex<T> goal) { final int size = graph.getVertices().size(); // used to size data structures appropriately final Set<Graph.Vertex<T>> closedSet = new HashSet<Graph.Vertex<T>>(size); // The set of nodes already evaluated. final List<Graph.Vertex<T>> openSet = new ArrayList<Graph.Vertex<T>>(size); // The set of tentative nodes to be evaluated, initially containing the start node openSet.add(start); final Map<Graph.Vertex<T>,Graph.Vertex<T>> cameFrom = new HashMap<Graph.Vertex<T>,Graph.Vertex<T>>(size); // The map of navigated nodes. final Map<Graph.Vertex<T>,Integer> gScore = new HashMap<Graph.Vertex<T>,Integer>(); // Cost from start along best known path. gScore.put(start, 0); // Estimated total cost from start to goal through y. final Map<Graph.Vertex<T>,Integer> fScore = new HashMap<Graph.Vertex<T>,Integer>(); for (Graph.Vertex<T> v : graph.getVertices()) fScore.put(v, Integer.MAX_VALUE); fScore.put(start, heuristicCostEstimate(start,goal)); final Comparator<Graph.Vertex<T>> comparator = new Comparator<Graph.Vertex<T>>() { /** * {@inheritDoc} */ @Override public int compare(Vertex<T> o1, Vertex<T> o2) { if (fScore.get(o1) < fScore.get(o2)) return -1; if (fScore.get(o2) < fScore.get(o1)) return 1; return 0; } }; while (!openSet.isEmpty()) { final Graph.Vertex<T> current = openSet.get(0); if (current.equals(goal)) return reconstructPath(cameFrom, goal); openSet.remove(0); closedSet.add(current); for (Graph.Edge<T> edge : current.getEdges()) { final Graph.Vertex<T> neighbor = edge.getToVertex(); if (closedSet.contains(neighbor)) continue; // Ignore the neighbor which is already evaluated. final int tenativeGScore = gScore.get(current) + distanceBetween(current,neighbor); // length of this path. if (!openSet.contains(neighbor)) openSet.add(neighbor); // Discover a new node else if (tenativeGScore >= gScore.get(neighbor)) continue; // This path is the best until now. Record it! cameFrom.put(neighbor, current); gScore.put(neighbor, tenativeGScore); final int estimatedFScore = gScore.get(neighbor) + heuristicCostEstimate(neighbor, goal); fScore.put(neighbor, estimatedFScore); // fScore has changed, re-sort the list Collections.sort(openSet,comparator); } } return null; }
Example 19
Source File: PRClientServerRegionFunctionExecutionDUnitTest.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
public static void serverBug43430() { Region region = cache.getRegion(PartitionedRegionName); assertNotNull(region); final String testKey = "execKey"; final Set testKeysSet = new HashSet(); testKeysSet.add(testKey); DistributedSystem.setThreadsSocketPolicy(false); Execution dataSet = FunctionService.onRegion(region); region.put(testKey, new Integer(1)); try { cache.getLogger().info("<ExpectedException action=add>" + "Could not create an instance of com.gemstone.gemfire.internal.cache.execute.PRClientServerRegionFunctionExecutionDUnitTest$UnDeserializable" + "</ExpectedException>"); dataSet.withFilter(testKeysSet).withArgs(new UnDeserializable()).execute(new FunctionAdapter(){ @Override public void execute(FunctionContext context) { if (context.getArguments() instanceof String) { context.getResultSender().lastResult( "Success"); } context.getResultSender().lastResult( "Failure"); } @Override public String getId() { return getClass().getName(); } @Override public boolean hasResult() { return true; } }); } catch (Exception expected) { getLogWriter().fine("Exception occured : " + expected.getMessage()); assertTrue(expected.getCause().getMessage().contains( "Could not create an instance of com.gemstone.gemfire.internal.cache.execute.PRClientServerRegionFunctionExecutionDUnitTest$UnDeserializable")); } finally { cache.getLogger().info("<ExpectedException action=remove>" + "Could not create an instance of com.gemstone.gemfire.internal.cache.execute.PRClientServerRegionFunctionExecutionDUnitTest$UnDeserializable" + "</ExpectedException>"); } }
Example 20
Source File: SimpleLoadManagerImplTest.java From pulsar with Apache License 2.0 | 4 votes |
@Test(enabled = false) public void testPrimarySecondary() throws Exception { createNamespacePolicies(pulsar1); LocalZooKeeperCache mockCache = mock(LocalZooKeeperCache.class); ZooKeeperChildrenCache zooKeeperChildrenCache = mock(ZooKeeperChildrenCache.class); Set<String> activeBrokers = Sets.newHashSet("prod2-broker7.messaging.use.example.com:8080", "prod2-broker8.messaging.use.example.com:8080", "prod2-broker9.messaging.use.example.com:8080"); when(mockCache.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)).thenReturn(activeBrokers); when(zooKeeperChildrenCache.get()).thenReturn(activeBrokers); when(zooKeeperChildrenCache.get(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)).thenReturn(activeBrokers); Field zkCacheField = PulsarService.class.getDeclaredField("localZkCache"); zkCacheField.setAccessible(true); LocalZooKeeperCache originalLZK1 = (LocalZooKeeperCache) zkCacheField.get(pulsar1); LocalZooKeeperCache originalLZK2 = (LocalZooKeeperCache) zkCacheField.get(pulsar2); log.info("lzk are {} 2: {}", originalLZK1.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT), originalLZK2.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)); zkCacheField.set(pulsar1, mockCache); LocalZooKeeperCache newZk = (LocalZooKeeperCache) pulsar1.getLocalZkCache(); log.info("lzk mocked are {}", newZk.getChildren(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)); ZooKeeperChildrenCache availableActiveBrokers = new ZooKeeperChildrenCache(pulsar1.getLocalZkCache(), SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT); log.info("lzk mocked active brokers are {}", availableActiveBrokers.get(SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT)); LoadManager loadManager = new SimpleLoadManagerImpl(pulsar1); PulsarResourceDescription rd = new PulsarResourceDescription(); rd.put("memory", new ResourceUsage(1024, 4096)); rd.put("cpu", new ResourceUsage(10, 100)); rd.put("bandwidthIn", new ResourceUsage(250 * 1024, 1024 * 1024)); rd.put("bandwidthOut", new ResourceUsage(550 * 1024, 1024 * 1024)); ResourceUnit ru1 = new SimpleResourceUnit("http://prod2-broker7.messaging.usw.example.com:8080", rd); Set<ResourceUnit> rus = new HashSet<ResourceUnit>(); rus.add(ru1); LoadRanker lr = new ResourceAvailabilityRanker(); AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRankingsInstance = new AtomicReference<>(Maps.newTreeMap()); sortedRankingsInstance.get().put(lr.getRank(rd), rus); Field sortedRankings = SimpleLoadManagerImpl.class.getDeclaredField("sortedRankings"); sortedRankings.setAccessible(true); sortedRankings.set(loadManager, sortedRankingsInstance); ResourceUnit found = ((SimpleLoadManagerImpl) loadManager) .getLeastLoaded(NamespaceName.get("pulsar/use/primary-ns.10")).get(); assertEquals(found.getResourceId(), ru1.getResourceId()); zkCacheField.set(pulsar1, originalLZK1); }