List of usage examples for com.google.common.collect ImmutableMap values
public ImmutableCollection<V> values()
From source file:io.druid.indexing.overlord.setup.EqualDistributionWorkerSelectStrategy.java
@Override public Optional<ImmutableZkWorker> findWorkerForTask(RemoteTaskRunnerConfig config, ImmutableMap<String, ImmutableZkWorker> zkWorkers, Task task) { final TreeSet<ImmutableZkWorker> sortedWorkers = Sets.newTreeSet(new Comparator<ImmutableZkWorker>() { @Override/* w ww . j av a 2 s. c o m*/ public int compare(ImmutableZkWorker zkWorker, ImmutableZkWorker zkWorker2) { return -Ints.compare(zkWorker2.getCurrCapacityUsed(), zkWorker.getCurrCapacityUsed()); } }); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableZkWorker zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }
From source file:dagger.internal.codegen.SimpleMethodBindingExpression.java
@Override Expression getDependencyExpression(ClassName requestingClass) { ImmutableMap<DependencyRequest, Expression> arguments = ImmutableMap.copyOf(Maps .asMap(provisionBinding.dependencies(), request -> dependencyArgument(request, requestingClass))); Function<DependencyRequest, CodeBlock> argumentsFunction = request -> arguments.get(request).codeBlock(); return requiresInjectionMethod(provisionBinding, arguments.values().asList(), compilerOptions, requestingClass.packageName(), types) ? invokeInjectionMethod(argumentsFunction, requestingClass) : invokeMethod(argumentsFunction, requestingClass); }
From source file:google.registry.xml.XmlTransformer.java
/** * Create a new XmlTransformer that validates using the given schemas and marshals to and from * classes generated off of those schemas. * * @param schemaNamesToFilenames map of schema names to filenames, immutable because ordering is * significant and ImmutableMap preserves insertion order. The filenames are relative to * this package.//from ww w.j ava 2s . c om */ public XmlTransformer(Package pakkage, ImmutableMap<String, String> schemaNamesToFilenames) { try { this.jaxbContext = initJaxbContext(pakkage, schemaNamesToFilenames.keySet()); this.schema = loadXmlSchemas(ImmutableList.copyOf(schemaNamesToFilenames.values())); } catch (JAXBException e) { throw new RuntimeException(e); } }
From source file:paperparcel.PaperParcelWriter.java
private FieldSpec creator(ClassName className) { UniqueNameSet readNames = new UniqueNameSet(); ClassName creator = ClassName.get("android.os", "Parcelable", "Creator"); TypeName creatorOfClass = ParameterizedTypeName.get(creator, className); ParameterSpec in = ParameterSpec.builder(PARCEL, readNames.getUniqueName("in")).build(); MethodSpec.Builder createFromParcel = MethodSpec.methodBuilder("createFromParcel") .addAnnotation(Override.class).addModifiers(PUBLIC).returns(className).addParameter(in); if (descriptor.isSingleton()) { createFromParcel.addStatement("return $T.INSTANCE", className); } else {//from ww w . j a va 2 s.c om // Read the fields from the parcel ImmutableMap<String, FieldSpec> fieldMap = readFields(in, readNames); for (FieldSpec field : fieldMap.values()) { createFromParcel.addStatement("$T $N = $L", field.type, field.name, field.initializer); } // Re-construct the model and return FieldSpec model = initModel(className, readNames, fieldMap); createFromParcel.addStatement("$T $N = $L", model.type, model.name, model.initializer) .addCode(setFields(model, fieldMap)).addStatement("return $N", model.name); } MethodSpec.Builder newArray = MethodSpec.methodBuilder("newArray").addAnnotation(Override.class) .addModifiers(PUBLIC).addParameter(int.class, "size").returns(ArrayTypeName.of(className)) .addStatement("return new $T[size]", className); TypeSpec initializer = TypeSpec.anonymousClassBuilder("").addSuperinterface(creatorOfClass) .addMethod(createFromParcel.build()).addMethod(newArray.build()).build(); return FieldSpec.builder(creatorOfClass, "CREATOR", STATIC, FINAL).initializer("$L", initializer) .addAnnotation(NonNull.class).build(); }
From source file:com.google.idea.blaze.java.libraries.JarCache.java
private void refresh(@Nullable BlazeContext context, boolean removeMissingFiles) { if (!enabled || sourceFileToCacheKey == null) { return;/*from w w w. j a va 2 s. c o m*/ } // Ensure the cache dir exists if (!cacheDir.exists()) { if (!cacheDir.mkdirs()) { LOG.error("Could not create jar cache directory"); return; } } // Discover state of source jars ImmutableMap<File, Long> sourceFileTimestamps = FileDiffer.readFileState(sourceFileToCacheKey.keySet()); if (sourceFileTimestamps == null) { return; } ImmutableMap.Builder<String, Long> sourceFileCacheKeyToTimestamp = ImmutableMap.builder(); for (Map.Entry<File, Long> entry : sourceFileTimestamps.entrySet()) { String cacheKey = sourceFileToCacheKey.get(entry.getKey()); sourceFileCacheKeyToTimestamp.put(cacheKey, entry.getValue()); } // Discover current on-disk cache state File[] cacheFiles = cacheDir.listFiles(); assert cacheFiles != null; ImmutableMap<File, Long> cacheFileTimestamps = FileDiffer.readFileState(Lists.newArrayList(cacheFiles)); if (cacheFileTimestamps == null) { return; } ImmutableMap.Builder<String, Long> cachedFileCacheKeyToTimestamp = ImmutableMap.builder(); for (Map.Entry<File, Long> entry : cacheFileTimestamps.entrySet()) { String cacheKey = entry.getKey().getName(); // Cache key == file name cachedFileCacheKeyToTimestamp.put(cacheKey, entry.getValue()); } List<String> updatedFiles = Lists.newArrayList(); List<String> removedFiles = Lists.newArrayList(); FileDiffer.diffState(cachedFileCacheKeyToTimestamp.build(), sourceFileCacheKeyToTimestamp.build(), updatedFiles, removedFiles); ListeningExecutorService executor = FetchExecutor.EXECUTOR; List<ListenableFuture<?>> futures = Lists.newArrayList(); Map<String, File> cacheKeyToSourceFile = sourceFileToCacheKey.inverse(); for (String cacheKey : updatedFiles) { File sourceFile = cacheKeyToSourceFile.get(cacheKey); File cacheFile = cacheFileForKey(cacheKey); futures.add(executor.submit(() -> { try { Files.copy(Paths.get(sourceFile.getPath()), Paths.get(cacheFile.getPath()), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } catch (IOException e) { LOG.warn(e); } })); } if (removeMissingFiles) { for (String cacheKey : removedFiles) { File cacheFile = cacheFileForKey(cacheKey); futures.add(executor.submit(() -> { try { Files.deleteIfExists(Paths.get(cacheFile.getPath())); } catch (IOException e) { LOG.warn(e); } })); } } try { Futures.allAsList(futures).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.warn(e); } catch (ExecutionException e) { LOG.error(e); } if (context != null && updatedFiles.size() > 0) { context.output(PrintOutput.log(String.format("Copied %d jars", updatedFiles.size()))); } if (context != null && removedFiles.size() > 0 && removeMissingFiles) { context.output(PrintOutput.log(String.format("Removed %d jars", removedFiles.size()))); } if (context != null) { try { File[] finalCacheFiles = cacheDir.listFiles(); assert finalCacheFiles != null; ImmutableMap<File, Long> cacheFileSizes = FileSizeScanner .readFilesizes(Lists.newArrayList(finalCacheFiles)); Long total = cacheFileSizes.values().stream().reduce((size1, size2) -> size1 + size2).orElse(0L); context.output(PrintOutput.log(String.format("Total Jar Cache size: %d kB (%d files)", total / 1024, finalCacheFiles.length))); } catch (Exception e) { LOG.warn("Could not determine cache size", e); } } }
From source file:com.opengamma.strata.pricer.swaption.HullWhiteSwaptionPhysicalProductPricer.java
/** * Calculates the present value sensitivity of the swaption product. * <p>/* w w w. ja v a 2 s . co m*/ * The present value sensitivity of the product is the sensitivity of the present value to * the underlying curves. * * @param swaption the product * @param ratesProvider the rates provider * @param hwProvider the Hull-White model parameter provider * @return the point sensitivity to the rate curves */ public PointSensitivityBuilder presentValueSensitivityRates(ResolvedSwaption swaption, RatesProvider ratesProvider, HullWhiteOneFactorPiecewiseConstantParametersProvider hwProvider) { validate(swaption, ratesProvider, hwProvider); ResolvedSwap swap = swaption.getUnderlying(); LocalDate expiryDate = swaption.getExpiryDate(); if (expiryDate.isBefore(ratesProvider.getValuationDate())) { // Option has expired already return PointSensitivityBuilder.none(); } ImmutableMap<Payment, PointSensitivityBuilder> cashFlowEquivSensi = CashFlowEquivalentCalculator .cashFlowEquivalentAndSensitivitySwap(swap, ratesProvider); ImmutableList<Payment> list = cashFlowEquivSensi.keySet().asList(); ImmutableList<PointSensitivityBuilder> listSensi = cashFlowEquivSensi.values().asList(); int nPayments = list.size(); double[] alpha = new double[nPayments]; double[] discountedCashFlow = new double[nPayments]; for (int loopcf = 0; loopcf < nPayments; loopcf++) { Payment payment = list.get(loopcf); alpha[loopcf] = hwProvider.alpha(ratesProvider.getValuationDate(), expiryDate, expiryDate, payment.getDate()); discountedCashFlow[loopcf] = paymentPricer.presentValueAmount(payment, ratesProvider); } double omega = (swap.getLegs(SwapLegType.FIXED).get(0).getPayReceive().isPay() ? -1d : 1d); double kappa = computeKappa(hwProvider, discountedCashFlow, alpha, omega); PointSensitivityBuilder point = PointSensitivityBuilder.none(); for (int loopcf = 0; loopcf < nPayments; loopcf++) { Payment payment = list.get(loopcf); double cdf = NORMAL.getCDF(omega * (kappa + alpha[loopcf])); point = point .combinedWith(paymentPricer.presentValueSensitivity(payment, ratesProvider).multipliedBy(cdf)); if (!listSensi.get(loopcf).equals(PointSensitivityBuilder.none())) { point = point.combinedWith(listSensi.get(loopcf).multipliedBy( cdf * ratesProvider.discountFactor(payment.getCurrency(), payment.getDate()))); } } return swaption.getLongShort().isLong() ? point : point.multipliedBy(-1d); }
From source file:com.lyndir.lhunath.snaplog.model.service.impl.AWSSourceServiceImpl.java
@Override public void loadMedia(final SSecurityToken token, final S3Source source) throws PermissionDeniedException { checkNotNull(source, "Given source must not be null."); securityService.assertAccess(Permission.ADMINISTER, token, source); // Fetch objects at all qualities from S3 Map<String, Map<Quality, S3Object>> mediaObjects = Maps.newHashMap(); for (final Quality quality : Quality.values()) { for (final S3Object s3Object : awsService.listObjects(getObjectKey(source, quality))) { if (!s3Object.getKey().endsWith(".jpg")) // Ignore files that don't have a valid media name. continue; String mediaName = Iterables.getLast(Splitter.on('/').split(s3Object.getKey())); if (mediaName.startsWith(".")) // Ignore hidden files. continue; Map<Quality, S3Object> qualityObjects = mediaObjects.get(mediaName); if (qualityObjects == null) mediaObjects.put(mediaName, qualityObjects = Maps.newHashMap()); qualityObjects.put(quality, s3Object); }/*w ww. j a v a2 s.com*/ } // Find all existing media that is not contained in the set of media fetched from S3 // These are media that have been removed from S3 since the last sync; purge them. logger.dbg("Looking for media to purge..."); ImmutableMap.Builder<String, Media> existingMediaBuilder = ImmutableMap.builder(); for (final Media media : mediaDAO.listMedia(source, true)) existingMediaBuilder.put(media.getName(), media); ImmutableMap<String, Media> existingMedia = existingMediaBuilder.build(); Set<Media> purgeMedia = Sets.newHashSet(existingMedia.values()); for (final String mediaName : mediaObjects.keySet()) { Media media = existingMedia.get(mediaName); if (media != null) // This media was found in S3's list of current media data; don't purge it. purgeMedia.remove(media); } logger.dbg("Purging %d / %d media from db", purgeMedia.size(), existingMedia.size()); mediaDAO.delete(purgeMedia); int o = 0; for (final Map.Entry<String, Map<Quality, S3Object>> mediaObjectsEntry : mediaObjects.entrySet()) { if (o++ % 100 == 0) logger.dbg("Loading media %d / %d", ++o, mediaObjects.size()); String mediaName = mediaObjectsEntry.getKey(); Map<Quality, S3Object> qualityObjects = mediaObjectsEntry.getValue(); S3Media media = mediaDAO.findMedia(source, mediaName); if (media == null) media = new S3Media(source, mediaName); // Create/update mediaData for the object. for (final Map.Entry<Quality, S3Object> qualityObjectsEntry : qualityObjects.entrySet()) { Quality quality = qualityObjectsEntry.getKey(); S3Object mediaObject = qualityObjectsEntry.getValue(); setMediaData(media, quality, mediaObject); } } }
From source file:com.googlesource.gerrit.plugins.uploadvalidator.BlockedKeywordValidator.java
@Override public List<CommitValidationMessage> onCommitReceived(CommitReceivedEvent receiveEvent) throws CommitValidationException { try {/*from ww w. ja v a2 s. c o m*/ PluginConfig cfg = cfgFactory.getFromProjectConfigWithInheritance(receiveEvent.project.getNameKey(), pluginName); if (isActive(cfg) && validatorConfig.isEnabledForRef(receiveEvent.user, receiveEvent.getProjectNameKey(), receiveEvent.getRefName(), KEY_CHECK_BLOCKED_KEYWORD)) { ImmutableMap<String, Pattern> blockedKeywordPatterns = patternCache .getAll(Arrays.asList(cfg.getStringList(KEY_CHECK_BLOCKED_KEYWORD_PATTERN))); try (Repository repo = repoManager.openRepository(receiveEvent.project.getNameKey())) { List<CommitValidationMessage> messages = performValidation(repo, receiveEvent.commit, receiveEvent.revWalk, blockedKeywordPatterns.values(), cfg); if (!messages.isEmpty()) { throw new CommitValidationException("includes files containing blocked keywords", messages); } } } } catch (NoSuchProjectException | IOException | ExecutionException e) { throw new CommitValidationException("failed to check on blocked keywords", e); } return Collections.emptyList(); }
From source file:dagger2.internal.codegen.FactoryGenerator.java
@Override ImmutableSet<JavaWriter> write(ClassName generatedTypeName, ProvisionBinding binding) { // We don't want to write out resolved bindings -- we want to write out the generic version. checkState(!binding.hasNonDefaultTypeParameters()); TypeMirror keyType = binding.provisionType().equals(Type.MAP) ? Util.getProvidedValueTypeOfMap(MoreTypes.asDeclared(binding.key().type())) : binding.key().type();/*www . java 2 s . c o m*/ TypeName providedTypeName = TypeNames.forTypeMirror(keyType); JavaWriter writer = JavaWriter.inPackage(generatedTypeName.packageName()); final TypeWriter factoryWriter; final Optional<ConstructorWriter> constructorWriter; List<TypeVariableName> typeParameters = Lists.newArrayList(); for (TypeParameterElement typeParameter : binding.bindingTypeElement().getTypeParameters()) { typeParameters.add(TypeVariableName.fromTypeParameterElement(typeParameter)); } switch (binding.factoryCreationStrategy()) { case ENUM_INSTANCE: EnumWriter enumWriter = writer.addEnum(generatedTypeName.simpleName()); enumWriter.addConstant("INSTANCE"); constructorWriter = Optional.absent(); factoryWriter = enumWriter; // If we have type parameters, then remove the parameters from our providedTypeName, // since we'll be implementing an erased version of it. if (!typeParameters.isEmpty()) { factoryWriter.annotate(SuppressWarnings.class).setValue("rawtypes"); providedTypeName = ((ParameterizedTypeName) providedTypeName).type(); } break; case CLASS_CONSTRUCTOR: ClassWriter classWriter = writer.addClass(generatedTypeName.simpleName()); classWriter.addTypeParameters(typeParameters); classWriter.addModifiers(FINAL); constructorWriter = Optional.of(classWriter.addConstructor()); constructorWriter.get().addModifiers(PUBLIC); factoryWriter = classWriter; if (binding.bindingKind().equals(PROVISION) && !binding.bindingElement().getModifiers().contains(STATIC)) { TypeName enclosingType = TypeNames.forTypeMirror(binding.bindingTypeElement().asType()); factoryWriter.addField(enclosingType, "module").addModifiers(PRIVATE, FINAL); constructorWriter.get().addParameter(enclosingType, "module"); constructorWriter.get().body().addSnippet("assert module != null;") .addSnippet("this.module = module;"); } break; default: throw new AssertionError(); } factoryWriter.annotate(Generated.class).setValue(ComponentProcessor.class.getName()); factoryWriter.addModifiers(PUBLIC); factoryWriter.addImplementedType( ParameterizedTypeName.create(ClassName.fromClass(Factory.class), providedTypeName)); MethodWriter getMethodWriter = factoryWriter.addMethod(providedTypeName, "get"); getMethodWriter.annotate(Override.class); getMethodWriter.addModifiers(PUBLIC); if (binding.memberInjectionRequest().isPresent()) { ParameterizedTypeName membersInjectorType = ParameterizedTypeName.create(MembersInjector.class, providedTypeName); factoryWriter.addField(membersInjectorType, "membersInjector").addModifiers(PRIVATE, FINAL); constructorWriter.get().addParameter(membersInjectorType, "membersInjector"); constructorWriter.get().body().addSnippet("assert membersInjector != null;") .addSnippet("this.membersInjector = membersInjector;"); } ImmutableMap<BindingKey, FrameworkField> fields = SourceFiles .generateBindingFieldsForDependencies(dependencyRequestMapper, binding.dependencies()); for (FrameworkField bindingField : fields.values()) { TypeName fieldType = bindingField.frameworkType(); FieldWriter field = factoryWriter.addField(fieldType, bindingField.name()); field.addModifiers(PRIVATE, FINAL); constructorWriter.get().addParameter(field.type(), field.name()); constructorWriter.get().body().addSnippet("assert %s != null;", field.name()) .addSnippet("this.%1$s = %1$s;", field.name()); } // If constructing a factory for @Inject or @Provides bindings, we use a static create method // so that generated components can avoid having to refer to the generic types // of the factory. (Otherwise they may have visibility problems referring to the types.) switch (binding.bindingKind()) { case INJECTION: case PROVISION: // The return type is usually the same as the implementing type, except in the case // of enums with type variables (where we cast). TypeName returnType = ParameterizedTypeName.create(ClassName.fromClass(Factory.class), TypeNames.forTypeMirror(keyType)); MethodWriter createMethodWriter = factoryWriter.addMethod(returnType, "create"); createMethodWriter.addTypeParameters(typeParameters); createMethodWriter.addModifiers(Modifier.PUBLIC, Modifier.STATIC); Map<String, TypeName> params = constructorWriter.isPresent() ? constructorWriter.get().parameters() : ImmutableMap.<String, TypeName>of(); for (Map.Entry<String, TypeName> param : params.entrySet()) { createMethodWriter.addParameter(param.getValue(), param.getKey()); } switch (binding.factoryCreationStrategy()) { case ENUM_INSTANCE: if (typeParameters.isEmpty()) { createMethodWriter.body().addSnippet("return INSTANCE;"); } else { // We use an unsafe cast here because the types are different. // It's safe because the type is never referenced anywhere. createMethodWriter.annotate(SuppressWarnings.class).setValue("unchecked"); createMethodWriter.body().addSnippet("return (Factory) INSTANCE;"); } break; case CLASS_CONSTRUCTOR: createMethodWriter.body().addSnippet("return new %s(%s);", parameterizedFactoryNameForProvisionBinding(binding), Joiner.on(", ").join(params.keySet())); break; default: throw new AssertionError(); } break; default: // do nothing. } List<Snippet> parameters = Lists.newArrayList(); for (DependencyRequest dependency : binding.dependencies()) { parameters.add(frameworkTypeUsageStatement(Snippet.format(fields.get(dependency.bindingKey()).name()), dependency.kind())); } Snippet parametersSnippet = makeParametersSnippet(parameters); if (binding.bindingKind().equals(PROVISION)) { Snippet providesMethodInvocation = Snippet.format("%s.%s(%s)", binding.bindingElement().getModifiers().contains(STATIC) ? ClassName.fromTypeElement(binding.bindingTypeElement()) : "module", binding.bindingElement().getSimpleName(), parametersSnippet); if (binding.provisionType().equals(SET)) { TypeName paramTypeName = TypeNames .forTypeMirror(MoreTypes.asDeclared(keyType).getTypeArguments().get(0)); // TODO(cgruber): only be explicit with the parameter if paramType contains wildcards. getMethodWriter.body().addSnippet("return %s.<%s>singleton(%s);", ClassName.fromClass(Collections.class), paramTypeName, providesMethodInvocation); } else if (binding.nullableType().isPresent() || nullableValidationType.equals(Diagnostic.Kind.WARNING)) { if (binding.nullableType().isPresent()) { getMethodWriter.annotate((ClassName) TypeNames.forTypeMirror(binding.nullableType().get())); } getMethodWriter.body().addSnippet("return %s;", providesMethodInvocation); } else { StringLiteral failMsg = StringLiteral .forValue(CANNOT_RETURN_NULL_FROM_NON_NULLABLE_PROVIDES_METHOD); getMethodWriter.body() .addSnippet(Snippet.format( Joiner.on('\n').join("%s provided = %s;", "if (provided == null) {", " throw new NullPointerException(%s);", "}", "return provided;"), getMethodWriter.returnType(), providesMethodInvocation, failMsg)); } } else if (binding.memberInjectionRequest().isPresent()) { getMethodWriter.body().addSnippet("%1$s instance = new %1$s(%2$s);", providedTypeName, parametersSnippet); getMethodWriter.body().addSnippet("membersInjector.injectMembers(instance);"); getMethodWriter.body().addSnippet("return instance;"); } else { getMethodWriter.body().addSnippet("return new %s(%s);", providedTypeName, parametersSnippet); } // TODO(gak): write a sensible toString return ImmutableSet.of(writer); }
From source file:com.google.devtools.build.android.PlaceholderIdFieldInitializerBuilder.java
private Map<String, FieldInitializer> getStyleableInitializers(Map<String, Integer> attrAssignments, Collection<String> styleableFields) throws AttrLookupException { ImmutableMap.Builder<String, FieldInitializer> initList = ImmutableMap.builder(); for (String field : styleableFields) { Set<String> attrs = styleableAttrs.get(field).keySet(); ImmutableMap.Builder<String, Integer> arrayInitValues = ImmutableMap.builder(); for (String attr : attrs) { Integer attrId = attrAssignments.get(attr); if (attrId == null) { // It should be a framework resource, otherwise we don't know about the resource. if (!attr.startsWith(NORMALIZED_ANDROID_PREFIX)) { throw new AttrLookupException("App attribute not found: " + attr); }/*from w w w .j a va 2s . c om*/ String attrWithoutPrefix = attr.substring(NORMALIZED_ANDROID_PREFIX.length()); attrId = androidIdProvider.getAttrId(attrWithoutPrefix); } arrayInitValues.put(attr, attrId); } // The styleable array should be sorted by ID value. // Make sure that if we have android: framework attributes, their IDs are listed first. ImmutableMap<String, Integer> arrayInitMap = arrayInitValues .orderEntriesByValue(Ordering.<Integer>natural()).build(); initList.put(field, IntArrayFieldInitializer.of(arrayInitMap.values())); int index = 0; for (String attr : arrayInitMap.keySet()) { initList.put(field + "_" + attr, IntFieldInitializer.of(index)); ++index; } } return initList.build(); }