Example usage for java.io File isDirectory

List of usage examples for java.io File isDirectory

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a directory.

Usage

From source file:com.github.s4ke.moar.cli.Main.java

public static void main(String[] args) throws ParseException, IOException {
    // create Options object
    Options options = new Options();

    options.addOption("rf", true,
            "file containing the regexes to test against (multiple regexes are separated by one empty line)");
    options.addOption("r", true, "regex to test against");

    options.addOption("mf", true, "file/folder to read the MOA from");
    options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)");

    options.addOption("sf", true, "file to read the input string(s) from");
    options.addOption("s", true, "string to test the MOA/Regex against");

    options.addOption("m", false, "multiline matching mode (search in string for regex)");

    options.addOption("ls", false, "treat every line of the input string file as one string");
    options.addOption("t", false, "trim lines if -ls is set");

    options.addOption("d", false, "only do determinism check");

    options.addOption("help", false, "prints this dialog");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("moar-cli", options);
        return;/*from   ww  w.j ava 2s . c  om*/
    }

    List<String> patternNames = new ArrayList<>();
    List<MoaPattern> patterns = new ArrayList<>();
    List<String> stringsToCheck = new ArrayList<>();

    if (cmd.hasOption("r")) {
        String regexStr = cmd.getOptionValue("r");
        try {
            patterns.add(MoaPattern.compile(regexStr));
            patternNames.add(regexStr);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    if (cmd.hasOption("rf")) {
        String fileName = cmd.getOptionValue("rf");
        List<String> regexFileContents = readFileContents(new File(fileName));
        int emptyLineCountAfterRegex = 0;
        StringBuilder regexStr = new StringBuilder();
        for (String line : regexFileContents) {
            if (emptyLineCountAfterRegex >= 1) {
                if (regexStr.length() > 0) {
                    patterns.add(MoaPattern.compile(regexStr.toString()));
                    patternNames.add(regexStr.toString());
                }
                regexStr.setLength(0);
                emptyLineCountAfterRegex = 0;
            }
            if (line.trim().equals("")) {
                if (regexStr.length() > 0) {
                    ++emptyLineCountAfterRegex;
                }
            } else {
                regexStr.append(line);
            }
        }
        if (regexStr.length() > 0) {
            try {
                patterns.add(MoaPattern.compile(regexStr.toString()));
                patternNames.add(regexStr.toString());
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return;
            }
            regexStr.setLength(0);
        }
    }

    if (cmd.hasOption("mf")) {
        String fileName = cmd.getOptionValue("mf");
        File file = new File(fileName);
        if (file.isDirectory()) {
            System.out.println(fileName + " is a directory, using all *.moar files as patterns");
            File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar"));
            for (File moar : moarFiles) {
                String jsonString = readWholeFile(moar);
                patterns.add(MoarJSONSerializer.fromJSON(jsonString));
                patternNames.add(moar.getAbsolutePath());
            }
        } else {
            System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)");
            String jsonString = readWholeFile(file);
            patterns.add(MoarJSONSerializer.fromJSON(jsonString));
            patternNames.add(fileName);
        }
    }

    if (cmd.hasOption("s")) {
        String str = cmd.getOptionValue("s");
        stringsToCheck.add(str);
    }

    if (cmd.hasOption("sf")) {
        boolean treatLineAsString = cmd.hasOption("ls");
        boolean trim = cmd.hasOption("t");
        String fileName = cmd.getOptionValue("sf");
        StringBuilder stringBuilder = new StringBuilder();
        boolean firstLine = true;
        for (String str : readFileContents(new File(fileName))) {
            if (treatLineAsString) {
                if (trim) {
                    str = str.trim();
                    if (str.length() == 0) {
                        continue;
                    }
                }
                stringsToCheck.add(str);
            } else {
                if (!firstLine) {
                    stringBuilder.append("\n");
                }
                if (firstLine) {
                    firstLine = false;
                }
                stringBuilder.append(str);
            }
        }
        if (!treatLineAsString) {
            stringsToCheck.add(stringBuilder.toString());
        }
    }

    if (cmd.hasOption("d")) {
        //at this point we have already built the Patterns
        //so just give the user a short note.
        System.out.println("All Regexes seem to be deterministic.");
        return;
    }

    if (patterns.size() == 0) {
        System.out.println("no patterns to check");
        return;
    }

    if (cmd.hasOption("mo")) {
        String folder = cmd.getOptionValue("mo");
        File folderFile = new File(folder);
        if (!folderFile.exists()) {
            System.out.println(folder + " does not exist. creating...");
            if (!folderFile.mkdirs()) {
                System.out.println("folder " + folder + " could not be created");
            }
        }
        int cnt = 0;
        for (MoaPattern pattern : patterns) {
            String patternAsJSON = MoarJSONSerializer.toJSON(pattern);
            try (BufferedWriter writer = new BufferedWriter(
                    new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) {
                writer.write(patternAsJSON);
            }
        }
        System.out.println("stored " + cnt + " patterns in " + folder);
    }

    if (stringsToCheck.size() == 0) {
        System.out.println("no strings to check");
        return;
    }

    boolean multiline = cmd.hasOption("m");

    for (String string : stringsToCheck) {
        int curPattern = 0;
        for (MoaPattern pattern : patterns) {
            MoaMatcher matcher = pattern.matcher(string);
            if (!multiline) {
                if (matcher.matches()) {
                    System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\"");
                } else {
                    System.out.println(
                            "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\"");
                }
            } else {
                StringBuilder buffer = new StringBuilder(string);
                int additionalCharsPerMatch = ("<match>" + "</match>").length();
                int matchCount = 0;
                while (matcher.nextMatch()) {
                    buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch,
                            matcher.getEnd() + matchCount * additionalCharsPerMatch,
                            "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>");
                    ++matchCount;
                }
                System.out.println(buffer.toString());
            }
        }
        ++curPattern;
    }
}

From source file:com.utiles.files.MetodosFiles.java

public static void main(String[] args) {
    MetodosFiles metodosFiles = new MetodosFiles();
    String nombreClase;/*from  ww  w .  jav a 2 s .  co m*/
    try {
        //            File directorio = new File(DIRECTORIO_PRUEBA);
        //            metodosFiles.eliminarSystemOuts(FILE_PRUEBA);
        //            metodosFiles.agregarPrintException(FILE_PRUEBA);
        //            nombreClase = metodosFiles.detectarNombreClase("   public class GestionReporteHelper   {");
        //            System.out.println("nombreClase-->" + nombreClase);
        //            metodosFiles.armarCadenaPrintException("ClasePrueba");
        //            metodosFiles.listarArchivosDeDirectorio(directorio);
        //            System.out.println("--> " + metodosFiles.validarLineaSinComentario("//File directorio = new File(DIRECTORIO_PRUEBA);"));

        //           metodosFiles.eliminarSystemOuts(nombreClase);
        File directorio = new File("D:\\dev\\Netbeans\\Interact-Web\\reportes-jasper-util\\");
        if (directorio.isDirectory()) {
            metodosFiles.listarArchivosDeDirectorio(directorio);
        }

    } catch (Exception e) {
        printException("[ MetodosFiles ]", e);
    }
}

From source file:jenkins.model.RunIdMigrator.java

/**
 * Reverses the migration, in case you want to revert to the older format.
 * @param args one parameter, {@code $JENKINS_HOME}
 *///from  w w  w. j  av  a  2 s .  c  o  m
public static void main(String... args) throws Exception {
    if (args.length != 1) {
        throw new Exception("pass one parameter, $JENKINS_HOME");
    }
    File root = new File(args[0]);
    File jobs = new File(root, "jobs");
    if (!jobs.isDirectory()) {
        throw new FileNotFoundException("no such $JENKINS_HOME " + root);
    }
    new RunIdMigrator().unmigrateJobsDir(jobs);
}

From source file:net.agkn.field_stripe.FileRecordEncoder.java

/**
 * @param  args refer to the {@link FileRecordEncoder class JavaDoc} for the
 *         required parameters. This can never be <code>null</code>.
 *//* ww  w .j  a va  2  s . co m*/
public static void main(final String[] args) {
    if (args.length != 4) {
        showUsage();
        System.exit(1/*EXIT_FAILURE*/);
        return;
    } /* else -- there are the expected number of arguments */

    // validate all input parameters
    final File idlBasePath = new File(args[0]);
    if (!idlBasePath.exists()) {
        System.err.println("The IDL base path does not exist: " + args[0]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    if (!idlBasePath.isDirectory()) {
        System.err.println("The IDL base path is not a directory: " + args[0]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    final String fqMessageName = args[1];
    final File jsonInputRecord = new File(args[2]);
    if (!jsonInputRecord.exists()) {
        System.err.println("The input JSON record file does not exist: " + args[2]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    if (jsonInputRecord.isDirectory()) {
        System.err.println("The input JSON record is not a file: " + args[2]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    final File outputPath = new File(args[3]);
    if (!outputPath.exists()) {
        System.err.println("The output base path does not exist: " + args[3]);
        System.exit(1/*EXIT_FAILURE*/);
    }
    if (!outputPath.isDirectory()) {
        System.err.println("The output base path is not a directory: " + args[3]);
        System.exit(1/*EXIT_FAILURE*/);
    }

    IFieldStripeWriterFactory fieldStripeWriterFactory = null/*none to start*/;
    try {
        final ICompositeType schema = createSchema(idlBasePath, fqMessageName);
        final IRecordReader recordReader = createRecordReader(jsonInputRecord);
        fieldStripeWriterFactory = createFieldStripeWriterFactory(outputPath);
        final RootFieldStripeEncoder rootEncoder = createEncoderTree(schema, fieldStripeWriterFactory);

        // encode each record
        while (rootEncoder.encode(recordReader))
            ;
    } catch (final OperationFailedException ofe) {
        System.err.println(
                "An error occurred while encoding records into field-stripes: " + ofe.getLocalizedMessage());
        System.exit(1/*EXIT_FAILURE*/);
    } finally {
        try {
            if (fieldStripeWriterFactory != null)
                fieldStripeWriterFactory.closeAllWriters();
        } catch (final OperationFailedException ofe) {
            System.err.println(
                    "An error occurred while closing field-stripe writers: " + ofe.getLocalizedMessage());
            System.exit(1/*EXIT_FAILURE*/);
        }
    }

    System.exit(0/*EXIT_SUCCESS*/);
}

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  a  va  2s.  c om*/
    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:com.meltmedia.rodimus.RodimusCli.java

public static void main(String... args) {
    try {/*from w w  w. j av a2  s .  c  om*/
        final Cli<RodimusInterface> cli = CliFactory.createCli(RodimusInterface.class);
        final RodimusInterface options = cli.parseArguments(args);

        // if help was requested, then display the help message and exit.
        if (options.isHelp()) {
            System.out.println(cli.getHelpMessage());
            return;
        }

        final boolean verbose = options.isVerbose();

        if (options.getFiles() == null || options.getFiles().size() < 1) {
            System.out.println(cli.getHelpMessage());
            return;
        }

        // get the input file.
        File inputFile = options.getFiles().get(0);

        // get the output file.
        File outputDir = null;
        if (options.getFiles().size() > 1) {
            outputDir = options.getFiles().get(1);
        } else {
            outputDir = new File(inputFile.getName().replaceFirst("\\.[^.]+\\Z", ""));
        }
        if (outputDir.exists() && !outputDir.isDirectory()) {
            throw new Exception(outputDir + " is not a directory.");
        }
        outputDir.mkdirs();

        transformDocument(inputFile, outputDir, verbose);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:edu.harvard.hul.ois.fits.Fits.java

public static void main(String[] args) throws FitsException, IOException, ParseException, XMLStreamException {
    Fits fits = new Fits();

    Options options = new Options();
    options.addOption("i", true, "input file or directory");
    options.addOption("r", false, "process directories recursively when -i is a directory ");
    options.addOption("o", true, "output file");
    options.addOption("h", false, "print this message");
    options.addOption("v", false, "print version information");
    OptionGroup outputOptions = new OptionGroup();
    Option stdxml = new Option("x", false, "convert FITS output to a standard metadata schema");
    Option combinedStd = new Option("xc", false,
            "output using a standard metadata schema and include FITS xml");
    outputOptions.addOption(stdxml);//from w  w w .ja  va  2s.  co m
    outputOptions.addOption(combinedStd);
    options.addOptionGroup(outputOptions);

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        fits.printHelp(options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println(Fits.VERSION);
        System.exit(0);
    }
    if (cmd.hasOption("r")) {
        traverseDirs = true;
    } else {
        traverseDirs = false;
    }

    if (cmd.hasOption("i")) {
        String input = cmd.getOptionValue("i");
        File inputFile = new File(input);

        if (inputFile.isDirectory()) {
            String outputDir = cmd.getOptionValue("o");
            if (outputDir == null || !(new File(outputDir).isDirectory())) {
                throw new FitsException(
                        "When FITS is run in directory processing mode the output location must be a diretory");
            }
            fits.doDirectory(inputFile, new File(outputDir), cmd.hasOption("x"), cmd.hasOption("xc"));
        } else {
            FitsOutput result = fits.doSingleFile(inputFile);
            fits.outputResults(result, cmd.getOptionValue("o"), cmd.hasOption("x"), cmd.hasOption("xc"), false);
        }
    } else {
        System.err.println("Invalid CLI options");
        fits.printHelp(options);
        System.exit(-1);
    }

    System.exit(0);
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSwingHttpCLI.CFAsteriskSwingHttpCLI.java

public static void main(String args[]) {
    final String S_ProcName = "CFAsteriskSwingHttpCLI.main() ";
    initConsoleLog();// w ww.j  a  v a2  s.  c  o m
    boolean fastExit = false;

    String homeDirName = System.getProperty("HOME");
    if (homeDirName == null) {
        homeDirName = System.getProperty("user.home");
        if (homeDirName == null) {
            log.message(S_ProcName + "ERROR: Home directory not set");
            return;
        }
    }
    File homeDir = new File(homeDirName);
    if (!homeDir.exists()) {
        log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
        return;
    }
    if (!homeDir.isDirectory()) {
        log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
        return;
    }

    CFAsteriskClientConfigurationFile cFAsteriskClientConfig = new CFAsteriskClientConfigurationFile();
    String cFAsteriskClientConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskclientrc";
    cFAsteriskClientConfig.setFileName(cFAsteriskClientConfigFileName);
    File cFAsteriskClientConfigFile = new File(cFAsteriskClientConfigFileName);
    if (!cFAsteriskClientConfigFile.exists()) {
        String cFAsteriskKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
        cFAsteriskClientConfig.setKeyStore(cFAsteriskKeyStoreFileName);
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            localHost = null;
        }
        if (localHost == null) {
            log.message(S_ProcName + "ERROR: LocalHost is null");
            return;
        }
        String hostName = localHost.getHostName();
        if ((hostName == null) || (hostName.length() <= 0)) {
            log.message("ERROR: LocalHost.HostName is null or empty");
            return;
        }
        String userName = System.getProperty("user.name");
        if ((userName == null) || (userName.length() <= 0)) {
            log.message("ERROR: user.name is null or empty");
            return;
        }
        String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                + userName.replaceAll("[^\\w]", "_").toLowerCase();
        cFAsteriskClientConfig.setDeviceName(deviceName);
        cFAsteriskClientConfig.save();
        log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                + cFAsteriskClientConfigFileName);
        fastExit = true;
    }
    if (!cFAsteriskClientConfigFile.isFile()) {
        log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFAsteriskClientConfigFileName
                + " is not a file.");
        fastExit = true;
    }
    if (!cFAsteriskClientConfigFile.canRead()) {
        log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                + cFAsteriskClientConfigFileName);
        fastExit = true;
    }
    cFAsteriskClientConfig.load();

    if (fastExit) {
        return;
    }

    // Configure logging
    Properties sysProps = System.getProperties();
    sysProps.setProperty("log4j.rootCategory", "WARN");
    sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    Logger httpLogger = Logger.getLogger("org.apache.http");
    httpLogger.setLevel(Level.WARN);

    // The Invoker and it's implementation
    CFAsteriskXMsgClientHttpSchema invoker = new CFAsteriskXMsgClientHttpSchema();

    // And now for the client side cache implementation that invokes it
    ICFAsteriskSchemaObj clientSchemaObj = new CFAsteriskSchemaObj() {
        public void logout() {
            CFAsteriskXMsgClientHttpSchema invoker = (CFAsteriskXMsgClientHttpSchema) getBackingStore();
            try {
                invoker.logout(getAuthorization());
            } catch (RuntimeException e) {
            }
            setAuthorization(null);
        }
    };
    clientSchemaObj.setBackingStore(invoker);
    // And stitch the response handler to reference our client instance
    invoker.setResponseHandlerSchemaObj(clientSchemaObj);
    // And now we can stitch together the CLI to the SAX loader code
    CFAsteriskSwingHttpCLI cli = new CFAsteriskSwingHttpCLI();
    cli.setXMsgClientHttpSchema(invoker);
    cli.setSchema(clientSchemaObj);
    ICFAsteriskSwingSchema swing = cli.getSwingSchema();
    swing.setClientConfigurationFile(cFAsteriskClientConfig);
    swing.setSchema(clientSchemaObj);
    swing.setClusterName("system");
    swing.setTenantName("system");
    swing.setSecUserName("system");
    JFrame jframe = cli.getDesktop();
    jframe.setVisible(true);
    jframe.toFront();
}

From source file:it.jnrpe.server.JNRPEServer.java

/**
 * The main method.//from   w ww  .ja va  2s  .co  m
 * 
 * @param args
 *            The command line
 */
public static void main(final String[] args) {
    CommandLine cl = parseCommandLine(args);
    if (cl.hasOption("--help")) {
        if (!cl.hasOption("--conf")) {
            printUsage(null);
        }
    }

    if (cl.hasOption("--version")) {
        printVersion();
        System.exit(0);
    }

    JNRPEConfiguration conf = null;
    try {
        conf = loadConfiguration((String) cl.getValue("--conf"));
    } catch (Exception e) {
        System.out.println("Unable to parse the configuration at " + cl.getValue("--conf") + ". The error is : "
                + e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    }

    String sPluginPath = conf.getServerSection().getPluginPath();
    if (sPluginPath == null) {
        System.out.println("Plugin path has not been specified");
        System.exit(-1);
    }
    File fPluginPath = new File(sPluginPath);

    if (fPluginPath.exists()) {
        if (!fPluginPath.isDirectory()) {
            System.out.println("Specified plugin path ('" + sPluginPath + "') must be a directory");
            System.exit(-1);
        }
    } else {
        System.out.println("Specified plugin path ('" + sPluginPath + "') do not exist");
        System.exit(-1);
    }

    IPluginRepository pr = null;
    try {
        pr = loadPluginDefinitions(conf.getServerSection().getPluginPath());
    } catch (PluginConfigurationException e) {
        System.out.println("An error has occurred while parsing " + "the plugin packages : " + e.getMessage());
        System.exit(-1);
    }

    if (cl.hasOption("--help") && cl.getValue("--help") != null) {
        printHelp(pr, (String) cl.getValue("--help"));
    }

    if (cl.hasOption("--list")) {
        printPluginList(pr);
    }

    CommandRepository cr = conf.createCommandRepository();

    JNRPEBuilder builder = JNRPEBuilder.forRepositories(pr, cr)
            .acceptParams(conf.getServerSection().acceptParams())
            .withMaxAcceptedConnections(conf.getServerSection().getBacklogSize())
            .withReadTimeout(conf.getServerSection().getReadTimeout())
            .withWriteTimeout(conf.getServerSection().getWriteTimeout())
            .withListener(new EventLoggerListener());

    for (String sAcceptedAddress : conf.getServerSection().getAllowedAddresses()) {
        builder.acceptHost(sAcceptedAddress);
    }

    JNRPE jnrpe = builder.build();

    for (BindAddress bindAddress : conf.getServerSection().getBindAddresses()) {
        int iPort = DEFAULT_PORT;
        String[] vsParts = bindAddress.getBindingAddress().split(":");
        String sIp = vsParts[0];
        if (vsParts.length > 1) {
            iPort = Integer.parseInt(vsParts[1]);
        }

        try {
            jnrpe.listen(sIp, iPort, bindAddress.isSSL());
        } catch (UnknownHostException e) {
            System.out.println(
                    String.format("Error binding the server to %s:%d : %s", sIp, iPort, e.getMessage()));
        }
    }

    if (cl.hasOption("--interactive")) {
        new JNRPEConsole(jnrpe, pr, cr).start();
        System.exit(0);
    }
}

From source file:com.tamingtext.classifier.bayes.ExtractTrainingData.java

public static void main(String[] args) {

    log.info("Command-line arguments: " + Arrays.toString(args));

    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("dir").withRequired(true)
            .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
            .withDescription("Lucene index directory containing input data").withShortName("d").create();

    Option categoryOpt = obuilder.withLongName("categories").withRequired(true)
            .withArgument(abuilder.withName("file").withMinimum(1).withMaximum(1).create())
            .withDescription("File containing a list of categories").withShortName("c").create();

    Option outputOpt = obuilder.withLongName("output").withRequired(false)
            .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create())
            .withDescription("Output directory").withShortName("o").create();

    Option categoryFieldsOpt = obuilder.withLongName("category-fields").withRequired(true)
            .withArgument(abuilder.withName("fields").withMinimum(1).withMaximum(1).create())
            .withDescription("Fields to match categories against (comma-delimited)").withShortName("cf")
            .create();//from ww  w  .  j  a  v  a  2s. c  o  m

    Option textFieldsOpt = obuilder.withLongName("text-fields").withRequired(true)
            .withArgument(abuilder.withName("fields").withMinimum(1).withMaximum(1).create())
            .withDescription("Fields from which to extract training text (comma-delimited)").withShortName("tf")
            .create();

    Option useTermVectorsOpt = obuilder.withLongName("use-term-vectors").withDescription(
            "Extract term vectors containing preprocessed data " + "instead of unprocessed, stored text values")
            .withShortName("tv").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(categoryOpt)
            .withOption(outputOpt).withOption(categoryFieldsOpt).withOption(textFieldsOpt)
            .withOption(useTermVectorsOpt).create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputDir = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputDir.isDirectory()) {
            throw new IllegalArgumentException(inputDir + " does not exist or is not a directory");
        }

        File categoryFile = new File(cmdLine.getValue(categoryOpt).toString());

        if (!categoryFile.isFile()) {
            throw new IllegalArgumentException(categoryFile + " does not exist or is not a directory");
        }

        File outputDir = new File(cmdLine.getValue(outputOpt).toString());

        outputDir.mkdirs();

        if (!outputDir.isDirectory()) {
            throw new IllegalArgumentException(outputDir + " is not a directory or could not be created");
        }

        Collection<String> categoryFields = stringToList(cmdLine.getValue(categoryFieldsOpt).toString());

        if (categoryFields.size() < 1) {
            throw new IllegalArgumentException("At least one category field must be spcified.");
        }

        Collection<String> textFields = stringToList(cmdLine.getValue(textFieldsOpt).toString());

        if (categoryFields.size() < 1) {
            throw new IllegalArgumentException("At least one text field must be spcified.");
        }

        boolean useTermVectors = cmdLine.hasOption(useTermVectorsOpt);

        extractTraininingData(inputDir, categoryFile, categoryFields, textFields, outputDir, useTermVectors);

    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    } catch (IOException e) {
        log.error("IOException", e);
    } finally {
        closeWriters();
    }
}