Example usage for org.apache.commons.io FileUtils listFiles

List of usage examples for org.apache.commons.io FileUtils listFiles

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils listFiles.

Prototype

public static Collection listFiles(File directory, String[] extensions, boolean recursive) 

Source Link

Document

Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.

Usage

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step1DebateFilter.java

/**
 * Computes statistics over full debate dataset
 *
 * @param inputDir input dir/*w  w w . ja  va  2  s.  c  o  m*/
 * @throws IOException IO exception
 */
public static void computeRawLengthStatistics(String inputDir) throws IOException {
    DescriptiveStatistics fullWordCountStatistics = new DescriptiveStatistics();

    // read all debates and filter them
    for (File file : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
        Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8"));

        for (Argument argument : debate.getArgumentList()) {

            // we have a first-level argument
            if (argument.getParentId() == null) {
                // now check the length
                int wordCount = argument.getText().split("\\s+").length;

                fullWordCountStatistics.addValue(wordCount);
            }
        }
    }

    System.out.println("Full word count statistics");
    System.out.println(fullWordCountStatistics);
}

From source file:com.enioka.jqm.tools.BasicTest.java

@Before
public void before() throws Exception {
    jqmlogger.debug("********* TEST INIT");

    em = Helpers.getNewEm();//from  w ww  . java  2 s  .  c  om
    TestHelpers.cleanup(em);
    TestHelpers.createTestData(em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "true", em);
    Helpers.setSingleParam("enableWsApiSsl", "false", em);
    File jar = FileUtils.listFiles(new File("../../jqm-ws/target/"), new String[] { "war" }, false).iterator()
            .next();
    FileUtils.copyFile(jar, new File("./webapp/jqm-ws.war"));

    em.getTransaction().begin();
    Node n = em.find(Node.class, TestHelpers.node.getId());
    em.createQuery("UPDATE GlobalParameter gp set gp.value='true' WHERE gp.key = 'logFilePerLaunch'")
            .executeUpdate();
    n.setRepo("./../..");

    TestHelpers.node.setLoadApiAdmin(true);
    TestHelpers.node.setLoadApiClient(true);
    TestHelpers.node.setLoapApiSimple(true);
    em.getTransaction().commit();

    engine1 = new JqmEngine();
    engine1.start("localhost");

    // Test user
    RRole r = em.createQuery("SELECT rr from RRole rr WHERE rr.name = :r", RRole.class)
            .setParameter("r", "client power user").getSingleResult();
    CreationTools.createUser(em, "test", "test", r);

    Properties p = new Properties();
    em.refresh(n);
    System.out.println(n.getPort());
    p.put("com.enioka.jqm.ws.url", "http://" + n.getDns() + ":" + n.getPort() + "/ws/client");
    p.put("com.enioka.jqm.ws.login", "test");
    p.put("com.enioka.jqm.ws.password", "test");
    JqmClientFactory.setProperties(p);
}

From source file:fr.norsys.asoape.mojo.GenerateAndroidClientMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    //  Redirecting Velocity log to the Maven output.
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, this);
    WSDLGenerator generator = new WSDLGenerator();
    generator.setOutputDirectory(outputDirectory);
    generator.setBeanSerializable(beanSerializable);
    for (File definitionFile : FileUtils.listFiles(definitionsDirectory, new String[] { "wsdl" }, true)) {
        Definition definition = readDefinitionFrom(definitionFile);
        try {/* w  ww.  j a v a2s .  com*/
            generator.generateFrom(definition);
        } catch (WSDLGenerationException cause) {
            throw new MojoExecutionException("Error occurs during code generation process", cause);
        }
    }
    project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
}

From source file:com.liferay.ide.alloy.core.webresources.PortalResourcesProvider.java

@Override
public File[] getResources(IWebResourcesContext context) {
    File[] retval = null;//from   w w w .  j  a  v a 2 s.  c  o  m
    final IFile htmlFile = context.getHtmlFile();
    final ILiferayProject project = LiferayCore.create(htmlFile.getProject());

    if (htmlFile != null && project != null) {
        final ILiferayPortal portal = project.adapt(ILiferayPortal.class);

        if (portal != null && ProjectUtil.isPortletProject(htmlFile.getProject())) {
            final IPath portalDir = portal.getAppServerPortalDir();

            if (portalDir != null) {
                final IPath cssPath = portalDir.append("html/themes/_unstyled/css");

                if (cssPath.toFile().exists()) {
                    synchronized (fileCache) {
                        final Collection<File> cachedFiles = fileCache.get(cssPath);

                        if (cachedFiles != null) {
                            retval = cachedFiles.toArray(new File[0]);
                        } else {
                            final Collection<File> files = FileUtils.listFiles(cssPath.toFile(),
                                    new String[] { "css", "scss" }, true);

                            final Collection<File> cached = new HashSet<File>();

                            for (File file : files) {
                                if (file.getName().endsWith("scss")) {
                                    final File cachedFile = new File(file.getParent(),
                                            ".sass-cache/" + file.getName().replaceAll("scss$", "css"));

                                    if (cachedFile.exists()) {
                                        cached.add(file);
                                    }
                                }
                            }

                            files.removeAll(cached);

                            if (files != null) {
                                retval = files.toArray(new File[0]);
                            }

                            fileCache.put(cssPath, files);
                        }
                    }
                }
            }
        } else if (portal != null && ProjectUtil.isLayoutTplProject(htmlFile.getProject())) {
            // return the static css resource for layout template names based on the version

            final String version = portal.getVersion();

            try {
                if (version != null && (version.startsWith("6.0") || version.startsWith("6.1"))) {
                    retval = createLayoutHelperFiles("resources/layouttpl-6.1.css");
                } else if (version != null) {
                    retval = createLayoutHelperFiles("resources/layouttpl-6.2.css");
                }
            } catch (IOException e) {
                AlloyCore.logError("Unable to load layout template helper css files", e);
            }
        }
    }

    return retval;
}

From source file:com.polarion.pso.license.FetchUserLicenseTypeServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    ISecurityService securityService = (ISecurityService) PlatformContext.getPlatform()
            .lookupService(ISecurityService.class);
    ITrackerService trackerService = (ITrackerService) PlatformContext.getPlatform()
            .lookupService(ITrackerService.class);

    String userId = securityService.getCurrentUser();
    String userName = trackerService.getTrackerUser(userId).getName();

    long cutoff = System.currentTimeMillis() - (1000);
    File directory = new File("./logs/main");

    FileFilter wcFilter = new WildcardFileFilter("log4j-licensing-*.log");
    AgeFileFilter ageFilter = new AgeFileFilter(cutoff);
    FileFilter andFilter = new org.apache.commons.io.filefilter.AndFileFilter((IOFileFilter) ageFilter,
            (IOFileFilter) wcFilter);//from   ww w  . ja  v  a2s . c  o m

    Collection<File> matches = FileUtils.listFiles(directory, (IOFileFilter) andFilter, null);

    if (!matches.isEmpty()) {

        File myFile = matches.iterator().next();
        RandomAccessFile licFile = new RandomAccessFile(myFile, "r");

        // Read the last 1024 bytes
        Long fileLength = licFile.length();
        Long offSet = fileLength - 1024;
        byte[] bStr = new byte[1024];
        licFile.seek(offSet);
        licFile.read(bStr);
        licFile.close();

        String logString = new java.lang.String(bStr);

        String[] lineArray = logString.split("\n");

        String searchString = "INFO  PolarionLicensing  - User \'" + userId + "\' logged in";
        Boolean found = false;
        Integer size = lineArray.length - 1;
        String licType = directory.toString();

        for (int i = size; i >= 0; i--) {
            String line = lineArray[i];
            if (line.contains(searchString) && found == false) {
                found = true;
                i = -1;
                Integer startIndex = line.indexOf(searchString) + searchString.length() + 6;
                licType = line.substring(startIndex);
                licType = licType.replace("\r", "");
                licType = licType.trim();
            }
        }

        req.setAttribute("userId", userName);
        req.setAttribute("licType", licType);
    } else {
        req.setAttribute("userId", userName);
        req.setAttribute("licType", "Not Found");
    }

    getServletContext().getRequestDispatcher("/currentUserLicenseType.jsp").forward(req, resp);
}

From source file:net.jakubholy.jeeutils.jsfelcheck.expressionfinder.impl.facelets.ValidatingFaceletsParserExecutor.java

@SuppressWarnings("unchecked")
private Collection<File> findViewFiles() {
    return FileUtils.listFiles(viewFilesRoot, new String[] { "xhtml" }, true);
}

From source file:com.screenslicer.webapp.WebAppConfig.java

public WebAppConfig(boolean isClient) throws IOException {
    Collection<String> mimeTypeList = new HashSet<String>();
    mimeTypeList.add(MediaType.APPLICATION_FORM_URLENCODED);
    mimeTypeList.add(MediaType.APPLICATION_JSON);
    mimeTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
    mimeTypeList.add(MediaType.APPLICATION_SVG_XML);
    mimeTypeList.add(MediaType.APPLICATION_XHTML_XML);
    mimeTypeList.add(MediaType.APPLICATION_XML);
    mimeTypeList.add(MediaType.MULTIPART_FORM_DATA);
    mimeTypeList.add(MediaType.TEXT_HTML);
    mimeTypeList.add(MediaType.TEXT_PLAIN);
    mimeTypeList.add(MediaType.TEXT_XML);
    if (new File("./htdocs").exists()) {
        Collection<File> files = FileUtils.listFiles(new File("./htdocs"), null, true);
        for (File file : files) {
            final byte[] contents = FileUtils.readFileToByteArray(file);
            Resource.Builder resourceBuilder = Resource.builder();
            resourceBuilder.path(file.getAbsolutePath().split("/htdocs/")[1]);
            final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
            String mimeType = MimeTypeFinder.probeContentType(Paths.get(file.toURI()));
            if (!mimeTypeList.contains(mimeType) && !file.getName().toLowerCase().endsWith(".jpg")
                    && !file.getName().toLowerCase().endsWith(".jpeg")
                    && !file.getName().toLowerCase().endsWith(".png")
                    && !file.getName().toLowerCase().endsWith(".gif")
                    && !file.getName().toLowerCase().endsWith(".ico")) {
                mimeTypeList.add(mimeType);
            }/*from   w  w w . ja v a2 s.co  m*/
            final File myFile = file;
            methodBuilder.produces(mimeType).handledBy(new Inflector<ContainerRequestContext, byte[]>() {
                @Override
                public byte[] apply(ContainerRequestContext req) {
                    if (!WebApp.DEV) {
                        return contents;
                    }
                    try {
                        return FileUtils.readFileToByteArray(myFile);
                    } catch (IOException e) {
                        return contents;
                    }
                }
            });
            registerResources(resourceBuilder.build());
        }
    }
    register(MultiPartFeature.class);
    Reflections reflections = new Reflections(
            new ConfigurationBuilder().setUrls(ClasspathHelper.forJavaClassPath())
                    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.screenslicer"))));
    Set<Class<? extends WebResource>> webResourceClasses = reflections.getSubTypesOf(WebResource.class);
    if (!isClient) {
        for (Class<? extends WebResource> webpageClass : webResourceClasses) {
            registerResources(Resource.builder(webpageClass).build());
        }
    }
    if (isClient) {
        Set<Class<? extends ClientWebResource>> customWebAppClasses = reflections
                .getSubTypesOf(ClientWebResource.class);
        for (Class<? extends ClientWebResource> customWebAppClass : customWebAppClasses) {
            registerResources(Resource.builder(customWebAppClass).build());
        }
    }
    register(ExceptionHandler.class);
    mimeTypes = mimeTypeList.toArray(new String[0]);
}

From source file:dkpro.similarity.uima.io.MeterCorpusReader.java

@Override
public List<CombinationPair> getAlignedPairs() throws ResourceInitializationException {
    List<CombinationPair> pairs = new ArrayList<CombinationPair>();

    List<File> sourceDirs = listDirectories(new File(inputDir.getAbsolutePath() + "/PA/annotated"));
    for (File sourceDir : sourceDirs) {
        File sourceFile = new ArrayList<File>(FileUtils.listFiles(sourceDir, new String[] { "sgml" }, false))
                .get(0);//from ww  w  .  jav a 2 s  . c  o  m

        File suspiciousDir = new File(
                sourceDir.getAbsolutePath().replace("PA", "newspapers").replace("annotated", "rawtexts"));

        Collection<File> suspiciousFiles = FileUtils.listFiles(suspiciousDir, new String[] { "txt" }, false);

        for (File suspiciousFile : suspiciousFiles) {
            try {
                // Source files has a 13-line header. Remove it first.
                List<String> sourceLines = FileUtils.readLines(sourceFile);
                for (int i = 0; i < 13; i++) {
                    sourceLines.remove(0);
                }

                // Also remove the 5-line footer
                for (int i = 0; i < 5; i++) {
                    sourceLines.remove(sourceLines.size() - 1);
                }

                // Besides that, lines may end with a "<" character. Remove it, too.
                for (int i = 0; i < sourceLines.size(); i++) {
                    String line = sourceLines.get(i);

                    if (line.endsWith("<")) {
                        line = line.substring(0, line.length() - 1);
                        sourceLines.set(i, line);
                    }
                }

                String source = StringUtils.join(sourceLines, LF);
                String suspicious = FileUtils.readFileToString(suspiciousFile);

                // Get IDs
                String sourceID = sourceFile.getAbsolutePath()
                        .substring(sourceFile.getAbsolutePath().indexOf("meter") + 6);
                sourceID = sourceID.substring(0, sourceID.length() - 5);
                sourceID = sourceID.replace("annotated/", "");

                String suspiciousID = suspiciousFile.getAbsolutePath()
                        .substring(suspiciousFile.getAbsolutePath().indexOf("meter") + 6);
                suspiciousID = suspiciousID.substring(0, suspiciousID.length() - 4);
                suspiciousID = suspiciousID.replace("rawtexts/", "");

                CombinationPair pair = new CombinationPair(inputDir.getAbsolutePath());
                pair.setID1(suspiciousID);
                pair.setID2(sourceID);
                pair.setText1(suspicious);
                pair.setText2(source);

                pairs.add(pair);
            } catch (IOException e) {
                throw new ResourceInitializationException(e);
            }
        }
    }

    return pairs;
}

From source file:com.centeractive.ws.builder.DefinitionSaveTest.java

public static File findFile(File folder, String name) {
    final boolean RECURSIVE = true;
    String[] extensions = new String[] { FilenameUtils.getExtension(name) };
    Collection<File> files = FileUtils.listFiles(folder, extensions, RECURSIVE);
    if (files.isEmpty() == false) {
        return files.iterator().next();
    }/*from  w w  w.j  a  va  2 s .  co m*/
    throw new RuntimeException("File not found " + name);
}

From source file:com.phoenixnap.oss.ramlapisync.plugin.ClassLoaderUtils.java

public static List<String> loadClasses(MavenProject mavenProject) throws MojoExecutionException {

    List<String> classes = Lists.newArrayList();

    File rootDir = new File(mavenProject.getBuild().getSourceDirectory());
    Collection<File> files = FileUtils.listFiles(rootDir, new SuffixFileFilter(".java"), TrueFileFilter.TRUE);
    for (File file : files) {
        String clazz = file.getName().replace(".java", "");
        if (!clazz.isEmpty()) {
            classes.add(clazz);/*from   w  w w  . j  av  a2 s  .  c om*/
        }
    }
    return classes;
}