Search in sources :

Example 71 with Predicate

use of com.google.common.base.Predicate in project aic-expresso by aic-sri-international.

the class Context method extendWith.

/**
	 * Extends context with index expressions, taking into account that new contextual variables may collide with existing ones.
	 * In this case, it renames the incoming variables to unique identifiers and replaces them in the types of remaining
	 * index expressions. It also renames the variables in a given expressions supposed to be in their scope (for example,
	 * the head and condition of an intensionally defined set).
	 * Returns the new context and the index expressions and expression in scope after the renaming.
	 * @param indexExpressions
	 * @param expressionInScope
	 * @return the new context and the index expressions and expression in scope after the renaming
	 */
default default Triple<Context, ExtensionalIndexExpressionsSet, Expression> extendWith(ExtensionalIndexExpressionsSet indexExpressions, Expression expressionInScope) {
    Triple<Context, ExtensionalIndexExpressionsSet, Expression> result;
    if (thereExists(getIndices(indexExpressions), index -> this.containsSymbol(index))) {
        // OPTIMIZATION: only kick in this entire procedure when extending with symbol in the context (previous ones could have been dealt with normally).
        // the objects to be returned in the triple:
        Context newContext = this;
        ArrayList<Expression> newIndexExpressionsList = new ArrayList<>(indexExpressions.getList());
        Expression newExpressionInScope = expressionInScope;
        // Collects all existing symbols to be able to create unique symbols
        Set<Expression> alreadyDefined = Util.set();
        alreadyDefined.addAll(this.getSymbols());
        alreadyDefined.addAll(Expressions.freeSymbols(new DefaultTuple(newIndexExpressionsList), this));
        alreadyDefined.addAll(Expressions.freeSymbols(expressionInScope, this));
        Predicate<Expression> isAlreadyDefined = e -> alreadyDefined.contains(e);
        for (int i = 0; i != newIndexExpressionsList.size(); i++) {
            Expression indexExpression = newIndexExpressionsList.get(i);
            Symbol index = (Symbol) indexExpression.get(0);
            Expression type = indexExpression.get(1);
            PairOf<Expression> newIndexAndNewExpressionInScope = Expressions.standardizeApart(index, isAlreadyDefined, newExpressionInScope);
            Expression newIndex = newIndexAndNewExpressionInScope.first;
            newExpressionInScope = newIndexAndNewExpressionInScope.second;
            // type should not contain the index
            Expression newIndexExpression = apply(IN, newIndex, type);
            newIndexExpressionsList.set(i, newIndexExpression);
            alreadyDefined.add(newIndex);
            for (int j = i + 1; j != newIndexExpressionsList.size(); j++) {
                Expression anotherIndexExpression = newIndexExpressionsList.get(j);
                Expression anotherIndex = anotherIndexExpression.get(0);
                Expression anotherType = anotherIndexExpression.get(1);
                Expression newAnotherType = anotherType.replaceSymbol(index, newIndex, this);
                // anotherIndex is a symbols and does not contain index
                Expression newAnotherIndexExpression = apply(IN, anotherIndex, newAnotherType);
                newIndexExpressionsList.set(j, newAnotherIndexExpression);
            }
        }
        ExtensionalIndexExpressionsSet newIndexExpressions = new ExtensionalIndexExpressionsSet(newIndexExpressionsList);
        newContext = newContext.extendWith(newIndexExpressions);
        result = triple(newContext, newIndexExpressions, newExpressionInScope);
    } else {
        // no collision; usual extension and the expressions do not change.
        result = triple(extendWith(indexExpressions), indexExpressions, expressionInScope);
    }
    return result;
}
Also used : IN(com.sri.ai.grinder.sgdpllt.library.FunctorConstants.IN) Type(com.sri.ai.expresso.api.Type) Triple(com.sri.ai.util.base.Triple) Collection(java.util.Collection) Expressions(com.sri.ai.expresso.helper.Expressions) Set(java.util.Set) PairOf(com.sri.ai.util.base.PairOf) Expression(com.sri.ai.expresso.api.Expression) Triple.triple(com.sri.ai.util.base.Triple.triple) DefaultTuple(com.sri.ai.expresso.core.DefaultTuple) ArrayList(java.util.ArrayList) Beta(com.google.common.annotations.Beta) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Symbol(com.sri.ai.expresso.api.Symbol) Expressions.apply(com.sri.ai.expresso.helper.Expressions.apply) Predicate(com.google.common.base.Predicate) Map(java.util.Map) IndexExpressionsSet(com.sri.ai.expresso.api.IndexExpressionsSet) Registry(com.sri.ai.grinder.api.Registry) Util(com.sri.ai.util.Util) IndexExpressions.getIndices(com.sri.ai.grinder.sgdpllt.library.indexexpression.IndexExpressions.getIndices) Util.thereExists(com.sri.ai.util.Util.thereExists) Symbol(com.sri.ai.expresso.api.Symbol) ArrayList(java.util.ArrayList) DefaultTuple(com.sri.ai.expresso.core.DefaultTuple) ExtensionalIndexExpressionsSet(com.sri.ai.expresso.core.ExtensionalIndexExpressionsSet) Expression(com.sri.ai.expresso.api.Expression)

Example 72 with Predicate

use of com.google.common.base.Predicate in project beam by apache.

the class LocalFileSystem method matchOne.

private MatchResult matchOne(String spec) throws IOException {
    File file = Paths.get(spec).toFile();
    if (file.exists()) {
        return MatchResult.create(Status.OK, ImmutableList.of(toMetadata(file)));
    }
    File parent = file.getAbsoluteFile().getParentFile();
    if (!parent.exists()) {
        return MatchResult.create(Status.NOT_FOUND, Collections.<Metadata>emptyList());
    }
    // Method getAbsolutePath() on Windows platform may return something like
    // "c:\temp\file.txt". FileSystem.getPathMatcher() call below will treat
    // '\' (backslash) as an escape character, instead of a directory
    // separator. Replacing backslash with double-backslash solves the problem.
    // We perform the replacement on all platforms, even those that allow
    // backslash as a part of the filename, because Globs.toRegexPattern will
    // eat one backslash.
    String pathToMatch = file.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\"));
    final PathMatcher matcher = java.nio.file.FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch);
    // TODO: Avoid iterating all files: https://issues.apache.org/jira/browse/BEAM-1309
    Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().preOrderTraversal(parent);
    Iterable<File> matchedFiles = Iterables.filter(files, Predicates.and(com.google.common.io.Files.isFile(), new Predicate<File>() {

        @Override
        public boolean apply(File input) {
            return matcher.matches(input.toPath());
        }
    }));
    List<Metadata> result = Lists.newLinkedList();
    for (File match : matchedFiles) {
        result.add(toMetadata(match));
    }
    if (result.isEmpty()) {
        // TODO: consider to return Status.OK for globs.
        return MatchResult.create(Status.NOT_FOUND, new FileNotFoundException(String.format("No files found for spec: %s.", spec)));
    } else {
        return MatchResult.create(Status.OK, result);
    }
}
Also used : PathMatcher(java.nio.file.PathMatcher) Metadata(org.apache.beam.sdk.io.fs.MatchResult.Metadata) FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) Predicate(com.google.common.base.Predicate)

Example 73 with Predicate

use of com.google.common.base.Predicate in project jackrabbit-oak by apache.

the class ObservationTest method filterPropertyOfChild.

@Test
public void filterPropertyOfChild() throws RepositoryException, ExecutionException, InterruptedException {
    assumeTrue(observationManager instanceof ObservationManagerImpl);
    ObservationManagerImpl oManager = (ObservationManagerImpl) observationManager;
    ExpectationListener listener = new ExpectationListener();
    FilterBuilder builder = new FilterBuilder();
    // Events for all items that have a property "b/c/foo" with value "bar"
    builder.condition(builder.property(Selectors.fromThis("b/c"), "foo", new Predicate<PropertyState>() {

        @Override
        public boolean apply(PropertyState property) {
            return "bar".equals(property.getValue(STRING));
        }
    }));
    oManager.addEventListener(listener, builder.build());
    Node testNode = getNode(TEST_PATH);
    Node a = testNode.addNode("a");
    a.addNode("b").addNode("c").setProperty("foo", "bar");
    a.addNode("d");
    Node x = testNode.addNode("x");
    x.addNode("b").addNode("c").setProperty("foo", "baz");
    x.addNode("d");
    listener.expect(a.getPath(), NODE_ADDED);
    testNode.getSession().save();
    List<Expectation> missing = listener.getMissing(TIME_OUT, TimeUnit.SECONDS);
    assertTrue("Missing events: " + missing, missing.isEmpty());
    List<Event> unexpected = listener.getUnexpected();
    assertTrue("Unexpected events: " + unexpected, unexpected.isEmpty());
}
Also used : FilterBuilder(org.apache.jackrabbit.oak.plugins.observation.filter.FilterBuilder) JackrabbitNode(org.apache.jackrabbit.api.JackrabbitNode) Node(javax.jcr.Node) Event(javax.jcr.observation.Event) Predicate(com.google.common.base.Predicate) PropertyState(org.apache.jackrabbit.oak.api.PropertyState) AbstractRepositoryTest(org.apache.jackrabbit.oak.jcr.AbstractRepositoryTest) Test(org.junit.Test)

Example 74 with Predicate

use of com.google.common.base.Predicate in project phoenix by apache.

the class TestNonTxIndexBuilder method assertContains.

// Assert that the given collection of indexUpdates contains the given cell
private void assertContains(Collection<Pair<Mutation, byte[]>> indexUpdates, final long mutationTs, final byte[] row, final Type cellType, final byte[] fam, final byte[] qual, final long cellTs) {
    Predicate<Pair<Mutation, byte[]>> hasCellPredicate = new Predicate<Pair<Mutation, byte[]>>() {

        @Override
        public boolean apply(Pair<Mutation, byte[]> input) {
            assertEquals(TEST_TABLE_INDEX_STRING, Bytes.toString(input.getSecond()));
            Mutation mutation = input.getFirst();
            if (mutationTs == mutation.getTimeStamp()) {
                NavigableMap<byte[], List<Cell>> familyCellMap = mutation.getFamilyCellMap();
                Cell updateCell = familyCellMap.get(fam).get(0);
                if (cellType == KeyValue.Type.codeToType(updateCell.getTypeByte()) && Bytes.compareTo(fam, CellUtil.cloneFamily(updateCell)) == 0 && Bytes.compareTo(qual, CellUtil.cloneQualifier(updateCell)) == 0 && cellTs == updateCell.getTimestamp()) {
                    return true;
                }
            }
            return false;
        }
    };
    Optional<Pair<Mutation, byte[]>> tryFind = Iterables.tryFind(indexUpdates, hasCellPredicate);
    assertTrue(tryFind.isPresent());
}
Also used : List(java.util.List) Mutation(org.apache.hadoop.hbase.client.Mutation) MultiMutation(org.apache.phoenix.hbase.index.MultiMutation) Cell(org.apache.hadoop.hbase.Cell) Predicate(com.google.common.base.Predicate) Pair(org.apache.hadoop.hbase.util.Pair)

Example 75 with Predicate

use of com.google.common.base.Predicate in project jackrabbit-oak by apache.

the class FileCacheStats method build.

/**
     * Retrieves all the files present in the fs cache folder and builds the in-memory cache.
     */
private int build() {
    int count = 0;
    // Move older generation cache downloaded files to the new folder
    DataStoreCacheUpgradeUtils.moveDownloadCache(parent);
    // Iterate over all files in the cache folder
    Iterator<File> iter = Files.fileTreeTraverser().postOrderTraversal(cacheRoot).filter(new Predicate<File>() {

        @Override
        public boolean apply(File input) {
            return input.isFile() && !normalizeNoEndSeparator(input.getParent()).equals(cacheRoot.getAbsolutePath());
        }
    }).iterator();
    while (iter.hasNext()) {
        File toBeSyncedFile = iter.next();
        try {
            put(toBeSyncedFile.getName(), toBeSyncedFile, false);
            count++;
            LOG.trace("Added file [{}} to in-memory cache", toBeSyncedFile);
        } catch (Exception e) {
            LOG.error("Error in putting cached file in map[{}]", toBeSyncedFile);
        }
    }
    LOG.trace("[{}] files put in im-memory cache", count);
    return count;
}
Also used : FileUtils.copyInputStreamToFile(org.apache.commons.io.FileUtils.copyInputStreamToFile) File(java.io.File) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Predicate(com.google.common.base.Predicate)

Aggregations

Predicate (com.google.common.base.Predicate)217 List (java.util.List)37 Test (org.junit.Test)37 ArrayList (java.util.ArrayList)34 Nullable (javax.annotation.Nullable)33 Map (java.util.Map)24 UUID (java.util.UUID)21 IOException (java.io.IOException)20 File (java.io.File)18 HashMap (java.util.HashMap)15 Set (java.util.Set)14 Test (org.testng.annotations.Test)14 ImmutableList (com.google.common.collect.ImmutableList)13 Collection (java.util.Collection)11 DateTime (org.joda.time.DateTime)9 BigDecimal (java.math.BigDecimal)8 Path (javax.ws.rs.Path)8 Expression (com.sri.ai.expresso.api.Expression)7 Util (com.sri.ai.util.Util)7 XtextResource (org.eclipse.xtext.resource.XtextResource)7