List of usage examples for java.util Collections newSetFromMap
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map)
From source file:de.unentscheidbar.csv2.CaseInsensitiveBenchmark.java
static Collection<String> getLotsOfColumnNames() { Random rnd = new Random(0); Set<String> names = Collections.newSetFromMap(new CaseInsensitiveMap<String, Boolean>()); while (names.size() < 100) { names.add(randomString(rnd, 1 + rnd.nextInt(30))); }// w ww. jav a2s . c o m List<String> uniqueNames = new ArrayList<>(names); /* For predictable iteration order: */ Collections.sort(uniqueNames); Collections.shuffle(uniqueNames, rnd); return Collections.unmodifiableList(uniqueNames); }
From source file:com.bzcentre.dapiPush.DapiReceiver.java
public DapiReceiver() { try {/*from w w w. j a va2 s .c o m*/ fcmProxy = FcmProxy.prepareClient(); dbconn = connectMySql(); stmt = dbconn.createStatement(); BLKCheck = dbconn.createStatement(); serverSentEventSubscribers = Collections.newSetFromMap(new ConcurrentHashMap<>()); NginxClojureRT.getAppEventListenerManager().addListener(this); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e1) { NginxClojureRT.log.info(TAG + "Database connecting failed..." + e1.getMessage()); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.apache.bookkeeper.metadata.etcd.Etcd64bitIdGeneratorTest.java
/** * Test generating id in parallel and ensure there is no duplicated id. */// w ww .j a v a 2s. com @Test public void testGenerateIdParallel() throws Exception { final int numThreads = 10; @Cleanup("shutdown") ExecutorService executor = Executors.newFixedThreadPool(numThreads); final int numIds = 10000; final AtomicLong totalIds = new AtomicLong(numIds); final Set<Long> ids = Collections.newSetFromMap(new ConcurrentHashMap<>()); final RateLimiter limiter = RateLimiter.create(1000); final CompletableFuture<Void> doneFuture = new CompletableFuture<>(); for (int i = 0; i < numThreads; i++) { executor.submit(() -> { Client client = Client.builder().endpoints(etcdContainer.getClientEndpoint()).build(); Etcd64bitIdGenerator gen = new Etcd64bitIdGenerator(client.getKVClient(), scope); AtomicBoolean running = new AtomicBoolean(true); while (running.get()) { limiter.acquire(); GenericCallbackFuture<Long> genFuture = new GenericCallbackFuture<>(); gen.generateLedgerId(genFuture); genFuture.thenAccept(lid -> { boolean duplicatedFound = !(ids.add(lid)); if (duplicatedFound) { running.set(false); doneFuture.completeExceptionally( new IllegalStateException("Duplicated id " + lid + " generated : " + ids)); return; } else { if (totalIds.decrementAndGet() <= 0) { running.set(false); doneFuture.complete(null); } } }).exceptionally(cause -> { running.set(false); doneFuture.completeExceptionally(cause); return null; }); } }); } FutureUtils.result(doneFuture); assertTrue(totalIds.get() <= 0); assertTrue(ids.size() >= numIds); }
From source file:org.amplafi.hivemind.factory.servicessetter.ServicesSetterImpl.java
/** * @see com.sworddance.core.ServicesSetter#wire(java.lang.Object, java.lang.Iterable) *///from w w w . j ava 2 s . c o m @Override @SuppressWarnings("unchecked") public void wire(Object obj, Iterable<String> excludedProperties) { if (obj == null) { return; } List<String> props = getWriteableProperties(obj); Set<String> alwaysExcludedCollection = this.cachedAlwaysExcludedMap.get(obj.getClass()); if (alwaysExcludedCollection != null) { props.removeAll(alwaysExcludedCollection); if (getLog().isDebugEnabled()) { getLog().debug(obj.getClass() + ": autowiring. Class has already been filtered down to " + props.size() + "properties. props={" + join(props, ",") + "}"); } } else { if (getLog().isDebugEnabled()) { getLog().debug(obj.getClass() + ": autowiring for the first time. Class has at most " + props.size() + "properties. props={" + join(props, ",") + "}"); } alwaysExcludedCollection = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); this.cachedAlwaysExcludedMap.putIfAbsent(obj.getClass(), alwaysExcludedCollection); alwaysExcludedCollection = this.cachedAlwaysExcludedMap.get(obj.getClass()); } for (String exclude : excludedProperties) { props.remove(exclude); } int wiredCount = 0; for (String prop : props) { PropertyAdaptor type = getPropertyAdaptor(obj, prop); Class propertyType = type.getPropertyType(); if (!isWireableClass(propertyType)) { // if it is a standard java class then lets exclude it. alwaysExcludedCollection.add(prop); continue; } // if it is not readable then, then we can't verify that // we are not overwriting non-null property. if (!type.isReadable() || !type.isWritable()) { alwaysExcludedCollection.add(prop); continue; } // check to see if we have a service to offer before bothering // to checking if the property can be set. This avoids triggering // actions caused by calling the get/setters. Object srv = null; if (type.getPropertyType() == Log.class) { // log is special. srv = LogFactory.getLog(obj.getClass()); } else { ConcurrentMap<String, String> classServiceMap = this.serviceMap.get(obj.getClass()); if (classServiceMap == null) { this.serviceMap.putIfAbsent(obj.getClass(), new ConcurrentHashMap<String, String>()); classServiceMap = this.serviceMap.get(obj.getClass()); } String serviceName = classServiceMap.get(prop); if (serviceName == null) { InjectService service; try { service = findInjectService(obj, type); } catch (DontInjectException e) { // do nothing alwaysExcludedCollection.add(prop); continue; } if (service != null) { serviceName = service.value(); if (isNotBlank(serviceName)) { for (String attempt : new String[] { serviceName, serviceName + '.' + type.getPropertyName(), serviceName + '.' + StringUtils.capitalize(type.getPropertyName()) }) { srv = getService(attempt, propertyType); if (srv != null) { serviceName = attempt; break; } } } } if (srv != null) { classServiceMap.putIfAbsent(prop, serviceName); } else { // we looked but did not find... no need to look again. classServiceMap.putIfAbsent(prop, ""); } } else if (!serviceName.isEmpty()) { // we already found the service. srv = getService(serviceName, propertyType); } if (srv == null && !noServiceForType.containsKey(propertyType)) { try { srv = this.module.getService(propertyType); } catch (Exception e) { noServiceForType.put(propertyType, e); getLog().debug("Look up of class " + propertyType + " failed. The failure is caused if there is not exactly 1 service implementing the class. Further searches by this property class will be ignored."); } } } if (srv == null) { alwaysExcludedCollection.add(prop); } else if (type.read(obj) == null) { // Doing the read check last avoids // triggering problems caused by lazy initialization and read-only properties. if (type.getPropertyType().isAssignableFrom(srv.getClass())) { type.write(obj, srv); wiredCount++; } else { // this is probably an error so we do not just add to the exclude list. throw new ApplicationRuntimeException("Trying to set property " + obj.getClass() + "." + prop + " however, the property type=" + type.getPropertyType() + " is not a superclass or same class as " + srv.getClass() + ". srv=" + srv); } } } if (getLog().isDebugEnabled()) { getLog().debug(obj.getClass() + ": done autowiring. actual number of properties wired=" + wiredCount + " excluded properties=" + alwaysExcludedCollection); } }
From source file:com.chinaftw.music.model.MusicProvider.java
public MusicProvider() { mMusicListByGenre = new ConcurrentHashMap<>(); mMusicListById = new ConcurrentHashMap<>(); mFavoriteTracks = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); }
From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.dependency.DependencyQueueTaskDispatcher.java
/** * Constructor use by default constructor and for unit tests. * * @param gerritHandler the handler//from w w w . j av a2s . c om */ DependencyQueueTaskDispatcher(GerritHandler gerritHandler) { this.currentlyTriggeringEvents = Collections .newSetFromMap(new ConcurrentHashMap<GerritTriggeredEvent, Boolean>()); if (gerritHandler == null) { logger.error("Gerrit Handler was not available to construct DependencyQueueTaskDispatcher"); } else { gerritHandler.addListener(this); } logger.debug("Registered to gerrit events"); }
From source file:com.buaa.cfs.security.Groups.java
public Groups(Configuration conf, final Timer timer) { impl = ReflectionUtils.newInstance(conf.getClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, ShellBasedUnixGroupsMapping.class, GroupMappingServiceProvider.class), conf); cacheTimeout = conf.getLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS_DEFAULT) * 1000; negativeCacheTimeout = conf.getLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS_DEFAULT) * 1000; warningDeltaMs = conf.getLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_WARN_AFTER_MS, CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_WARN_AFTER_MS_DEFAULT); parseStaticMapping(conf);/*from w w w . j a v a2s. c om*/ this.timer = timer; this.cache = CacheBuilder.newBuilder().refreshAfterWrite(cacheTimeout, TimeUnit.MILLISECONDS) .ticker(new TimerToTickerAdapter(timer)).expireAfterWrite(10 * cacheTimeout, TimeUnit.MILLISECONDS) .build(new GroupCacheLoader()); if (negativeCacheTimeout > 0) { Cache<String, Boolean> tempMap = CacheBuilder.newBuilder() .expireAfterWrite(negativeCacheTimeout, TimeUnit.MILLISECONDS) .ticker(new TimerToTickerAdapter(timer)).build(); negativeCache = Collections.newSetFromMap(tempMap.asMap()); } if (LOG.isDebugEnabled()) LOG.debug("Group mapping impl=" + impl.getClass().getName() + "; cacheTimeout=" + cacheTimeout + "; warningDeltaMs=" + warningDeltaMs); }
From source file:org.apache.hadoop.hbase.client.transactional.TransactionState.java
public TransactionState(final long transactionId) { this.transactionId = transactionId; setStatus(TransState.STATE_ACTIVE); countLock = new Object(); commitSendLock = new Object(); requestPendingCount = 0;/* w w w . j a va 2 s .c o m*/ requestReceivedCount = 0; commitSendDone = false; hasError = false; ddlTrans = false; if (getCHMVariable) { String concurrentHM = System.getenv("DTM_USE_CONCURRENTHM"); if (concurrentHM != null) { useConcurrentHM = (Integer.parseInt(concurrentHM) == 0) ? false : true; } if (LOG.isTraceEnabled()) { if (useConcurrentHM) { LOG.trace("Using ConcurrentHashMap synchronization to synchronize participatingRegions"); } else { LOG.trace("Using synchronizedSet to synchronize participatingRegions"); } } getCHMVariable = false; } if (useConcurrentHM) { participatingRegions = Collections .newSetFromMap((new ConcurrentHashMap<TransactionRegionLocation, Boolean>())); } else { participatingRegions = Collections.synchronizedSet(new HashSet<TransactionRegionLocation>()); } String localTxns = System.getenv("DTM_LOCAL_TRANSACTIONS"); if (localTxns != null) { localTransaction = (Integer.parseInt(localTxns) == 0) ? false : true; //System.out.println("TS begin local txn id " + transactionId); if (LOG.isTraceEnabled()) LOG.trace("TransactionState local transaction begun: " + transactionId); } else { localTransaction = false; if (LOG.isTraceEnabled()) LOG.trace("TransactionState global transaction begun: " + transactionId); } }
From source file:org.apache.hive.ptest.execution.PTest.java
public PTest(final TestConfiguration configuration, final ExecutionContext executionContext, final String buildTag, final File logDir, final LocalCommandFactory localCommandFactory, final SSHCommandExecutor sshCommandExecutor, final RSyncCommandExecutor rsyncCommandExecutor, final Logger logger) throws Exception { mConfiguration = configuration;//from w w w .j a v a 2s. co m mLogger = logger; mBuildTag = buildTag; mExecutedTests = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); mFailedTests = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); mAddedTests = new HashSet<String>(); mExecutionContext = executionContext; mSshCommandExecutor = sshCommandExecutor; mRsyncCommandExecutor = rsyncCommandExecutor; mExecutor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool( new ThreadFactoryBuilder().setDaemon(true).setNameFormat("HostExecutor %d").build())); final File failedLogDir = Dirs.create(new File(logDir, "failed")); final File succeededLogDir = Dirs.create(new File(logDir, "succeeded")); final File scratchDir = Dirs.createEmpty(new File(mExecutionContext.getLocalWorkingDirectory(), "scratch")); File patchDir = Dirs.createEmpty(new File(logDir, "patches")); File patchFile = null; if (!configuration.getPatch().isEmpty()) { patchFile = new File(patchDir, buildTag + ".patch"); Files.write(Resources.toByteArray(new URL(configuration.getPatch())), patchFile); } ImmutableMap.Builder<String, String> templateDefaultsBuilder = ImmutableMap.builder(); templateDefaultsBuilder.put("repository", configuration.getRepository()) .put("repositoryName", configuration.getRepositoryName()) .put("repositoryType", configuration.getRepositoryType()) .put("buildTool", configuration.getBuildTool()).put("branch", configuration.getBranch()) .put("clearLibraryCache", String.valueOf(configuration.isClearLibraryCache())) .put("workingDir", mExecutionContext.getLocalWorkingDirectory()).put("buildTag", buildTag) .put("logDir", logDir.getAbsolutePath()).put("javaHome", configuration.getJavaHome()) .put("javaHomeForTests", configuration.getJavaHomeForTests()) .put("antEnvOpts", configuration.getAntEnvOpts()).put("antArgs", configuration.getAntArgs()) .put("antTestArgs", configuration.getAntTestArgs()) .put("antTestTarget", configuration.getAntTestTarget()) .put("mavenEnvOpts", configuration.getMavenEnvOpts()).put("mavenArgs", configuration.getMavenArgs()) .put("mavenBuildArgs", configuration.getMavenBuildArgs()) .put("mavenTestArgs", configuration.getMavenTestArgs()); if (!Strings.isNullOrEmpty(configuration.getAdditionalProfiles())) { templateDefaultsBuilder.put("additionalProfiles", configuration.getAdditionalProfiles()); } templateDefaults = templateDefaultsBuilder.build(); TestParser testParser = new TestParser(configuration.getContext(), new AtomicInteger(1), configuration.getTestCasePropertyName(), new File(mExecutionContext.getLocalWorkingDirectory(), configuration.getRepositoryName() + "-source"), logger); HostExecutorBuilder hostExecutorBuilder = new HostExecutorBuilder() { @Override public HostExecutor build(Host host) { return new HostExecutor(host, executionContext.getPrivateKey(), mExecutor, sshCommandExecutor, rsyncCommandExecutor, templateDefaults, scratchDir, succeededLogDir, failedLogDir, 10, configuration.shouldFetchLogsForSuccessfulTests(), logger); } }; List<HostExecutor> hostExecutors = new ArrayList<HostExecutor>(); for (Host host : mExecutionContext.getHosts()) { hostExecutors.add(hostExecutorBuilder.build(host)); } mHostExecutors = new CopyOnWriteArrayList<HostExecutor>(hostExecutors); mPhases = Lists.newArrayList(); mPhases.add(new TestCheckPhase(mHostExecutors, localCommandFactory, templateDefaults, patchFile, logger, mAddedTests)); mPhases.add(new PrepPhase(mHostExecutors, localCommandFactory, templateDefaults, scratchDir, patchFile, logger)); mPhases.add(new ExecutionPhase(mHostExecutors, mExecutionContext, hostExecutorBuilder, localCommandFactory, templateDefaults, succeededLogDir, failedLogDir, testParser.parse(), mExecutedTests, mFailedTests, logger)); mPhases.add(new ReportingPhase(mHostExecutors, localCommandFactory, templateDefaults, logger)); }
From source file:com.whitecloud.ron.musicplayer.model.MusicProvider.java
public MusicProvider() { mMusicListByGenre = new ConcurrentHashMap<>(); mMusicListById = new ConcurrentHashMap<>(); mMusicSourceList = new ConcurrentHashMap<>(); mFavoriteTracks = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); SpotifyApi api = new SpotifyApi(); spotify = api.getService();/*from ww w. ja v a2 s. c om*/ mArtists = new ArrayList<>(); mSongs = new ArrayList<>(); }