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   Source Code and License 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   Source Code and License 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: pyplyn   File: ArgusClientTest.java   Source Code and License 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 4
Project: Reer   File: ManagedProxyClassGenerator.java   Source Code and License 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 5
Project: Reer   File: ModelPathSuggestionProvider.java   Source Code and License 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 6
Project: morf   File: UpgradePath.java   Source Code and License 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 7
Project: hadoop   File: TestFileInputFormat.java   Source Code and License 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 8
Project: QDrill   File: ListSchema.java   Source Code and License 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 9
Project: hashsdn-controller   File: ClientTransaction.java   Source Code and License 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 10
Project: dremio-oss   File: CompareFunction.java   Source Code and License 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 11
Project: googles-monorepo-demo   File: AbstractServiceTest.java   Source Code and License 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 12
Project: googles-monorepo-demo   File: MultisetEntrySetTester.java   Source Code and License 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 13
Project: Backmemed   File: LanguageMap.java   Source Code and License 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 14
Project: Elasticsearch   File: TableFunctionCollectSource.java   Source Code and License 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 15
Project: BaseClient   File: Lang.java   Source Code and License 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 16
Project: martini-core   File: DefaultCategories.java   Source Code and License 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 17
Project: airsonic   File: PodcastService.java   Source Code and License 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 18
Project: n4js   File: JSLibSingleTestConfigProvider.java   Source Code and License 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 19
Project: hadoop-oss   File: TestMetricsSystemImpl.java   Source Code and License 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 20
Project: Reer   File: DefaultTaskOutputs.java   Source Code and License 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 21
Project: REST-Web-Services   File: MoviePersistenceServiceImpl.java   Source Code and License 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 22
Project: googles-monorepo-demo   File: PopulatedCachesTest.java   Source Code and License 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 23
Project: n4js   File: TypeUtils.java   Source Code and License 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 24
Project: guava-mock   File: CloserTest.java   Source Code and License 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 25
Project: n4js   File: MemberMatrix.java   Source Code and License 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 26
Project: appinventor-extensions   File: FileImporterImpl.java   Source Code and License 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 27
Project: Elasticsearch   File: OrderedDocCollector.java   Source Code and License 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 28
Project: ProjectAres   File: TypeMap.java   Source Code and License 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 29
Project: powsybl-core   File: MergedBus.java   Source Code and License 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 30
Project: n4js   File: N4ClassifierDefinitionImpl.java   Source Code and License 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 31
Project: dremio-oss   File: DatasetVersionMutator.java   Source Code and License 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 32
Project: n4js   File: N4ClassifierDeclarationImpl.java   Source Code and License 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 33
Project: dremio-oss   File: RexBiShuttle.java   Source Code and License 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 34
Project: morf   File: SqlParameter.java   Source Code and License 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 35
Project: devtools-driver   File: InspectorMessenger.java   Source Code and License 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 36
Project: MCOpts   File: Expect.java   Source Code and License 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 37
Project: de.flapdoodle.solid   File: Path.java   Source Code and License 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 38
Project: powsybl-core   File: MergedBus.java   Source Code and License 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 39
Project: andbg   File: DexWriter.java   Source Code and License 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;
}
 
Example 40
Project: dremio-oss   File: NamespaceServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Map.Entry<NamespaceKey, NameSpaceContainer>> find(FindByCondition condition) {
  return Iterables.transform(namespace.find(condition), new Function<Map.Entry<byte[], NameSpaceContainer>, Map.Entry<NamespaceKey, NameSpaceContainer>>() {
    @Override
    public Map.Entry<NamespaceKey, NameSpaceContainer> apply(Map.Entry<byte[], NameSpaceContainer> input) {
      return new AbstractMap.SimpleEntry<>(new NamespaceKey(input.getValue().getFullPathList()), input.getValue());
    }
  });
}
 
Example 41
Project: wall-t   File: WallView.java   Source Code and License 5 votes vote down vote up
private void updateLayout( ) {
    getChildren( ).clear( );

    final Collection<TileViewModel> builds = _model.getDisplayedBuilds( );
    final Collection<ProjectTileViewModel> projects = _model.getDisplayedProjects( );

    final int totalTilesCount = builds.size( ) + projects.size( );

    final int maxTilesByColumn = _model.getMaxTilesByColumnProperty( ).get( );
    final int maxTilesByRow = _model.getMaxTilesByRowProperty( ).get( );

    final int maxByScreens = max( 1, maxTilesByColumn * maxTilesByRow );

    final int nbScreen = max( 1, totalTilesCount / maxByScreens + ( ( totalTilesCount % maxByScreens > 0 ? 1 : 0 ) ) );

    int byScreen = max( 1, totalTilesCount / nbScreen + ( ( totalTilesCount % nbScreen > 0 ? 1 : 0 ) ) );
    // We search to complete columns of screen with tiles, not to have empty blanks (ie having a number of column which are all completed)
    while ( byScreen % maxTilesByColumn != 0 )
        byScreen++;

    final int nbColums = max( 1, byScreen / maxTilesByColumn + ( ( byScreen % maxTilesByColumn > 0 ? 1 : 0 ) ) );
    final int byColums = max( 1, byScreen / nbColums + ( ( byScreen % nbColums > 0 ? 1 : 0 ) ) );

    final Iterable<List<Object>> screenPartition = Iterables.partition( Iterables.concat( builds, projects ), byScreen );
    for ( final List<Object> buildsInScreen : screenPartition ) {
        final GridPane screenPane = buildScreenPane( buildsInScreen, nbColums, byColums );
        screenPane.setVisible( false );
        getChildren( ).add( screenPane );
    }

    displayNextScreen( );
}
 
Example 42
Project: empiria.player   File: VariableInterpreter.java   Source Code and License 5 votes vote down vote up
private Iterable<String> transformTokens(List<Token> tokensFromContent, final int refItemIndex) {
    return Iterables.transform(tokensFromContent, new Function<Token, String>() {
        @Override
        public String apply(Token token) {
            if (token.isFieldInfo()) {
                return getFieldInfoValue(refItemIndex, token);
            }
            return token.getName();
        }

    });
}
 
Example 43
Project: ProjectAres   File: IterableUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Return the concatenation of the {@link Iterables} in the given {@link Collection}.
 *
 * Result is equivalent to {@link Iterables#concat}, but there are some optimizations
 * for the cases where size == 0 and size == 1.
 */
public static <T> Iterable<T> concat(Collection<? extends Iterable<? extends T>> iterables) {
    switch(iterables.size()) {
        case 0: return emptyIterable();
        case 1: return (Iterable<T>) getFirst(iterables);
        default: return Iterables.concat(iterables);
    }
}
 
Example 44
Project: stroom-stats   File: StatisticsTestService.java   Source Code and License 5 votes vote down vote up
private int countRows(final Table table) throws IOException {
    int count = 0;
    final Scan scan = new Scan();
    scan.addFamily(EventStoreColumnFamily.COUNTS.asByteArray());
    scan.addFamily(EventStoreColumnFamily.VALUES.asByteArray());
    try (final ResultScanner results = table.getScanner(scan)) {
        count = Iterables.size(results);
    }
    return count;
}
 
Example 45
Project: dremio-oss   File: PseudoDistributedFileSystem.java   Source Code and License 5 votes vote down vote up
private Iterable<NodeEndpoint> getEndpoints(){
  if(Iterables.isEmpty(endpointProvider.get())){
    return globalConfig.getEndpointProvider().get();
  } else {
    return endpointProvider.get();
  }
}
 
Example 46
Project: Reer   File: AmbiguousConfigurationSelectionException.java   Source Code and License 5 votes vote down vote up
static int maxLength(Collection<String> strings) {
    return Ordering.natural().max(Iterables.transform(strings, new Function<String, Integer>() {
        @Override
        public Integer apply(String input) {
            return input.length();
        }
    }));
}
 
Example 47
Project: org.xtext.dsl.restaurante   File: GeneradorTexto.java   Source Code and License 5 votes vote down vote up
public void compilar() {
  StringBuilder sb = new StringBuilder();
  Iterable<Ingrediente> _filter = Iterables.<Ingrediente>filter(IteratorExtensions.<EObject>toIterable(this.resource.getAllContents()), Ingrediente.class);
  for (final Ingrediente i : _filter) {
    sb.append(this.compilarTexto(i));
  }
  this.fsa.generateFile("ingredientes.txt", sb.toString());
  Iterable<Restaurante> _filter_1 = Iterables.<Restaurante>filter(IteratorExtensions.<EObject>toIterable(this.resource.getAllContents()), Restaurante.class);
  for (final Restaurante r : _filter_1) {
    this.fsa.generateFile("resto_informacion.txt", this.compilarTexto(r));
  }
}
 
Example 48
Project: Reer   File: JacocoAgentJar.java   Source Code and License 5 votes vote down vote up
public boolean supportsJmx() {
    boolean pre062 = Iterables.any(getAgentConfConventionValue(), new Predicate<File>() {
        @Override
        public boolean apply(File file) {
            return V_0_6_2_0.compareTo(extractVersion(file.getName())) > 0;
        }
    });
    return !pre062;
}
 
Example 49
Project: powsybl-core   File: MergedBus.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Line> getLines() {
    checkValidity();
    List<Iterable<Line>> iterables = new ArrayList<>(buses.size());
    for (ConfiguredBus bus : buses) {
        iterables.add(bus.getLines());
    }
    return Iterables.concat(iterables);
}
 
Example 50
Project: Reer   File: Assembler.java   Source Code and License 5 votes vote down vote up
@Override
protected Iterable<String> buildPerFileArgs(List<String> genericArgs, List<String> sourceArgs, List<String> outputArgs, List<String> pchArgs) {
    if (pchArgs != null && !pchArgs.isEmpty()) {
        throw new UnsupportedOperationException("Precompiled header arguments cannot be specified for a Assembler compiler.");
    }
    // ml/ml64 have position sensitive arguments,
    // e.g., /Fo must appear before /c and /c must appear before the source file.

    return Iterables.concat(outputArgs, genericArgs, sourceArgs);
}
 
Example 51
Project: hadoop   File: AggregatedLogFormat.java   Source Code and License 5 votes vote down vote up
private Set<File> getPendingLogFilesToUpload(File containerLogDir) {
  Set<File> candidates =
      new HashSet<File>(Arrays.asList(containerLogDir.listFiles()));
  for (File logFile : candidates) {
    this.allExistingFileMeta.add(getLogFileMetaData(logFile));
  }

  if (this.logAggregationContext != null && candidates.size() > 0) {
    filterFiles(
      this.appFinished ? this.logAggregationContext.getIncludePattern()
          : this.logAggregationContext.getRolledLogsIncludePattern(),
      candidates, false);

    filterFiles(
      this.appFinished ? this.logAggregationContext.getExcludePattern()
          : this.logAggregationContext.getRolledLogsExcludePattern(),
      candidates, true);

    Iterable<File> mask =
        Iterables.filter(candidates, new Predicate<File>() {
          @Override
          public boolean apply(File next) {
            return !alreadyUploadedLogFiles
              .contains(getLogFileMetaData(next));
          }
        });
    candidates = Sets.newHashSet(mask);
  }
  return candidates;
}
 
Example 52
Project: guava-mock   File: SplitterBenchmark.java   Source Code and License 5 votes vote down vote up
@Benchmark void stringSplitter(int reps) {
  int total = 0;

  for (int i = 0; i < reps; i++) {
   total += Iterables.size(STRING_SPLITTER.split(input));
  }
}
 
Example 53
Project: CustomWorldGen   File: Clips.java   Source Code and License 5 votes vote down vote up
public Iterable<Event> pastEvents(float lastPollTime, float time)
{
    if(parameter.apply(lastPollTime) < 0 && parameter.apply(time) >= 0)
    {
        return Iterables.mergeSorted(ImmutableSet.of(
            clip.pastEvents(lastPollTime, time),
            ImmutableSet.of(new Event(event, 0))
        ), Ordering.<Event>natural());
    }
    return clip.pastEvents(lastPollTime, time);
}
 
Example 54
Project: Re-Collector   File: PatternChunkSplitterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void successfulSplit() {
    final PatternChunkSplitter splitter = new PatternChunkSplitter("^(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)");

    String logLines = "Feb 20 17:05:18 otter kernel[0]: CODE SIGNING: cs_invalid_page(0x1000): p=32696[GoogleSoftwareUp] final status 0x0, allow (remove VALID)ing page\n" +
            "Feb 20 17:05:18 otter GoogleSoftwareUpdateDaemon[32697]: -[KeystoneDaemon logServiceState] GoogleSoftwareUpdate daemon (1.1.0.3659) vending:\n" +
            "\t\tcom.google.Keystone.Daemon.UpdateEngine: 2 connection(s)\n" +
            "\t\tcom.google.Keystone.Daemon.Administration: 0 connection(s)\n" +
            "Feb 20 17:05:18 otter GoogleSoftwareUpdateDaemon[32697]: -[KSUpdateEngine updateProductID:] KSUpdateEngine updating product ID: \"com.google.Keystone\"\n";
    final ByteBuf buffer = Unpooled.copiedBuffer(logLines, UTF_8);
    final Iterable<String> firstTwoChunks = splitter.split(buffer, UTF_8);
    final Iterable<String> remainingChunk = splitter.splitRemaining(buffer, UTF_8);

    int messageNum = 0;
    for (String chunk : Iterables.concat(firstTwoChunks, remainingChunk)) {
        switch (++messageNum) {
            case 1:
                assertEquals("Feb 20 17:05:18 otter kernel[0]: CODE SIGNING: cs_invalid_page(0x1000): p=32696[GoogleSoftwareUp] final status 0x0, allow (remove VALID)ing page\n", chunk);
                break;
            case 2:
                assertEquals("Feb 20 17:05:18 otter GoogleSoftwareUpdateDaemon[32697]: -[KeystoneDaemon logServiceState] GoogleSoftwareUpdate daemon (1.1.0.3659) vending:\n" +
                                "\t\tcom.google.Keystone.Daemon.UpdateEngine: 2 connection(s)\n" +
                                "\t\tcom.google.Keystone.Daemon.Administration: 0 connection(s)\n",
                        chunk);
                break;
            case 3:
                assertEquals("Feb 20 17:05:18 otter GoogleSoftwareUpdateDaemon[32697]: -[KSUpdateEngine updateProductID:] KSUpdateEngine updating product ID: \"com.google.Keystone\"\n", chunk);
                break;
        }
    }

    assertEquals("the last chunk should have triggered a message (no follow mode active)", 3, messageNum);
}
 
Example 55
Project: dremio-oss   File: ProvisioningServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<ClusterEnriched> getClustersInfo() throws ProvisioningHandlingException {
  // get info about cluster
  // children should do the rest
  Iterable<Map.Entry<ClusterId, Cluster>> clusters = store.find();
  return Iterables.transform(clusters, new InfoFunctionTransformer());
}
 
Example 56
Project: robird-reborn   File: BaseTimelineFragment.java   Source Code and License 5 votes vote down vote up
protected int findPosition(final long tweetId) {
    return Iterables.indexOf(mTweets, new Predicate<Tweet>() {
        @Override
        public boolean apply(Tweet input) {
            return tweetId == input.tweetId();
        }
    });
}
 
Example 57
Project: martini-core   File: DefaultMixologyTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testParameterization() throws IOException {
	Resource resource = new ClassPathResource("/subsystem/parameters.feature");
	Iterable<Recipe> recipes = factory.get(resource);

	int recipeCount = Iterables.size(recipes);
	assertEquals(2, recipeCount, "wrong number of Recipe objects returned");
}
 
Example 58
Project: neoscada   File: ImportWizard.java   Source Code and License 5 votes vote down vote up
protected void applyDiff ( final IProgressMonitor parentMonitor ) throws InterruptedException, ExecutionException
{
    final SubMonitor monitor = SubMonitor.convert ( parentMonitor, 100 );
    monitor.setTaskName ( Messages.ImportWizard_TaskName );

    final Collection<DiffEntry> result = this.mergeController.merge ( wrap ( monitor.newChild ( 10 ) ) );
    if ( result.isEmpty () )
    {
        monitor.done ();
        return;
    }

    final Iterable<List<DiffEntry>> splitted = Iterables.partition ( result, Activator.getDefault ().getPreferenceStore ().getInt ( PreferenceConstants.P_DEFAULT_CHUNK_SIZE ) );

    final SubMonitor sub = monitor.newChild ( 90 );

    try
    {
        final int size = Iterables.size ( splitted );
        sub.beginTask ( Messages.ImportWizard_TaskName, size );

        int pos = 0;
        for ( final Iterable<DiffEntry> i : splitted )
        {
            sub.subTask ( String.format ( Messages.ImportWizard_SubTaskName, pos, size ) );
            final List<DiffEntry> entries = new LinkedList<DiffEntry> ();
            Iterables.addAll ( entries, i );
            final NotifyFuture<Void> future = this.connection.getConnection ().applyDiff ( entries, null, new DisplayCallbackHandler ( getShell (), "Apply diff", "Confirmation for applying diff is required" ) );
            future.get ();

            pos++;
            sub.worked ( 1 );
        }
    }
    finally
    {
        sub.done ();
    }

}
 
Example 59
Project: Reer   File: IdeaScalaConfigurer.java   Source Code and License 5 votes vote down vote up
private static Iterable<File> getIdeaModuleLibraryDependenciesAsFiles(IdeaModule ideaModule) {
    // could make resolveDependencies() cache its result for later use by GenerateIdeaModule
    Set<Dependency> dependencies = ideaModule.resolveDependencies();
    List<File> files = Lists.newArrayList();
    for(ModuleLibrary moduleLibrary : Iterables.filter(dependencies, ModuleLibrary.class)) {
        for (FilePath filePath : Iterables.filter(moduleLibrary.getClasses(), FilePath.class)) {
            files.add(filePath.getFile());
        }
    }
    return files;
}
 
Example 60
Project: Reer   File: IdeaNameDeduper.java   Source Code and License 5 votes vote down vote up
public void configureRoot(Project rootProject) {
    Set<Project> projects = Sets.filter(rootProject.getAllprojects(), HAS_IDEA_PLUGIN);
    Iterable<IdeaModule> ideaModules = Iterables.transform(projects, GET_IDEA_MODULE);
    HierarchicalElementDeduplicator<IdeaModule> deduplicator = new HierarchicalElementDeduplicator<IdeaModule>(new IdeaDeduplicationAdapter());
    Map<IdeaModule, String> deduplicated = deduplicator.deduplicate(ideaModules);
    for (Map.Entry<IdeaModule, String> entry : deduplicated.entrySet()) {
        entry.getKey().setName(entry.getValue());
    }
}