Search in sources :

Example 86 with Predicate

use of com.google.common.base.Predicate in project cdap by caskdata.

the class WorkflowTest method testOneActionWorkflow.

@Test(timeout = 120 * 1000L)
public void testOneActionWorkflow() throws Exception {
    final ApplicationWithPrograms app = AppFabricTestHelper.deployApplicationWithManager(OneActionWorkflowApp.class, TEMP_FOLDER_SUPPLIER);
    final Injector injector = AppFabricTestHelper.getInjector();
    final ProgramDescriptor programDescriptor = Iterators.filter(app.getPrograms().iterator(), new Predicate<ProgramDescriptor>() {

        @Override
        public boolean apply(ProgramDescriptor input) {
            return input.getProgramId().getType() == ProgramType.WORKFLOW;
        }
    }).next();
    final SettableFuture<String> completion = SettableFuture.create();
    final ProgramController controller = AppFabricTestHelper.submit(app, programDescriptor.getSpecification().getClassName(), new BasicArguments(), TEMP_FOLDER_SUPPLIER);
    controller.addListener(new AbstractListener() {

        @Override
        public void init(ProgramController.State currentState, @Nullable Throwable cause) {
            LOG.info("Initializing");
            injector.getInstance(Store.class).setStart(controller.getProgramRunId().getParent(), controller.getProgramRunId().getRun(), System.currentTimeMillis());
        }

        @Override
        public void completed() {
            LOG.info("Completed");
            completion.set("Completed");
        }

        @Override
        public void error(Throwable cause) {
            LOG.info("Error", cause);
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    String run = completion.get();
    Assert.assertEquals("Completed", run);
}
Also used : ProgramController(co.cask.cdap.app.runtime.ProgramController) ApplicationWithPrograms(co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) Injector(com.google.inject.Injector) AbstractListener(co.cask.cdap.internal.app.runtime.AbstractListener) ProgramDescriptor(co.cask.cdap.app.program.ProgramDescriptor) BasicArguments(co.cask.cdap.internal.app.runtime.BasicArguments) Predicate(com.google.common.base.Predicate) Test(org.junit.Test)

Example 87 with Predicate

use of com.google.common.base.Predicate in project cdap by caskdata.

the class LeaderElectionInfoServiceTest method testParticipants.

@Test
public void testParticipants() throws Exception {
    final int size = 5;
    String prefix = "/election";
    List<ZKClientService> zkClients = new ArrayList<>();
    ZKClientService infoZKClient = DefaultZKClientService.Builder.of(zkServer.getConnectionStr()).build();
    infoZKClient.startAndWait();
    zkClients.add(infoZKClient);
    // Start the LeaderElectionInfoService
    LeaderElectionInfoService infoService = new LeaderElectionInfoService(infoZKClient, prefix);
    infoService.startAndWait();
    // This will timeout as there is no leader election node created yet
    try {
        infoService.getParticipants(1, TimeUnit.SECONDS);
        Assert.fail("Expected timeout");
    } catch (TimeoutException e) {
    // Expected
    }
    // Starts multiple leader elections
    List<LeaderElection> leaderElections = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        ZKClientService zkClient = DefaultZKClientService.Builder.of(zkServer.getConnectionStr()).build();
        zkClient.startAndWait();
        zkClients.add(zkClient);
        final int participantId = i;
        LeaderElection leaderElection = new LeaderElection(zkClient, prefix, new ElectionHandler() {

            @Override
            public void leader() {
                LOG.info("Leader: {}", participantId);
            }

            @Override
            public void follower() {
                LOG.info("Follow: {}", participantId);
            }
        });
        leaderElection.start();
        leaderElections.add(leaderElection);
    }
    // Get the dynamic participants map
    final SortedMap<Integer, LeaderElectionInfoService.Participant> participants = infoService.getParticipants(5, TimeUnit.SECONDS);
    // Expects to set all participants with hostname information
    Tasks.waitFor(true, new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            if (participants.size() != size) {
                return false;
            }
            return Iterables.all(participants.values(), new Predicate<LeaderElectionInfoService.Participant>() {

                @Override
                public boolean apply(LeaderElectionInfoService.Participant input) {
                    return input.getHostname() != null;
                }
            });
        }
    }, 5, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    // Fetch the static snapshot. It should be the same as the dynamic participants.
    SortedMap<Integer, LeaderElectionInfoService.Participant> snapshot = infoService.fetchCurrentParticipants();
    Assert.assertEquals(size, snapshot.size());
    Assert.assertEquals(participants, snapshot);
    int expectedSize = size;
    for (LeaderElection leaderElection : leaderElections) {
        leaderElection.stopAndWait();
        Tasks.waitFor(--expectedSize, new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                return participants.size();
            }
        }, 5, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    }
    // Fetch the static snapshot again. It should be empty and the same as the dynamic one.
    snapshot = infoService.fetchCurrentParticipants();
    Assert.assertTrue(snapshot.isEmpty());
    Assert.assertEquals(participants, snapshot);
    infoService.stopAndWait();
    for (ZKClientService zkClient : zkClients) {
        zkClient.stopAndWait();
    }
}
Also used : ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) Predicate(com.google.common.base.Predicate) ZKClientService(org.apache.twill.zookeeper.ZKClientService) DefaultZKClientService(org.apache.twill.internal.zookeeper.DefaultZKClientService) LeaderElection(org.apache.twill.internal.zookeeper.LeaderElection) ElectionHandler(org.apache.twill.api.ElectionHandler) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 88 with Predicate

use of com.google.common.base.Predicate in project android by JetBrains.

the class AndroidModuleInfoTest method testManifestMerger.

public void testManifestMerger() throws Exception {
    loadProject(MODULE_INFO_MANIFEST_MERGER);
    assertNotNull(myAndroidFacet);
    assertEquals(1, AndroidUtils.getAllAndroidDependencies(myAndroidFacet.getModule(), true).size());
    MergedManifest manifestInfo = MergedManifest.get(myAndroidFacet);
    List<Element> mergedActivities = manifestInfo.getActivities();
    assertEquals(3, mergedActivities.size());
    Set<String> activities = Sets.newHashSet(ActivityLocatorUtils.getQualifiedName(mergedActivities.get(0)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(1)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(2)));
    assertTrue(activities.contains("test.helloworldapp.Debug"));
    assertTrue(activities.contains("test.helloworldapp.MyActivity"));
    assertTrue(activities.contains("test.helloworldapp.lib.LibActivity"));
    assertNotNull(manifestInfo.getVersionCode());
    assertEquals(2, manifestInfo.getVersionCode().intValue());
    // Make a change to the psi
    VirtualFile manifestFile = AndroidRootUtil.getPrimaryManifestFile(myAndroidFacet);
    assertNotNull(manifestFile);
    PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(manifestFile);
    assertNotNull(psiFile);
    new WriteCommandAction.Simple(getProject(), psiFile) {

        @Override
        protected void run() throws Throwable {
            assertNotNull(myAndroidFacet.getManifest());
            XmlTag manifestTag = myAndroidFacet.getManifest().getXmlTag();
            XmlTag applicationTag = Iterables.find(Arrays.asList(manifestTag.getSubTags()), new Predicate<XmlTag>() {

                @Override
                public boolean apply(@Nullable XmlTag input) {
                    assertNotNull(input);
                    return "application".equals(input.getName());
                }
            });
            XmlTag activityTag = applicationTag.createChildTag("activity", "", null, false);
            activityTag.setAttribute("android:name", ".AddedActivity");
            applicationTag.addSubTag(activityTag, false);
        }
    }.execute();
    UIUtil.dispatchAllInvocationEvents();
    // reload data and check it is correct
    manifestInfo.clear();
    mergedActivities = manifestInfo.getActivities();
    assertEquals(4, mergedActivities.size());
    activities = Sets.newHashSet(ActivityLocatorUtils.getQualifiedName(mergedActivities.get(0)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(1)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(2)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(3)));
    assertTrue(activities.contains("test.helloworldapp.Debug"));
    assertTrue(activities.contains("test.helloworldapp.MyActivity"));
    assertTrue(activities.contains("test.helloworldapp.lib.LibActivity"));
    assertTrue(activities.contains("test.helloworldapp.AddedActivity"));
    // make a change to the psi
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    final Document document = documentManager.getDocument(psiFile);
    WriteCommandAction.runWriteCommandAction(null, new Runnable() {

        @Override
        public void run() {
            assertNotNull(document);
            int index = document.getText().indexOf("</application>");
            document.insertString(index, "<activity android:name=\".AddedActivity2\" />\n");
            documentManager.commitDocument(document);
        }
    });
    UIUtil.dispatchAllInvocationEvents();
    // reload data and check it is correct
    manifestInfo.clear();
    mergedActivities = manifestInfo.getActivities();
    assertEquals(5, mergedActivities.size());
    activities = Sets.newHashSet(ActivityLocatorUtils.getQualifiedName(mergedActivities.get(0)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(1)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(2)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(3)), ActivityLocatorUtils.getQualifiedName(mergedActivities.get(4)));
    assertTrue(activities.contains("test.helloworldapp.Debug"));
    assertTrue(activities.contains("test.helloworldapp.MyActivity"));
    assertTrue(activities.contains("test.helloworldapp.lib.LibActivity"));
    assertTrue(activities.contains("test.helloworldapp.AddedActivity"));
    assertTrue(activities.contains("test.helloworldapp.AddedActivity2"));
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Element(org.w3c.dom.Element) Document(com.intellij.openapi.editor.Document) Predicate(com.google.common.base.Predicate) PsiFile(com.intellij.psi.PsiFile) Nullable(org.jetbrains.annotations.Nullable) XmlTag(com.intellij.psi.xml.XmlTag) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 89 with Predicate

use of com.google.common.base.Predicate in project GeoGig by boundlessgeo.

the class ShowRef method runInternal.

@Override
public void runInternal(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();
    ForEachRef op = geogig.command(ForEachRef.class);
    Predicate<Ref> filter = new Predicate<Ref>() {

        @Override
        public boolean apply(Ref ref) {
            String name = ref.getName();
            if (!name.startsWith(Ref.REFS_PREFIX)) {
                return false;
            }
            boolean match = patterns.isEmpty() ? true : false;
            for (String pattern : patterns) {
                if (Strings.isNullOrEmpty(pattern)) {
                    match = true;
                } else if (name.endsWith("/" + pattern)) {
                    match = true;
                    break;
                }
            }
            return match;
        }
    };
    op.setFilter(filter);
    ImmutableSet<Ref> refs = op.call();
    for (Ref ref : refs) {
        console.println(ref.getObjectId() + " " + ref.getName());
    }
}
Also used : Ref(org.locationtech.geogig.api.Ref) ForEachRef(org.locationtech.geogig.api.plumbing.ForEachRef) ConsoleReader(jline.console.ConsoleReader) ForEachRef(org.locationtech.geogig.api.plumbing.ForEachRef) GeoGIG(org.locationtech.geogig.api.GeoGIG) Predicate(com.google.common.base.Predicate)

Example 90 with Predicate

use of com.google.common.base.Predicate in project GeoGig by boundlessgeo.

the class LocalRemoteRepo method copyNewObjects.

private void copyNewObjects(RevTree oldTree, RevTree newTree, final ObjectDatabase fromDb, final ObjectDatabase toDb, final ProgressListener progress) {
    checkNotNull(oldTree);
    checkNotNull(newTree);
    checkNotNull(fromDb);
    checkNotNull(toDb);
    checkNotNull(progress);
    // the diff walk uses fromDb as both left and right data source since we're comparing what
    // we have in the "origin" database against trees on the same repository
    PostOrderDiffWalk diffWalk = new PostOrderDiffWalk(oldTree, newTree, fromDb, fromDb);
    // holds object ids that need to be copied to the target db. Pruned when it reaches a
    // threshold.
    final Set<ObjectId> ids = new HashSet<ObjectId>();
    // This filter further refines the post order diff walk by making it ignore trees/buckets
    // that are already present in the target db
    Predicate<Bounded> filter = new Predicate<Bounded>() {

        @Override
        public boolean apply(@Nullable Bounded b) {
            if (b == null) {
                return false;
            }
            if (progress.isCanceled()) {
                // abort traversal
                return false;
            }
            ObjectId id;
            if (b instanceof Node) {
                Node node = (Node) b;
                if (RevObject.TYPE.TREE.equals(node.getType())) {
                    // check of existence of trees only. For features the diff filtering is good
                    // enough and checking for existence on each feature would be killer
                    // performance wise
                    id = node.getObjectId();
                } else {
                    return true;
                }
            } else {
                id = ((Bucket) b).id();
            }
            boolean exists = ids.contains(id) || toDb.exists(id);
            return !exists;
        }
    };
    // receives notifications of feature/bucket/tree diffs. Only interested in the "new"/right
    // side of the comparisons
    Consumer consumer = new Consumer() {

        final int bulkSize = 10_000;

        @Override
        public void feature(@Nullable Node left, Node right) {
            add(left);
            add(right);
        }

        @Override
        public void tree(@Nullable Node left, Node right) {
            add(left);
            add(right);
        }

        private void add(@Nullable Node node) {
            if (node == null) {
                return;
            }
            ids.add(node.getObjectId());
            Optional<ObjectId> metadataId = node.getMetadataId();
            if (metadataId.isPresent()) {
                ids.add(metadataId.get());
            }
            checkLimitAndCopy();
        }

        @Override
        public void bucket(int bucketIndex, int bucketDepth, @Nullable Bucket left, Bucket right) {
            if (left != null) {
                ids.add(left.id());
            }
            if (right != null) {
                ids.add(right.id());
            }
            checkLimitAndCopy();
        }

        private void checkLimitAndCopy() {
            if (ids.size() >= bulkSize) {
                copy(ids, fromDb, toDb, progress);
                ids.clear();
            }
        }
    };
    diffWalk.walk(filter, consumer);
    // copy remaining objects
    copy(ids, fromDb, toDb, progress);
}
Also used : ObjectId(org.locationtech.geogig.api.ObjectId) Node(org.locationtech.geogig.api.Node) Predicate(com.google.common.base.Predicate) Bounded(org.locationtech.geogig.api.Bounded) Consumer(org.locationtech.geogig.api.plumbing.diff.PostOrderDiffWalk.Consumer) Bucket(org.locationtech.geogig.api.Bucket) PostOrderDiffWalk(org.locationtech.geogig.api.plumbing.diff.PostOrderDiffWalk) Nullable(javax.annotation.Nullable) HashSet(java.util.HashSet)

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