org.junit.contrib.java.lang.system.Assertion#com.google.common.base.Predicate源码实例Demo

下面列出了org.junit.contrib.java.lang.system.Assertion#com.google.common.base.Predicate 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: coming   文件: jMutRepair_003_s.java
/**
 * Apply the supplied predicate against
 * all possible result Nodes of the expression.
 */
static boolean anyResultsMatch(Node n, Predicate<Node> p) {
  switch (n.getType()) {
    case Token.ASSIGN:
    case Token.COMMA:
      return anyResultsMatch(n.getLastChild(), p);
    case Token.AND:
    case Token.OR:
      return anyResultsMatch(n.getFirstChild(), p)
          || anyResultsMatch(n.getLastChild(), p);
    case Token.HOOK:
      return anyResultsMatch(n.getFirstChild().getNext(), p)
          || anyResultsMatch(n.getLastChild(), p);
    default:
      return p.apply(n);
  }
}
 
源代码2 项目: brooklyn-server   文件: SshMachineLocationTest.java
@Test
public void testDoesNotLogPasswordsInEnvironmentVariables() {
    List<String> loggerNames = ImmutableList.of(
            SshMachineLocation.class.getName(), 
            BrooklynLogging.SSH_IO, 
            SshjTool.class.getName());
    ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.DEBUG;
    Predicate<ILoggingEvent> filter = Predicates.or(
            EventPredicates.containsMessage("DB_PASSWORD"), 
            EventPredicates.containsMessage("mypassword"));
    try (LogWatcher watcher = new LogWatcher(loggerNames, logLevel, filter)) {
        host.execCommands("mySummary", ImmutableList.of("true"), ImmutableMap.of("DB_PASSWORD", "mypassword"));
        watcher.assertHasEventEventually();
        
        Optional<ILoggingEvent> eventWithPasswd = Iterables.tryFind(watcher.getEvents(), EventPredicates.containsMessage("mypassword"));
        assertFalse(eventWithPasswd.isPresent(), "event="+eventWithPasswd);
    }
}
 
源代码3 项目: hraven   文件: ObjectMapperProvider.java
@Override
public void serialize(Configuration conf, JsonGenerator jsonGenerator,
    SerializerProvider serializerProvider) throws IOException {
  SerializationContext context = RestResource.serializationContext
      .get();
  Predicate<String> configFilter = context.getConfigurationFilter();
  Iterator<Map.Entry<String, String>> keyValueIterator = conf.iterator();

  jsonGenerator.writeStartObject();

  // here's where we can filter out keys if we want
  while (keyValueIterator.hasNext()) {
    Map.Entry<String, String> kvp = keyValueIterator.next();
    if (configFilter == null || configFilter.apply(kvp.getKey())) {
      jsonGenerator.writeFieldName(kvp.getKey());
      jsonGenerator.writeString(kvp.getValue());
    }
  }
  jsonGenerator.writeEndObject();
}
 
源代码4 项目: dsl-devkit   文件: FormatJavaValidator.java
/**
 * Verify that only rule self directives are used for terminal, enum and data type rules.
 *
 * @param model
 *          the GrammarRule
 */
@Check
public void checkDataTypeOrEnumRule(final GrammarRule model) {
  if (model.getTargetRule() instanceof TerminalRule || model.getTargetRule() instanceof EnumRule
      || (model.getTargetRule() instanceof ParserRule && GrammarUtil.isDatatypeRule((ParserRule) model.getTargetRule()))) {
    Iterator<EObject> grammarElementAccessors = collectGrammarElementAccessors(model);
    boolean selfAccessOnly = Iterators.all(grammarElementAccessors, new Predicate<EObject>() {
      @Override
      public boolean apply(final EObject input) {
        return input instanceof GrammarElementReference && ((GrammarElementReference) input).getSelf() != null;
      }
    });
    if (!selfAccessOnly) {
      error(NLS.bind("For data type, enum or terminal rule {0} only ''rule'' directive may be used", model.getTargetRule().getName()), FormatPackage.Literals.GRAMMAR_RULE__DIRECTIVES, ILLEGAL_DIRECTIVE_CODE);
    }
  }
}
 
源代码5 项目: putnami-web-toolkit   文件: IssueServiceImpl.java
@Override
public List<Issue> searchIssues(final String name, final String label) {
	Iterable<Issue> filteredIterable = Iterables.filter(issues.values(), new Predicate<Issue>() {

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

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

				});
				result = result && filteredLabels.iterator().hasNext();
			}
			return result;
		}
	});
	return Lists.newArrayList(filteredIterable);
}
 
private static void trueMain(final String[] argv) throws IOException {
  if (argv.length == 1) {
    final Parameters params = Parameters.loadSerifStyle(new File(argv[0]));
    log.info(params.dump());

    final Function<DocumentSystemOutput, DocumentSystemOutput> filter =
        getSystemOutputFilter(params);
    final Predicate<Symbol> docIdFilter = getDocIdFilter(params);

    final SystemOutputLayout outputLayout = SystemOutputLayout.ParamParser.fromParamVal(
        params.getString("outputLayout"));
    final AssessmentSpecFormats.Format annStoreFileFormat =
        params.getEnum("annStore.fileFormat", AssessmentSpecFormats.Format.class);

    final ImmutableSet<SystemOutputStore> systemOutputs =
        loadSystemOutputStores(params, outputLayout);
    final ImmutableSet<AnnotationStore> annotationStores =
        loadAnnotationStores(params, annStoreFileFormat);

    importSystemOutputToAnnotationStore(systemOutputs, annotationStores, filter,
        docIdFilter);
  } else {
    usage();
  }
}
 
源代码7 项目: coming   文件: jMutRepair_003_t.java
/**
 * @return Whether the predicate is true for the node or any of its children.
 */
static boolean has(Node node,
                   Predicate<Node> pred,
                   Predicate<Node> traverseChildrenPred) {
  if (pred.apply(node)) {
    return true;
  }

  if (!traverseChildrenPred.apply(node)) {
    return false;
  }

  for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
    if (has(c, pred, traverseChildrenPred)) {
      return true;
    }
  }

  return false;
}
 
源代码8 项目: xtext-extras   文件: ResolvedTypes.java
@Override
public Collection<ILinkingCandidate> getFollowUpErrors() {
	Collection<?> rawResult = Collections2.filter(basicGetLinkingMap().values(), new Predicate<IApplicableCandidate>() {
		@Override
		public boolean apply(/* @Nullable */ IApplicableCandidate input) {
			if (input == null)
				throw new IllegalArgumentException();
			if (input instanceof FollowUpError)
				return true;
			return false;
		}
	});
	@SuppressWarnings("unchecked") // cast is safe
	Collection<ILinkingCandidate> result = (Collection<ILinkingCandidate>) rawResult;
	return result;
}
 
源代码9 项目: rocket-console   文件: ConsumerServiceImpl.java
@Override
public List<TopicConsumerInfo> queryConsumeStatsList(final String topic, String groupName) {
    ConsumeStats consumeStats = null;
    try {
        consumeStats = mqAdminExt.examineConsumeStats(groupName); // todo  ConsumeStats examineConsumeStats(final String consumerGroup, final String topic) can use
    } catch (Exception e) {
        throw propagate(e);
    }
    List<MessageQueue> mqList = Lists.newArrayList(Iterables.filter(consumeStats.getOffsetTable().keySet(), new Predicate<MessageQueue>() {
        @Override
        public boolean apply(MessageQueue o) {
            return StringUtils.isBlank(topic) || o.getTopic().equals(topic);
        }
    }));
    Collections.sort(mqList);
    List<TopicConsumerInfo> topicConsumerInfoList = Lists.newArrayList();
    TopicConsumerInfo nowTopicConsumerInfo = null;
    for (MessageQueue mq : mqList) {
        if (nowTopicConsumerInfo == null || (!StringUtils.equals(mq.getTopic(), nowTopicConsumerInfo.getTopic()))) {
            nowTopicConsumerInfo = new TopicConsumerInfo(mq.getTopic());
            topicConsumerInfoList.add(nowTopicConsumerInfo);
        }
        nowTopicConsumerInfo.appendQueueStatInfo(QueueStatInfo.fromOffsetTableEntry(mq, consumeStats.getOffsetTable().get(mq)));
    }
    return topicConsumerInfoList;
}
 
源代码10 项目: SimFix   文件: 1_NodeUtil.java
/**
 * Apply the supplied predicate against the potential
 * all possible result of the expression.
 */
static boolean valueCheck(Node n, Predicate<Node> p) {
  switch (n.getType()) {
    case Token.ASSIGN:
    case Token.COMMA:
      return valueCheck(n.getLastChild(), p);
    case Token.AND:
    case Token.OR:
      return valueCheck(n.getFirstChild(), p)
          && valueCheck(n.getLastChild(), p);
    case Token.HOOK:
      return valueCheck(n.getFirstChild().getNext(), p)
          && valueCheck(n.getLastChild(), p);
    default:
      return p.apply(n);
  }
}
 
/**
 * A raw dataset version is qualified to be deleted, iff the corresponding refined paths exist, and the latest
 * mod time of all files is in the raw dataset is earlier than the latest mod time of all files in the refined paths.
 */
protected Collection<FileSystemDatasetVersion> listQualifiedRawFileSystemDatasetVersions(Collection<FileSystemDatasetVersion> allVersions) {
  return Lists.newArrayList(Collections2.filter(allVersions, new Predicate<FileSystemDatasetVersion>() {
    @Override
    public boolean apply(FileSystemDatasetVersion version) {
      Iterable<Path> refinedDatasetPaths = getRefinedDatasetPaths(version);
      try {
        Optional<Long> latestRawDatasetModTime = getLatestModTime(version.getPaths());
        Optional<Long> latestRefinedDatasetModTime = getLatestModTime(refinedDatasetPaths);
        return latestRawDatasetModTime.isPresent() && latestRefinedDatasetModTime.isPresent()
            && latestRawDatasetModTime.get() <= latestRefinedDatasetModTime.get();
      } catch (IOException e) {
        throw new RuntimeException("Failed to get modification time", e);
      }
    }
  }));
}
 
源代码12 项目: coming   文件: Closure_75_NodeUtil_s.java
/**
 * Apply the supplied predicate against the potential
 * all possible result of the expression.
 */
static boolean valueCheck(Node n, Predicate<Node> p) {
  switch (n.getType()) {
    case Token.ASSIGN:
    case Token.COMMA:
      return valueCheck(n.getLastChild(), p);
    case Token.AND:
    case Token.OR:
      return valueCheck(n.getFirstChild(), p)
          && valueCheck(n.getLastChild(), p);
    case Token.HOOK:
      return valueCheck(n.getFirstChild().getNext(), p)
          && valueCheck(n.getLastChild(), p);
    default:
      return p.apply(n);
  }
}
 
源代码13 项目: coming   文件: Closure_86_NodeUtil_s.java
/**
 * @return The number of times the the predicate is true for the node
 * or any of its children.
 */
static int getCount(
    Node n, Predicate<Node> pred, Predicate<Node> traverseChildrenPred) {
  int total = 0;

  if (pred.apply(n)) {
    total++;
  }

  if (traverseChildrenPred.apply(n)) {
    for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
      total += getCount(c, pred, traverseChildrenPred);
    }
  }

  return total;
}
 
源代码14 项目: arcusplatform   文件: ValueChangeConfig.java
@Override
public Condition generate(Map<String, Object> values) {
   Preconditions.checkState(attribute != null, "must specify an attribute name");
   
   String attributeName;
   Object oldValue = null;
   Object newValue = null;
   Predicate<Model> query = Predicates.alwaysTrue();
   
   
   attributeName = FunctionFactory.toString(this.attribute.toTemplate(), values);
   if(this.oldValue != null) {
      oldValue = this.oldValue.toTemplate().apply(values);
   }
   if(this.newValue != null) {
      newValue = this.newValue.toTemplate().apply(values);
   }
   if(this.query != null) {
      query = FunctionFactory.toModelPredicate(this.query.toTemplate(), values);
   }
   return new ValueChangeTrigger(attributeName, oldValue, newValue, query);
}
 
源代码15 项目: xtext-xtend   文件: ConvertJavaCode.java
private boolean validateResource(Resource resource) {
	if (resource.getErrors().size() == 0) {
		List<Issue> issues = Lists.newArrayList(filter(((XtextResource) resource).getResourceServiceProvider()
				.getResourceValidator().validate(resource, CheckMode.ALL, CancelIndicator.NullImpl),
				new Predicate<Issue>() {
					@Override
					public boolean apply(Issue issue) {
						String code = issue.getCode();
						return issue.getSeverity() == Severity.ERROR
								&& !(IssueCodes.DUPLICATE_TYPE.equals(code) || org.eclipse.xtend.core.validation.IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH
										.equals(code));
					}
				}));
		return issues.size() == 0;
	}
	return false;
}
 
源代码16 项目: coming   文件: Closure_60_NodeUtil_t.java
/**
 * Apply the supplied predicate against the potential
 * all possible result of the expression.
 */
static boolean valueCheck(Node n, Predicate<Node> p) {
  switch (n.getType()) {
    case Token.ASSIGN:
    case Token.COMMA:
      return valueCheck(n.getLastChild(), p);
    case Token.AND:
    case Token.OR:
      return valueCheck(n.getFirstChild(), p)
          && valueCheck(n.getLastChild(), p);
    case Token.HOOK:
      return valueCheck(n.getFirstChild().getNext(), p)
          && valueCheck(n.getLastChild(), p);
    default:
      return p.apply(n);
  }
}
 
源代码17 项目: codebuff   文件: FilteredEntryMultimap.java
boolean removeEntriesIf(Predicate<? super Entry<K, Collection<V>>> predicate) {
  Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator();
  boolean changed = false;
  while (entryIterator.hasNext()) {
    Entry<K, Collection<V>> entry = entryIterator.next();
    K key = entry.getKey();
    Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key));
    if (!collection.isEmpty() && predicate.apply(Maps.immutableEntry(key, collection))) {
      if (collection.size() == entry.getValue().size()) {
        entryIterator.remove();
      } else {
        collection.clear();
      }
      changed = true;
    }
  }
  return changed;
}
 
源代码18 项目: xtext-core   文件: ValidationTestHelper.java
protected Iterable<Issue> doMatchIssues(final Resource resource, final EClass objectType, final String code,
		final int offset, final int length, final Severity severity, final List<Issue> validate,
		final String... messageParts) {
	return Iterables.filter(validate, new Predicate<Issue>() {
		@Override
		public boolean apply(Issue input) {
			if (Strings.equal(input.getCode(), code) && input.getSeverity()==severity) {
				if ((offset < 0 || offset == input.getOffset()) && (length < 0 || length == input.getLength())) {
					EObject object = resource.getResourceSet().getEObject(input.getUriToProblem(), true);
					if (objectType.isInstance(object)) {
						for (String messagePart : messageParts) {
							if(!isValidationMessagePartMatches(input.getMessage(), messagePart)){
								return false;
							}
						}
						return true;
					}
				}
			}
			return false;
		}
	});
}
 
源代码19 项目: enderutilities   文件: TileEntityElevator.java
public static Predicate<TileEntity> isMatchingElevator(final EnumDyeColor color)
{
    return new Predicate<TileEntity> ()
    {
        @Override
        public boolean apply(TileEntity te)
        {
            if ((te instanceof TileEntityElevator) == false)
            {
                return false;
            }

            IBlockState state = te.getWorld().getBlockState(te.getPos());

            return state.getBlock() instanceof BlockElevator && state.getValue(BlockElevator.COLOR) == color;
        }
    };
}
 
/**
 * Returns whether the EntityAIBase should begin execution.
 */
@SuppressWarnings("unchecked")
public boolean shouldExecute() {
	if (this.targetChance > 0 && this.taskOwner.getRNG().nextInt(this.targetChance) != 0) {
		return false;
	} else if (this.targetClass != EntityPlayer.class && this.targetClass != EntityPlayerMP.class) {
		List<T> list = this.taskOwner.world.getEntitiesWithinAABB(this.targetClass, this.getTargetableArea(this.getTargetDistance()), this.targetEntitySelector);

		if (list.isEmpty()) {
			return false;
		} else {
			list.sort(this.sorter);
			this.targetEntity = list.get(0);
			return true;
		}
	} else {
		this.targetEntity = (T) this.taskOwner.world.getNearestAttackablePlayer(this.taskOwner.posX, this.taskOwner.posY + (double) this.taskOwner.getEyeHeight(), this.taskOwner.posZ, this.getTargetDistance(), this.getTargetDistance(), new Function<EntityPlayer, Double>() {
			@Nullable
			public Double apply(@Nullable EntityPlayer p_apply_1_) {
				ItemStack itemstack = p_apply_1_.getItemStackFromSlot(EntityEquipmentSlot.HEAD);

				if (itemstack.getItem() == Items.SKULL) {
					int i = itemstack.getItemDamage();
					boolean flag = EntityAINearestAttackableTargetFiltered.this.taskOwner instanceof EntitySkeleton && i == 0;
					boolean flag1 = EntityAINearestAttackableTargetFiltered.this.taskOwner instanceof EntityZombie && i == 2;
					boolean flag2 = EntityAINearestAttackableTargetFiltered.this.taskOwner instanceof EntityCreeper && i == 4;

					if (flag || flag1 || flag2) {
						return Double.valueOf(0.5D);
					}
				}

				return Double.valueOf(1.0D);
			}
		}, (Predicate<EntityPlayer>) this.targetEntitySelector);
		return this.targetEntity != null;
	}
}
 
源代码21 项目: metron   文件: PcapTopologyIntegrationTest.java
@Test
public void filters_results_by_dst_port_greater_than_value_with_query_filter() throws Exception {
  PcapOptions.FILTER_IMPL.put(configuration, new QueryPcapFilter.Configurator());
  PcapOptions.START_TIME_NS.put(configuration, getTimestamp(0, pcapEntries));
  PcapOptions.END_TIME_NS
      .put(configuration, getTimestamp(pcapEntries.size() - 1, pcapEntries) + 1);
  PcapOptions.FIELDS.put(configuration, "ip_dst_port > 55790");
  PcapJob<String> job = new PcapJob<>();
  Statusable<Path> results = job.submit(PcapFinalizerStrategies.CLI, configuration);
  assertEquals(Statusable.JobType.MAP_REDUCE, results.getJobType());
  waitForJob(results);

  assertEquals(JobStatus.State.SUCCEEDED, results.getStatus().getState());
  Pageable<Path> resultPages = results.get();
  Iterable<byte[]> bytes = Iterables.transform(resultPages, path -> {
    try {
      return HDFSUtils.readBytes(path);
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  });
  assertInOrder(bytes);
  assertEquals(Iterables.size(filterPcaps(pcapEntries, new Predicate<JSONObject>() {
            @Override
            public boolean apply(@Nullable JSONObject input) {
              Object prt = input.get(Constants.Fields.DST_PORT.getName());
              return prt != null && (Long) prt > 55790;
            }
          }, withHeaders)
      ), resultPages.getSize()
  );
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PcapMerger.merge(baos, HDFSUtils.readBytes(resultPages.getPage(0)));
  assertTrue(baos.toByteArray().length > 0);
}
 
源代码22 项目: sql-layer   文件: OverloadsFolder.java
public InputSetFlags toInputSetFlags(Predicate<? super T> predicate) {
    boolean[] finites = new boolean[finiteArityList.size()];
    for (int i = 0; i < finites.length; ++i) {
        finites[i] = predicate.apply(finiteArityList.get(i));
    }
    boolean infinite = predicate.apply(infiniteArityElement);
    return new InputSetFlags(finites, infinite);
}
 
源代码23 项目: bonita-studio   文件: FormMappingConstraint.java
private Predicate<FormMapping> withType(final FormMappingType type) {
    return new Predicate<FormMapping>() {

        @Override
        public boolean apply(final FormMapping input) {
            return input.getType() == type;
        }
    };
}
 
@Test
public final void givenEvenNumbers_whenCheckingIfAllSatisfyTheEvenPredicate_thenYes() {
    final List<Integer> evenNumbers = Lists.newArrayList(2, 6, 8, 10, 34, 90);
    final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() {
        @Override
        public final boolean apply(final Integer number) {
            return (number % 2) == 0;
        }
    };

    assertTrue(Iterables.all(evenNumbers, acceptEvenNumber));
}
 
源代码25 项目: codebuff   文件: Maps.java
FilteredKeyMap(
                 Map<K, V> unfiltered,
                 Predicate<? super K> keyPredicate,
                 Predicate<? super Entry<K, V>> entryPredicate) {
  super(unfiltered, entryPredicate);
  this.keyPredicate = keyPredicate;
}
 
源代码26 项目: pushfish-android   文件: ScopeVisitor.java
private void addCreator(String path, ClosureExpression creator) {
    final ImmutableMap<String, String> referenceAliasesMap = ImmutableMap.copyOf(referenceAliases);
    ReferenceExtractor extractor = new ReferenceExtractor(sourceUnit, referenceAliasesMap);
    Iterators.removeIf(creator.getVariableScope().getReferencedLocalVariablesIterator(), new Predicate<Variable>() {
        public boolean apply(Variable variable) {
            return referenceAliasesMap.keySet().contains(variable.getName());
        }
    });
    creator.getCode().visit(extractor);
    statementGenerator.addCreator(path, creator, extractor.getReferencedPaths());
}
 
源代码27 项目: xtext-core   文件: XtextLinkingService.java
private EPackage findPackageInScope(EObject context, QualifiedName packageNsURI) {
	IScope scopedPackages = scopeProvider.getScope(context.eResource(), XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, new Predicate<IEObjectDescription>() {
		@Override
		public boolean apply(IEObjectDescription input) {
			return isNsUriIndexEntry(input);
		}
	});
	IEObjectDescription description = scopedPackages.getSingleElement(packageNsURI);
	if (description != null) {
		return getResolvedEPackage(description, context);
	}
	return null;
}
 
源代码28 项目: arcusplatform   文件: ExpressionBuilder.java
@Override
protected Predicate<Model> doBuild() {
       switch(operator) {
       case IS:
          return Predicates.isA(namespace);
       case HAS:
          return Predicates.hasA(namespace);
       default:
          throw new IllegalArgumentException("Unrecognized operator " + operator);
       }
}
 
源代码29 项目: codebuff   文件: TypeToken.java
@Override
public Set<Class<? super T>> rawTypes() {
  // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
  @SuppressWarnings({"unchecked", "rawtypes"})
  ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
  return FluentIterable.from(collectedTypes).filter(new Predicate<Class<?>>() {
                                                      @Override
                                                      public boolean apply(Class<?> type) {
                                                        return type.isInterface();
                                                      }
                                                    }).toSet();
}
 
源代码30 项目: xtext-core   文件: EObjectDescriptionLookUp.java
@Override
public Iterable<IEObjectDescription> getExportedObjectsByType(final EClass type) {
	if (allDescriptions.isEmpty())
		return Collections.emptyList();
	return Iterables.filter(allDescriptions, new Predicate<IEObjectDescription>() {
		@Override
		public boolean apply(IEObjectDescription input) {
			return EcoreUtil2.isAssignableFrom(type, input.getEClass());
		}
	});
}