List of usage examples for com.google.common.collect ImmutableList isEmpty
boolean isEmpty();
From source file:com.google.caliper.runner.options.ParsedOptions.java
@Leftovers private void setLeftovers(ImmutableList<String> leftovers) throws InvalidCommandException { if (requireBenchmarkClassName) { if (leftovers.isEmpty()) { throw new InvalidCommandException("No benchmark class specified"); }/* www. j a v a 2s . co m*/ if (leftovers.size() > 1) { throw new InvalidCommandException("Extra stuff, expected only class name: " + leftovers); } this.benchmarkClassName = leftovers.get(0); } else { if (!leftovers.isEmpty()) { throw new InvalidCommandException("Extra stuff, did not expect non-option arguments: " + leftovers); } } }
From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java
public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext, final ModelSchemaCache cache) { ModelType<R> type = extractionContext.getType(); Class<? super R> clazz = type.getRawClass(); if (clazz.isAnnotationPresent(Managed.class)) { validateType(type, extractionContext); Iterable<Method> methods = Arrays.asList(clazz.getMethods()); if (!clazz.isInterface()) { methods = filterIgnoredMethods(methods); }//from w ww . j a v a 2s . c o m ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods, new Function<Method, String>() { public String apply(Method method) { return method.getName(); } }); ensureNoOverloadedMethods(extractionContext, methodsByName); List<ModelProperty<?>> properties = Lists.newLinkedList(); List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length); ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering(); for (String methodName : methodsByName.keySet()) { if (methodName.startsWith("get") && !methodName.equals("get")) { ImmutableList<Method> getterMethods = methodsByName.get(methodName); // The overload check earlier verified that all methods for are equivalent for our purposes // So, taking the first one with the most specialized return type is fine. Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods); boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers()); if (sampleMethod.getParameterTypes().length != 0) { throw invalidMethod(extractionContext, "getter methods cannot take parameters", sampleMethod); } Character getterPropertyNameFirstChar = methodName.charAt(3); if (!Character.isUpperCase(getterPropertyNameFirstChar)) { throw invalidMethod(extractionContext, "the 4th character of the getter method name must be an uppercase character", sampleMethod); } ModelType<?> returnType = ModelType.returnType(sampleMethod); String propertyNameCapitalized = methodName.substring(3); String propertyName = StringUtils.uncapitalize(propertyNameCapitalized); String setterName = "set" + propertyNameCapitalized; ImmutableList<Method> setterMethods = methodsByName.get(setterName); boolean isWritable = !setterMethods.isEmpty(); if (isWritable) { Method setter = setterMethods.get(0); if (!abstractGetter) { throw invalidMethod(extractionContext, "setters are not allowed for non-abstract getters", setter); } validateSetter(extractionContext, returnType, setter); handled.addAll(setterMethods); } if (abstractGetter) { ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() { public ModelType<?> apply(Method input) { return ModelType.of(input.getDeclaringClass()); } })); boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() { public boolean apply(Method input) { return input.getAnnotation(Unmanaged.class) != null; } }); properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses, unmanaged)); } handled.addAll(getterMethods); } } Iterable<Method> notHandled = Iterables.filter(methodsByName.values(), Predicates.not(Predicates.in(handled))); // TODO - should call out valid getters without setters if (!Iterables.isEmpty(notHandled)) { throw invalidMethods(extractionContext, "only paired getter/setter methods are supported", notHandled); } Class<R> concreteClass = type.getConcreteClass(); Class<? extends R> implClass = classGenerator.generate(concreteClass); final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass); extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() { @Override public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) { ensureCanBeInstantiated(extractionContext, schema); } }); Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties, new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() { public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) { return toPropertyExtractionContext(extractionContext, property, cache); } }); return new ModelSchemaExtractionResult<R>(schema, propertyDependencies); } else { return null; } }
From source file:org.apache.flink.table.plan.rules.logical.FlinkFilterJoinRule.java
protected void perform(RelOptRuleCall call, Filter filter, Join join) { final List<RexNode> joinFilters = RelOptUtil.conjunctions(join.getCondition()); final List<RexNode> origJoinFilters = com.google.common.collect.ImmutableList.copyOf(joinFilters); // If there is only the joinRel, // make sure it does not match a cartesian product joinRel // (with "true" condition), otherwise this rule will be applied // again on the new cartesian product joinRel. if (filter == null && joinFilters.isEmpty()) { return;/*from w ww . j a va2s .c o m*/ } final List<RexNode> aboveFilters = filter != null ? conjunctions(filter.getCondition()) : new ArrayList<>(); final com.google.common.collect.ImmutableList<RexNode> origAboveFilters = com.google.common.collect.ImmutableList .copyOf(aboveFilters); // Simplify Outer Joins JoinRelType joinType = join.getJoinType(); if (smart && !origAboveFilters.isEmpty() && join.getJoinType() != JoinRelType.INNER) { joinType = FlinkRelOptUtil.simplifyJoin(join, origAboveFilters, joinType); } final List<RexNode> leftFilters = new ArrayList<>(); final List<RexNode> rightFilters = new ArrayList<>(); // TODO - add logic to derive additional filters. E.g., from // (t1.a = 1 AND t2.a = 2) OR (t1.b = 3 AND t2.b = 4), you can // derive table filters: // (t1.a = 1 OR t1.b = 3) // (t2.a = 2 OR t2.b = 4) // Try to push down above filters. These are typically where clause // filters. They can be pushed down if they are not on the NULL // generating side. boolean filterPushed = false; if (FlinkRelOptUtil.classifyFilters(join, aboveFilters, joinType, !(join instanceof EquiJoin), !joinType.generatesNullsOnLeft(), !joinType.generatesNullsOnRight(), joinFilters, leftFilters, rightFilters)) { filterPushed = true; } // Move join filters up if needed validateJoinFilters(aboveFilters, joinFilters, join, joinType); // If no filter got pushed after validate, reset filterPushed flag if (leftFilters.isEmpty() && rightFilters.isEmpty() && joinFilters.size() == origJoinFilters.size()) { if (com.google.common.collect.Sets.newHashSet(joinFilters) .equals(com.google.common.collect.Sets.newHashSet(origJoinFilters))) { filterPushed = false; } } boolean isAntiJoin = joinType == JoinRelType.ANTI; // Try to push down filters in ON clause. A ON clause filter can only be // pushed down if it does not affect the non-matching set, i.e. it is // not on the side which is preserved. // A ON clause filter of anti-join can not be pushed down. if (!isAntiJoin && FlinkRelOptUtil.classifyFilters(join, joinFilters, joinType, false, !joinType.generatesNullsOnRight(), !joinType.generatesNullsOnLeft(), joinFilters, leftFilters, rightFilters)) { filterPushed = true; } // if nothing actually got pushed and there is nothing leftover, // then this rule is a no-op if ((!filterPushed && joinType == join.getJoinType()) || (joinFilters.isEmpty() && leftFilters.isEmpty() && rightFilters.isEmpty())) { return; } // create Filters on top of the children if any filters were // pushed to them final RexBuilder rexBuilder = join.getCluster().getRexBuilder(); final RelBuilder relBuilder = call.builder(); final RelNode leftRel = relBuilder.push(join.getLeft()).filter(leftFilters).build(); final RelNode rightRel = relBuilder.push(join.getRight()).filter(rightFilters).build(); // create the new join node referencing the new children and // containing its new join filters (if there are any) final com.google.common.collect.ImmutableList<RelDataType> fieldTypes = com.google.common.collect.ImmutableList .<RelDataType>builder().addAll(RelOptUtil.getFieldTypeList(leftRel.getRowType())) .addAll(RelOptUtil.getFieldTypeList(rightRel.getRowType())).build(); final RexNode joinFilter = RexUtil.composeConjunction(rexBuilder, RexUtil.fixUp(rexBuilder, joinFilters, fieldTypes)); // If nothing actually got pushed and there is nothing leftover, // then this rule is a no-op if (joinFilter.isAlwaysTrue() && leftFilters.isEmpty() && rightFilters.isEmpty() && joinType == join.getJoinType()) { return; } RelNode newJoinRel = join.copy(join.getTraitSet(), joinFilter, leftRel, rightRel, joinType, join.isSemiJoinDone()); call.getPlanner().onCopy(join, newJoinRel); if (!leftFilters.isEmpty()) { call.getPlanner().onCopy(filter, leftRel); } if (!rightFilters.isEmpty()) { call.getPlanner().onCopy(filter, rightRel); } relBuilder.push(newJoinRel); // Create a project on top of the join if some of the columns have become // NOT NULL due to the join-type getting stricter. relBuilder.convert(join.getRowType(), false); // create a FilterRel on top of the join if needed relBuilder.filter(RexUtil.fixUp(rexBuilder, aboveFilters, RelOptUtil.getFieldTypeList(relBuilder.peek().getRowType()))); call.transformTo(relBuilder.build()); }
From source file:net.sourceforge.jwbf.mediawiki.actions.queries.BacklinkTitles.java
private RequestBuilder newRequestBuilder(String title, RedirectFilter redirectFilter, ImmutableList<Integer> namespaces) { RequestBuilder builder = new ApiRequestBuilder() // .action("query") // .paramNewContinue(bot.getVersion()) // .formatXml() // .param("list", "backlinks") // .param("bllimit", backlinksPerRequestLimit) // .param("bltitle", MediaWiki.urlEncode(title)) // .param("blfilterredir", MediaWiki.urlEncode(redirectFilter.toString())); if (!namespaces.isEmpty()) { builder.param("blnamespace", MediaWiki.urlEncode(MWAction.createNsString(namespaces))); }/*from www . jav a 2s. c o m*/ return builder; }
From source file:com.google.devtools.build.lib.rules.android.AndroidBinary.java
/** * Applies the proguard specifications, and creates a ProguardedJar. Proguard's output artifacts * are added to the given {@code filesBuilder}. *//*ww w . j a va2 s .c om*/ private static ProguardOutput applyProguard(RuleContext ruleContext, AndroidCommon common, JavaSemantics javaSemantics, Artifact deployJarArtifact, NestedSetBuilder<Artifact> filesBuilder, ImmutableList<Artifact> proguardSpecs, Artifact proguardMapping) throws InterruptedException { Artifact proguardOutputJar = ruleContext .getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_BINARY_PROGUARD_JAR); // Proguard will be only used for binaries which specify a proguard_spec if (proguardSpecs.isEmpty()) { // Although normally the Proguard jar artifact is not needed for binaries which do not specify // proguard_specs, targets which use a select to provide an empty list to proguard_specs will // still have a Proguard jar implicit output, as it is impossible to tell what a select will // produce at the time of implicit output determination. As a result, this artifact must // always be created. return createEmptyProguardAction(ruleContext, javaSemantics, proguardOutputJar, deployJarArtifact); } AndroidSdkProvider sdk = AndroidSdkProvider.fromRuleContext(ruleContext); NestedSet<Artifact> libraryJars = NestedSetBuilder.<Artifact>naiveLinkOrder().add(sdk.getAndroidJar()) .addTransitive(common.getTransitiveNeverLinkLibraries()).build(); Artifact proguardSeeds = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_PROGUARD_SEEDS); Artifact proguardUsage = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_PROGUARD_USAGE); ProguardOutput result = ProguardHelper.createProguardAction(ruleContext, sdk.getProguard(), deployJarArtifact, proguardSpecs, proguardSeeds, proguardUsage, proguardMapping, libraryJars, proguardOutputJar, javaSemantics, getProguardOptimizationPasses(ruleContext)); // Since Proguard is being run, add its output artifacts to the given filesBuilder result.addAllToSet(filesBuilder); return result; }
From source file:com.google.errorprone.bugpatterns.LambdaFunctionalInterface.java
/** * Identifies methods with parameters that have a generic argument with Int, Long, or Double. If * pre-conditions are met, it refactors them to the primitive specializations. * * <pre>PreConditions:/*from w w w . j a v a 2 s . c om*/ * (1): The method declaration has to be private (to do a safe refactoring) * (2): Its parameters have to meet the following conditions: * 2.1 Contain type java.util.function.Function * 2.2 At least one argument type of the Function must be subtype of Number * (3): All its invocations in the top-level enclosing class have to meet the following * conditions as well: * 3.1: lambda argument of Kind.LAMBDA_EXPRESSION * 3.2: same as 2.1 * 3.3: same as 2.2 * </pre> * * <pre> * Refactoring Changes for matched methods: * (1) Add the imports * (2) Change the method signature to use utility function instead of Function * (3) Find and change the 'apply' calls to the corresponding applyAsT * </pre> */ @Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol methodSym = ASTHelpers.getSymbol(tree); // precondition (1) if (!methodSym.getModifiers().contains(Modifier.PRIVATE)) { return Description.NO_MATCH; } ImmutableList<Tree> params = tree.getParameters().stream().filter(param -> hasFunctionAsArg(param, state)) .filter(param -> isFunctionArgSubtypeOf(param, 0, state.getTypeFromString(JAVA_LANG_NUMBER), state) || isFunctionArgSubtypeOf(param, 1, state.getTypeFromString(JAVA_LANG_NUMBER), state)) .collect(toImmutableList()); // preconditions (2) and (3) if (params.isEmpty() || !methodCallsMeetConditions(methodSym, state)) { return Description.NO_MATCH; } SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); for (Tree param : params) { getMappingForFunctionFromTree(param).ifPresent(mappedFunction -> { fixBuilder.addImport(getImportName(mappedFunction)); fixBuilder.replace(param, getFunctionName(mappedFunction) + " " + ASTHelpers.getSymbol(param).name); refactorInternalApplyMethods(tree, fixBuilder, param, mappedFunction); }); } return describeMatch(tree, fixBuilder.build()); }
From source file:com.google.jimfs.FileTree.java
@Nullable private DirectoryEntry lookUp(File dir, JimfsPath path, Set<? super LinkOption> options, int linkDepth) throws IOException { ImmutableList<Name> names = path.names(); if (path.isAbsolute()) { // look up the root directory DirectoryEntry entry = getRoot(path.root()); if (entry == null) { // root not found; always return null as no real parent directory exists // this prevents new roots from being created in file systems supporting multiple roots return null; } else if (names.isEmpty()) { // root found, no more names to look up return entry; } else {/* w w w. j a v a 2s . co m*/ // root found, more names to look up; set dir to the root directory for the path dir = entry.file(); } } else if (isEmpty(names)) { // set names to the canonical list of names for an empty path (singleton list of ".") names = EMPTY_PATH_NAMES; } return lookUp(dir, names, options, linkDepth); }
From source file:org.elasticsearch.action.admin.cluster.snapshots.status.TransportSnapshotsStatusAction.java
private SnapshotsStatusResponse buildResponse(SnapshotsStatusRequest request, ImmutableList<SnapshotMetaData.Entry> currentSnapshots, TransportNodesSnapshotsStatus.NodesSnapshotStatus nodeSnapshotStatuses) { // First process snapshot that are currently processed ImmutableList.Builder<SnapshotStatus> builder = ImmutableList.builder(); Set<SnapshotId> currentSnapshotIds = newHashSet(); if (!currentSnapshots.isEmpty()) { Map<String, TransportNodesSnapshotsStatus.NodeSnapshotStatus> nodeSnapshotStatusMap; if (nodeSnapshotStatuses != null) { nodeSnapshotStatusMap = nodeSnapshotStatuses.getNodesMap(); } else {//from w w w . j a v a 2 s . com nodeSnapshotStatusMap = newHashMap(); } for (SnapshotMetaData.Entry entry : currentSnapshots) { currentSnapshotIds.add(entry.snapshotId()); ImmutableList.Builder<SnapshotIndexShardStatus> shardStatusBuilder = ImmutableList.builder(); for (ImmutableMap.Entry<ShardId, SnapshotMetaData.ShardSnapshotStatus> shardEntry : entry.shards() .entrySet()) { SnapshotMetaData.ShardSnapshotStatus status = shardEntry.getValue(); if (status.nodeId() != null) { // We should have information about this shard from the shard: TransportNodesSnapshotsStatus.NodeSnapshotStatus nodeStatus = nodeSnapshotStatusMap .get(status.nodeId()); if (nodeStatus != null) { ImmutableMap<ShardId, SnapshotIndexShardStatus> shardStatues = nodeStatus.status() .get(entry.snapshotId()); if (shardStatues != null) { SnapshotIndexShardStatus shardStatus = shardStatues.get(shardEntry.getKey()); if (shardStatus != null) { // We have full information about this shard shardStatusBuilder.add(shardStatus); continue; } } } } final SnapshotIndexShardStage stage; switch (shardEntry.getValue().state()) { case FAILED: case ABORTED: case MISSING: stage = SnapshotIndexShardStage.FAILURE; break; case INIT: case WAITING: case STARTED: stage = SnapshotIndexShardStage.STARTED; break; case SUCCESS: stage = SnapshotIndexShardStage.DONE; break; default: throw new ElasticsearchIllegalArgumentException( "Unknown snapshot state " + shardEntry.getValue().state()); } SnapshotIndexShardStatus shardStatus = new SnapshotIndexShardStatus( shardEntry.getKey().getIndex(), shardEntry.getKey().getId(), stage); shardStatusBuilder.add(shardStatus); } builder.add(new SnapshotStatus(entry.snapshotId(), entry.state(), shardStatusBuilder.build())); } } // Now add snapshots on disk that are not currently running if (Strings.hasText(request.repository())) { if (request.snapshots() != null && request.snapshots().length > 0) { for (String snapshotName : request.snapshots()) { SnapshotId snapshotId = new SnapshotId(request.repository(), snapshotName); if (currentSnapshotIds.contains(snapshotId)) { // This is a snapshot the is currently running - skipping continue; } Snapshot snapshot = snapshotsService.snapshot(snapshotId); ImmutableList.Builder<SnapshotIndexShardStatus> shardStatusBuilder = ImmutableList.builder(); if (snapshot.state().completed()) { ImmutableMap<ShardId, IndexShardSnapshotStatus> shardStatues = snapshotsService .snapshotShards(snapshotId); for (ImmutableMap.Entry<ShardId, IndexShardSnapshotStatus> shardStatus : shardStatues .entrySet()) { shardStatusBuilder.add( new SnapshotIndexShardStatus(shardStatus.getKey(), shardStatus.getValue())); } final SnapshotMetaData.State state; switch (snapshot.state()) { case FAILED: state = SnapshotMetaData.State.FAILED; break; case SUCCESS: case PARTIAL: // Translating both PARTIAL and SUCCESS to SUCCESS for now // TODO: add the differentiation on the metadata level in the next major release state = SnapshotMetaData.State.SUCCESS; break; default: throw new ElasticsearchIllegalArgumentException( "Unknown snapshot state " + snapshot.state()); } builder.add(new SnapshotStatus(snapshotId, state, shardStatusBuilder.build())); } } } } return new SnapshotsStatusResponse(builder.build()); }
From source file:ru.org.linux.topic.TopicController.java
private ModelAndView jumpMessage(HttpServletRequest request, int msgid, int cid, boolean skipDeleted) throws Exception { Template tmpl = Template.getTemplate(request); Topic topic = messageDao.getById(msgid); CommentList comments = commentService.getCommentList(topic, false); CommentNode node = comments.getNode(cid); if (node == null && skipDeleted) { ImmutableList<Comment> list = comments.getList(); if (list.isEmpty()) { return new ModelAndView(new RedirectView(topic.getLink())); }/*from ww w . j a v a2 s. com*/ Comment c = list.stream().filter(v -> v.getId() > cid).findFirst().orElse(list.get(list.size() - 1)); node = comments.getNode(c.getId()); } boolean deleted = false; if (node == null && tmpl.isModeratorSession()) { comments = commentService.getCommentList(topic, true); node = comments.getNode(cid); deleted = true; } if (node == null) { throw new MessageNotFoundException(topic, cid, " #" + cid + " ??"); } int pagenum = deleted ? 0 : comments.getCommentPage(node.getComment(), tmpl.getProf()); TopicLinkBuilder redirectUrl = TopicLinkBuilder.pageLink(topic, pagenum) .lastmod(tmpl.getProf().getMessages()).comment(node.getComment().getId()); if (deleted) { redirectUrl = redirectUrl.showDeleted(); } if (tmpl.isSessionAuthorized() && !deleted) { Set<Integer> ignoreList = ignoreListDao.get(tmpl.getCurrentUser()); Set<Integer> hideSet = commentService.makeHideSet(comments, getDefaultFilter(tmpl.getProf(), ignoreList.isEmpty()), ignoreList); if (hideSet.contains(node.getComment().getId())) { redirectUrl = redirectUrl.filter(CommentFilter.FILTER_NONE); } } return new ModelAndView(new RedirectView(redirectUrl.build())); }
From source file:com.intelligentsia.dowsers.entity.view.View.java
/** * Build a new instance of View.java./*from w w w .j a va 2 s .c o m*/ * * @param name * @param processor * @param entities * @throws NullPointerException * if one of parameters is null * @throws IllegalArgumentException * if entities is empty */ public View(final String name, final Processor processor, final Splitter splitter, final ImmutableList<Reference> entities, final ViewStore viewStore) throws NullPointerException, IllegalArgumentException { super(); this.name = Preconditions.checkNotNull(name); this.processor = Preconditions.checkNotNull(processor); this.splitter = splitter; this.entities = Preconditions.checkNotNull(entities); Preconditions.checkArgument(!entities.isEmpty()); this.viewStore = Preconditions.checkNotNull(viewStore); }