Java Code Examples for com.google.common.collect.Iterables#filter()

The following examples show how to use com.google.common.collect.Iterables#filter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InterProcessReadWriteLock.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<String> getParticipantNodes() throws Exception
{
    Collection<String>  nodes = super.getParticipantNodes();
    Iterable<String>    filtered = Iterables.filter
    (
        nodes,
        new Predicate<String>()
        {
            @Override
            public boolean apply(String node)
            {
                return node.contains(lockName);
            }
        }
    );
    return ImmutableList.copyOf(filtered);
}
 
Example 2
Source File: CoreLibraryDefaultFeatureValueProvider.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
public IStatus validateConfiguration(FeatureConfiguration configuration) {
	String outEventAPI = configuration.getType().getName();
	if (!ICoreLibraryConstants.FEATURE_OUT_EVENT_API.equals(outEventAPI)) {
		return Status.OK_STATUS;
	}
	FeatureParameterValue observablesValue = configuration.getParameterValue(ICoreLibraryConstants.PARAMETER_OUT_EVENT_OBSERVABLES);
	if (observablesValue == null || observablesValue.getBooleanValue()) {
		return Status.OK_STATUS; // default is true
	}
	Iterable<FeatureParameterValue> trueValues = Iterables.filter(configuration.getParameterValues(),
			p -> p.getBooleanValue());
	if (trueValues.iterator().hasNext()) {
		return Status.OK_STATUS;
	}
	return error(String.format(REQUIRED_TRUE_PARAMETER, outEventAPI));
}
 
Example 3
Source File: IssueServiceImpl.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<Issue> searchIssues(final String name, final String label) {
	Iterable<Issue> filteredIterable = Iterables.filter(issues.values(), new Predicate<Issue>() {

		@Override
		public boolean apply(Issue issue) {
			boolean result = true;
			if (name != null) {
				result = issue.getName() != null && issue.getName().toLowerCase().contains(name.toLowerCase());
			}
			if (result && label != null) {
				Iterable<String> filteredLabels = Iterables.filter(issue.getLabels(), new Predicate<String>() {

					@Override
					public boolean apply(String issueLabel) {
						return issueLabel != null && issueLabel.toLowerCase().contains(label.toLowerCase());
					}

				});
				result = result && filteredLabels.iterator().hasNext();
			}
			return result;
		}
	});
	return Lists.newArrayList(filteredIterable);
}
 
Example 4
Source File: NeutronNetworkingApi.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Get the {@link Port} by its fixed IP
 *
 * @param fixedIP the fixed IP of the port to be retrieved
 * @return the {@link Port} if found, null otherwise
 */
private Port getPortByFixedIP(final String fixedIP) {
    if (!isValidIP(fixedIP)) {
        return null;
    }

    Iterable<Port> port = Iterables.filter(portApi.list().concat().toList(),
            new Predicate<Port>() {
                @Override
                public boolean apply(Port input) {
                    for (IP ip : input.getFixedIps()) {
                        if (ip.getIpAddress() != null
                                && ip.getIpAddress().equals(fixedIP)) {
                            return true;
                        }
                    }
                    return false;
                }
            });

    // a fixed/private IP can be associated with at most one port
    if (port.iterator().hasNext()) {
        return port.iterator().next();
    }
    return null;
}
 
Example 5
Source File: TestSuiteBuilder.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a TestSuite containing the tests from the given
 * classes and/or packages which matched the given tags.
 */
public Set<Class<?>> create() {
  Set<Class<?>> result = new LinkedHashSet<>();
  for (Class<?> testClass : Iterables.filter(testClasses, matchClassPredicate)) {
    result.add(testClass);
  }
  if (tolerateEmptyTestSuites && result.isEmpty()) {
    // We have some cases where the resulting test suite is empty, which some of our test
    // infrastructure treats as an error.
    result.add(TautologyTest.class);
  }
  return result;
}
 
Example 6
Source File: N4ClassifierDeclarationImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public EList<N4GetterDeclaration> getOwnedGetters() {
	final Iterable<N4GetterDeclaration> getters = Iterables.<N4GetterDeclaration>filter(this.getOwnedMembersRaw(), N4GetterDeclaration.class);
	List<N4GetterDeclaration> _list = IterableExtensions.<N4GetterDeclaration>toList(getters);
	return new BasicEList<N4GetterDeclaration>(_list);
}
 
Example 7
Source File: XtextGenerator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void checkConfigurationInternal(final Issues issues) {
  this.initialize();
  final MweIssues generatorIssues = new MweIssues(this, issues);
  this.configuration.checkConfiguration(generatorIssues);
  final HashMap<String, Grammar> uris = new HashMap<String, Grammar>();
  for (final XtextGeneratorLanguage language : this.languageConfigs) {
    {
      language.checkConfiguration(generatorIssues);
      Iterable<GeneratedMetamodel> _filter = Iterables.<GeneratedMetamodel>filter(language.getGrammar().getMetamodelDeclarations(), GeneratedMetamodel.class);
      for (final GeneratedMetamodel generatedMetamodel : _filter) {
        {
          final String nsURI = generatedMetamodel.getEPackage().getNsURI();
          boolean _containsKey = uris.containsKey(nsURI);
          if (_containsKey) {
            String _name = uris.get(nsURI).getName();
            String _plus = ((("Duplicate generated grammar with nsURI \'" + nsURI) + "\' in ") + _name);
            String _plus_1 = (_plus + " and ");
            String _name_1 = language.getGrammar().getName();
            String _plus_2 = (_plus_1 + _name_1);
            generatorIssues.addError(_plus_2);
          } else {
            uris.put(nsURI, language.getGrammar());
          }
        }
      }
    }
  }
}
 
Example 8
Source File: ContainerQuery.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Run a query on a single container.
 *
 * @param container
 *          The container
 * @return The query result.
 */
public Iterable<IEObjectDescription> execute(final IContainer container) { // NOPMD NPathComplexity by WTH on 24.11.10 06:07
  if (domains != null && !domains.isEmpty() && domainMapper != null) {
    IDomain domain = domainMapper.map(container);
    if (domain != null && !domains.contains(domain.getName())) {
      // Query not applicable to this container.
      return ImmutableList.of();
    }
  }

  // Warning: we assume that our Containers and ResourceDescriptions from the index can handle name patterns.
  Iterable<IEObjectDescription> result = namePattern != null ? container.getExportedObjects(getType(), namePattern, doIgnoreCase)
      : container.getExportedObjectsByType(getType());

  if (getUserData() != null && !getUserData().isEmpty()) {
    final Map<String, String> userDataEquals = getUserData();
    final Predicate<IEObjectDescription> userDataPredicate = new Predicate<IEObjectDescription>() {
      @Override
      public boolean apply(final IEObjectDescription input) {
        for (final Entry<String, String> entry : userDataEquals.entrySet()) {
          if (!entry.getValue().equals(input.getUserData(entry.getKey()))) {
            return false;
          }
        }
        return true;
      }
    };
    result = Iterables.filter(result, userDataPredicate);
  }

  return result;
}
 
Example 9
Source File: ValidScopeProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the Eclass scope provider (all EClasses from the parent classifiers, referenced by their fully qualified (::) names.
 * 
 * @param parent
 *          the parent
 * @param classifiers
 *          the classifiers
 * @return the i scope
 */
private IScope createEClassScope(final IScope parent, final Iterable<EClassifier> classifiers) {
  final Iterable<EClass> classes = Iterables.filter(classifiers, EClass.class);
  Iterable<IEObjectDescription> elements = EObjectDescriptions.all(classes, EcorePackage.Literals.ENAMED_ELEMENT__NAME);
  elements = Iterables.concat(elements, EObjectDescriptions.all(classes, new AbstractNameFunction() {
    public QualifiedName apply(final EObject from) {
      final EClass param = (EClass) from;
      return QualifiedName.create(param.getEPackage().getNsPrefix(), param.getName());
    }
  }));
  return new SimpleScope(parent, elements);
}
 
Example 10
Source File: AnnotationValidation.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkAnnotation(final XtendAnnotationType it) {
  Iterable<XtendField> _filter = Iterables.<XtendField>filter(it.getMembers(), XtendField.class);
  for (final XtendField it_1 : _filter) {
    {
      boolean _isValidAnnotationValueType = this.isValidAnnotationValueType(it_1.getType());
      boolean _not = (!_isValidAnnotationValueType);
      if (_not) {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("Invalid type ");
        String _simpleName = it_1.getType().getSimpleName();
        _builder.append(_simpleName);
        _builder.append(" for the annotation attribute ");
        String _name = it_1.getName();
        _builder.append(_name);
        _builder.append("; only primitive type, String, Class, annotation, enumeration are permitted or 1-dimensional arrays thereof");
        this.error(_builder.toString(), it_1, 
          XtendPackage.Literals.XTEND_FIELD__TYPE, 
          IssueCodes.INVALID_ANNOTATION_VALUE_TYPE);
      }
      XExpression _initialValue = it_1.getInitialValue();
      boolean _tripleNotEquals = (_initialValue != null);
      if (_tripleNotEquals) {
        this.annotationValueValidator.validateAnnotationValue(it_1.getInitialValue(), this);
      }
    }
  }
}
 
Example 11
Source File: SelectableBasedScope.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Iterable<IEObjectDescription> filterLocalElements(Iterable<IEObjectDescription> unfiltered) {
	if (filter != null) {
		Iterable<IEObjectDescription> result = Iterables.filter(unfiltered, filter);
		return result;
	}
	return unfiltered;
}
 
Example 12
Source File: ArgumentOutput.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
public ArgumentOutput copyWithFilteredResponses(Predicate<Scored<Response>> predicate) {
  final Iterable<Scored<Response>> scoredResponses =
      Iterables.filter(scoredResponses(), predicate);
  final ImmutableSet<Response> responses = ImmutableSet.copyOf(
      transform(scoredResponses, Scoreds.<Response>itemsOnly()));
  final Predicate<Response> retainedResponse = Predicates.in(responses);
  // retain only the responses and metadata that this predicate filters
  return ArgumentOutput
      .from(docId(), scoredResponses, Maps.filterKeys(metadata, retainedResponse));
}
 
Example 13
Source File: ECDeviceStore.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<Device> getAvailableDevices() {
    return Iterables.filter(Iterables.transform(availableDevices, devices::get), d -> d != null);
}
 
Example 14
Source File: AbstractOutputManager.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Iterable<IDisplayOutput> getDisplayOutputs() {
	return Iterables.filter(outputs.values(), IDisplayOutput.class);
}
 
Example 15
Source File: FileType.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * A filter for Iterable<? extends HasFileType> that returns only those of the specified file
 * type.
 */
public static <T extends HasFileType> Iterable<T> filter(
    final Iterable<T> items, FileType fileType) {
  return Iterables.filter(items, typeMatchingPredicateFor(fileType));
}
 
Example 16
Source File: SchemaContainer.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
public Iterable<PropertyKeyDefinition> getPropertyKeys() {
    return Iterables.filter(relationTypes.values(),PropertyKeyDefinition.class);
}
 
Example 17
Source File: AndroidDataBindingV2Test.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test
public void dataBindingCompilationUsesMetadataFromDeps() throws Exception {

  writeDataBindingFiles();

  ConfiguredTarget ctapp = getConfiguredTarget("//java/android/binary:app");
  Set<Artifact> allArtifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(ctapp));

  // The library's compilation doesn't include any of the -setter_store.bin, layoutinfo.bin, etc.
  // files that store a dependency's data binding results (since the library has no deps).
  // We check that they don't appear as compilation inputs.
  JavaCompileAction libCompileAction =
      (JavaCompileAction)
          getGeneratingAction(
              getFirstArtifactEndingWith(allArtifacts, "lib2_with_databinding.jar"));
  assertThat(
          Iterables.filter(
              libCompileAction.getInputs().toList(),
              ActionsTestUtil.getArtifactSuffixMatcher(".bin")))
      .isEmpty();

  // The binary's compilation includes the library's data binding results.
  JavaCompileAction binCompileAction =
      (JavaCompileAction)
          getGeneratingAction(getFirstArtifactEndingWith(allArtifacts, "app.jar"));
  Iterable<Artifact> depMetadataInputs =
      Iterables.filter(
          binCompileAction.getInputs().toList(),
          ActionsTestUtil.getArtifactSuffixMatcher(".bin"));

  final String appDependentLibArtifacts =
      Iterables.getFirst(depMetadataInputs, null).getRoot().getExecPathString()
          + "/java/android/binary/databinding/app/dependent-lib-artifacts/";
  ActionsTestUtil.execPaths(
      Iterables.filter(
          binCompileAction.getInputs().toList(),
          ActionsTestUtil.getArtifactSuffixMatcher(".bin")));
  assertThat(ActionsTestUtil.execPaths(depMetadataInputs))
      .containsExactly(
          appDependentLibArtifacts
              + "java/android/library/databinding/"
              + "lib_with_databinding/bin-files/android.library-android.library-br.bin",
          appDependentLibArtifacts
              + "java/android/library/databinding/"
              + "lib_with_databinding/bin-files/android.library-android.library-setter_store.bin",
          appDependentLibArtifacts
              + "java/android/library2/databinding/"
              + "lib2_with_databinding/bin-files/android.library2-android.library2-br.bin");
}
 
Example 18
Source File: StandardChangeState.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
private Iterable<TitanRelation> getRelations(final Change change, final Predicate<TitanRelation> filter) {
    Iterable<TitanRelation> base;
    if(change.isProper()) base=relations.get(change);
    else base=Iterables.concat(relations.get(Change.ADDED),relations.get(Change.REMOVED));
    return Iterables.filter(base,filter);
}
 
Example 19
Source File: FlowRuleService.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a list of rules filtered by device id and flow state.
 *
 * @param deviceId the device id to lookup
 * @param flowState the flow state to lookup
 * @return collection of flow entries
 */
default Iterable<FlowEntry> getFlowEntriesByState(DeviceId deviceId,
                                             FlowEntry.FlowEntryState flowState) {
    return Iterables.filter(getFlowEntries(deviceId), fe -> fe.state() == flowState);
}
 
Example 20
Source File: Entities.java    From brooklyn-server with Apache License 2.0 2 votes vote down vote up
/**
 * Return all descendants of given entity of the given type, potentially including the given root.
 *
 * @see #descendants(Entity)
 * @see Iterables#filter(Iterable, Class)
 */
public static <T extends Entity> Iterable<T> descendantsAndSelf(Entity root, Class<T> ofType) {
    return Iterables.filter(descendantsAndSelf(root), ofType);
}