Example usage for java.io FilenameFilter FilenameFilter

List of usage examples for java.io FilenameFilter FilenameFilter

Introduction

In this page you can find the example usage for java.io FilenameFilter FilenameFilter.

Prototype

FilenameFilter

Source Link

Usage

From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java

public static void main(final String[] args) throws Exception {
    // 1. check input directory
    final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports");
    if (!reportdir.isDirectory()) {
        throw new IllegalArgumentException("Expected directory, got " + args[0]);
    }/*  w w w . j ava 2 s.c  om*/

    // 2. read test data from surefire output
    final File[] xmlReports = reportdir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith("-output.txt");
        }
    });

    final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>();

    for (File xmlReport : xmlReports) {
        final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport));
        try {
            while (reportReader.ready()) {
                String line = reportReader.readLine();
                final String[] parts = line.substring(0, line.indexOf(':')).split("\\.");

                final String testClass = parts[0];
                if (!testData.containsKey(testClass)) {
                    testData.put(testClass, new TreeMap<String, Double>());
                }

                line = reportReader.readLine();

                testData.get(testClass).put(parts[1],
                        Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('['))));
            }
        } finally {
            IOUtils.closeQuietly(reportReader);
        }
    }

    // 3. build XSLX output (from template)
    final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src"
            + File.separator + "test" + File.separator + "resources" + File.separator + XLS));

    for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) {
        final Sheet sheet = workbook.getSheet(entry.getKey());

        int rows = 0;

        for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) {
            final Row row = sheet.createRow(rows++);

            Cell cell = row.createCell(0);
            cell.setCellValue(subentry.getKey());

            cell = row.createCell(1);
            cell.setCellValue(subentry.getValue());
        }
    }

    final FileOutputStream out = new FileOutputStream(
            args[0] + File.separator + "target" + File.separator + XLS);
    try {
        workbook.write(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.bluexml.tools.miscellaneous.Translate.java

/**
 * @param args/*from   w ww .j a  v  a 2  s. c  om*/
 */
public static void main(String[] args) {
    System.out.println("Translate.main() 1");
    Console console = System.console();

    System.out.println("give path to folder that contains properties files");
    Scanner scanIn = new Scanner(System.in);

    try {
        // TODO Auto-generated method stub
        String sWhatever;

        System.out.println("Translate.main() 2");
        sWhatever = scanIn.nextLine();
        System.out.println("Translate.main() 3");

        System.out.println(sWhatever);

        File inDir = new File(sWhatever);

        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith("properties");
            }
        };
        File[] listFiles = inDir.listFiles(filter);
        for (File file : listFiles) {

            prapareFileToTranslate(file, inDir);

        }

        System.out.println("please translate text files and press enter");
        String readLine = scanIn.nextLine();
        System.out.println("Translate.main() 4");
        for (File file : listFiles) {

            File values = new File(file.getParentFile(), file.getName() + ".txt");
            writeBackValues(values, file);
            values.delete();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        scanIn.close();
    }

}

From source file:de.dfki.resc28.ole.bootstrap.App.java

public static void main(String[] args) throws IOException {
    configure();// ww w .j av a 2s.  c  o m
    initRepoModel();

    File[] files = new File(fPartsDirectory).listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".dat");
        }
    });

    if (files == null) {
        System.err.format("Error: %s is not a directory%n", fPartsDirectory);
        System.exit(1);
    }

    int fileCounter = 0;

    for (File file : files) {
        System.out.format("Parsing file: %s [%d/%d]...%n", file.getAbsolutePath(), fileCounter + 1,
                files.length);

        parseFile(file);

        fileCounter++;
    }

    fGraphStore.addToNamedGraph(fRepo.getURI(), fRepoModel);

    System.exit(0);
}

From source file:com.linkedin.pinot.perf.FilterOperatorBenchmark.java

public static void main(String[] args) throws Exception {
    String rootDir = args[0];/* w w w.j a  v  a2  s . c  o  m*/
    File[] segmentDirs = new File(rootDir).listFiles();
    String query = args[1];
    AtomicInteger totalDocsMatched = new AtomicInteger(0);
    Pql2Compiler pql2Compiler = new Pql2Compiler();
    BrokerRequest brokerRequest = pql2Compiler.compileToBrokerRequest(query);
    List<Callable<Void>> segmentProcessors = new ArrayList<>();
    long[] timesSpent = new long[segmentDirs.length];
    for (int i = 0; i < segmentDirs.length; i++) {
        File indexSegmentDir = segmentDirs[i];
        System.out.println("Loading " + indexSegmentDir.getName());
        Configuration tableDataManagerConfig = new PropertiesConfiguration();
        List<String> invertedColumns = new ArrayList<>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".bitmap.inv");
            }
        };
        String[] indexFiles = indexSegmentDir.list(filter);
        for (String indexFileName : indexFiles) {
            invertedColumns.add(indexFileName.replace(".bitmap.inv", ""));
        }
        tableDataManagerConfig.setProperty(IndexLoadingConfigMetadata.KEY_OF_LOADING_INVERTED_INDEX,
                invertedColumns);
        IndexLoadingConfigMetadata indexLoadingConfigMetadata = new IndexLoadingConfigMetadata(
                tableDataManagerConfig);
        IndexSegmentImpl indexSegmentImpl = (IndexSegmentImpl) Loaders.IndexSegment.load(indexSegmentDir,
                ReadMode.heap, indexLoadingConfigMetadata);
        segmentProcessors
                .add(new SegmentProcessor(i, indexSegmentImpl, brokerRequest, totalDocsMatched, timesSpent));
    }
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int run = 0; run < 5; run++) {
        System.out.println("START RUN:" + run);
        totalDocsMatched.set(0);
        long start = System.currentTimeMillis();
        List<Future<Void>> futures = executorService.invokeAll(segmentProcessors);
        for (int i = 0; i < futures.size(); i++) {
            futures.get(i).get();
        }
        long end = System.currentTimeMillis();
        System.out.println("Total docs matched:" + totalDocsMatched + " took:" + (end - start));
        System.out.println("Times spent:" + Arrays.toString(timesSpent));
        System.out.println("END RUN:" + run);
    }
    System.exit(0);
}

From source file:disko.PDFDocument.java

public static void main(String[] args) {
    File dir = new File("/var/tmp/muriloq/mdc/selected");

    File[] pdfFiles = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".pdf");
        }/*w w  w.  j ava2 s.  c om*/
    });

    for (File f : pdfFiles) {
        try {
            System.out.println(f.getName());
            PDFDocument pdf = new PDFDocument(f);
            pdf.getFullText();
            System.out.println(pdf.getFullText());
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

From source file:data_gen.Data_gen.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    long startTime = System.nanoTime();
    if (args.length < 2) {
        System.out.println("Usage:");
        System.out.println(//  w  w w. jav a  2 s  . c  o  m
                "java -jar \"jarfile\" [Directory of text source folder] [Dierctory of configration file]"
                        + "\n");
        System.exit(0);
    }

    String Dir = args[0]; // get text source dir from user
    String config_dir = args[1];
    File folder = new File(Dir);
    if (folder.isDirectory() == false) {
        System.out.println("Text souce folder is not a Directory." + "\n");
        System.exit(0);
    }
    if (!config_dir.endsWith(".properties") && !config_dir.endsWith(".PROPERTIES")) {
        System.out.println("\n"
                + "There was error parsing dataset parameters from configuration file, make sure you have the 4 parameters specified and the right type of file"
                + "\n");
        System.exit(0);
    }

    listOfFiles = folder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");
        }
    });

    if (listOfFiles.length == 0) {
        System.out.println("Text source folder is empty ! Have at least one .txt file there" + "\n");
        System.exit(0);
    }

    System.out.println("\n");
    Parse_Document_values(config_dir);// parse config file to get class attribute values
    document_size = Docments_Total_size / documents_count; // to get each document size 
    max = (long) ((double) document_size * 1.8);
    min = (long) ((double) document_size * 0.2);

    schema_fields = Parse_Document_fields(config_dir);

    try {
        LineIterator it = FileUtils.lineIterator(listOfFiles[0]);

        while (it.hasNext()) {
            tx.add(it.nextLine());
        }
    } catch (NullPointerException | FileNotFoundException e) {
        System.out.println("The text source file could not be found." + "\n");
        System.exit(0);
    }

    new File(output_dir).mkdir();
    //////////////////////////////////////////////////////////////// build json or .dat
    ////////////////////////////////////////////////////////////////////     
    if (Default_DataSet_name.endsWith(".json")) {
        Build_json_file(config_dir, startTime);
    }

    if (Default_DataSet_name.endsWith(".dat")) {
        Build_dat_file(config_dir, startTime);
    }

    generate_xml();
    generate_field_map();

}

From source file:TestDumpRecord.java

public static void main(String[] args) throws NITFException {
    List<String> argList = Arrays.asList(args);
    List<File> files = new LinkedList<File>();
    for (String arg : argList) {
        File f = new File(arg);
        if (f.isDirectory()) {
            File[] dirFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    String ext = FilenameUtils.getExtension(name).toLowerCase();
                    return ext.matches("nitf|nsf|ntf");
                }/* w  w w. j a  v a 2  s .co  m*/
            });
            files.addAll(Arrays.asList(dirFiles));
        } else
            files.add(f);
    }

    Reader reader = new Reader();
    for (File file : files) {
        PrintStream out = System.out;

        out.println("=== " + file.getAbsolutePath() + " ===");
        IOHandle handle = new IOHandle(file.getAbsolutePath());
        Record record = reader.read(handle);
        dumpRecord(record, reader, out);
        handle.close();

        record.destruct(); // tells the memory manager to decrement the ref
        // count
    }
}

From source file:com.twentyn.patentScorer.ScoreMerger.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//w w  w  .  j  av  a 2s  .c  o  m
    Options opts = new Options();
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());

    opts.addOption(Option.builder("r").longOpt("results").required().hasArg()
            .desc("A directory of search results to read").build());
    opts.addOption(Option.builder("s").longOpt("scores").required().hasArg()
            .desc("A directory of patent classification scores to read").build());
    opts.addOption(Option.builder("o").longOpt("output").required().hasArg()
            .desc("The output file where results will be written.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }
    File scoresDirectory = new File(cmdLine.getOptionValue("scores"));
    if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) {
        LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores"));
    }

    File resultsDirectory = new File(cmdLine.getOptionValue("results"));
    if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) {
        LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results"));
    }

    FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    FilenameFilter jsonFilter = new FilenameFilter() {
        public final Pattern JSON_PATTERN = Pattern.compile("\\.json$");

        public boolean accept(File dir, String name) {
            return JSON_PATTERN.matcher(name).find();
        }
    };

    Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>();
    LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath());
    for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) {
        BufferedReader reader = new BufferedReader(new FileReader(scoreFile));
        int count = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            PatentScorer.ClassificationResult res = objectMapper.readValue(line,
                    PatentScorer.ClassificationResult.class);
            scores.put(res.docId, res);
            count++;
        }
        LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath());
    }

    Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>();
    Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>();
    LOGGER.info("Reading results from directory at " + resultsDirectory);
    // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference.
    JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class,
            DocumentSearch.SearchResult.class);

    List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter));
    Collections.sort(resultsFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (File resultsFile : resultsFiles) {
        BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
        CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue());
        int bytesRead = reader.read(buffer);
        LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is "
                + resultsFile.length() + ")");
        List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()),
                resultsType);

        LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath());

        int count = 0;
        for (DocumentSearch.SearchResult sres : results) {
            for (DocumentSearch.ResultDocument resDoc : sres.getResults()) {
                String docId = resDoc.getDocId();
                PatentScorer.ClassificationResult classificationResult = scores.get(docId);
                if (classificationResult == null) {
                    LOGGER.warn("No classification result found for " + docId);
                } else {
                    resDoc.setClassifierScore(classificationResult.getScore());
                }
            }
            if (!synonymsToResults.containsKey(sres.getSynonym())) {
                synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>());
            }
            synonymsToResults.get(sres.getSynonym()).add(sres);
            count++;
            if (count % 1000 == 0) {
                LOGGER.info("Processed " + count + " search result documents");
            }
        }
    }

    Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() {
        @Override
        public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) {
            int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore());
            if (cmp != 0) {
                return cmp;
            }
            cmp = o2.getScore().compareTo(o1.getScore());
            return cmp;
        }
    };

    for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) {
        DocumentSearch.SearchResult newSearchRes = null;
        // Merge all result documents into a single search result.
        for (DocumentSearch.SearchResult sr : entry.getValue()) {
            if (newSearchRes == null) {
                newSearchRes = sr;
            } else {
                newSearchRes.getResults().addAll(sr.getResults());
            }
        }
        if (newSearchRes == null || newSearchRes.getResults() == null) {
            LOGGER.error("Search results for " + entry.getKey() + " are null.");
            continue;
        }
        Collections.sort(newSearchRes.getResults(), resultDocumentComparator);
        if (!inchisToResults.containsKey(newSearchRes.getInchi())) {
            inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>());
        }
        inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes);
    }

    List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet());
    Collections.sort(sortedKeys);
    List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size());
    Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() {
        @Override
        public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) {
            return o1.getSynonym().compareTo(o2.getSynonym());
        }
    };
    for (String inchi : sortedKeys) {
        List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi);
        Collections.sort(res, synonymSorter);
        orderedResults.add(new GroupedInchiResults(inchi, res));
    }

    objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults);
    outputWriter.close();
}

From source file:Gen.java

public static void main(String[] args) throws Exception {

    try {/*from  ww  w. j a  va  2  s. co  m*/

        File[] files = null;
        if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) {
            files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".XML");
                };
            });
        } else {
            String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("")
                    ? System.getProperty("file")
                    : "rjmap.xml";
            files = new File[] { new File(fileName) };
        }

        log.info("files : " + Arrays.toString(files));

        if (files == null || files.length == 0) {
            log.info("no files to parse");
            System.exit(0);
        }

        boolean formatsource = true;
        if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("")
                && System.getProperty("formatsource").equalsIgnoreCase("false")) {
            formatsource = false;
        }

        GEN_ROOT = System.getProperty("outputdir");

        if (GEN_ROOT == null || GEN_ROOT.equals("")) {
            GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib";
        }

        GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/');
        if (GEN_ROOT.endsWith("/"))
            GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1);

        System.out.println("GEN ROOT:" + GEN_ROOT);

        MAPPING_JAR_NAME = System.getProperty("mappingjar") != null
                && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar")
                        : "mapping.jar";
        if (!MAPPING_JAR_NAME.endsWith(".jar"))
            MAPPING_JAR_NAME += ".jar";

        GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src";
        GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + "";

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

        for (int f = 0; f < files.length; ++f) {
            log.info("parsing file : " + files[f]);
            Document document = documentBuilder.parse(files[f]);

            Vector<Node> initNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript",
                    initNodes);
            for (int i = 0; i < initNodes.size(); ++i) {
                NamedNodeMap attrs = initNodes.elementAt(i).getAttributes();
                boolean embed = attrs.getNamedItem("embed") != null
                        && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true");
                StringBuffer vbuffer = new StringBuffer();
                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue());
                    vbuffer.append('\n');
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    vbuffer.append(Utils.getFileAsStringBuffer(fname));
                }
                initScriptBuffer.append(vbuffer);
                if (embed)
                    embedScriptBuffer.append(vbuffer);
            }

            Vector<Node> packageInitNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript",
                    packageInitNodes);
            for (int i = 0; i < packageInitNodes.size(); ++i) {
                NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes();
                String packageName = attrs.getNamedItem("package").getNodeValue();

                if (packageName.equals(""))
                    packageName = "rGlobalEnv";

                if (!packageName.endsWith("Function"))
                    packageName += "Function";
                if (packageEmbedScriptHashMap.get(packageName) == null) {
                    packageEmbedScriptHashMap.put(packageName, new StringBuffer());
                }
                StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName);

                // if (!packageName.equals("rGlobalEnvFunction")) {
                // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n");
                // }

                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                    initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname);
                    vbuffer.append(fileBuffer);
                    initScriptBuffer.append(fileBuffer);
                }
            }

            Vector<Node> functionsNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function",
                    functionsNodes);
            for (int i = 0; i < functionsNodes.size(); ++i) {
                NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes();
                String functionName = attrs.getNamedItem("name").getNodeValue();

                boolean forWeb = attrs.getNamedItem("forWeb") != null
                        && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true");

                String signature = (attrs.getNamedItem("signature") == null ? ""
                        : attrs.getNamedItem("signature").getNodeValue() + ",");
                String renameTo = (attrs.getNamedItem("renameTo") == null ? null
                        : attrs.getNamedItem("renameTo").getNodeValue());

                HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName);

                if (sigMap == null) {
                    sigMap = new HashMap<String, FAttributes>();
                    Globals._functionsToPublish.put(functionName, sigMap);

                    if (attrs.getNamedItem("returnType") == null) {
                        _functionsVector.add(new String[] { functionName });
                    } else {
                        _functionsVector.add(
                                new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() });
                    }

                }

                sigMap.put(signature, new FAttributes(renameTo, forWeb));

                if (forWeb)
                    _webPublishingEnabled = true;

            }

            if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("")
                    && System.getProperty("targetjdk").compareTo("1.5") < 0) {
                if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null
                        && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) {
                    log.info("be careful, web publishing disabled beacuse target JDK<1.5");
                }
                _webPublishingEnabled = false;
            } else {

                if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("")
                        || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) {
                    _webPublishingEnabled = true;
                }

                if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) {
                    log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use");
                    _webPublishingEnabled = false;
                }
            }

            Vector<Node> s4Nodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes);

            if (s4Nodes.size() > 0) {
                String formalArgs = "";
                String signature = "";
                for (int i = 0; i < s4Nodes.size(); ++i) {
                    NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes();
                    String s4Name = attrs.getNamedItem("name").getNodeValue();
                    formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ",");
                    signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ",");
                }
                String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs
                        + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER
                        + "', signature(" + signature + ") , function(" + formalArgs + ") {   })";
                initScriptBuffer.append(genBeansScriptlet);
                _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" });
            }

        }

        if (!new File(GEN_ROOT_LIB).exists())
            regenerateDir(GEN_ROOT_LIB);
        else {
            clean(GEN_ROOT_LIB, true);
        }

        for (int i = 0; i < rwebservicesScripts.length; ++i)
            DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]);

        String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() {
            public void run(Rengine e) {
                DirectJNI.getInstance().toggleMarker();
                DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString());
                log.info(" init  script status : " + DirectJNI.getInstance().cutStatusSinceMarker());

                for (int i = 0; i < _functionsVector.size(); ++i) {

                    String[] functionPair = _functionsVector.elementAt(i);
                    log.info("dealing with : " + functionPair[0]);

                    regenerateDir(GEN_ROOT_SRC);

                    String createMapStr = "createMap(";
                    boolean isGeneric = e.rniGetBoolArrayI(
                            e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1;

                    log.info("is Generic : " + isGeneric);
                    if (isGeneric) {
                        createMapStr += functionPair[0];
                    } else {
                        createMapStr += "\"" + functionPair[0] + "\"";
                    }
                    createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC
                            .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\"";
                    createMapStr += ", typeMode=\"robject\"";
                    createMapStr += (functionPair.length == 1 || functionPair[1] == null
                            || functionPair[1].trim().equals("") ? ""
                                    : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1]
                                            + "\")");
                    createMapStr += ")";

                    log.info("------------------------------------------");
                    log.info("-- createMapStr=" + createMapStr);
                    DirectJNI.getInstance().toggleMarker();
                    e.rniEval(e.rniParse(createMapStr, 1), 0);
                    String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker();
                    log.info(" createMap status : " + createMapStatus);
                    log.info("------------------------------------------");

                    deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms");
                    compile(GEN_ROOT_SRC);
                    jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null);

                    URL url = null;
                    try {
                        url = new URL(
                                "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar")
                                        .replace('\\', '/') + "!/");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    DirectJNI.generateMaps(url, true);
                }

            }
        });

        log.info(lastStatus);

        log.info(DirectJNI._rPackageInterfacesHash);
        regenerateDir(GEN_ROOT_SRC);
        for (int i = 0; i < _functionsVector.size(); ++i) {
            unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC);
        }

        regenerateRPackageClass(true);

        generateS4BeanRef();

        if (formatsource)
            applyJalopy(GEN_ROOT_SRC);

        compile(GEN_ROOT_SRC);

        for (String k : DirectJNI._rPackageInterfacesHash.keySet()) {
            Rmic rmicTask = new Rmic();
            rmicTask.setProject(_project);
            rmicTask.setTaskName("rmic_packages");
            rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC));
            rmicTask.setBase(new File(GEN_ROOT_SRC));
            rmicTask.setClassname(k + "ImplRemote");
            rmicTask.init();
            rmicTask.execute();
        }

        // DirectJNI._rPackageInterfacesHash=new HashMap<String,
        // Vector<Class<?>>>();
        // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new
        // Vector<Class<?>>());

        if (_webPublishingEnabled) {

            jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null);
            URL url = new URL(
                    "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/");
            ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader());

            for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
                if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0)
                    continue;
                log.info("######## " + className);

                WsGen wsgenTask = new WsGen();
                wsgenTask.setProject(_project);
                wsgenTask.setTaskName("wsgen");

                FileSet rjb_fileSet = new FileSet();
                rjb_fileSet.setProject(_project);
                rjb_fileSet.setDir(new File("."));
                rjb_fileSet.setIncludes("RJB.jar");

                DirSet src_dirSet = new DirSet();
                src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                Path classPath = new Path(_project);
                classPath.addFileset(rjb_fileSet);
                classPath.addDirset(src_dirSet);
                wsgenTask.setClasspath(classPath);
                wsgenTask.setKeep(true);
                wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setSei(className + "Web");

                wsgenTask.init();
                wsgenTask.execute();
            }

            new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete();

        }

        embedRScripts();

        HashMap<String, String> marker = new HashMap<String, String>();
        marker.put("RJBMAPPINGJAR", "TRUE");

        Properties props = new Properties();
        props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames));
        props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping));
        props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert));
        props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping));
        props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash));
        props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash));
        props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories));
        new File(GEN_ROOT_SRC + "/" + "maps").mkdirs();
        FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml");
        props.storeToXML(fos, null);
        fos.close();

        jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker);

        if (_webPublishingEnabled)
            genWeb();

        DirectJNI._mappingClassLoader = null;

    } finally {

        System.exit(0);

    }
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/* w  ww .j av  a 2 s  .  c  o  m*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}