List of usage examples for com.google.common.collect ImmutableSet size
int size();
From source file:org.elasticsearch.indices.InternalIndicesService.java
@Override protected void doStop() throws ElasticsearchException { ImmutableSet<String> indices = ImmutableSet.copyOf(this.indices.keySet()); final CountDownLatch latch = new CountDownLatch(indices.size()); final ExecutorService indicesStopExecutor = Executors.newFixedThreadPool(5, EsExecutors.daemonThreadFactory("indices_shutdown")); final ExecutorService shardsStopExecutor = Executors.newFixedThreadPool(5, EsExecutors.daemonThreadFactory("shards_shutdown")); for (final String index : indices) { indicesStopExecutor.execute(new Runnable() { @Override//from ww w . ja va 2 s. co m public void run() { try { removeIndex(index, "shutdown", shardsStopExecutor); } catch (Throwable e) { logger.warn("failed to delete index on stop [" + index + "]", e); } finally { latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { // ignore } finally { shardsStopExecutor.shutdown(); indicesStopExecutor.shutdown(); } }
From source file:dagger.internal.codegen.BindingMethodValidator.java
/** Adds an error if the method has more than one {@linkplain Qualifier qualifier} annotation. */ protected void checkQualifiers(ValidationReport.Builder<ExecutableElement> builder) { ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(builder.getSubject()); if (qualifiers.size() > 1) { for (AnnotationMirror qualifier : qualifiers) { builder.addError(BINDING_METHOD_MULTIPLE_QUALIFIERS, builder.getSubject(), qualifier); }//from w ww . jav a2s . c o m } }
From source file:com.qubole.quark.planner.parser.SqlQueryParser.java
public SqlQueryParserResult parse(String sql) throws SQLException { DataSourceSchema dataSource = this.context.getDefaultDataSource(); final AtomicBoolean foundNonQuarkScan = new AtomicBoolean(false); final ImmutableSet.Builder<DataSourceSchema> dsBuilder = new ImmutableSet.Builder<>(); try {//from w ww .ja v a2 s.co m final SqlKind kind = getSqlParser(sql).parseQuery().getKind(); SqlQueryParserResult result = new SqlQueryParserResult(stripNamespace(sql, dataSource), dataSource, kind, null, false); RelNode relNode = parseInternal(sql); final RelVisitor relVisitor = new RelVisitor() { @Override public void visit(RelNode node, int ordinal, RelNode parent) { if (node instanceof QuarkViewScan) { visitQuarkViewScan((QuarkViewScan) node); } else if (node instanceof QuarkTileScan) { visitQuarkTileScan((QuarkTileScan) node); } else if (node instanceof TableScan) { visitNonQuarkScan((TableScan) node); } super.visit(node, ordinal, parent); } private void visitNonQuarkScan(TableScan node) { foundNonQuarkScan.set(true); final String schemaName = node.getTable().getQualifiedName().get(0); CalciteSchema schema = CalciteSchema.from(getRootSchma()).getSubSchema(schemaName, false); dsBuilder.addAll(getDrivers(schema)); } private void visitQuarkTileScan(QuarkTileScan node) { QuarkTile quarkTile = node.getQuarkTile(); CalciteCatalogReader calciteCatalogReader = new CalciteCatalogReader( CalciteSchema.from(getRootSchma()), false, context.getDefaultSchemaPath(), getTypeFactory()); CalciteSchema tileSchema = calciteCatalogReader.getTable(quarkTile.tableName) .unwrap(CalciteSchema.class); dsBuilder.addAll(getDrivers(tileSchema)); } private void visitQuarkViewScan(QuarkViewScan node) { QuarkTable table = node.getQuarkTable(); if (table instanceof QuarkViewTable) { final CalciteSchema tableSchema = ((QuarkViewTable) table).getBackupTableSchema(); dsBuilder.addAll(getDrivers(tableSchema)); } } private ImmutableSet<DataSourceSchema> getDrivers(CalciteSchema tableSchema) { final ImmutableSet.Builder<DataSourceSchema> dsBuilder = new ImmutableSet.Builder<>(); SchemaPlus tableSchemaPlus = tableSchema.plus(); while (tableSchemaPlus != null) { Schema schema = CalciteSchema.from(tableSchemaPlus).schema; if (schema instanceof DataSourceSchema) { dsBuilder.add((DataSourceSchema) schema); } tableSchemaPlus = tableSchemaPlus.getParentSchema(); } return dsBuilder.build(); } }; relVisitor.go(relNode); ImmutableSet<DataSourceSchema> dataSources = dsBuilder.build(); if (!foundNonQuarkScan.get() && dataSources.size() == 1) { /** * Check if query is completely optimized for a data source */ final DataSourceSchema newDataSource = dataSources.asList().get(0); final SqlDialect dialect = newDataSource.getDataSource().getSqlDialect(); final String parsedSql = getParsedSql(relNode, dialect); result = new SqlQueryParserResult(parsedSql, newDataSource, kind, relNode, true); } else if (foundNonQuarkScan.get() && dataSources.size() == 1) { /** * Check if its not optimized */ final DataSourceSchema newDataSource = dataSources.asList().get(0); final String stripNamespace = stripNamespace(sql, newDataSource); result = new SqlQueryParserResult(stripNamespace, newDataSource, kind, relNode, true); } else if (this.context.isUnitTestMode()) { String parsedSql = getParsedSql(relNode, new SqlDialect(SqlDialect.DatabaseProduct.UNKNOWN, "UNKNOWN", null, true)); result = new SqlQueryParserResult(parsedSql, null, kind, relNode, true); } else if (dataSources.size() > 1) { /** * Check if it's partially optimized, i.e., tablescans of multiple datasources * are found in RelNode. We currently donot support multiple datasources. */ throw new SQLException("Federation between data sources is not allowed", "0A001"); } else if (dataSources.isEmpty()) { throw new SQLException("No dataSource found for query", "3D001"); } return result; } catch (SQLException e) { throw e; } catch (Exception e) { throw new SQLException(e); } }
From source file:org.dcache.webdav.macaroons.MacaroonRequestHandler.java
private MacaroonContext buildContext(String target, Request request) throws ErrorResponseException { MacaroonContext context = new MacaroonContext(); FsPath userRoot = FsPath.ROOT;// w ww . j a v a 2 s.com for (LoginAttribute attr : AuthenticationHandler.getLoginAttributes(request)) { if (attr instanceof HomeDirectory) { context.setHome(FsPath.ROOT.resolve(((HomeDirectory) attr).getHome())); } else if (attr instanceof RootDirectory) { userRoot = FsPath.ROOT.resolve(((RootDirectory) attr).getRoot()); } else if (attr instanceof Expiry) { context.updateExpiry(((Expiry) attr).getExpiry()); } else if (attr instanceof DenyActivityRestriction) { context.removeActivities(((DenyActivityRestriction) attr).getDenied()); } else if (attr instanceof PrefixRestriction) { ImmutableSet<FsPath> paths = ((PrefixRestriction) attr).getPrefixes(); if (target.equals("/")) { checkArgument(paths.size() == 1, "Cannot serialise with multiple path restrictions"); context.setPath(paths.iterator().next()); } else { FsPath desiredPath = _pathMapper.asDcachePath(request, target); if (!paths.stream().anyMatch(desiredPath::hasPrefix)) { throw new ErrorResponseException(SC_BAD_REQUEST, "Bad request path: Desired path not within existing path"); } context.setPath(desiredPath); } } else if (attr instanceof Restriction) { throw new ErrorResponseException(SC_BAD_REQUEST, "Cannot serialise restriction " + attr.getClass().getSimpleName()); } else if (attr instanceof MaxUploadSize) { try { context.updateMaxUpload(((MaxUploadSize) attr).getMaximumSize()); } catch (InvalidCaveatException e) { throw new ErrorResponseException(SC_BAD_REQUEST, "Cannot add max-upload: " + e.getMessage()); } } } Subject subject = getSubject(); context.setUid(Subjects.getUid(subject)); context.setGids(Subjects.getGids(subject)); context.setUsername(Subjects.getUserName(subject)); context.setRoot(_pathMapper.effectiveRoot(userRoot, m -> new ErrorResponseException(SC_BAD_REQUEST, m))); if (!target.equals("/") && !context.getPath().isPresent()) { context.setPath(_pathMapper.asDcachePath(request, target)); } return context; }
From source file:org.waveprotocol.box.server.persistence.migration.DeltaMigrator.java
public void run() { LOG.info("Starting Wave migration from " + sourceStore.getClass().getSimpleName() + " to " + targetStore.getClass().getSimpleName()); long startTime = System.currentTimeMillis(); try {/*from w w w . ja v a2s. c o m*/ ExceptionalIterator<WaveId, PersistenceException> srcItr = sourceStore.getWaveIdIterator(); // Waves while (srcItr.hasNext()) { WaveId waveId = srcItr.next(); ImmutableSet<WaveletId> waveletIds = sourceStore.lookup(waveId); if (!targetStore.lookup(waveId).isEmpty()) { LOG.info("Skipping Wave because it's found in target store : " + waveId.toString()); continue; } LOG.info("Migrating Wave : " + waveId.toString() + " with " + waveletIds.size() + " wavelets"); int waveletsTotal = waveletIds.size(); int waveletsCount = 0; // Wavelets for (WaveletId waveletId : waveletIds) { waveletsCount++; LOG.info("Migrating wavelet " + waveletsCount + "/" + waveletsTotal + " : " + waveletId.toString()); DeltasAccess sourceDeltas = sourceStore.open(WaveletName.of(waveId, waveletId)); DeltasAccess targetDeltas = targetStore.open(WaveletName.of(waveId, waveletId)); // Get all deltas from last version to initial version (0): reverse // order int deltasCount = 0; ArrayList<WaveletDeltaRecord> deltas = new ArrayList<WaveletDeltaRecord>(); HashedVersion deltaResultingVersion = sourceDeltas.getEndVersion(); // Deltas while (deltaResultingVersion != null && deltaResultingVersion.getVersion() != 0) { deltasCount++; WaveletDeltaRecord deltaRecord = sourceDeltas .getDeltaByEndVersion(deltaResultingVersion.getVersion()); deltas.add(deltaRecord); // get the previous delta, this is the appliedAt deltaResultingVersion = deltaRecord.getAppliedAtVersion(); } LOG.info("Appending " + deltasCount + "deltas to target"); targetDeltas.append(deltas); } } // While Waves long endTime = System.currentTimeMillis(); LOG.info("Migration completed. Total time = " + (endTime - startTime) + "ms"); } catch (PersistenceException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.aurora.scheduler.state.SchedulerCoreImpl.java
@Override public void addInstances(final IJobKey jobKey, final ImmutableSet<Integer> instanceIds, final ITaskConfig config) throws ScheduleException { storage.write(new MutateWork.NoResult<ScheduleException>() { @Override//from w w w .ja v a 2 s. c o m protected void execute(MutableStoreProvider storeProvider) throws ScheduleException { validateTaskLimits(config, instanceIds.size()); ImmutableSet<IScheduledTask> tasks = storeProvider.getTaskStore() .fetchTasks(Query.jobScoped(jobKey).active()); Set<Integer> existingInstanceIds = FluentIterable.from(tasks) .transform(Tasks.SCHEDULED_TO_INSTANCE_ID).toSet(); if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) { throw new ScheduleException("Instance ID collision detected."); } stateManager.insertPendingTasks(Maps.asMap(instanceIds, Functions.constant(config))); } }); }
From source file:fr.inria.atlanmod.instantiator.neoEMF.GenericMetamodelConfig.java
@Override public EClass getNextRootEClass(ImmutableSet<EClass> rootEClasses) { if (rootEClasses.size() == 1) return rootEClasses.asList().get(0); IntegerDistribution distribution = distributions.get(rootEClasses); if (distribution == null) { distribution = new UniformIntegerDistribution(0, rootEClasses.size() - 1); distribution.reseedRandomGenerator(random.nextLong()); distributions.put(rootEClasses, distribution); }/* w w w .j a v a2s.c o m*/ return rootEClasses.asList().get(distribution.sample()); }
From source file:dagger.internal.codegen.BindingMethodValidator.java
/** * Adds errors if the method has more than one {@linkplain MultibindingAnnotations multibinding * annotation} or if it has a multibinding annotation and its {@link Provides} or {@link Produces} * annotation has a {@code type} parameter. *///from ww w .jav a2s.c o m protected void checkMultibindings(ValidationReport.Builder<ExecutableElement> builder) { if (!allowsMultibindings.allowsMultibindings()) { return; } ImmutableSet<AnnotationMirror> multibindingAnnotations = MultibindingAnnotations .forMethod(builder.getSubject()); if (multibindingAnnotations.size() > 1) { for (AnnotationMirror annotation : multibindingAnnotations) { builder.addError(formatErrorMessage(MULTIPLE_MULTIBINDING_ANNOTATIONS_ON_METHOD), builder.getSubject(), annotation); } } AnnotationMirror bindingAnnotationMirror = getAnnotationMirror(builder.getSubject(), methodAnnotation) .get(); boolean usesProvidesType = false; for (ExecutableElement member : bindingAnnotationMirror.getElementValues().keySet()) { usesProvidesType |= member.getSimpleName().contentEquals("type"); } if (usesProvidesType && !multibindingAnnotations.isEmpty()) { builder.addError(formatErrorMessage(MULTIBINDING_ANNOTATION_CONFLICTS_WITH_BINDING_ANNOTATION_ENUM), builder.getSubject()); } }
From source file:org.jclouds.ec2.suppliers.DescribeAvailabilityZonesInRegion.java
@Override public Map<String, Supplier<Set<String>>> get() { Builder<String, Set<String>> map = ImmutableMap.builder(); HttpResponseException exception = null; // TODO: this should be parallel for (String region : regions.get()) { try {/*from w w w . ja v a 2 s . c o m*/ ImmutableSet<String> zones = ImmutableSet .copyOf(Iterables.transform(client.describeAvailabilityZonesInRegion(region), new Function<AvailabilityZoneInfo, String>() { @Override public String apply(AvailabilityZoneInfo arg0) { return arg0.getZone(); } })); if (zones.size() > 0) map.put(region, zones); } catch (HttpResponseException e) { // TODO: this should be in retry handler, not here. if (e.getMessage().contains("Unable to tunnel through proxy")) { exception = e; logger.error(e, "Could not describe availability zones in Region: %s", region); } else { throw e; } } } ImmutableMap<String, Set<String>> result = map.build(); if (result.isEmpty() && exception != null) { throw exception; } return Maps.transformValues(result, Suppliers2.<Set<String>>ofInstanceFunction()); }
From source file:com.google.auto.value.processor.BuilderMethodClassifier.java
private void checkForFailedJavaBean(ExecutableElement rejectedSetter) { ImmutableSet<ExecutableElement> allGetters = getterToPropertyName.keySet(); ImmutableSet<ExecutableElement> prefixedGetters = AutoValueProcessor.prefixedGettersIn(allGetters); if (prefixedGetters.size() < allGetters.size() && prefixedGetters.size() >= allGetters.size() / 2) { String note = "This might be because you are using the getFoo() convention" + " for some but not all methods. These methods don't follow the convention: " + Sets.difference(allGetters, prefixedGetters); errorReporter.reportNote(note, rejectedSetter); }/*from w w w . ja v a 2 s. c o m*/ }