Example usage for org.apache.commons.collections CollectionUtils filter

List of usage examples for org.apache.commons.collections CollectionUtils filter

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils filter.

Prototype

public static void filter(Collection collection, Predicate predicate) 

Source Link

Document

Filter the collection by applying a Predicate to each element.

Usage

From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java

/**
 * @param args//from w w w  .  j a v  a2  s.c om
 */
public static void main(String[] args) throws Exception {

    logger.info("start time ==== " + System.currentTimeMillis());

    try {
        //load the adb location from the props file
        Properties props = new Properties();
        props.load(new FileInputStream(new File("adb.props")));

        //set the adb location
        WindowUpdate.adbLocation = props.getProperty("adb_location");
        adbLocation = props.getProperty("adb_location");
        //set root dir
        ROOT_DIRECTORY = props.getProperty("root_dir");
        //completed txt
        completedFile = new File(ROOT_DIRECTORY + "tested.txt");
        //db location for static analysis
        dbLocation = props.getProperty("db_location");
        //location for smart input generation output
        smartInputLocation = props.getProperty("smart_input_location");

        //udp dump location
        udpDumpLocation = props.getProperty("udp_dump_location");
        //logcat dump location
        logCatLocation = props.getProperty("log_cat_location");
        //strace output location
        straceOutputLocation = props.getProperty("strace_output_location");
        //strace dump location
        straceDumpLocation = props.getProperty("strace_output_location");

        //set x and y coords
        UIEnumerator.screenX = props.getProperty("x");
        UIEnumerator.screenY = props.getProperty("y");

        DeviceOfflineMonitor.START_EMULATOR = props.getProperty("restart");

        //read output of static analysis
        readFromStaticAnalysisText();
        logger.info("Read static analysis output");

        readFromSmartInputText();
        logger.info("Read smart input generation output");

        //populate the queue with apps which are only present in the static analysis
        @SuppressWarnings("unchecked")
        final Set<? extends String> sslApps = new HashSet<String>(
                CollectionUtils.collect(FileUtils.readLines(new File(dbLocation)), new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        //get app file name
                        String temp = StringUtils.substringBefore(input.toString(), " ");
                        return StringUtils.substringAfterLast(temp, "/");
                    }
                }));
        Collection<File> fileList = FileUtils.listFiles(new File(ROOT_DIRECTORY), new String[] { "apk" },
                false);
        CollectionUtils.filter(fileList, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                return sslApps.contains(StringUtils.substringAfterLast(object.toString(), "/"));
            }
        });
        apkQueue = new LinkedBlockingDeque<File>(fileList);

        logger.info("finished listing files from the root directory");

        try {
            //populate the tested apk list
            completedApps.addAll(FileUtils.readLines(completedFile));
        } catch (Exception e) {
            //pass except
            logger.info("No tested.txt file found");

            //create new file
            if (completedFile.createNewFile()) {
                logger.info("tested.txt created in root directory");
            } else {
                logger.info("tested.txt file could not be created");
            }

        }

        //get the executors for managing the emulators
        executors = Executors.newCachedThreadPool();

        //set the devicemonitor exec
        DeviceOfflineMonitor.exec = executors;

        final List<Future<?>> futureList = new ArrayList<Future<?>>();

        //start the offline device monitor (emulator management thread)
        logger.info("Starting Device Offline Monitor Thread");
        executors.submit(new DeviceOfflineMonitor());

        //get ADB backend object for device change listener
        AdbBackend adb = new AdbBackend();

        //register for device change and wait for events
        //once event is received, start the MonkeyMe thread
        MonkeyDeviceChangeListener deviceChangeListener = new MonkeyDeviceChangeListener(executors, futureList);
        AndroidDebugBridge.addDeviceChangeListener(deviceChangeListener);
        logger.info("Listening to changes in devices (emulators)");

        //wait for the latch to come down
        //this means that all the apks have been processed
        cdl.await();

        logger.info("Finished testing all apps waiting for threads to join");

        //now wait for every thread to finish
        for (Future<?> future : futureList) {
            future.get();
        }

        logger.info("All threads terminated");

        //stop listening for device update
        AndroidDebugBridge.removeDeviceChangeListener(deviceChangeListener);

        //stop the debug bridge
        AndroidDebugBridge.terminate();

        //stop offline device monitor
        DeviceOfflineMonitor.stop = true;

        logger.info("adb and listeners terminated");

    } finally {
        logger.info("Executing this finally");
        executors.shutdownNow();
    }

    logger.info("THE END!!");
}

From source file:adalid.commons.util.ColUtils.java

public static <T> Collection<T> filter(Collection<T> collection, Predicate predicate) {
    if (collection == null || collection.isEmpty() || predicate == null) {
        return collection;
    } else {/*www  .  jav a  2 s. c o m*/
        //          Collection<T> list = new ArrayList<T>();
        //          list.addAll(collection);
        Collection<T> list = new ArrayList<>(collection);
        CollectionUtils.filter(list, predicate);
        return list;
    }
}

From source file:net.shopxx.service.impl.ParameterValueServiceImpl.java

public void filter(List<ParameterValue> parameterValues) {
    CollectionUtils.filter(parameterValues, new Predicate() {
        public boolean evaluate(Object object) {
            ParameterValue parameterValue = (ParameterValue) object;
            if (parameterValue == null || StringUtils.isEmpty(parameterValue.getGroup())) {
                return false;
            }//  ww w.  j a v  a2  s. co m
            CollectionUtils.filter(parameterValue.getEntries(), new Predicate() {
                private Set<String> set = new HashSet<String>();

                public boolean evaluate(Object object) {
                    ParameterValue.Entry entry = (ParameterValue.Entry) object;
                    return entry != null && StringUtils.isNotEmpty(entry.getName())
                            && StringUtils.isNotEmpty(entry.getValue()) && set.add(entry.getName());
                }
            });
            return CollectionUtils.isNotEmpty(parameterValue.getEntries());
        }
    });
}

From source file:net.shopxx.service.impl.SpecificationItemServiceImpl.java

public void filter(List<SpecificationItem> specificationItems) {
    CollectionUtils.filter(specificationItems, new Predicate() {
        public boolean evaluate(Object object) {
            SpecificationItem specificationItem = (SpecificationItem) object;
            if (specificationItem == null || StringUtils.isEmpty(specificationItem.getName())) {
                return false;
            }/*from w  w w.  j a v  a2 s. c  o m*/
            CollectionUtils.filter(specificationItem.getEntries(), new Predicate() {
                private Set<Integer> idSet = new HashSet<Integer>();
                private Set<String> valueSet = new HashSet<String>();

                public boolean evaluate(Object object) {
                    SpecificationItem.Entry entry = (SpecificationItem.Entry) object;
                    return entry != null && entry.getId() != null && StringUtils.isNotEmpty(entry.getValue())
                            && entry.getIsSelected() != null && idSet.add(entry.getId())
                            && valueSet.add(entry.getValue());
                }
            });
            return CollectionUtils.isNotEmpty(specificationItem.getEntries()) && specificationItem.isSelected();
        }
    });
}

From source file:com.ibm.amc.data.filter.QueryFilterEngine.java

@SuppressWarnings("unchecked")
public static <T> List<T> filter(List<T> objects, Set<Map.Entry<String, List<String>>> queryParams) {
    if (logger.isEntryEnabled())
        logger.entry("filter", objects, queryParams);

    /* use a HashSet to remove duplicates */
    HashSet<T> filteredObjects = new HashSet<T>();

    QueryFilter filter = QueryFilterFactory.build(queryParams);

    if (filter.getOperator().equals(Operator.AND)) {
        if (logger.isDebugEnabled())
            logger.debug("filter", "Filter operator: AND");
        for (Predicate predicate : filter.getClauses()) {
            CollectionUtils.filter(objects, predicate);
        }// w  w w  . ja va  2s . c  o m

        /* need to muck about to get compatible types */
        ArrayList<T> temp;
        if (objects instanceof ArrayList) {
            temp = (ArrayList<T>) objects;
        } else {
            temp = new ArrayList<T>(objects);
        }

        filteredObjects.addAll(temp);
    } else {
        if (logger.isDebugEnabled())
            logger.debug("filter", "Filter operator: OR");
        for (Predicate predicate : filter.getClauses()) {
            filteredObjects.addAll(CollectionUtils.select(objects, predicate));
        }
    }

    if (logger.isEntryEnabled())
        logger.exit("filter", filteredObjects);
    return new ArrayList<T>(filteredObjects);
}

From source file:controllers.BranchApp.java

@IsAllowed(Operation.READ)
public static Result branches(String loginId, String projectName) throws IOException, GitAPIException {
    Project project = Project.findByOwnerAndProjectName(loginId, projectName);
    GitRepository gitRepository = new GitRepository(project);
    List<GitBranch> allBranches = gitRepository.getBranches();
    final GitBranch headBranch = gitRepository.getHeadBranch();

    // filter the head branch from all branch list.
    CollectionUtils.filter(allBranches, new Predicate() {
        @Override//from w  w  w .j  a va  2s .  c om
        public boolean evaluate(Object o) {
            GitBranch gitBranch = (GitBranch) o;
            return !gitBranch.getName().equals(headBranch.getName());
        }
    });

    return ok(branches.render(project, allBranches, headBranch));
}

From source file:adalid.commons.util.ColUtils.java

public static <T> Collection<T> allFilter(Collection<T> collection, Predicate... predicates) {
    if (collection == null || collection.isEmpty() || predicates == null) {
        return collection;
    } else {/*  w  ww  .  ja  va2  s  .  c  om*/
        //          Collection<T> list = new ArrayList<T>();
        //          list.addAll(collection);
        Collection<T> list = new ArrayList<>(collection);
        Predicate predicate = PredicateUtils.allPredicate(predicates);
        CollectionUtils.filter(list, predicate);
        return list;
    }
}

From source file:gov.nih.nci.caarray.domain.permissions.SampleSecurityLevel.java

/**
 * @return the list of SecurityLevels that are available to the public access profile
 *//*from   w ww .j  av a2 s  .c om*/
public static List<SampleSecurityLevel> publicLevels() {
    List<SampleSecurityLevel> levels = new ArrayList<SampleSecurityLevel>(
            Arrays.asList(SampleSecurityLevel.values()));
    CollectionUtils.filter(levels, new Predicate() {
        public boolean evaluate(Object o) {
            return ((SampleSecurityLevel) o).isAvailableToPublic();
        }
    });
    return levels;
}

From source file:net.sf.wickedshell.util.ShellViewUtil.java

@SuppressWarnings("unchecked")
public static final ShellView selectTargetFromAvailable(String action, final IShellViewFilter filter,
        boolean provideNewShell) {
    ShellView targetShellView = null;//from w w w. j a  v  a 2  s  .  c om
    List applicableRegisteredShellViews = new ArrayList(
            Arrays.asList(ShellPlugin.getDefault().getRegisteredShellViews()));
    if (filter != null) {
        CollectionUtils.filter(applicableRegisteredShellViews, new Predicate() {
            /**
             * @see org.apache.commons.collections.Predicate#evaluate(java.lang.Object)
             */
            public boolean evaluate(Object object) {
                ShellView shellView = (ShellView) object;
                return filter.isApplicable(shellView);
            }
        });
    }
    if (provideNewShell) {
        applicableRegisteredShellViews.add(PreferenceHelper.getActiveShellDescriptor());
    }
    if (applicableRegisteredShellViews.size() == 1) {
        targetShellView = (ShellView) applicableRegisteredShellViews.get(0);
    } else if (applicableRegisteredShellViews.size() != 0) {
        ListDialog listDialog = new ListDialog(Display.getDefault().getActiveShell());
        listDialog.setContentProvider(new ArrayContentProvider());
        listDialog.setLabelProvider(new LabelProvider() {
            /**
             * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
             */
            public String getText(Object element) {
                StringBuffer buffer = new StringBuffer();
                if (element instanceof ShellView) {
                    ShellView shellView = (ShellView) element;
                    buffer.append(shellView.getPartName());
                    buffer.append(" [");
                    buffer.append(shellView.getContentDescription());
                    buffer.append("]");
                } else {
                    IShellDescriptor shellDescriptor = (IShellDescriptor) element;
                    buffer.append("New Shell [");
                    buffer.append(shellDescriptor.getName());
                    buffer.append("]");
                }
                return buffer.toString();
            }
        });
        listDialog.setTitle("Wicked Shell - " + action);
        listDialog.setHelpAvailable(false);
        listDialog.setMessage("Please choose target from the available Shells.");
        listDialog.setInput(applicableRegisteredShellViews);
        listDialog.open();
        Object[] result = listDialog.getResult();
        if (result != null) {
            if (listDialog.getResult()[0] instanceof ShellView) {
                targetShellView = (ShellView) listDialog.getResult()[0];
            } else {
                try {
                    targetShellView = (ShellView) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
                            .getActivePage().showView(ShellID.SHELL_VIEW_ID,
                                    String.valueOf(System.currentTimeMillis()), IWorkbenchPage.VIEW_ACTIVATE);
                } catch (PartInitException exception) {
                    exception.printStackTrace();
                }
            }
        }
    }
    return targetShellView;
}

From source file:filter.ccimpl.CCFilter.java

public String[] filter(String[] values, final String prefix) {
    if (values == null) {
        return null;
    }//from ww w  .  j a va 2 s  .  c om
    if (prefix == null) {
        return values;
    }

    List result = new ArrayList(Arrays.asList(values));
    CollectionUtils.filter(result, new Predicate() {
        public boolean evaluate(Object o) {
            return o != null && o.toString().startsWith(prefix);
        }
    });
    return (String[]) result.toArray(new String[result.size()]);
}