Example usage for org.apache.commons.collections Predicate Predicate

List of usage examples for org.apache.commons.collections Predicate Predicate

Introduction

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

Prototype

Predicate

Source Link

Usage

From source file:com.github.liyp.test.TestMain.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    // add a shutdown hook to stop the server
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override//ww  w  .ja  v a 2  s . c o m
        public void run() {
            System.out.println("########### shoutdown begin....");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("########### shoutdown end....");
        }
    }));

    System.out.println(args.length);
    Iterator<String> iterator1 = IteratorUtils
            .arrayIterator(new String[] { "one", "two", "three", "11", "22", "AB" });
    Iterator<String> iterator2 = IteratorUtils.arrayIterator(new String[] { "a", "b", "c", "33", "ab", "aB" });

    Iterator<String> chainedIter = IteratorUtils.chainedIterator(iterator1, iterator2);

    System.out.println("==================");

    Iterator<String> iter = IteratorUtils.filteredIterator(chainedIter, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            System.out.println("xx:" + arg0.toString());
            String str = (String) arg0;
            return str.matches("([a-z]|[A-Z]){2}");
        }
    });
    while (iter.hasNext()) {
        System.out.println(iter.next());
    }

    System.out.println("===================");

    System.out.println("asas".matches("[a-z]{4}"));

    System.out.println("Y".equals(null));

    System.out.println(String.format("%02d", 1000L));

    System.out.println(ArrayUtils.toString(splitAndTrim(" 11, 21,12 ,", ",")));

    System.out.println(new ArrayList<String>().toString());

    JSONObject json = new JSONObject("{\"keynull\":null}");
    json.put("bool", false);
    json.put("keya", "as");
    json.put("key2", 2212222222222222222L);
    System.out.println(json);
    System.out.println(json.get("keynull").equals(null));

    String a = String.format("{\"id\":%d,\"method\":\"testCrossSync\"," + "\"circle\":%d},\"isEnd\":true", 1,
            1);
    System.out.println(a.getBytes().length);

    System.out.println(new String[] { "a", "b" });

    System.out.println(new JSONArray("[\"aa\",\"\"]"));

    String data = String.format("%9d %s", 1, RandomStringUtils.randomAlphanumeric(10));
    System.out.println(data.getBytes().length);

    System.out.println(ArrayUtils.toString("1|2| 3|  333||| 3".split("\\|")));

    JSONObject j1 = new JSONObject("{\"a\":\"11111\"}");
    JSONObject j2 = new JSONObject(j1.toString());
    j2.put("b", "22222");
    System.out.println(j1 + " | " + j2);

    System.out.println("======================");

    String regex = "\\d+(\\-\\d+){2} \\d+(:\\d+){2}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher("2015-12-28 15:46:14  _NC250_MD:motion de\n");
    String eventDate = matcher.find() ? matcher.group() : "";

    System.out.println(eventDate);
}

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

/**
 * @param args/*from  www.  j a  va 2s  .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:com.nwea.samples.apachecommons.collections.SampleCollectionUtils.java

@SuppressWarnings("unchecked")
public static Collection<Student> findStudentsBySex(Collection<Student> students, final String sex) {
    return CollectionUtils.select(students, new Predicate() {
        public boolean evaluate(java.lang.Object s) {
            Student student = (Student) s;
            return student.getSex().equals(sex);
        }/*from   w w w. j  a  v  a  2  s  .  c o  m*/
    });
}

From source file:mondrian.spi.DataServicesLocator.java

public static DataServicesProvider getDataServicesProvider(final String className) {
    if (Util.isEmpty(className)) {
        return new DefaultDataServicesProvider();
    } else {//from  w w  w.j  a va  2 s.  c  o m
        ServiceDiscovery<DataServicesProvider> discovery = ServiceDiscovery
                .forClass(DataServicesProvider.class);
        List<Class<DataServicesProvider>> implementors = discovery.getImplementor();
        Predicate providerNamePredicate = new Predicate() {
            public boolean evaluate(Object o) {
                Class<DataServicesProvider> providerClass = (Class<DataServicesProvider>) o;
                return providerClass.getName().equals(className);
            }
        };
        Class<DataServicesProvider> provider = (Class<DataServicesProvider>) find(implementors,
                providerNamePredicate);
        if (provider != null) {
            try {
                return provider.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException("Unrecognized Service Provider: " + className);
    }
}

From source file:find.FindFile.java

private static Collection find(Collection files, final String name) {
    return CollectionUtils.select(files, new Predicate() {
        public boolean evaluate(Object o) {
            return ((File) o).getName().indexOf(name) != -1;
        }/*from  ww w  .j av  a 2  s. c om*/
    });
}

From source file:net.sourceforge.fenixedu.domain.messaging.AnnouncementCategoryType.java

public static AnnouncementCategory getAnnouncementCategoryByType(final AnnouncementCategoryType type) {

    return (AnnouncementCategory) CollectionUtils.find(Bennu.getInstance().getCategoriesSet(), new Predicate() {

        @Override/*from w  w  w  .j  av  a 2  s.  com*/
        public boolean evaluate(Object arg0) {
            return ((AnnouncementCategory) arg0).getType().equals(type);
        }

    });
}

From source file:com.codenjoy.dojo.tetris.model.TestUtils.java

public static void assertContainsPlot(final int x, final int y, final PlotColor color, List<Plot> plots) {
    Object foundPlot = CollectionUtils.find(plots, new Predicate() {
        @Override//from  w  w w  .jav a  2 s.com
        public boolean evaluate(Object object) {
            Plot plot = (Plot) object;
            return plot.getColor() == color && plot.getX() == x && plot.getY() == y;
        }
    });
    assertNotNull("Plot with coordinates (" + x + "," + y + ") color: " + color + " not found", foundPlot);
}

From source file:com.nwea.samples.apachecommons.collections.SampleCollectionUtils.java

@SuppressWarnings("unchecked")
public static void setDefaultHomeroomsBySex(Collection<Student> students, final String femaleHomeroom,
        final String maleHomeroom) {
    // predicate returns true if student sex is "F"
    Predicate ifStatement = new Predicate() {
        public boolean evaluate(Object obj) {
            Student student = (Student) obj;
            return student.getSex().equals("F");
        }//www  .ja  v a  2  s .  co m
    };

    // closure calls setHomeroom() on Student refs.
    // allows to set "homeRoom" var in instance initializer
    class SetHomeroom implements Closure {
        String homeRoom;

        public void execute(Object obj) {
            Student student = (Student) obj;
            student.setHomeroom(homeRoom);
        }
    }

    CollectionUtils.forAllDo(students, ClosureUtils.ifClosure(ifStatement, new SetHomeroom() {
        {
            homeRoom = femaleHomeroom;
        }
    }, new SetHomeroom() {
        {
            homeRoom = maleHomeroom;
        }
    })); // crazy braces/parens!
}

From source file:com.cognifide.cq.cqsm.core.scripts.ScriptFilters.java

public static Predicate filterExecutionEnabled(final boolean flag) {
    return new Predicate() {
        @Override//  ww  w  .j av a  2  s  .  c  om
        public boolean evaluate(Object o) {
            return ((Script) o).isExecutionEnabled() == flag;
        }
    };
}

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;
            }//  w w  w .jav a 2 s .c  o 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());
        }
    });
}