java类com.google.common.collect.FluentIterable的实例源码

ElasticMappingSet.java 文件源码 项目:dremio-oss 阅读 28 收藏 0 点赞 0 评论 0
public ElasticIndex filterToType(String name){
  List<ElasticMapping> filtered = new ArrayList<>();
  for(ElasticMapping m : mappings){
    for(String namePiece : name.split(",")){
      if(m.getName().equals(namePiece)){
        filtered.add(m);
      }
    }
  }
  if(filtered.isEmpty()){
    return null;
  }
  return new ElasticIndex(name, ImmutableList.<String>of(), FluentIterable.from(filtered).uniqueIndex(new Function<ElasticMapping, String>(){

    @Override
    public String apply(ElasticMapping input) {
      return input.getName();
    }}));
}
RequestOptionsGenerator.java 文件源码 项目:GitHub 阅读 40 收藏 0 点赞 0 评论 0
private MethodSpec generateRequestOptionOverride(ExecutableElement methodToOverride) {
  return MethodSpec.overriding(methodToOverride)
      .returns(glideOptionsName)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(", glideOptionsName, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
Metaservices.java 文件源码 项目:GitHub 阅读 36 收藏 0 点赞 0 评论 0
private Set<String> useProvidedTypesForServices(TypeElement typeElement, ImmutableList<TypeMirror> typesMirrors) {
  List<String> wrongTypes = Lists.newArrayList();
  List<String> types = Lists.newArrayList();
  for (TypeMirror typeMirror : typesMirrors) {
    if (typeMirror.getKind() != TypeKind.DECLARED
        || !processing().getTypeUtils().isAssignable(typeElement.asType(), typeMirror)) {
      wrongTypes.add(typeMirror.toString());
    } else {
      types.add(typeMirror.toString());
    }
  }

  if (!wrongTypes.isEmpty()) {
    processing().getMessager().printMessage(
        Diagnostic.Kind.ERROR,
        "@Metainf.Service(value = {...}) contains types that are not implemented by "
            + typeElement.getSimpleName()
            + ": " + wrongTypes,
        typeElement,
        AnnotationMirrors.findAnnotation(typeElement.getAnnotationMirrors(), Metainf.Service.class));
  }

  return FluentIterable.from(types).toSet();
}
DefaultRolePermissionService.java 文件源码 项目:apollo-custom 阅读 40 收藏 0 点赞 0 评论 0
/**
 * Create permissions, note that permissionType + targetId should be unique
 */
@Transactional
public Set<Permission> createPermissions(Set<Permission> permissions) {
    Multimap<String, String> targetIdPermissionTypes = HashMultimap.create();
    for (Permission permission : permissions) {
        targetIdPermissionTypes.put(permission.getTargetId(), permission.getPermissionType());
    }

    for (String targetId : targetIdPermissionTypes.keySet()) {
        Collection<String> permissionTypes = targetIdPermissionTypes.get(targetId);
        List<Permission> current =
                permissionRepository.findByPermissionTypeInAndTargetId(permissionTypes, targetId);
        Preconditions.checkState(CollectionUtils.isEmpty(current),
                "Permission with permissionType %s targetId %s already exists!", permissionTypes,
                targetId);
    }

    Iterable<Permission> results = permissionRepository.save(permissions);
    return FluentIterable.from(results).toSet();
}
FilteredDataSetProducerAdapter.java 文件源码 项目:morf 阅读 27 收藏 0 点赞 0 评论 0
/**
 * Create a filtered adapter, passing in the list of tables to include.
 * @param producer The wrapped {@link DataSetProducer}.
 * @param includedTables The tables to include.
 */
public FilteredDataSetProducerAdapter(DataSetProducer producer, Collection<String> includedTables) {
  super(producer);
  final Set<String> includedSet = FluentIterable.from(includedTables)
                                                .transform(new Function<String, String>() {
                                                   @Override
                                                   public String apply(String str) {
                                                     return str.toUpperCase();
                                                   }
                                                 })
                                                .toSet();

  this.includingPredicate = new Predicate<String>() {
    @Override
    public boolean apply(String input) {
      return includedSet.contains(input);
    }
  };
}
TypeToken.java 文件源码 项目:googles-monorepo-demo 阅读 42 收藏 0 点赞 0 评论 0
@Override
protected Set<TypeToken<? super T>> delegate() {
  ImmutableSet<TypeToken<? super T>> result = classes;
  if (result == null) {
    @SuppressWarnings({"unchecked", "rawtypes"})
    ImmutableList<TypeToken<? super T>> collectedTypes =
        (ImmutableList)
            TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
    return (classes =
        FluentIterable.from(collectedTypes)
            .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
            .toSet());
  } else {
    return result;
  }
}
ValidateSystemOutput.java 文件源码 项目:tac-kbp-eal 阅读 42 收藏 0 点赞 0 评论 0
private void assertExactlyTwoSubdirectories(final File outputStoreDir) throws IOException {
  checkArgument(outputStoreDir.isDirectory());
  if (!new File(outputStoreDir, "arguments").isDirectory()) {
    throw new IOException(
        "Expected system output to be contain a subdirectory named 'arguments'");
  }
  if (!new File(outputStoreDir, "linking").isDirectory()) {
    throw new IOException("Expected system output to be contain a subdirectory named 'linking'");
  }
  final ImmutableSet<String> subdirectoryNames =
      FluentIterable.from(ImmutableList.copyOf(outputStoreDir.listFiles()))
          .transform(FileUtils.ToName)
          .toSet();
  final boolean hasValidDirectoryStructure = subdirectoryNames.containsAll(REQUIRED_SUBDIRS)
      && ALLOWED_SUBDIRS.containsAll(subdirectoryNames);

  if (!hasValidDirectoryStructure) {
    throw new IOException(
        "Invalid subdirectories ) " + subdirectoryNames + ". Required are: " + REQUIRED_SUBDIRS
        + "; allowed are " + ALLOWED_SUBDIRS);
  }
}
AccelerationAnalyzer.java 文件源码 项目:dremio-oss 阅读 34 收藏 0 点赞 0 评论 0
protected Iterable<StatColumn> getStatColumnsPerField(final RelDataTypeField field) {
  final RelDataTypeFamily family = field.getType().getFamily();
  final Collection<StatType> dims = DIMENSIONS.get(family);
  if (dims.isEmpty()) {
    return ImmutableList.of();
  }

  return FluentIterable.from(dims)
      .transform(new Function<StatType, StatColumn>() {
        @Nullable
        @Override
        public StatColumn apply(@Nullable final StatType type) {
          return new StatColumn(type, field);
        }
      });
}
Proto.java 文件源码 项目:GitHub 阅读 36 收藏 0 点赞 0 评论 0
@Value.Lazy
List<TypeElement> builderIncludedTypes() {
  Optional<FIncludeMirror> includes = builderInclude();

  ImmutableList<TypeMirror> typeMirrors = includes.isPresent()
      ? ImmutableList.copyOf(includes.get().valueMirror())
      : ImmutableList.<TypeMirror>of();

  FluentIterable<TypeElement> typeElements = FluentIterable.from(typeMirrors)
      .filter(DeclaredType.class)
      .transform(DeclatedTypeToElement.FUNCTION);

  ImmutableSet<String> uniqueTypeNames = typeElements
      .filter(IsPublic.PREDICATE)
      .transform(ElementToName.FUNCTION)
      .toSet();

  if (uniqueTypeNames.size() != typeMirrors.size()) {
    report().annotationNamed(IncludeMirror.simpleName())
        .warning("Some types were ignored, non-supported for inclusion: duplicates,"
            + " non declared reference types, non-public");
  }

  return typeElements.toList();
}
TypeFetchers.java 文件源码 项目:raml-java-tools 阅读 32 收藏 0 点赞 0 评论 0
public static TypeFetcher fromTypes() {

        return new TypeFetcher() {

            // this is technically invalid, as different apis might call.  Won't happen, but could.
            // make better
            Iterable<TypeDeclaration> foundInApi;
            @Override
            public TypeDeclaration fetchType(Api api, final String name) throws GenerationException {

                return FluentIterable.from(Optional.fromNullable(foundInApi).or(api.types()))
                        .firstMatch(namedPredicate(name)).or(fail(name));
            }

        };
    }
FilterToolHelp.java 文件源码 项目:circus-train 阅读 33 收藏 0 点赞 0 评论 0
@Override
public String toString() {
  Iterable<String> errorMessages = FluentIterable.from(errors).transform(OBJECT_ERROR_TO_TABBED_MESSAGE);

  StringBuilder help = new StringBuilder(500)
      .append("Usage: check-filters.sh --config=<config_file>[,<config_file>,...]")
      .append(System.lineSeparator())
      .append("Errors found in the provided configuration file:")
      .append(System.lineSeparator())
      .append(Joiner.on(System.lineSeparator()).join(errorMessages))
      .append(System.lineSeparator())
      .append("Configuration file help:")
      .append(System.lineSeparator())
      .append(TAB)
      .append("For more information and help please refer to ")
      .append(
          "https://stash/projects/HDW/repos/circus-train/circus-train-tool/circus-train-filter-tool/browse/README.md");
  return help.toString();
}
DependencyGraph.java 文件源码 项目:dremio-oss 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Creates a chain executor for the given sub graph of layouts, that last started at the given time, at the given
 * refresh period.
 *
 * @param graph dependency graph
 * @param subGraph sub graph
 * @param startTimeOfLastChain last start time of the chain
 * @param refreshPeriod refresh period
 * @return chain executor
 */
private ChainExecutor createChainExecutor(DirectedGraph<DependencyNode, DefaultEdge> graph,
                                          DirectedGraph<DependencyNode, DefaultEdge> subGraph,
                                          long startTimeOfLastChain, long refreshPeriod, long gracePeriod) {
  final List<Layout> layouts = FluentIterable.from(TopologicalOrderIterator.of(subGraph))
    .transform(new Function<DependencyNode, Layout>() {
      @Override
      public Layout apply(DependencyNode node) {
        return node.getLayout();
      }
    }).toList();

  String uuid = UUID.randomUUID().toString();
  String rootId = layouts.get(0).getId().getId();
  logger.info("Creating chain executor for root node {} with id {}.", rootId, uuid);
  if (logger.isDebugEnabled()) {
    logger.debug("Sub graph for chain executor {}:{} is: {}.", rootId, uuid, layouts.toString());
  }

  return new ChainExecutor(graph, layouts, startTimeOfLastChain, refreshPeriod, gracePeriod, schedulerService,
    materializationContext, accelerationService.getSettings().getLayoutRefreshMaxAttempts(), rootId + ":" + uuid);
}
MoreMapUtils.java 文件源码 项目:circus-train 阅读 47 收藏 0 点赞 0 评论 0
private static <T> List<T> getList(
    Map<?, ?> map,
    Object key,
    List<T> defaultValue,
    Function<Object, T> transformation) {
  Object value = map.get(key);
  if (value == null) {
    return defaultValue;
  }

  if (value instanceof String) {
    value = Splitter.on(',').splitToList(value.toString());
  }

  if (!(value instanceof Collection)) {
    return Collections.singletonList(transformation.apply(value));
  }

  return FluentIterable.from((Collection<?>) value).transform(transformation).toList();
}
ScanCrel.java 文件源码 项目:dremio-oss 阅读 37 收藏 0 点赞 0 评论 0
@Override
public TableScan projectInvisibleColumn(String name) {
  Set<String> names = new HashSet<>();
  names.addAll(FluentIterable.from(projectedColumns).transform(new Function<SchemaPath, String>(){

    @Override
    public String apply(SchemaPath input) {
      return input.getRootSegment().getPath();
    }}).toList());

  if(names.contains(name)){
    // already included.
    return this;
  }
  List<SchemaPath> columns = new ArrayList<>();
  columns.addAll(projectedColumns);
  columns.add(SchemaPath.getSimplePath(name));
  return this.cloneWithProject(columns);
}
TypeToken.java 文件源码 项目:guava-mock 阅读 54 收藏 0 点赞 0 评论 0
@Override
protected Set<TypeToken<? super T>> delegate() {
  ImmutableSet<TypeToken<? super T>> filteredTypes = types;
  if (filteredTypes == null) {
    // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
    @SuppressWarnings({"unchecked", "rawtypes"})
    ImmutableList<TypeToken<? super T>> collectedTypes =
        (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
    return (types =
        FluentIterable.from(collectedTypes)
            .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
            .toSet());
  } else {
    return filteredTypes;
  }
}
InjectingSerializer.java 文件源码 项目:dremio-oss 阅读 39 收藏 0 点赞 0 评论 0
protected CachedField[] transform(final CachedField[] fields) {
  return FluentIterable
      .from(Arrays.asList(fields))
      .transform(new Function<CachedField, CachedField>() {
        @Nullable
        @Override
        public CachedField apply(@Nullable final CachedField field) {
          final CachedField newField = mapping.findInjection(field.getField().getType())
              .transform(new Function<Injection, CachedField>() {
                @Nullable
                @Override
                public CachedField apply(@Nullable final Injection injection) {
                  return new InjectingCachedField(field, injection.getValue());
                }
              })
              .or(field);

          return newField;
        }
      })
      .toArray(CachedField.class);
}
MoreTypes.java 文件源码 项目:android-auto-mapper 阅读 48 收藏 0 点赞 0 评论 0
/**
 * Returns the non-object superclass of the type with the proper type parameters.
 * An absent Optional is returned if there is no non-Object superclass.
 */
public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements,
                                                         DeclaredType type) {
    checkNotNull(types);
    checkNotNull(elements);
    checkNotNull(type);

    final TypeMirror objectType =
            elements.getTypeElement(Object.class.getCanonicalName()).asType();
    // It's guaranteed there's only a single CLASS superclass because java doesn't have multiple
    // class inheritance.
    TypeMirror superclass = getOnlyElement(FluentIterable.from(types.directSupertypes(type))
            .filter(new Predicate<TypeMirror>() {
                @Override
                public boolean apply(TypeMirror input) {
                    return input.getKind().equals(TypeKind.DECLARED)
                            && (MoreElements.asType(
                            MoreTypes.asDeclared(input).asElement())).getKind().equals(ElementKind.CLASS)
                            && !types.isSameType(objectType, input);
                }
            }), null);
    return superclass != null
            ? Optional.of(MoreTypes.asDeclared(superclass))
            : Optional.<DeclaredType>absent();
}
ValidateSystemOutput.java 文件源码 项目:tac-kbp-eal 阅读 40 收藏 0 点赞 0 评论 0
/**
 * Warns about CAS offsets for Responses being inconsistent with actual document text for non-TIME
 * roles
 */
private void warnOnMissingOffsets(final File systemOutputStoreFile, final Symbol docID,
    final ImmutableSet<Response> responses,
    final Map<Symbol, File> docIDMap) throws IOException {
  final String text = Files.asCharSource(docIDMap.get(docID), Charsets.UTF_8).read();
  for (final Response r : FluentIterable.from(responses)
      .filter(Predicates.compose(not(equalTo(TIME)), ResponseFunctions.role()))) {
    final KBPString cas = r.canonicalArgument();
    final String casTextInRaw =
        resolveCharOffsets(cas.charOffsetSpan(), docID, text).replaceAll("\\s+", " ");
    // allow whitespace
    if (!casTextInRaw.contains(cas.string())) {
      log.warn("Warning for {} - response {} CAS does not match text span of {} ",
          systemOutputStoreFile.getAbsolutePath(), renderResponse(r, text), casTextInRaw);
    }
  }
}
SchemaUtilities.java 文件源码 项目:dremio-oss 阅读 31 收藏 0 点赞 0 评论 0
public List<NameAndGranularity> qualifyColumnsWithGranularity(List<NameAndGranularity> strings){
  final RelDataType type = table.getRowType(new JavaTypeFactoryImpl());
  return FluentIterable.from(strings).transform(new Function<NameAndGranularity, NameAndGranularity>(){

    @Override
    public NameAndGranularity apply(NameAndGranularity input) {
      RelDataTypeField field = type.getField(input.getName(), false, false);
      if(field == null){
        throw UserException.validationError()
          .message("Unable to find field %s in table %s. Available fields were: %s.",
              input.getName(),
              SqlUtils.quotedCompound(path),
              FluentIterable.from(type.getFieldNames()).transform(SqlUtils.QUOTER).join(Joiner.on(", "))
            ).build(logger);
      }

      return new NameAndGranularity(field.getName(), input.getGranularity());
    }

  }).toList();

}
DefaultRolePermissionService.java 文件源码 项目:apollo-custom 阅读 43 收藏 0 点赞 0 评论 0
/**
 * Query users with role
 */
public Set<UserInfo> queryUsersWithRole(String roleName) {
    Role role = findRoleByRoleName(roleName);

    if (role == null) {
        return Collections.emptySet();
    }

    List<UserRole> userRoles = userRoleRepository.findByRoleId(role.getId());

    Set<UserInfo> users = FluentIterable.from(userRoles).transform(userRole -> {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userRole.getUserId());
        return userInfo;
    }).toSet();

    return users;
}
AnswerKey.java 文件源码 项目:tac-kbp-eal 阅读 38 收藏 0 点赞 0 评论 0
private void assertNoIncompatibleCorefAnnotations() {
  final ImmutableSet<KBPString> allResponseCASes = FluentIterable
      .from(allResponses())
      .transform(ResponseFunctions.canonicalArgument())
      .toSet();
  checkSetsEqual(corefAnnotation.allCASes(), "CASes in coref annotation",
      allResponseCASes, "CASes in responses");

  // all correctly assessed responses must have coreffed CASes. Coref of others is optional.
  for (final AssessedResponse assessedResponse : annotatedResponses()) {
    if (assessedResponse.assessment().entityCorrectFiller().isPresent()
        && assessedResponse.assessment().entityCorrectFiller().get().isAcceptable()) {
      if (!corefAnnotation.annotatedCASes().contains(
          assessedResponse.response().canonicalArgument()))
      {
        throw new IllegalArgumentException("Coref annotation is missing coref for canonical argument "
        + assessedResponse.response().canonicalArgument() + " for " + assessedResponse);
      }
    }
  }

  // further consistency checking already done within the corefAnnotation object
}
TableDataHomology.java 文件源码 项目:morf 阅读 41 收藏 0 点赞 0 评论 0
/**
 * @return A sorted copy of the Record list
 */
private List<Record> copyAndSort(final Table table, Iterable<Record> records, Comparator<Record> comparator) {
  // we need to transform the records to RecordBeans so we don't re-use the Record
  return FluentIterable.from(records)
      .transform(r -> RecordHelper.copy(r, table.columns()))
      .toSortedList(comparator);
}
TableDataHomology.java 文件源码 项目:morf 阅读 45 收藏 0 点赞 0 评论 0
/**
 * Compare all the records for this table.
 *
 * @param table the active {@link Table}
 * @param records1 the first set of records
 * @param records2 the second set of records
 */
public void compareTable(final Table table, Iterable<Record> records1, Iterable<Record> records2) {

  Iterator<Record> iterator1;
  Iterator<Record> iterator2;

  if (orderComparator == null) {
    // no comparator - just compare the results in the order they arrive.
    iterator1 = records1.iterator();
    iterator2 = records2.iterator();
  } else {
    // There is a comparator. Sort the rows before comparison
    iterator1 = copyAndSort(table, records1, orderComparator).iterator();
    iterator2 = copyAndSort(table, records2, orderComparator).iterator();
  }

  int recordNumber = 0;

  List<Column> primaryKeys = primaryKeysForTable(table);
  List<Column> primaryKeysForComparison = FluentIterable.from(primaryKeys).filter(excludingExcludedColumns()).toList();

  Optional<Record> next1 = optionalNext(iterator1);
  Optional<Record> next2 = optionalNext(iterator2);
  while (moreRecords(table, next1, next2, primaryKeys)) {
    int compareResult = primaryKeysForComparison.isEmpty() ? 0 : compareKeys(next1, next2, primaryKeysForComparison);
    if (compareResult > 0) {
      differences.add(String.format("Table [%s]: Dataset1 is missing %s (Dataset2=%s)", table.getName(), keyColumnsIds(next2.get(), primaryKeysForComparison), RecordHelper.joinRecordValues(table.columns(), next2.get(), ",", "null")));
      next2 = optionalNext(iterator2);
    } else if (compareResult < 0) {
      differences.add(String.format("Table [%s]: Dataset2 is missing %s (Dataset1=%s)", table.getName(), keyColumnsIds(next1.get(), primaryKeysForComparison), RecordHelper.joinRecordValues(table.columns(), next1.get(), ",", "null")));
      next1 = optionalNext(iterator1);
    } else {
      compareRecords(table, recordNumber++, next1.get(), next2.get(), primaryKeys);
      next1 = optionalNext(iterator1);
      next2 = optionalNext(iterator2);
    }
  }
}
AccelerationMapper.java 文件源码 项目:dremio-oss 阅读 39 收藏 0 点赞 0 评论 0
public static AccelerationMapper create(final RowType schema) {
  final Map<String, ViewFieldType> fields = FluentIterable.from(AccelerationUtils.selfOrEmpty(schema.getFieldList()))
      .uniqueIndex(new Function<ViewFieldType, String>() {
        @Nullable
        @Override
        public String apply(@Nullable final ViewFieldType input) {
          return input.getName();
        }
      });

  return new AccelerationMapper(fields);
}
FileOutputDiffListener.java 文件源码 项目:circus-train 阅读 40 收藏 0 点赞 0 评论 0
@Override
public void onChangedPartition(String partitionName, Partition partition, List<Diff<Object, Object>> differences) {
  out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
  out.println("Partition differs: ");
  out.println(partitionName);
  out.print("\t");
  out.println(NEWLINE_TAB_JOINER.join(FluentIterable.from(differences).transform(DIFF_TO_STRING).toList()));
}
RequestManagerGenerator.java 文件源码 项目:GitHub 阅读 50 收藏 0 点赞 0 评论 0
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerMethodOverride(ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  return MethodSpec.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(",
              generatedRequestBuilderOfType, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
RequestBuilderGenerator.java 文件源码 项目:GitHub 阅读 43 收藏 0 点赞 0 评论 0
/**
 * Generates an override of a particular method in {@link com.bumptech.glide.RequestBuilder} that
 * returns {@link com.bumptech.glide.RequestBuilder} so that it returns our generated subclass
 * instead.
 */
private MethodSpec generateRequestBuilderOverride(ExecutableElement methodToOverride) {
  // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  return MethodSpec.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(",
              generatedRequestBuilderOfType, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
RequestBuilderGenerator.java 文件源码 项目:GitHub 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Generates a particular method with  an equivalent name and arguments to the given method
 * from the generated {@link com.bumptech.glide.request.BaseRequestBuilder} subclass.
 */
private MethodSpec generateGeneratedRequestOptionEquivalent(MethodSpec requestOptionMethod) {
  CodeBlock callRequestOptionsMethod = CodeBlock.builder()
      .add(".$N(", requestOptionMethod.name)
      .add(FluentIterable.from(requestOptionMethod.parameters)
          .transform(new Function<ParameterSpec, String>() {
            @Override
            public String apply(ParameterSpec input) {
              return input.name;
            }
          })
          .join(Joiner.on(", ")))
      .add(");\n")
      .build();

  return MethodSpec.methodBuilder(requestOptionMethod.name)
      .addJavadoc(
          processorUtil.generateSeeMethodJavadoc(requestOptionsClassName, requestOptionMethod))
      .addModifiers(Modifier.PUBLIC)
      .addTypeVariables(requestOptionMethod.typeVariables)
      .addParameters(requestOptionMethod.parameters)
      .returns(generatedRequestBuilderOfTranscodeType)
      .beginControlFlow(
          "if (getMutableOptions() instanceof $T)", requestOptionsClassName)
      .addCode("this.requestOptions = (($T) getMutableOptions())",
          requestOptionsClassName)
      .addCode(callRequestOptionsMethod)
      .nextControlFlow("else")
      .addCode(CodeBlock.of("this.requestOptions = new $T().apply(this.requestOptions)",
          requestOptionsClassName))
      .addCode(callRequestOptionsMethod)
      .endControlFlow()
      .addStatement("return this")
      .build();
}
Node.java 文件源码 项目:dremio-oss 阅读 45 收藏 0 点赞 0 评论 0
public Collection<Node> findDuplicates() {
  FluentIterable<Node> duplicates = FluentIterable.from(getConflictingChildren());
  for (Node child : children) {
    duplicates = duplicates.append(child.findDuplicates());
  }
  return duplicates.toList();
}
AccelerationUtils.java 文件源码 项目:dremio-oss 阅读 50 收藏 0 点赞 0 评论 0
private static List<String> getNames(List<LayoutField> fields){
  return FluentIterable.from(fields).transform(new Function<LayoutField, String>(){
    @Override
    public String apply(LayoutField input) {
      return input.getName();
    }}).toList();
}


问题


面经


文章

微信
公众号

扫码关注公众号