Example usage for java.nio.file Files isReadable

List of usage examples for java.nio.file Files isReadable

Introduction

In this page you can find the example usage for java.nio.file Files isReadable.

Prototype

public static boolean isReadable(Path path) 

Source Link

Document

Tests whether a file is readable.

Usage

From source file:Main.java

public static void main(String[] args) {

    Path path = FileSystems.getDefault().getPath("C:/tutorial/Java/JavaFX", "Demo.txt");

    boolean is_readable = Files.isReadable(path);
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*from  w  ww  . ja  va 2 s .c  om*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:lucene.IndexFiles.java

/** Index all text files under a directory. */
public static void main(String[] args) {
    String usage = "java org.apache.lucene.demo.IndexFiles"
            + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
            + "This indexes the documents in DOCS_PATH, creating a Lucene index"
            + "in INDEX_PATH that can be searched with SearchFiles";
    String indexPath = "E:/index26";
    // is DFR//from  w ww . j a v a 2s .  c o m
    //2 is normal
    //3 is ib with h3
    //4 is ib with h2 with porter stemmer
    //5 is ib with h2 with s stemmer
    //6 is ib with h2 without stemmer
    //7 is  without stemmer without <p
    //8 is basic with all tags
    //9 is ib with h2 and stopwords without stemmer
    //10 like  without ib, lower tags
    //11 like 10 with lower tags p, br and hr
    //12 like 11 with tags closed
    //13 is closed tags with punctuation replace and whitespace tokenizer with hyphen cared for
    //14 std tokenizer with hyphen taken cared for with stemmer
    //15 like 14 without stemming
    //16 like 15 with LMD
    //17 like 11 with LMD
    //18 with count of lower and upper delimiters of split
    //19 like 18 with (?i) to ignore case in all and valipas > 9
    //20 with (?i) in all
    //21 is fresh 19
    //22 is legalspans with LMD
    //23 is fresh 19 without 0 pass
    //24 is legalspans with InB2
    //25 is 23
    //26 is 25 with s stemmer and 0
    //27 is legalspans demo of 50 passages
    //28 is modified legal span and fast
    //29 is 28 with s-stemming
    //30 is 28 with porter stemming
    String docsPath = "E:/documents/text";
    boolean create = true;
    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            indexPath = args[i + 1];
            i++;
        } else if ("-docs".equals(args[i])) {
            docsPath = args[i + 1];
            i++;
        } else if ("-update".equals(args[i])) {
            create = false;
        }
    }

    if (docsPath == null) {
        System.err.println("Usage: " + usage);
        System.exit(1);
    }

    final Path docDir = Paths.get(docsPath);
    if (!Files.isReadable(docDir)) {
        System.out.println("Document directory dhfndk '" + docDir.toAbsolutePath()
                + "' does not exist or is not readable, please check the path");
        System.exit(1);
    }

    Date start = new Date();
    try {
        System.out.println("Indexing to directory '" + indexPath + "'...");

        Directory dir = FSDirectory.open(Paths.get(indexPath));
        //Analyzer analyzer = new StandardAnalyzer();
        //IndexWriterConfig iwc = new IndexWriterConfig(analyzer);

        StandardAnalyzer analyzer = new StandardAnalyzer();
        //Directory dir = new RAMDirectory();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        /*IBSimilarity similarity = new IBSimilarity(
              new DistributionLL(),//1 
              //new DistributionSPL(),//2
              new LambdaDF(),//1 
              //new LambdaTTF(), //2
              new NormalizationH2());*/
        /*DFRSimilarity similarity = new DFRSimilarity( ///////INB2 Similarity
          new BasicModelIn(),
          new AfterEffectL(),
          new NormalizationH1());*/
        LMDirichletSimilarity similarity = new LMDirichletSimilarity();//////// LMD Model
        iwc.setSimilarity(similarity);
        IndexWriter writer = new IndexWriter(dir, iwc);

        if (create) {
            // Create a new index in the directory, removing any
            // previously indexed documents:
            iwc.setOpenMode(OpenMode.CREATE);
        } else {
            // Add new documents to an existing index:
            iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
        }
        System.out.println("Test 1");

        // Optional: for better indexing performance, if you
        // are indexing many documents, increase the RAM
        // buffer.  But if you do this, increase the max heap
        // size to the JVM (eg add -Xmx512m or -Xmx1g):
        //
        // iwc.setRAMBufferSizeMB(256.0);

        //IndexWriter writer = new IndexWriter(dir, iwc);
        System.out.println("Test 2");
        indexDocs(writer, docDir);
        System.out.println("Test 3");

        // NOTE: if you want to maximize search performance,
        // you can optionally call forceMerge here.  This can be
        // a terribly costly operation, so generally it's only
        // worth it when your index is relatively static (ie
        // you're done adding documents to it):
        //
        // writer.forceMerge(1);

        writer.close();

        Date end = new Date();
        System.out.println(end.getTime() - start.getTime() + " total milliseconds");

    } catch (IOException e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    }
}

From source file:org.rdswicthboard.utils.rdf.oai.App.java

public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file");
    options.addOption("o", PROPERTY_OUTPUT_FILE, true,
            "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")");
    options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")");
    options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")");
    options.addOption("I", PROPERTY_INPUT_ENCODING, true,
            "input file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("O", PROPERTY_OUTPUT_ENCODING, true,
            "output file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding");
    options.addOption("h", PROPERTY_HELP, false, "print this message");

    try {//from ww w. java 2 s.  c  o m
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(PROPERTY_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]",
                    options);

            System.exit(0);
        }

        // variables to store program properties
        CompositeConfiguration config = new CompositeConfiguration();
        config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE);
        config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC);
        config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT);

        // check if arguments has input file properties 
        if (line.hasOption(PROPERTY_CONFIG_FILE)) {
            // if it does, load the specified configuration file
            Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE));
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            } else
                throw new Exception("Invalid configuration file: " + defaultConfig.toString());
        } else {
            // if it not, try to load default configurationfile
            Path defaultConfig = Paths.get(PROPERTIES_FILE);
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            }
        }

        // check if arguments has input file 
        if (line.hasOption(PROPERTY_INPUT_FILE))
            config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE));

        // check if arguments has output file
        if (line.hasOption(PROPERTY_OUTPUT_FILE))
            config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE));

        // check if arguments has set spec name
        if (line.hasOption(PROPERTY_SET_SPEC))
            config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC));

        // check if arguments has input encoding
        if (line.hasOption(PROPERTY_INPUT_ENCODING))
            config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_OUTPUT_ENCODING))
            config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_FORMAT_OUTPUT))
            config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes");

        // check if arguments has input file without a key
        if (line.getArgs().length > 0) {
            config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]);

            // check if arguments has output file without a key
            if (line.getArgs().length > 1) {
                config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]);

                // check if there is too many arguments
                if (line.getArgs().length > 2)
                    throw new Exception("Too many arguments");
            }
        }

        // The program has default output file, but input file must be presented
        if (!config.containsKey(PROPERTY_INPUT_FILE))
            throw new Exception("Please specify input file");

        // extract input file
        String inputFile = config.getString(PROPERTY_INPUT_FILE);

        // extract output file
        String outputFile = config.getString(PROPERTY_OUTPUT_FILE);

        // extract set spec
        String setSpecName = config.getString(PROPERTY_SET_SPEC);

        // extract encoding
        String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING);
        String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING);

        boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT);

        // test if source is an regular file and it is readable
        Path source = Paths.get(inputFile);
        if (!Files.isRegularFile(source))
            throw new Exception("The input file: " + source.toString() + " is not an regular file");
        if (!Files.isReadable(source))
            throw new Exception("The input file: " + source.toString() + " is not readable");

        Path target = Paths.get(outputFile);
        if (Files.exists(target)) {
            if (!Files.isRegularFile(target))
                throw new Exception("The output file: " + target.toString() + " is not an regular file");
            if (!Files.isWritable(target))
                throw new Exception("The output file: " + target.toString() + " is not writable");
        }

        // create and setup document builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        // create new document builder
        DocumentBuilder builder = factory.newDocumentBuilder();

        // create oai document
        Document oai = builder.newDocument();

        // set document version
        oai.setXmlVersion("1.0");
        oai.setXmlStandalone(true);

        // create root OAI-PMH element
        Element oaiPmh = oai.createElement("OAI-PMH");

        // set document namespaces
        oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/");
        oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        oaiPmh.setAttribute("xsi:schemaLocation",
                "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd");

        // append root node
        oai.appendChild(oaiPmh);

        // create responseDate element
        Element responseDate = oai.createElement("responseDate");

        // create simple date format
        DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT);

        // generate date
        String date = dateFormat.format(new Date());

        // set current date and time
        responseDate.setTextContent(date);

        oaiPmh.appendChild(responseDate);

        Element listRecords = oai.createElement("ListRecords");
        oaiPmh.appendChild(listRecords);

        // create xpath factory
        XPathFactory xPathfactory = XPathFactory.newInstance();

        // create namespace context
        NamespaceContext namespaceContext = new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                if (prefix.equals("rdf"))
                    return RDF_NAMESPACE;
                else if (prefix.equals("rns"))
                    return RNF_NAMESPACE;
                else
                    return null;
            }

            @Override
            public Iterator<?> getPrefixes(String val) {
                throw new IllegalAccessError("Not implemented!");
            }

            @Override
            public String getPrefix(String uri) {
                throw new IllegalAccessError("Not implemented!");
            }
        };

        // create xpath object
        XPath xpath = xPathfactory.newXPath();
        // set namespace contex
        xpath.setNamespaceContext(namespaceContext);

        // create XPath expressions
        XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about");
        XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']");

        // create RegEx patterns  
        Pattern pattern = Pattern.compile(
                "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>");

        // read file into a string
        String content = new String(Files.readAllBytes(source), inputEncoding);

        Matcher matcher = pattern.matcher(content);
        // process all records
        while (matcher.find()) {
            // convert string to input stream
            ByteArrayInputStream input = new ByteArrayInputStream(
                    matcher.group().getBytes(StandardCharsets.UTF_8.toString()));

            // parse the xml document
            Document doc = builder.parse(input);

            // remove all spaces
            NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET);
            // Remove each empty text node from document.
            for (int i = 0; i < emptyNodes.getLength(); i++) {
                Node emptyTextNode = emptyNodes.item(i);
                emptyTextNode.getParentNode().removeChild(emptyTextNode);
            }

            // obtain researcher id
            String id = (String) idExpr.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.isEmpty(id))
                throw new Exception("The record identifier can not be empty");

            // create record element
            Element record = oai.createElement("record");
            listRecords.appendChild(record);

            // create header element
            Element header = oai.createElement("header");
            record.appendChild(header);

            // create identifier element
            Element identifier = oai.createElement("identifier");
            identifier.setTextContent(id);
            header.appendChild(identifier);

            // create datestamp element
            Element datestamp = oai.createElement("datestamp");
            datestamp.setTextContent(date);
            header.appendChild(datestamp);

            // create set spec element if it exists
            if (!StringUtils.isEmpty(setSpecName)) {
                Element setSpec = oai.createElement("setSpec");
                setSpec.setTextContent(setSpecName);
                header.appendChild(setSpec);
            }

            // create metadata element
            Element metadata = oai.createElement("metadata");
            record.appendChild(metadata);

            // import the record
            metadata.appendChild(oai.importNode(doc.getDocumentElement(), true));
        }

        // create transformer factory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // create transformer
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

        if (formatOutput) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } else
            transformer.setOutputProperty(OutputKeys.INDENT, "no");

        // create dom source
        DOMSource oaiSource = new DOMSource(oai);

        // create stream result
        StreamResult result = new StreamResult(target.toFile());

        // stream xml to file
        transformer.transform(oaiSource, result);

        // optional stream xml to console for testing
        //StreamResult consoleResult = new StreamResult(System.out);
        //transformer.transform(oaiSource, consoleResult);

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());

        //e.printStackTrace();

        System.exit(1);
    }
}

From source file:io.anserini.search.SearchWebCollection.java

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

    SearchArgs searchArgs = new SearchArgs();
    CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));

    try {/*from   w ww .j a  va2  s .  co m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println("Example: SearchWebCollection" + parser.printExample(OptionHandlerFilter.REQUIRED));
        return;
    }

    LOG.info("Reading index at " + searchArgs.index);
    Directory dir;
    if (searchArgs.inmem) {
        LOG.info("Using MMapDirectory with preload");
        dir = new MMapDirectory(Paths.get(searchArgs.index));
        ((MMapDirectory) dir).setPreload(true);
    } else {
        LOG.info("Using default FSDirectory");
        dir = FSDirectory.open(Paths.get(searchArgs.index));
    }

    Similarity similarity = null;

    if (searchArgs.ql) {
        LOG.info("Using QL scoring model");
        similarity = new LMDirichletSimilarity(searchArgs.mu);
    } else if (searchArgs.bm25) {
        LOG.info("Using BM25 scoring model");
        similarity = new BM25Similarity(searchArgs.k1, searchArgs.b);
    } else {
        LOG.error("Error: Must specify scoring model!");
        System.exit(-1);
    }

    RerankerCascade cascade = new RerankerCascade();
    boolean useQueryParser = false;
    if (searchArgs.rm3) {
        cascade.add(new Rm3Reranker(new EnglishAnalyzer(), FIELD_BODY,
                "src/main/resources/io/anserini/rerank/rm3/rm3-stoplist.gov2.txt"));
        useQueryParser = true;
    } else {
        cascade.add(new IdentityReranker());
    }
    FeatureExtractors extractors = null;
    if (searchArgs.extractors != null) {
        extractors = FeatureExtractors.loadExtractor(searchArgs.extractors);
    }

    if (searchArgs.dumpFeatures) {
        PrintStream out = new PrintStream(searchArgs.featureFile);
        Qrels qrels = new Qrels(searchArgs.qrels);
        cascade.add(new WebCollectionLtrDataGenerator(out, qrels, extractors));
    }

    Path topicsFile = Paths.get(searchArgs.topics);

    if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
        throw new IllegalArgumentException(
                "Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
    }

    TopicReader tr = (TopicReader) Class
            .forName("io.anserini.search.query." + searchArgs.topicReader + "TopicReader")
            .getConstructor(Path.class).newInstance(topicsFile);
    SortedMap<Integer, String> topics = tr.read();

    final long start = System.nanoTime();
    SearchWebCollection searcher = new SearchWebCollection(searchArgs.index);
    searcher.search(topics, searchArgs.output, similarity, searchArgs.hits, cascade, useQueryParser,
            searchArgs.keepstop);
    searcher.close();
    final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    LOG.info("Total " + topics.size() + " topics searched in "
            + DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss"));
}

From source file:Test.java

private static void displayFileAttributes(Path path) throws Exception {
    String format = "Exists: %s %n" + "notExists: %s %n" + "Directory: %s %n" + "Regular: %s %n"
            + "Executable: %s %n" + "Readable: %s %n" + "Writable: %s %n" + "Hidden: %s %n" + "Symbolic: %s %n"
            + "Last Modified Date: %s %n" + "Size: %s %n";

    System.out.printf(format, Files.exists(path, LinkOption.NOFOLLOW_LINKS),
            Files.notExists(path, LinkOption.NOFOLLOW_LINKS),
            Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS),
            Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS), Files.isExecutable(path),
            Files.isReadable(path), Files.isWritable(path), Files.isHidden(path), Files.isSymbolicLink(path),
            Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS), Files.size(path));
}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {/* ww w  .  j  a v  a2 s  . c  om*/
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalUtils.java

public static void checkPrivilegesOnDirectory(Path location) {
    log.debug("Check the Location {}", location);
    Validate.isTrue(Files.exists(location));
    Validate.isTrue(Files.isDirectory(location));
    Validate.isTrue(Files.isReadable(location)); // List Files within Directory
    Validate.isTrue(Files.isExecutable(location)); // can change into Directory
    Validate.isTrue(Files.isWritable(location)); // can create or delete Files within Directory
}

From source file:io.redlink.solrlib.SolrCoreDescriptor.java

@SuppressWarnings("squid:S3725")
static void unpackSolrCoreDir(Path solrCoreBundle, Path solrCoreDir) throws IOException {
    LoggerFactory.getLogger(SolrCoreDescriptor.class).debug("Unpacking SolrCore directory {} to {}",
            solrCoreBundle, solrCoreDir);
    try (Stream<Path> pathStream = Files.find(solrCoreBundle, Integer.MAX_VALUE,
            (p, a) -> Files.isRegularFile(p) && Files.isReadable(p)
                    && "core.properties".equals(String.valueOf(p.getFileName())))) {
        final Optional<Path> coreProperties = pathStream.min(Comparator.comparingInt(Path::getNameCount));
        final Path sourceDir = coreProperties
                .orElseThrow(() -> new IllegalArgumentException(
                        "Invalid solrCoreBundle '" + solrCoreBundle + "': no core.properties found"))
                .getParent();/*w w  w.  ja v a2s. c  o m*/

        PathUtils.copyRecursive(sourceDir, solrCoreDir);
    }
}

From source file:audiomanagershell.commands.PlayCommand.java

@Override
public void execute() throws CommandException, IOException {
    String OS = System.getProperty("os.name").toLowerCase();
    Path file;//w w  w .j  av  a2s . c  o m
    if (OS.equals("windows"))
        file = Paths.get(this.pathRef.toString() + "\\" + this.arg);
    else
        file = Paths.get(this.pathRef.toString() + "/" + this.arg);
    String fileName = file.getFileName().toString();
    List<String> acceptedExtensions = Arrays.asList("wav", "mp3", "flac", "mp4");
    //Get the extension of the file
    String extension = FilenameUtils.getExtension(fileName);
    if (Files.isRegularFile(file) && Files.isReadable(file)) {
        if (acceptedExtensions.contains(extension)) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(file.toFile());
            System.out.printf("The file %s will open shortly...\n", fileName);
        } else {
            throw new NotAudioFileException(fileName);
        }
    } else {
        throw new CommandException(file.toString() + " not a file or can't read");
    }
}