Java Code Examples for com.google.common.collect.FluentIterable

The following are top voted examples for showing how to use com.google.common.collect.FluentIterable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dremio-oss   File: ElasticMappingSet.java   View source code 6 votes vote down vote up
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();
    }}));
}
 
Example 2
Project: GitHub   File: RequestOptionsGenerator.java   View source code 6 votes vote down vote up
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();
}
 
Example 3
Project: GitHub   File: Metaservices.java   View source code 6 votes vote down vote up
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();
}
 
Example 4
Project: apollo-custom   File: DefaultRolePermissionService.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 5
Project: morf   File: FilteredDataSetProducerAdapter.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example 6
Project: googles-monorepo-demo   File: TypeToken.java   View source code 6 votes vote down vote up
@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;
  }
}
 
Example 7
Project: tac-kbp-eal   File: ValidateSystemOutput.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 8
Project: dremio-oss   File: AccelerationAnalyzer.java   View source code 6 votes vote down vote up
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);
        }
      });
}
 
Example 9
Project: GitHub   File: Proto.java   View source code 6 votes vote down vote up
@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();
}
 
Example 10
Project: raml-java-tools   File: TypeFetchers.java   View source code 6 votes vote down vote up
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));
            }

        };
    }
 
Example 11
Project: circus-train   File: FilterToolHelp.java   View source code 6 votes vote down vote up
@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();
}
 
Example 12
Project: dremio-oss   File: DependencyGraph.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 13
Project: circus-train   File: MoreMapUtils.java   View source code 6 votes vote down vote up
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();
}
 
Example 14
Project: dremio-oss   File: ScanCrel.java   View source code 6 votes vote down vote up
@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);
}
 
Example 15
Project: guava-mock   File: TypeToken.java   View source code 6 votes vote down vote up
@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;
  }
}
 
Example 16
Project: dremio-oss   File: InjectingSerializer.java   View source code 6 votes vote down vote up
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);
}
 
Example 17
Project: android-auto-mapper   File: MoreTypes.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 18
Project: tac-kbp-eal   File: ValidateSystemOutput.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example 19
Project: dremio-oss   File: SchemaUtilities.java   View source code 6 votes vote down vote up
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();

}
 
Example 20
Project: apollo-custom   File: DefaultRolePermissionService.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: tac-kbp-eal   File: AnswerKey.java   View source code 6 votes vote down vote up
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
}
 
Example 22
Project: morf   File: TableDataHomology.java   View source code 5 votes vote down vote up
/**
 * @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);
}
 
Example 23
Project: morf   File: TableDataHomology.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example 24
Project: dremio-oss   File: AccelerationMapper.java   View source code 5 votes vote down vote up
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);
}
 
Example 25
Project: circus-train   File: FileOutputDiffListener.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 26
Project: GitHub   File: RequestManagerGenerator.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 27
Project: GitHub   File: RequestBuilderGenerator.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 28
Project: GitHub   File: RequestBuilderGenerator.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 29
Project: dremio-oss   File: Node.java   View source code 5 votes vote down vote up
public Collection<Node> findDuplicates() {
  FluentIterable<Node> duplicates = FluentIterable.from(getConflictingChildren());
  for (Node child : children) {
    duplicates = duplicates.append(child.findDuplicates());
  }
  return duplicates.toList();
}
 
Example 30
Project: dremio-oss   File: AccelerationUtils.java   View source code 5 votes vote down vote up
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();
}
 
Example 31
Project: dremio-oss   File: JobUI.java   View source code 5 votes vote down vote up
public JobUI(Job job) {
  this.jobId = job.getJobId();
  this.attempts = FluentIterable.from(job.getAttempts())
    .transform(new Function<JobAttempt, JobAttemptUI>() {
      @Override
      public JobAttemptUI apply(JobAttempt input) {
        return toUI(input);
      }
    }).toList();
  this.data = new JobDataWrapper(job.getData());
}
 
Example 32
Project: rejoiner   File: ProtoRegistryTest.java   View source code 5 votes vote down vote up
@Test
public void protoRegistryShouldIncludeAllProtoTypesFromFile() {
  Set<GraphQLType> graphQLTypes =
      ProtoRegistry.newBuilder().add(TestProto.getDescriptor()).build().listTypes();
  assertThat(FluentIterable.from(graphQLTypes).transform(GET_NAME))
      .containsExactly(
          "javatests_com_google_api_graphql_rejoiner_proto_Proto1",
          "javatests_com_google_api_graphql_rejoiner_proto_Proto2",
          "javatests_com_google_api_graphql_rejoiner_proto_Proto1_InnerProto",
          "javatests_com_google_api_graphql_rejoiner_proto_Proto2_TestEnum",
          "Input_javatests_com_google_api_graphql_rejoiner_proto_Proto1",
          "Input_javatests_com_google_api_graphql_rejoiner_proto_Proto2",
          "Input_javatests_com_google_api_graphql_rejoiner_proto_Proto1_InnerProto");
}
 
Example 33
Project: tac-kbp-eal   File: AnswerKey.java   View source code 5 votes vote down vote up
/**
 * Get all responses, assessed and unassessed
 */
public ImmutableSet<Response> allResponses() {
  return ImmutableSet.copyOf(
      concat(FluentIterable.from(annotatedResponses())
              .transform(AssessedResponseFunctions.response()),
          unannotatedResponses()));
}
 
Example 34
Project: apollo-custom   File: DefaultRoleInitializationService.java   View source code 5 votes vote down vote up
private void createAppMasterRole(String appId, String operator) {
  Set<Permission> appPermissions =
      FluentIterable.from(Lists.newArrayList(
          PermissionType.CREATE_CLUSTER, PermissionType.CREATE_NAMESPACE, PermissionType.ASSIGN_ROLE))
          .transform(permissionType -> createPermission(appId, permissionType, operator)).toSet();
  Set<Permission> createdAppPermissions = rolePermissionService.createPermissions(appPermissions);
  Set<Long>
      appPermissionIds =
      FluentIterable.from(createdAppPermissions).transform(permission -> permission.getId()).toSet();

  //create app master role
  Role appMasterRole = createRole(RoleUtils.buildAppMasterRoleName(appId), operator);

  rolePermissionService.createRoleWithPermissions(appMasterRole, appPermissionIds);
}
 
Example 35
Project: tac-kbp-eal   File: EREAligner.java   View source code 5 votes vote down vote up
/**
 * Gets an identifier corresponding to the ERE object the response aligns to, if any.
 */
public Optional<ScoringCorefID> argumentForResponse(final Response response) {
  if (response.role().equalTo(TIME)) {
    // time is a special case; its CAS is always its TIMEX form
    return Optional.of(new ScoringCorefID.Builder().scoringEntityType(ScoringEntityType.Time)
        .withinTypeID(response.canonicalArgument().string()).build());
  }

  final MappedEventTypeRole systemTypeRole = typeRoleForResponse(response);
  final ImmutableSet<CandidateAlignmentTarget> searchOrder =
      FluentIterable.from(candidateEREObjects)
          // alignment candidates which match the response in event type
          // and argument role will always be searched before other candidates
          // in order to be as generous as possible to systems.
          // Note ImmutableSets iterate deterministically in the order of insertion
          .filter(compose(containsElement(systemTypeRole), typeRolesSeen()))
          .append(candidateEREObjects)
          .toSet();

  // for each alignment rule in order, try to find an ERE object which aligns
  for (final ResponseToEREAlignmentRule responseChecker : responseMatchingStrategy) {
    for (final CandidateAlignmentTarget alignmentCandidate : searchOrder) {
      if (responseChecker.aligns(response, alignmentCandidate)) {
        return Optional.of(alignmentCandidate.id());
      }
    }
  }

  return Optional.absent();
}
 
Example 36
Project: ArchUnit   File: Locations.java   View source code 5 votes vote down vote up
private static Set<Location> jarLocationsOf(URLClassLoader loader) {
    return FluentIterable.from(Locations.of(ImmutableSet.copyOf(loader.getURLs())))
            .filter(new Predicate<Location>() {
                @Override
                public boolean apply(Location input) {
                    return input.isJar();
                }
            }).toSet();
}
 
Example 37
Project: dremio-oss   File: PlanningStage.java   View source code 5 votes vote down vote up
public static List<ViewFieldType> removeUpdateColumn(final List<ViewFieldType> fields) {
  return FluentIterable.from(fields).filter(new Predicate<ViewFieldType>() {
    @Override
    public boolean apply(@Nullable ViewFieldType input) {
      return !IncrementalUpdateUtils.UPDATE_COLUMN.equals(input.getName());
    }
  }).toList();
}
 
Example 38
Project: dremio-oss   File: ApiIntentMessageMapper.java   View source code 5 votes vote down vote up
private LayoutContainerDescriptor toIntentMessage(final LayoutContainerApiDescriptor descriptor) {
  return new LayoutContainerDescriptor()
      .setEnabled(descriptor.getEnabled())
      .setType(descriptor.getType())
      .setLayoutList(FluentIterable
          .from(descriptor.getLayoutList())
          .transform(new Function<LayoutApiDescriptor, LayoutDescriptor>() {
            @Nullable
            @Override
            public LayoutDescriptor apply(@Nullable final LayoutApiDescriptor input) {
              final LayoutDetailsApiDescriptor details = input.getDetails();
              return new LayoutDescriptor()
                  .setId(toLayoutId(input.getId()))
                  .setName(input.getName())
                  .setDetails(new LayoutDetailsDescriptor()
                      .setDisplayFieldList(toIntentFields(details.getDisplayFieldList()))
                      .setMeasureFieldList(toIntentFields(details.getMeasureFieldList()))
                      .setDimensionFieldList(toIntentDimensionFields(details.getDimensionFieldList()))
                      .setPartitionFieldList(toIntentFields(details.getPartitionFieldList()))
                      .setSortFieldList(toIntentFields(details.getSortFieldList()))
                      .setDistributionFieldList(toIntentFields(details.getDistributionFieldList()))
                      .setPartitionDistributionStrategy(details.getPartitionDistributionStrategy())
                  );
            }
          })
          .toList()
      );
}
 
Example 39
Project: tac-kbp-eal   File: EventArgumentEquivalenceSpecFormats.java   View source code 5 votes vote down vote up
@Override
public ImmutableSet<Symbol> docIDs() throws IOException {
  return FluentIterable.from(Arrays.asList(directory.listFiles()))
      .transform(FileUtils.ToName)
      .transform(Symbol.FromString)
      .toSet();
}
 
Example 40
Project: dremio-oss   File: AccelerationMapper.java   View source code 5 votes vote down vote up
public List<LayoutField> toLayoutFields(final List<LayoutFieldDescriptor> fields) {
  return FluentIterable.from(AccelerationUtils.selfOrEmpty(fields))
      .transform(new Function<LayoutFieldDescriptor, LayoutField>() {
        @Nullable
        @Override
        public LayoutField apply(@Nullable final LayoutFieldDescriptor field) {
          return toLayoutField(field);
        }
      })
      .toList();
}