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

The following are top voted examples for showing how to use com.google.common.collect.Iterables. 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: morf   File: TestOracleMetaDataProvider.java   View source code 6 votes vote down vote up
/**
 * Verify that the data type mapping is correct for date columns.
 */
@Test
public void testCorrectDataTypeMappingDate() throws SQLException {
  // Given
  final PreparedStatement statement = mock(PreparedStatement.class, RETURNS_SMART_NULLS);
  when(connection.prepareStatement(anyString())).thenReturn(statement);

  // This is the list of tables that's returned.
  when(statement.executeQuery()).thenAnswer(new ReturnTablesMockResultSet(1)).thenAnswer(new ReturnTablesWithDateColumnMockResultSet(2));

  // When
  final Schema oracleMetaDataProvider = oracle.openSchema(connection, "TESTDATABASE", "TESTSCHEMA");
  assertEquals("Table names", "[AREALTABLE]", oracleMetaDataProvider.tableNames().toString());
  Column dateColumn = Iterables.find(oracleMetaDataProvider.getTable("AREALTABLE").columns(), new Predicate<Column>() {

    @Override
    public boolean apply(Column input) {
      return "dateColumn".equalsIgnoreCase(input.getName());
    }
  });
  assertEquals("Date column type", dateColumn.getType(), DataType.DATE);
}
 
Example 2
Project: Elasticsearch   File: SqlFormatter.java   View source code 6 votes vote down vote up
@Override
protected Void visitSelect(Select node, Integer indent) {
    append(indent, "SELECT");
    if (node.isDistinct()) {
        builder.append(" DISTINCT");
    }

    if (node.getSelectItems().size() > 1) {
        boolean first = true;
        for (SelectItem item : node.getSelectItems()) {
            builder.append("\n")
                    .append(indentString(indent))
                    .append(first ? "  " : ", ");

            process(item, indent);
            first = false;
        }
    }
    else {
        builder.append(' ');
        process(Iterables.getOnlyElement(node.getSelectItems()), indent);
    }

    builder.append('\n');
    return null;
}
 
Example 3
Project: DecompiledMinecraft   File: SimpleReloadableResourceManager.java   View source code 6 votes vote down vote up
public void reloadResources(List<IResourcePack> p_110541_1_)
{
    this.clearResources();
    logger.info("Reloading ResourceManager: " + joinerResourcePacks.join(Iterables.transform(p_110541_1_, new Function<IResourcePack, String>()
    {
        public String apply(IResourcePack p_apply_1_)
        {
            return p_apply_1_.getPackName();
        }
    })));

    for (IResourcePack iresourcepack : p_110541_1_)
    {
        this.reloadResourcePack(iresourcepack);
    }

    this.notifyReloadListeners();
}
 
Example 4
Project: pyplyn   File: ArgusClientTest.java   View source code 6 votes vote down vote up
@Test
  public void attachTriggerToNotification() throws Exception {
  	// ARRANGE
TriggerObject triggerObj = ImmutableTriggerObject.builder().alertId(LONG_ID).id(LONG_ID).notificationIds(LIST_OF_LONG_ID).build();
  	Response<TriggerObject> response = Response.success(triggerObj);
  	
  	// ACT
  	@SuppressWarnings("unchecked")
Call<NotificationObject>responseCall = mock(Call.class);
  	doReturn(response).when(responseCall).execute();
doReturn(request).when(responseCall).request();
doReturn(responseCall).when(svc).attachTriggerToNotification(any(), anyLong(), anyLong(), anyLong());
  	
  	// ASSERT
  	TriggerObject notification = argus.attachTriggerToNotification(LONG_ID, Iterables.getOnlyElement(LIST_OF_LONG_ID), LONG_ID);
  	assertThat(notification.alertId(), is(LONG_ID));
  	assertThat(notification.notificationIds(), equalTo(LIST_OF_LONG_ID));
  	assertThat(notification.id(), is(LONG_ID));
  }
 
Example 5
Project: Reer   File: ManagedProxyClassGenerator.java   View source code 6 votes vote down vote up
private void writeViewPropertyDslMethods(ClassVisitor visitor, Type generatedType, Collection<ModelProperty<?>> viewProperties, Class<?> viewClass) {
    boolean writable = Iterables.any(viewProperties, new Predicate<ModelProperty<?>>() {
        @Override
        public boolean apply(ModelProperty<?> viewProperty) {
            return viewProperty.isWritable();
        }
    });
    // TODO:LPTR Instead of the first view property, we should figure out these parameters from the actual property
    ModelProperty<?> firstProperty = viewProperties.iterator().next();

    writeConfigureMethod(visitor, generatedType, firstProperty, writable);
    writeSetMethod(visitor, generatedType, firstProperty);
    writeTypeConvertingSetter(visitor, generatedType, viewClass, firstProperty);

    // TODO - this should be applied to all methods, including delegating methods
    writeReadOnlySetter(visitor, viewClass, writable, firstProperty);
}
 
Example 6
Project: Reer   File: ModelPathSuggestionProvider.java   View source code 6 votes vote down vote up
@Override
public List<ModelPath> transform(final ModelPath unavailable) {
    Iterable<Suggestion> suggestions = Iterables.transform(availablePaths, new Function<ModelPath, Suggestion>() {
        public Suggestion apply(ModelPath available) {
            int distance = StringUtils.getLevenshteinDistance(unavailable.toString(), available.toString());
            boolean suggest = distance <= Math.min(3, unavailable.toString().length() / 2);
            if (suggest) {
                return new Suggestion(distance, available);
            } else {
                // avoid excess creation of Suggestion objects
                return null;
            }
        }
    });

    suggestions = Iterables.filter(suggestions, REMOVE_NULLS);
    List<Suggestion> sortedSuggestions = CollectionUtils.sort(suggestions);
    return CollectionUtils.collect(sortedSuggestions, Suggestion.EXTRACT_PATH);
}
 
Example 7
Project: morf   File: UpgradePath.java   View source code 6 votes vote down vote up
/**
 * @return the sql
 */
public List<String> getSql() {
  List<String> results = Lists.newLinkedList();
  if (!sql.isEmpty() || !upgradeScriptAdditions.isEmpty())
    results.addAll(initialisationSql);

  results.addAll(sql);

  for (UpgradeScriptAddition addition : upgradeScriptAdditions) {
    Iterables.addAll(results, addition.sql());
  }

  if (!results.isEmpty())
    results.addAll(finalisationSql);

  return Collections.unmodifiableList(results);
}
 
Example 8
Project: hadoop   File: TestFileInputFormat.java   View source code 6 votes vote down vote up
public static void verifyFileStatuses(List<Path> expectedPaths,
    List<FileStatus> fetchedStatuses, final FileSystem localFs) {
  Assert.assertEquals(expectedPaths.size(), fetchedStatuses.size());

  Iterable<Path> fqExpectedPaths = Iterables.transform(expectedPaths,
      new Function<Path, Path>() {
        @Override
        public Path apply(Path input) {
          return localFs.makeQualified(input);
        }
      });

  Set<Path> expectedPathSet = Sets.newHashSet(fqExpectedPaths);
  for (FileStatus fileStatus : fetchedStatuses) {
    if (!expectedPathSet.remove(localFs.makeQualified(fileStatus.getPath()))) {
      Assert.fail("Found extra fetched status: " + fileStatus.getPath());
    }
  }
  Assert.assertEquals(
      "Not all expectedPaths matched: " + expectedPathSet.toString(), 0,
      expectedPathSet.size());
}
 
Example 9
Project: QDrill   File: ListSchema.java   View source code 6 votes vote down vote up
@Override
public Iterable<? extends Field> removeUnreadFields() {
    final List<Field> removedFields = Lists.newArrayList();
    Iterables.removeIf(fields, new Predicate<Field>() {
        @Override
        public boolean apply(Field field) {
            if (!field.isRead()) {
                removedFields.add(field);
                return true;
            } else if (field.hasSchema()) {
                Iterables.addAll(removedFields, field.getAssignedSchema().removeUnreadFields());
            }

            return false;
        }
    });
    return removedFields;
}
 
Example 10
Project: hashsdn-controller   File: ClientTransaction.java   View source code 6 votes vote down vote up
public DOMStoreThreePhaseCommitCohort ready() {
    final Collection<AbstractProxyTransaction> toReady = ensureClosed();
    Preconditions.checkState(toReady != null, "Attempted to submit a closed transaction %s", this);

    toReady.forEach(AbstractProxyTransaction::seal);
    final AbstractTransactionCommitCohort cohort;
    switch (toReady.size()) {
        case 0:
            cohort = new EmptyTransactionCommitCohort(parent(), getIdentifier());
            break;
        case 1:
            cohort = new DirectTransactionCommitCohort(parent(), getIdentifier(),
                Iterables.getOnlyElement(toReady));
            break;
        default:
            cohort = new ClientTransactionCommitCohort(parent(), getIdentifier(), toReady);
            break;
    }

    return parent().onTransactionReady(this, cohort);
}
 
Example 11
Project: dremio-oss   File: CompareFunction.java   View source code 6 votes vote down vote up
@Override
public FunctionRender render(FunctionRenderer renderer, RexCall call) {
  checkArity(call, 2);
  PredicateAnalyzer.checkForIncompatibleDateTimeOperands(call);

  RexNode o1 = call.getOperands().get(0);
  RexNode o2 = call.getOperands().get(1);

  FunctionRender op1 = o1.accept(renderer.getVisitor());
  FunctionRender op2 = o2.accept(renderer.getVisitor());

  boolean isTime1 = isTemporal(o1.getType());
  boolean isTime2 = isTemporal(o2.getType());

  if(isTime1 != isTime2){
    throw new RuntimeException("Can't do comparison between a date and a non-date field.");
  }

  // we need special handling in painless for temporal types and comparison other than equality/inequality.
  if(renderer.isUsingPainless() && isTime1 && type != Type.EQ && type != Type.NEQ){
    return handlePainlessTimeComparison(op1, op2);
  }

  String script = String.format("( %s %s %s )", op1.getScript(), elasticName, op2.getScript());
  return new FunctionRender(script, Iterables.concat(op1.getNulls(), op2.getNulls()));
}
 
Example 12
Project: googles-monorepo-demo   File: AbstractServiceTest.java   View source code 6 votes vote down vote up
@Override public synchronized void terminated(State from) {
  assertEquals(from, Iterables.getLast(stateHistory, State.NEW));
  stateHistory.add(State.TERMINATED);
  assertEquals(State.TERMINATED, service.state());
  if (from == State.NEW) {
    try {
      service.awaitRunning();
      fail();
    } catch (IllegalStateException expected) {
      assertNull(expected.getCause());
      assertTrue(expected.getMessage().equals(
          "Expected the service " + service + " to be RUNNING, but was TERMINATED"));
    }
  }
  completionLatch.countDown();
}
 
Example 13
Project: googles-monorepo-demo   File: MultisetEntrySetTester.java   View source code 6 votes vote down vote up
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ITERATOR_REMOVE)
@MultisetFeature.Require(ENTRIES_ARE_VIEWS)
public void testEntryReflectsIteratorRemove() {
  initThreeCopies();
  assertEquals(3, getMultiset().count(e0()));
  Multiset.Entry<E> entry = Iterables.getOnlyElement(getMultiset().entrySet());
  assertEquals(3, entry.getCount());
  Iterator<E> itr = getMultiset().iterator();
  itr.next();
  itr.remove();
  assertEquals(2, entry.getCount());
  itr.next();
  itr.remove();
  itr.next();
  itr.remove();
  assertEquals(0, entry.getCount());
}
 
Example 14
Project: Backmemed   File: LanguageMap.java   View source code 6 votes vote down vote up
public LanguageMap()
{
    try
    {
        InputStream inputstream = LanguageMap.class.getResourceAsStream("/assets/minecraft/lang/en_us.lang");

        for (String s : IOUtils.readLines(inputstream, Charsets.UTF_8))
        {
            if (!s.isEmpty() && s.charAt(0) != 35)
            {
                String[] astring = (String[])Iterables.toArray(EQUAL_SIGN_SPLITTER.split(s), String.class);

                if (astring != null && astring.length == 2)
                {
                    String s1 = astring[0];
                    String s2 = NUMERIC_VARIABLE_PATTERN.matcher(astring[1]).replaceAll("%$1s");
                    this.languageList.put(s1, s2);
                }
            }
        }

        this.lastUpdateTimeInMilliseconds = System.currentTimeMillis();
    }
    catch (IOException var7)
    {
        ;
    }
}
 
Example 15
Project: Elasticsearch   File: TableFunctionCollectSource.java   View source code 6 votes vote down vote up
@Override
public Collection<CrateCollector> getCollectors(CollectPhase collectPhase,
                                                RowReceiver downstream,
                                                JobCollectContext jobCollectContext) {
    TableFunctionCollectPhase phase = (TableFunctionCollectPhase) collectPhase;
    TableFunctionImplementation tableFunctionSafe = functions.getTableFunctionSafe(phase.functionName());
    TableInfo tableInfo = tableFunctionSafe.createTableInfo(clusterService, Symbols.extractTypes(phase.arguments()));
    //noinspection unchecked  Only literals can be passed to table functions. Anything else is invalid SQL
    List<Input<?>> inputs = (List<Input<?>>) (List) phase.arguments();

    final Context context = new Context(new ArrayList<>(tableInfo.columns()));
    List<Input<?>> topLevelInputs = new ArrayList<>(phase.toCollect().size());
    for (Symbol symbol : phase.toCollect()) {
        topLevelInputs.add(implementationVisitor.process(symbol, context));
    }
    Iterable<Row> rows = Iterables.transform(
            tableFunctionSafe.execute(inputs),
            InputRow.toInputRowFunction(topLevelInputs, context.collectExpressions));
    OrderBy orderBy = phase.orderBy();
    if (orderBy != null) {
        rows = SystemCollectSource.sortRows(Iterables.transform(rows, Row.MATERIALIZE), phase);
    }
    RowsCollector rowsCollector = new RowsCollector(downstream, rows);
    return Collections.<CrateCollector>singletonList(rowsCollector);
}
 
Example 16
Project: BaseClient   File: Lang.java   View source code 6 votes vote down vote up
public static void loadLocaleData(InputStream p_loadLocaleData_0_, Map p_loadLocaleData_1_) throws IOException
{
    for (String s : IOUtils.readLines(p_loadLocaleData_0_, Charsets.UTF_8))
    {
        if (!s.isEmpty() && s.charAt(0) != 35)
        {
            String[] astring = (String[])((String[])Iterables.toArray(splitter.split(s), String.class));

            if (astring != null && astring.length == 2)
            {
                String s1 = astring[0];
                String s2 = pattern.matcher(astring[1]).replaceAll("%$1s");
                p_loadLocaleData_1_.put(s1, s2);
            }
        }
    }
}
 
Example 17
Project: martini-core   File: DefaultCategories.java   View source code 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	Map<String, Category> beans = applicationContext.getBeansOfType(Category.class);
	Collection<Category> categories = beans.values();

	for (Category category : categories) {
		String name = category.getName();
		Iterable<String> parentNames = category.getParentNames();

		if (Iterables.isEmpty(parentNames)) {
			ascendingHierarchy.put(name, null);
		}
		else {
			for (String parentName : parentNames) {
				ascendingHierarchy.put(name, parentName);
			}
		}
	}
}
 
Example 18
Project: airsonic   File: PodcastService.java   View source code 6 votes vote down vote up
/**
 * Returns the N newest episodes.
 *
 * @return Possibly empty list of the newest Podcast episodes, sorted in
 *         reverse chronological order (newest episode first).
 */
public List<PodcastEpisode> getNewestEpisodes(int count) {
    List<PodcastEpisode> episodes = addMediaFileIdToEpisodes(podcastDao.getNewestEpisodes(count));

    return Lists.newArrayList(Iterables.filter(episodes, new Predicate<PodcastEpisode>() {
        @Override
        public boolean apply(PodcastEpisode episode) {
            Integer mediaFileId = episode.getMediaFileId();
            if (mediaFileId == null) {
                return false;
            }
            MediaFile mediaFile = mediaFileService.getMediaFile(mediaFileId);
            return mediaFile != null && mediaFile.isPresent();
        }
    }));
}
 
Example 19
Project: n4js   File: JSLibSingleTestConfigProvider.java   View source code 6 votes vote down vote up
/**
 * Merges several blacklists into one, may be used in custom {@link JSLibSingleTestConfigProvider} implementation.
 */
protected static Set<String> readModifierFiles(String... blacklistFileNames) throws IOException {
	Set<String> blacklist = new HashSet<>();
	if (blacklistFileNames != null) {
		for (String blacklistFileName : blacklistFileNames) {
			Iterable<String> entries = Iterables.filter(getFileLines(blacklistFileName), new Predicate<String>() {
				@Override
				public boolean apply(String s) {
					return !s.startsWith(BLACKLIST_LINECOMMENT) && !s.trim().isEmpty();
				}
			});
			for (String entry : entries) {
				if (!blacklist.add(entry)) {
					System.err.println("Duplicate blacklist entry: " + entry);
				}
			}
		}
	}
	return blacklist;
}
 
Example 20
Project: hadoop-oss   File: TestMetricsSystemImpl.java   View source code 6 votes vote down vote up
private void checkMetricsRecords(List<MetricsRecord> recs) {
  LOG.debug(recs);
  MetricsRecord r = recs.get(0);
  assertEquals("name", "s1rec", r.name());
  assertEquals("tags", new MetricsTag[] {
    tag(MsInfo.Context, "test"),
    tag(MsInfo.Hostname, hostname)}, r.tags());
  assertEquals("metrics", MetricsLists.builder("")
    .addCounter(info("C1", "C1 desc"), 1L)
    .addGauge(info("G1", "G1 desc"), 2L)
    .addCounter(info("S1NumOps", "Number of ops for s1"), 1L)
    .addGauge(info("S1AvgTime", "Average time for s1"), 0.0)
    .metrics(), r.metrics());

  r = recs.get(1);
  assertTrue("NumActiveSinks should be 3", Iterables.contains(r.metrics(),
             new MetricGaugeInt(MsInfo.NumActiveSinks, 3)));
}
 
Example 21
Project: Reer   File: DefaultTaskOutputs.java   View source code 6 votes vote down vote up
@Override
public SortedSet<TaskOutputFilePropertySpec> getFileProperties() {
    if (fileProperties == null) {
        TaskPropertyUtils.ensurePropertiesHaveNames(filePropertiesInternal);
        Iterator<TaskOutputFilePropertySpec> flattenedProperties = Iterators.concat(Iterables.transform(filePropertiesInternal, new Function<TaskPropertySpec, Iterator<? extends TaskOutputFilePropertySpec>>() {
            @Override
            public Iterator<? extends TaskOutputFilePropertySpec> apply(TaskPropertySpec propertySpec) {
                if (propertySpec instanceof CompositeTaskOutputPropertySpec) {
                    return ((CompositeTaskOutputPropertySpec) propertySpec).resolveToOutputProperties();
                } else {
                    return Iterators.singletonIterator((TaskOutputFilePropertySpec) propertySpec);
                }
            }
        }).iterator());
        fileProperties = TaskPropertyUtils.collectFileProperties("output", flattenedProperties);
    }
    return fileProperties;
}
 
Example 22
Project: REST-Web-Services   File: MoviePersistenceServiceImpl.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Long createOtherTitle(
        @NotNull @Valid final OtherTitle otherTitle,
        @NotNull final MovieEntity movie
) throws ResourceConflictException {
    log.info("Called with otherTitle {}, movie {}", otherTitle, movie);

    this.existsOtherTile(movie.getOtherTitles()
            .stream()
            .filter(ot -> ot.getStatus() == DataStatus.ACCEPTED)
            .collect(Collectors.toList()), otherTitle);

    final MovieOtherTitleEntity movieOtherTitle = new MovieOtherTitleEntity(otherTitle.getTitle(), otherTitle.getCountry());
    movieOtherTitle.setMovie(movie);

    movie.getOtherTitles().add(movieOtherTitle);

    this.movieRepository.save(movie);

    return Iterables.getLast(movie.getOtherTitles()).getId();
}
 
Example 23
Project: googles-monorepo-demo   File: PopulatedCachesTest.java   View source code 5 votes vote down vote up
private void assertCollectionSize(Collection<?> collection, int size) {
  assertEquals(size, collection.size());
  if (size > 0) {
    assertFalse(collection.isEmpty());
  } else {
    assertTrue(collection.isEmpty());
  }
  assertEquals(size, Iterables.size(collection));
  assertEquals(size, Iterators.size(collection.iterator()));
}
 
Example 24
Project: n4js   File: TypeUtils.java   View source code 5 votes vote down vote up
/**
 * Convenience method, returns directly declared super types (class, role, interface) of a classifier. May return an
 * empty list but never null. Order is always super class, super roles, super interfaces. For all non-classifiers
 * this method returns an empty list.
 */
@SuppressWarnings("unchecked")
public static Iterable<? extends ParameterizedTypeRef> declaredSuperTypes(final Type type) {
	if (type instanceof TClass) {
		final TClass c = (TClass) type;
		if (c.getSuperClassRef() != null) {
			return Iterables.concat(concat(singletonList(c.getSuperClassRef()),
					c.getImplementedInterfaceRefs()));
		} else {
			return c.getImplementedInterfaceRefs();
		}
	}
	if (type instanceof TInterface) {
		final TInterface r = (TInterface) type;
		return r.getSuperInterfaceRefs();
	}
	if (type instanceof PrimitiveType) {
		PrimitiveType assignmentCompatible = ((PrimitiveType) type).getAssignmentCompatible();
		if (assignmentCompatible != null) {
			ParameterizedTypeRef typeRef = TypeRefsFactory.eINSTANCE.createParameterizedTypeRef();
			typeRef.setDeclaredType(assignmentCompatible);
			return Collections.singletonList(typeRef);
		}
	}
	if (type instanceof TObjectPrototype) {
		// IDE-1221 string based enums: traversing super types for object prototypes as well
		TObjectPrototype tObjectPrototype = (TObjectPrototype) type;
		if (tObjectPrototype.getSuperType() != null) {
			return singletonList(tObjectPrototype.getSuperType());
		}
	}
	return Collections.emptyList();
}
 
Example 25
Project: guava-mock   File: CloserTest.java   View source code 5 votes vote down vote up
@AndroidIncompatible // TODO(cpovirk): Look up Build.VERSION.SDK_INT reflectively.
public void testCreate() {
  Closer closer = Closer.create();
  String javaVersion = System.getProperty("java.version");
  String secondPart = Iterables.get(Splitter.on('.').split(javaVersion), 1);
  int versionNumber = Integer.parseInt(secondPart);
  if (versionNumber < 7) {
    assertThat(closer.suppressor).isInstanceOf(Closer.LoggingSuppressor.class);
  } else {
    assertThat(closer.suppressor).isInstanceOf(Closer.SuppressingSuppressor.class);
  }
}
 
Example 26
Project: n4js   File: MemberMatrix.java   View source code 5 votes vote down vote up
private Iterable<TMember> members(int source) {
	return hasSource(source) ? Iterables.concat(members(
			source, GETTER),
			members(source, SETTER),
			members(source, FIELD),
			members(source, METHOD)) : MemberList.emptyList();
}
 
Example 27
Project: appinventor-extensions   File: FileImporterImpl.java   View source code 5 votes vote down vote up
@Override
public Set<String> getProjectNames(final String userId) {
  List<Long> projectIds = storageIo.getProjects(userId);
  Iterable<String> names = Iterables.transform(projectIds, new Function<Long, String>() {
    @Override
    public String apply(Long projectId) {
      return storageIo.getProjectName(userId, projectId);
    }
  });
  return ImmutableSet.copyOf(names);
}
 
Example 28
Project: Elasticsearch   File: OrderedDocCollector.java   View source code 5 votes vote down vote up
private KeyIterable<ShardId, Row> scoreDocToIterable(ScoreDoc[] scoreDocs) {
    exhausted = scoreDocs.length < batchSize;
    if (scoreDocs.length > 0) {
        lastDoc = (FieldDoc) scoreDocs[scoreDocs.length - 1];
    }
    return new KeyIterable<>(shardId, Iterables.transform(Arrays.asList(scoreDocs), rowFunction));
}
 
Example 29
Project: ProjectAres   File: TypeMap.java   View source code 5 votes vote down vote up
/**
 * Return a single value assigned to a key within the given bounds
 * @throws NoSuchElementException if no such value exists
 * @throws AmbiguousElementException if multiple such values exist
 */
public V oneAssignableTo(TypeToken<? extends K> bounds) {
    try {
        return Iterables.getOnlyElement(allAssignableTo(bounds));
    } catch(IllegalArgumentException e) {
        throw new AmbiguousElementException();
    }
}
 
Example 30
Project: powsybl-core   File: MergedBus.java   View source code 5 votes vote down vote up
@Override
public Iterable<Load> getLoads() {
    checkValidity();
    List<Iterable<Load>> iterables = new ArrayList<>(buses.size());
    for (ConfiguredBus bus : buses) {
        iterables.add(bus.getLoads());
    }
    return Iterables.concat(iterables);
}
 
Example 31
Project: n4js   File: N4ClassifierDefinitionImpl.java   View source code 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public EList<N4MemberDeclaration> getOwnedMembers() {
	final Function1<N4MemberDeclaration, Boolean> _function = new Function1<N4MemberDeclaration, Boolean>() {
		public Boolean apply(final N4MemberDeclaration it) {
			boolean _isCallableConstructor = it.isCallableConstructor();
			return Boolean.valueOf((!_isCallableConstructor));
		}
	};
	final Iterable<N4MemberDeclaration> methods = IterableExtensions.<N4MemberDeclaration>filter(Iterables.<N4MemberDeclaration>filter(this.getOwnedMembersRaw(), N4MemberDeclaration.class), _function);
	List<N4MemberDeclaration> _list = IterableExtensions.<N4MemberDeclaration>toList(methods);
	return new BasicEList<N4MemberDeclaration>(_list);
}
 
Example 32
Project: dremio-oss   File: DatasetVersionMutator.java   View source code 5 votes vote down vote up
public Iterable<VirtualDatasetUI> getAllVersions(DatasetPath path) throws DatasetVersionNotFoundException {
  return Iterables.transform(datasetVersions.find(
      new FindByRange<>(new VersionDatasetKey(path, MIN_VERSION), false, new VersionDatasetKey(path, MAX_VERSION), false)),
    new Function<Entry<VersionDatasetKey, VirtualDatasetVersion>, VirtualDatasetUI> () {
      @Override
      public VirtualDatasetUI apply(Entry<VersionDatasetKey, VirtualDatasetVersion> input) {
        return toVirtualDatasetUI(input.getValue());
      }
    });
}
 
Example 33
Project: n4js   File: N4ClassifierDeclarationImpl.java   View source code 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public EList<N4MethodDeclaration> getOwnedMethods() {
	final Function1<N4MethodDeclaration, Boolean> _function = new Function1<N4MethodDeclaration, Boolean>() {
		public Boolean apply(final N4MethodDeclaration it) {
			return Boolean.valueOf(((!it.isConstructor()) && (!it.isCallableConstructor())));
		}
	};
	final Iterable<N4MethodDeclaration> methods = IterableExtensions.<N4MethodDeclaration>filter(Iterables.<N4MethodDeclaration>filter(this.getOwnedMembersRaw(), N4MethodDeclaration.class), _function);
	List<N4MethodDeclaration> _list = IterableExtensions.<N4MethodDeclaration>toList(methods);
	return new BasicEList<N4MethodDeclaration>(_list);
}
 
Example 34
Project: dremio-oss   File: RexBiShuttle.java   View source code 5 votes vote down vote up
/**
 * Applies this shuttle to each expression in an iterable.
 */
public final Iterable<RexNode> apply(Iterable<? extends RexNode> iterable, final P arg) {
  return Iterables.transform(iterable, new Function<RexNode, RexNode>() {
    public RexNode apply(@Nullable RexNode t) {
      return t == null ? null : t.accept(RexBiShuttle.this, arg);
    }
  });
}
 
Example 35
Project: morf   File: SqlParameter.java   View source code 5 votes vote down vote up
/**
 * Generates an iterable of parameters from columns.
 *
 * @param columns table columns.
 * @return parameters matching these columns.
 */
public static Iterable<SqlParameter> parametersFromColumns(Iterable<Column> columns) {
  return Iterables.transform(columns, new Function<Column, SqlParameter>() {
    @Override
    public SqlParameter apply(Column column) {
      return new SqlParameter(column);
    }
  });
}
 
Example 36
Project: devtools-driver   File: InspectorMessenger.java   View source code 5 votes vote down vote up
@VisibleForTesting
@SuppressWarnings("GuardedBy")
Optional<ImmutableSet<AppListing>> getAllAppListings(String hostBundleId) {
  Set<AppListing> listings = appIdToListings.values();
  ImmutableSet<String> hostAppIds =
      listings
          .stream()
          .filter(appListing -> appListing.app.applicationBundleId().equals(hostBundleId))
          .map(appListing -> appListing.app.applicationId())
          .collect(ImmutableSet.toImmutableSet());
  Verify.verify(hostAppIds.size() <= 1, "multiple matching host apps: %s", hostAppIds);
  if (!hostAppIds.isEmpty()) {
    String hostAppId = Iterables.getOnlyElement(hostAppIds);
    ImmutableSet<AppListing> childListings =
        listings
            .stream()
            .filter(
                appListing ->
                    hostAppId.equals(appListing.app.optionalHostApplicationId().orNull()))
            .collect(ImmutableSet.toImmutableSet());
    if (!childListings.isEmpty()
        && childListings.stream().allMatch(appListing -> appListing.listing.isPresent())) {
      return Optional.of(childListings);
    }
  }
  return Optional.empty();
}
 
Example 37
Project: MCOpts   File: Expect.java   View source code 5 votes vote down vote up
/**
 * For quoted arguments with spaces that repeat just one completion
 */
public Expect words(Consumer<Expect> consumer)
{
    Expect inner = splitInner(expect -> expect.then(consumer).repeat());
    descriptionU(Iterables.getLast(inner.mapLastDescriptions((i, s) -> s)));
    return this;
}
 
Example 38
Project: de.flapdoodle.solid   File: Path.java   View source code 5 votes vote down vote up
@Auxiliary
public Pair<Path, Path> split(Predicate<Part> matcher) {
	int idx=Iterables.indexOf(parts(), p -> matcher.test(p));
	if (idx!=-1) {
		return Pair.of(Path.of(parts().subList(0, idx+1)), Path.of(parts().subList(idx+1, parts().size())));
	}
	return Pair.of(this, Path.emtpy());
}
 
Example 39
Project: powsybl-core   File: MergedBus.java   View source code 5 votes vote down vote up
@Override
public Iterable<ThreeWindingsTransformer> getThreeWindingTransformers() {
    checkValidity();
    List<Iterable<ThreeWindingsTransformer>> iterables = new ArrayList<>(buses.size());
    for (ConfiguredBus bus : buses) {
        iterables.add(bus.getThreeWindingTransformers());
    }
    return Iterables.concat(iterables);
}
 
Example 40
Project: andbg   File: DexWriter.java   View source code 5 votes vote down vote up
@Override public boolean equals(Object o) {
    if (o instanceof EncodedArrayKey) {
        EncodedArrayKey other = (EncodedArrayKey)o;
        if (elements.size() != other.elements.size()) {
            return false;
        }
        return Iterables.elementsEqual(elements, other.elements);
    }
    return false;
}