Example usage for org.apache.commons.io FilenameUtils wildcardMatch

List of usage examples for org.apache.commons.io FilenameUtils wildcardMatch

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils wildcardMatch.

Prototype

public static boolean wildcardMatch(String filename, String wildcardMatcher) 

Source Link

Document

Checks a filename to see if it matches the specified wildcard matcher, always testing case-sensitive.

Usage

From source file:com.edgenius.wiki.render.handler.PageIndexHandler.java

public List<RenderPiece> handle(RenderContext renderContext, Map<String, String> values)
        throws RenderHandlerException {
    if (indexer == null) {
        log.warn("Unable to find valid page for index");
        throw new RenderHandlerException("Unable to find valid page for index");
    }//from ww  w.ja  v a  2s  .c  o m

    List<String> filters = getFilterList(values != null ? StringUtils.trimToNull(values.get("filter")) : null);
    List<String> filtersOut = getFilterList(
            values != null ? StringUtils.trimToNull(values.get("filterout")) : null);

    //temporary cache for indexer after filter out
    TreeMap<Character, Integer> indexerFiltered = new TreeMap<Character, Integer>();
    List<RenderPiece> listPieces = new ArrayList<RenderPiece>();
    //render each character list
    Character indexKey = null;
    boolean requireEndOfMacroPageIndexList = false;
    for (Entry<String, LinkModel> entry : indexMap.entrySet()) {
        String title = entry.getKey();

        if (filters.size() > 0) {
            boolean out = false;
            for (String filter : filters) {
                if (!FilenameUtils.wildcardMatch(title.toLowerCase(), filter.toLowerCase())) {
                    out = true;
                    break;
                }
            }
            if (out)
                continue;
        }

        if (filtersOut.size() > 0) {
            boolean out = false;
            for (String filterOut : filtersOut) {
                if (FilenameUtils.wildcardMatch(title.toLowerCase(), filterOut.toLowerCase())) {
                    out = true;
                    break;
                }
            }
            if (out)
                continue;
        }

        Character first = Character.toUpperCase(title.charAt(0));
        if (!first.equals(indexKey)) {
            if (requireEndOfMacroPageIndexList) {
                listPieces.add(new TextModel("</div>")); //macroPageIndexList
            }
            Integer anchorIdx = indexer.get(first);
            indexKey = first;
            if (anchorIdx != null) {
                indexerFiltered.put(first, anchorIdx);
                listPieces.add(new TextModel(new StringBuilder().append(
                        "<div class=\"macroPageIndexList\"><div class=\"macroPageIndexKey\" id=\"pageindexanchor-")
                        .append(anchorIdx).append("\">").append(first).toString()));
                requireEndOfMacroPageIndexList = true;
                //up image line to return top
                if (RenderContext.RENDER_TARGET_PAGE.equals(renderContext.getRenderTarget())) {
                    LinkModel back = new LinkModel();
                    back.setAnchor("pageindexanchor-0");
                    back.setAid("Go back index character list");
                    back.setView(renderContext.buildSkinImageTag("render/link/up.png", NameConstants.AID,
                            SharedConstants.NO_RENDER_TAG));
                    listPieces.add(back);
                }

                listPieces.add(new TextModel("</div>"));//macroPageIndexKey
            } else {
                log.error("Unable to page indexer for {}", indexKey);
            }
        }
        listPieces.add(new TextModel("<div class=\"macroPageIndexLink\">"));
        LinkModel link = entry.getValue();
        link.setLinkTagStr(renderContext.buildURL(link));
        listPieces.add(link);
        listPieces.add(new TextModel("</div>"));//macroPageIndexLink

    }
    if (requireEndOfMacroPageIndexList) {
        listPieces.add(new TextModel("</div>")); //macroPageIndexList
    }

    //render sum of characters - although it display before page list, however, as filter may hide some characters, so display later than
    //other
    List<RenderPiece> pieces = new ArrayList<RenderPiece>();

    StringBuffer sbuf = new StringBuffer("<div aid=\"pageindex\" class=\"macroPageIndex ")
            .append(WikiConstants.mceNonEditable).append("\"");
    if (values != null && values.size() > 0) {
        sbuf.append(" wajax=\"")
                .append(RichTagUtil.buildWajaxAttributeString(this.getClass().getName(), values)).append("\" ");
    }
    sbuf.append("><div id=\"pageindexanchor-0\" class=\"macroPageIndexKeys\">");

    pieces.add(new TextModel(sbuf.toString()));
    for (Entry<Character, Integer> entry : indexerFiltered.entrySet()) {
        LinkModel anchor = new LinkModel();
        anchor.setView(entry.getKey().toString());
        anchor.setAnchor("pageindexanchor-" + entry.getValue());
        anchor.setLinkTagStr(renderContext.buildURL(anchor));
        pieces.add(anchor);
    }
    pieces.add(new TextModel("</div>")); //macroPageIndexKeys
    pieces.addAll(listPieces);
    pieces.add(new TextModel("</div>")); //macroPageIndex

    return pieces;

}

From source file:com.pieframework.runtime.core.ResourceLoader.java

public static List<File> findPath(String basePath, String query) {

    List<File> flist = new ArrayList<File>();

    if (!StringUtils.empty(basePath, query)) {
        String root = locate(basePath);
        query = FilenameUtils.separatorsToSystem(query);
        query = "*" + query + "*";

        //System.out.println(query+" "+root);
        File rootDir = new File(root);
        try {//  www  . j a va 2  s .  c  o m
            for (File f : listFilesAndDirectories(rootDir)) {
                //System.out.println(f.getPath());
                if (FilenameUtils.wildcardMatch(f.getPath(), query)) {
                    flist.add(f);
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return flist;
}

From source file:de.micromata.genome.util.matcher.string.MatchUtil.java

/**
 * Matches wild card.//from   w  ww. j ava  2 s.com
 *
 * @param rl the rl
 * @param stringToMatch the string to match
 * @param defaultValue the default value
 * @return the boolean
 */
public static Boolean matchesWildCard(List<Pair<Boolean, String>> rl, String stringToMatch,
        Boolean defaultValue) {
    Boolean ret = defaultValue;
    for (Pair<Boolean, String> pl : rl) {
        if (FilenameUtils.wildcardMatch(stringToMatch, pl.getSecond()) == true) {
            ret = pl.getFirst();
        }
    }
    return ret;
}

From source file:gov.redhawk.efs.sca.server.internal.FileSystemImpl.java

@Override
public FileInformationType[] list(final String fullPattern) throws FileException, InvalidFileName {
    final int index = fullPattern.lastIndexOf('/');
    final File container;
    if (index > 0) {
        container = new File(this.root, fullPattern.substring(0, index));
    } else {//from w w  w  .  j  a v  a  2s  . co  m
        container = this.root;
    }

    final String pattern = fullPattern.substring(index + 1, fullPattern.length());

    final String[] fileNames;

    if (pattern.length() == 0) {
        fileNames = new String[] { "" };
    } else {
        fileNames = container.list(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                if (!dir.equals(container)) {
                    return false;
                }
                return FilenameUtils.wildcardMatch(name, pattern);
            }
        });
    }

    final FileInformationType[] retVal = new FileInformationType[fileNames.length];
    for (int i = 0; i < fileNames.length; i++) {
        final FileInformationType fileInfo = new FileInformationType();
        final File file = new File(container, fileNames[i]);
        fileInfo.name = file.getName();
        fileInfo.size = file.length();
        if (file.isFile()) {
            fileInfo.kind = FileType.PLAIN;
        } else {
            fileInfo.kind = FileType.DIRECTORY;
        }
        final Any any = this.orb.create_any();
        any.insert_ulonglong(file.lastModified() / FileSystemImpl.MILLIS_PER_SEC);
        final DataType modifiedTime = new DataType("MODIFIED_TIME", any);

        fileInfo.fileProperties = new DataType[] { modifiedTime };

        retVal[i] = fileInfo;
    }
    return retVal;
}

From source file:com.pieframework.runtime.core.ResourceLoader.java

public static List<File> findExactPath(File dir, String query) {

    List<File> flist = new ArrayList<File>();

    if (!StringUtils.empty(query) && dir.exists()) {
        String root = dir.getPath();
        query = FilenameUtils.separatorsToSystem(query);
        String wildCard = "*" + query + "*";
        //System.out.println(query+" "+root);
        File rootDir = new File(root);
        try {/*from  ww w .j  av a 2s  .  co m*/
            for (File f : listFilesAndDirectories(rootDir)) {
                //System.out.println(f.getPath());

                if (FilenameUtils.wildcardMatch(f.getPath(), wildCard)) {
                    if (f.getName().equals(query)) {
                        flist.add(f);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return flist;
}

From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java

private static boolean extract(String uri, List<ExtractionPair> extractions) {
    URL url;/*w ww. j ava 2 s .  com*/
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        File downloadFile = File.createTempFile(uri.substring(lastSlash + 1), uri.substring(lastDot + 1));
        downloadFile.deleteOnExit();

        if (response == HttpURLConnection.HTTP_OK) {
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFile)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFile.getAbsolutePath());

            Set<ExtractionPair> usedExtractions = new HashSet<>();

            // Perform extractions
            try (ZipFile zipFile = new ZipFile(downloadFile)) {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();

                    // Only extract files
                    if (entry.isDirectory()) {
                        continue;
                    }

                    for (ExtractionPair extraction : extractions) {
                        String sourcePattern = extraction.source;
                        if (FilenameUtils.wildcardMatch(entry.getName(), sourcePattern)) {
                            usedExtractions.add(extraction);
                            LOG.debug("Found matching file {} for source pattern {}", entry.getName(),
                                    sourcePattern);
                            String filename = getSourcePatternMatch(entry.getName(), sourcePattern);
                            // Workaround: If there is no matcher in 'sourcePattern' it will return the
                            // complete path. Strip it down to the filename
                            if (filename.equals(entry.getName())) {
                                int lastIndexOf = filename.lastIndexOf('/');
                                if (lastIndexOf >= 0) {
                                    filename = filename.substring(lastIndexOf + 1);
                                }
                            }
                            String name = UrlUtil.concatenateUrlWithSlashes(extraction.destination, filename);
                            FileUtils.forceMkdir(new File(name).getParentFile());
                            try (InputStream in = zipFile.getInputStream(entry);
                                    FileOutputStream out = new FileOutputStream(name)) {
                                IOUtils.copy(in, out);
                            }
                            LOG.debug("Extracted {} to {} from {}", entry.getName(), name, uri);
                        }
                    }
                }
            }

            for (ExtractionPair extraction : extractions) {
                if (!usedExtractions.contains(extraction)) {
                    LOG.debug("Extraction {} to {} not used on {}", extraction.source, extraction.destination,
                            uri);
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (IOException e) {
        LOG.error("Could not download file: {}", e.getMessage(), e);
        return false;
    }
}

From source file:gov.redhawk.core.filemanager.filesystem.JavaFileSystem.java

@Override
public FileInformationType[] list(final String fullPattern) throws FileException, InvalidFileName {
    final int index = fullPattern.lastIndexOf('/');
    final File container;
    if (index > 0) {
        container = new File(this.root, fullPattern.substring(0, index));
    } else {//  ww w  .  j  a  v a2  s .c  o  m
        container = this.root;
    }

    final String pattern = fullPattern.substring(index + 1, fullPattern.length());

    final String[] fileNames;

    if (pattern.length() == 0) {
        fileNames = new String[] { "" };
    } else {
        fileNames = container.list(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                if (!dir.equals(container)) {
                    return false;
                }
                return FilenameUtils.wildcardMatch(name, pattern);
            }
        });
    }

    if (fileNames == null) {
        return new FileInformationType[0];
    }

    final FileInformationType[] retVal = new FileInformationType[fileNames.length];
    for (int i = 0; i < fileNames.length; i++) {
        final FileInformationType fileInfo = new FileInformationType();
        final File file = new File(container, fileNames[i]);
        fileInfo.name = file.getName();
        fileInfo.size = file.length();
        if (file.isFile()) {
            fileInfo.kind = FileType.PLAIN;
        } else {
            fileInfo.kind = FileType.DIRECTORY;
        }
        final Any any = this.orb.create_any();
        any.insert_ulonglong(file.lastModified() / JavaFileSystem.MILLIS_PER_SEC);
        final DataType modifiedTime = new DataType("MODIFIED_TIME", any);

        fileInfo.fileProperties = new DataType[] { modifiedTime };

        retVal[i] = fileInfo;
    }
    return retVal;
}

From source file:com.jaeksoft.searchlib.scheduler.task.TaskFileCrawlerEvent.java

@Override
public void execute(Client client, TaskProperties properties, Variables variables, TaskLog taskLog)
        throws SearchLibException, IOException, InterruptedException {
    taskLog.setInfo("File crawler event started");

    String filePath = properties.getValue(propFilePathItem);
    String directoryURL = properties.getValue(propDirectoryURL);
    String logFilePattern = properties.getValue(propLogFilePattern);
    String domain = properties.getValue(propDomain);
    String login = properties.getValue(propLogin);
    String password = properties.getValue(propPassword);

    FilePathItem filePathItem = client.getFilePathManager().find(filePath);
    if (filePathItem == null)
        throw new SearchLibException("File path item not found: " + filePath);

    final FilePathItem fpi;
    URI srcURI;/*from w  w  w  . jav a  2  s .co m*/
    try {
        srcURI = new URI(directoryURL);

        String scheme = srcURI.getScheme();
        if (scheme.equals("smb")) {
            fpi = new FilePathItem(client);
            fpi.setType(FileInstanceType.Smb);
            fpi.setHost(srcURI.getHost());
            if (domain != null)
                fpi.setDomain(domain);
            if (login != null)
                fpi.setUsername(login);
            if (password != null)
                fpi.setPassword(password);
        } else if (scheme.equals("file")) {
            fpi = new FilePathItem(client);
            fpi.setType(FileInstanceType.Local);
        } else
            throw new SearchLibException("Unsupported scheme: " + scheme);
        int count = 0;
        FileInstanceAbstract fileInstanceSource = FileInstanceAbstract.create(fpi, null, srcURI.getPath());
        FileInstanceAbstract[] fileInstances = fileInstanceSource.listFilesOnly();
        if (fileInstances == null)
            return;
        for (FileInstanceAbstract fileInstance : fileInstances) {
            if (!StringUtils.isEmpty(logFilePattern))
                if (!FilenameUtils.wildcardMatch(fileInstance.getFileName(), logFilePattern))
                    continue;
            count++;
            taskLog.setInfo("Extract #" + count + ": " + fileInstance.getURL());
            InputStream is = fileInstance.getInputStream();
            try {
                List<String> lines = IOUtils.readLines(is);
                if (lines == null)
                    continue;
                for (String line : lines) {
                    taskLog.setInfo("Crawl " + fileInstance.getURL());
                    client.getFileCrawlMaster().crawlDirectory(filePathItem, line);
                }
            } catch (NoSuchAlgorithmException e) {
                throw new SearchLibException(e);
            } catch (InstantiationException e) {
                throw new SearchLibException(e);
            } catch (IllegalAccessException e) {
                throw new SearchLibException(e);
            } catch (ClassNotFoundException e) {
                throw new SearchLibException(e);
            } catch (SmbException e) {
                throw new SearchLibException(e);
            } catch (HttpException e) {
                throw new SearchLibException(e);
            } finally {
                IOUtils.closeQuietly(is);
            }
            fileInstance.delete();
        }
        taskLog.setInfo(count + " file(s)");
    } catch (URISyntaxException e) {
        throw new SearchLibException(e);
    }
}

From source file:com.edgenius.wiki.render.handler.AttachmentHandler.java

/**
 * @param string//  w w  w.  j  av  a2  s. com
 * @return
 */
private List<FileNode> getFileList(String filterStr, String[] visibles) {
    List<String> filter = new ArrayList<String>();
    if (!StringUtils.isEmpty(filterStr)) {
        String[] fs = filterStr.split(",");
        for (String str : fs) {
            if (!StringUtils.isEmpty(str))
                filter.add(str.trim());
        }
    }
    List<FileNode> matched = new ArrayList<FileNode>();
    for (FileNode node : atts) {
        if (visibles != null && visibles.length > 0) {
            if (!StringUtil.containsIgnoreCase(visibles, node.getNodeUuid()))
                continue;
        } else {
            //normal render, for example, page view. Then only view non-draft
            if (node.getStatus() > 0)
                continue;
        }

        String name = node.getFilename();
        if (filter.size() > 0) {
            for (String flt : filter) {
                if (FilenameUtils.wildcardMatch(name.toLowerCase(), flt.toLowerCase())) {
                    matched.add(node);
                    break;
                }
            }
        } else {
            //no filter, then put all attachments
            matched.add(node);
        }
    }
    return matched;
}

From source file:gov.redhawk.sca.efs.server.tests.FileSystemImplTest.java

/**
 * Test method for//ww  w .j  ava2s .  c o m
 * {@link gov.redhawk.efs.sca.server.internal.FileSystemImpl#list(java.lang.String)}
 * .
 */
@Test
public void testList() {

    try {
        Assert.assertEquals(0, this.fileSystem.list("empty").length);

        FileInformationType[] result = this.fileSystem.list("*");
        Assert.assertEquals(FileSystemImplTest.root.list().length, result.length);
        for (final FileInformationType type : result) {
            final File subFile = new File(FileSystemImplTest.root, type.name);
            if (subFile.isDirectory()) {
                Assert.assertEquals(FileType.DIRECTORY, type.kind);
            } else {
                Assert.assertEquals(FileType.PLAIN, type.kind);
            }
        }

        result = this.fileSystem.list("subFolder/test*");
        final File subRoot = new File(FileSystemImplTest.root, "subFolder");
        Assert.assertEquals(subRoot.list(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                if (!dir.equals(subRoot)) {
                    return false;
                }
                return FilenameUtils.wildcardMatch(name, "test*");
            }
        }).length, result.length);
        for (final FileInformationType type : result) {
            final File subFile = new File(subRoot, type.name);
            if (subFile.isDirectory()) {
                Assert.assertEquals(FileType.DIRECTORY, type.kind);
            } else {
                Assert.assertEquals(FileType.PLAIN, type.kind);
            }
        }

        result = this.fileSystem.list("testFile.t??");
        Assert.assertEquals(1, result.length);
        Assert.assertEquals(FileType.PLAIN, result[0].kind);
    } catch (final FileException e) {
        Assert.fail(e.getMessage() + ": " + e.msg);
    } catch (final InvalidFileName e) {
        Assert.fail(e.getMessage() + ": " + e.msg);
    }
}