001package org.hl7.fhir.validation.cli.utils;
002
003import java.io.File;
004import java.io.FilenameFilter;
005import java.io.IOException;
006
007public class AsteriskFilter implements FilenameFilter {
008  String dir;
009  String regex;
010
011  public AsteriskFilter(String filter) throws IOException {
012    if (!filter.matches("(.*(\\\\|\\/))*(.*)\\*(.*)"))
013      throw new IOException("Filter names must have the following syntax: [directorypath][prefix]?*[suffix]?   I.e. The asterisk must be in the filename, not the directory path");
014    dir = filter.replaceAll("(.*(\\\\|\\/))*(.*)\\*(.*)", "$1");
015    String expression = filter.replaceAll("(.*(\\\\|\\/))*(.*)", "$3");
016    regex = "";
017    for (int i = 0; i < expression.length(); i++) {
018      if (Character.isAlphabetic(expression.codePointAt(i)) || Character.isDigit(expression.codePointAt(i)))
019        regex = regex + expression.charAt(i);
020      else if (expression.charAt(i) == '*')
021        regex = regex + ".*";
022      else
023        regex = regex + "\\" + expression.charAt(i);
024    }
025    File f = new File(dir);
026    if (!f.exists()) {
027      throw new IOException("Directory " + dir + " does not exist");
028    }
029    if (!f.isDirectory()) {
030      throw new IOException("Directory " + dir + " is not a directory");
031    }
032  }
033
034  public boolean accept(File dir, String s) {
035    return s.matches(regex);
036  }
037
038  public String getDir() {
039    return dir;
040  }
041}