/**
* 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);
}
java类com.google.common.collect.Iterables的实例源码
TestOracleMetaDataProvider.java 文件源码
项目:morf
阅读 34
收藏 0
点赞 0
评论 0
SqlFormatter.java 文件源码
项目:Elasticsearch
阅读 47
收藏 0
点赞 0
评论 0
@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;
}
SimpleReloadableResourceManager.java 文件源码
项目:DecompiledMinecraft
阅读 50
收藏 0
点赞 0
评论 0
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();
}
ArgusClientTest.java 文件源码
项目:pyplyn
阅读 36
收藏 0
点赞 0
评论 0
@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));
}
ManagedProxyClassGenerator.java 文件源码
项目:Reer
阅读 52
收藏 0
点赞 0
评论 0
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);
}
ModelPathSuggestionProvider.java 文件源码
项目:Reer
阅读 38
收藏 0
点赞 0
评论 0
@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);
}
UpgradePath.java 文件源码
项目:morf
阅读 26
收藏 0
点赞 0
评论 0
/**
* @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);
}
TestFileInputFormat.java 文件源码
项目:hadoop
阅读 51
收藏 0
点赞 0
评论 0
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());
}
ListSchema.java 文件源码
项目:QDrill
阅读 38
收藏 0
点赞 0
评论 0
@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;
}
ClientTransaction.java 文件源码
项目:hashsdn-controller
阅读 32
收藏 0
点赞 0
评论 0
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);
}
CompareFunction.java 文件源码
项目:dremio-oss
阅读 30
收藏 0
点赞 0
评论 0
@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()));
}
AbstractServiceTest.java 文件源码
项目:googles-monorepo-demo
阅读 44
收藏 0
点赞 0
评论 0
@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();
}
MultisetEntrySetTester.java 文件源码
项目:googles-monorepo-demo
阅读 46
收藏 0
点赞 0
评论 0
@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());
}
TableFunctionCollectSource.java 文件源码
项目:Elasticsearch
阅读 30
收藏 0
点赞 0
评论 0
@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);
}
Lang.java 文件源码
项目:BaseClient
阅读 36
收藏 0
点赞 0
评论 0
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);
}
}
}
}
DefaultCategories.java 文件源码
项目:martini-core
阅读 34
收藏 0
点赞 0
评论 0
@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);
}
}
}
}
PodcastService.java 文件源码
项目:airsonic
阅读 45
收藏 0
点赞 0
评论 0
/**
* 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();
}
}));
}
JSLibSingleTestConfigProvider.java 文件源码
项目:n4js
阅读 36
收藏 0
点赞 0
评论 0
/**
* 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;
}
TestMetricsSystemImpl.java 文件源码
项目:hadoop-oss
阅读 38
收藏 0
点赞 0
评论 0
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)));
}
DefaultTaskOutputs.java 文件源码
项目:Reer
阅读 30
收藏 0
点赞 0
评论 0
@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;
}
MoviePersistenceServiceImpl.java 文件源码
项目:REST-Web-Services
阅读 39
收藏 0
点赞 0
评论 0
/**
* {@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();
}
PopulatedCachesTest.java 文件源码
项目:googles-monorepo-demo
阅读 39
收藏 0
点赞 0
评论 0
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()));
}
TypeUtils.java 文件源码
项目:n4js
阅读 43
收藏 0
点赞 0
评论 0
/**
* 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();
}
CloserTest.java 文件源码
项目:guava-mock
阅读 37
收藏 0
点赞 0
评论 0
@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);
}
}
MemberMatrix.java 文件源码
项目:n4js
阅读 44
收藏 0
点赞 0
评论 0
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();
}
FileImporterImpl.java 文件源码
项目:appinventor-extensions
阅读 37
收藏 0
点赞 0
评论 0
@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);
}
OrderedDocCollector.java 文件源码
项目:Elasticsearch
阅读 46
收藏 0
点赞 0
评论 0
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));
}
TypeMap.java 文件源码
项目:ProjectAres
阅读 43
收藏 0
点赞 0
评论 0
/**
* 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();
}
}
MergedBus.java 文件源码
项目:powsybl-core
阅读 36
收藏 0
点赞 0
评论 0
@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);
}
N4ClassifierDefinitionImpl.java 文件源码
项目:n4js
阅读 43
收藏 0
点赞 0
评论 0
/**
* <!-- 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);
}