Example usage for java.io File mkdirs

List of usage examples for java.io File mkdirs

Introduction

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

Prototype

public boolean mkdirs() 

Source Link

Document

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

Usage

From source file:com.zimbra.cs.util.SpamExtract.java

public static void main(String[] args) throws ServiceException, HttpException, SoapFaultException, IOException {
    CommandLine cl = parseArgs(args);//ww  w  .j  a  v a 2  s  .  com

    if (cl.hasOption('D')) {
        CliUtil.toolSetup("DEBUG");
    } else {
        CliUtil.toolSetup("INFO");
    }
    if (cl.hasOption('v')) {
        verbose = true;
    }

    boolean optDelete = cl.hasOption('d');

    if (!cl.hasOption('o')) {
        usage("must specify directory to extract messages to");
    }
    String optDirectory = cl.getOptionValue('o');
    File outputDirectory = new File(optDirectory);
    if (!outputDirectory.exists()) {
        LOG.info("Creating directory: " + optDirectory);
        outputDirectory.mkdirs();
        if (!outputDirectory.exists()) {
            LOG.error("could not create directory " + optDirectory);
            System.exit(2);
        }
    }

    String optAdminUser;
    if (cl.hasOption('a')) {
        optAdminUser = cl.getOptionValue('a');
    } else {
        optAdminUser = LC.zimbra_ldap_user.value();
    }

    String optAdminPassword;
    if (cl.hasOption('p')) {
        optAdminPassword = cl.getOptionValue('p');
    } else {
        optAdminPassword = LC.zimbra_ldap_password.value();
    }

    String optQuery = "in:inbox";
    if (cl.hasOption('q')) {
        optQuery = cl.getOptionValue('q');
    }

    Account account = getAccount(cl);
    if (account == null) {
        System.exit(1);
    }

    boolean optRaw = cl.hasOption('r');

    if (verbose) {
        LOG.info("Extracting from account " + account.getName());
    }

    Server server = Provisioning.getInstance().getServer(account);

    String optAdminURL;
    if (cl.hasOption('u')) {
        optAdminURL = cl.getOptionValue('u');
    } else {
        optAdminURL = getSoapURL(server, true);
    }
    String adminAuthToken = getAdminAuthToken(optAdminURL, optAdminUser, optAdminPassword);
    String authToken = getDelegateAuthToken(optAdminURL, account, adminAuthToken);
    BATCH_SIZE = Provisioning.getInstance().getLocalServer().getAntispamExtractionBatchSize();
    SLEEP_TIME = Provisioning.getInstance().getLocalServer().getAntispamExtractionBatchDelay();
    extract(authToken, account, server, optQuery, outputDirectory, optDelete, optRaw);
}

From source file:edu.msu.cme.rdp.abundstats.cli.AbundMain.java

public static void main(String[] args) throws IOException {
    File inputFile;//from   w  w w .ja v a  2  s .c om
    File resultDir = new File(".");
    RPlotter plotter = null;
    boolean isClusterFile = true;
    List<AbundStatsCalculator> statCalcs = new ArrayList();
    double clustCutoffFrom = Double.MIN_VALUE, clustCutoffTo = Double.MAX_VALUE;

    String usage = "Main [options] <cluster file>";
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("result-dir")) {
            resultDir = new File(line.getOptionValue("result-dir"));
            if (!resultDir.exists() && !resultDir.mkdirs()) {
                throw new Exception(
                        "Result directory " + resultDir + " does not exist and could not be created");
            }
        }

        if (line.hasOption("R-location")) {
            plotter = new RPlotter();
            plotter.setCommandTemplate(rplotterTemplate);
            plotter.setRPath(line.getOptionValue("R-location"));
            plotter.setOutFileExt(".png");

            if (!new File(plotter.getRPath()).canExecute()) {
                throw new Exception(plotter.getRPath() + " does not exist or is not exectuable");
            }
        }

        if (line.hasOption("lower-cutoff")) {
            clustCutoffFrom = Double.valueOf(line.getOptionValue("lower-cutoff"));
        }

        if (line.hasOption("upper-cutoff")) {
            clustCutoffTo = Double.valueOf(line.getOptionValue("upper-cutoff"));
        }

        if (line.hasOption("jaccard")) {
            statCalcs.add(new Jaccard(true));
        }

        if (line.hasOption("sorensen")) {
            statCalcs.add(new Sorensen(true));
        }

        if (line.hasOption("otu-table")) {
            isClusterFile = false;
        }

        if (statCalcs.isEmpty()) {
            throw new Exception("Must specify at least one stat to compute (jaccard, sorensen)");
        }

        args = line.getArgs();
        if (args.length != 1) {
            throw new Exception("Unexpected number of command line arguments");
        }

        inputFile = new File(args[0]);

    } catch (Exception e) {
        new HelpFormatter().printHelp(usage, options);
        System.err.println("Error: " + e.getMessage());
        return;
    }

    if (isClusterFile) {
        RDPClustParser parser;
        parser = new RDPClustParser(inputFile);

        try {
            if (parser.getClusterSamples().size() == 1) {
                throw new IOException("Cluster file must have more than one sample");
            }

            List<Cutoff> cutoffs = parser.getCutoffs(clustCutoffFrom, clustCutoffTo);
            if (cutoffs.isEmpty()) {
                throw new IOException(
                        "No cutoffs in cluster file in range [" + clustCutoffFrom + "-" + clustCutoffTo + "]");
            }

            for (Cutoff cutoff : cutoffs) {
                List<Sample> samples = new ArrayList();

                for (ClusterSample clustSample : parser.getClusterSamples()) {
                    Sample s = new Sample(clustSample.getName());
                    for (Cluster clust : cutoff.getClusters().get(clustSample.getName())) {
                        s.addSpecies(clust.getNumberOfSeqs());
                    }
                    samples.add(s);
                }

                processSamples(samples, statCalcs, resultDir, cutoff.getCutoff() + "_", plotter);
            }

        } finally {
            parser.close();
        }
    } else {
        List<Sample> samples = new ArrayList();
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        String line = reader.readLine();

        if (line == null || line.split("\\s+").length < 2) {
            throw new IOException("Must be 2 or more samples for abundance statistic calculations!");
        }
        int numSamples = line.split("\\s+").length;

        boolean header = true;
        try {
            Integer.valueOf(line.split("\\s+")[0]);
            header = false;
        } catch (Exception e) {
        }

        if (header) {
            for (String s : line.split("\\s+")) {
                samples.add(new Sample(s));
            }
        } else {
            int sample = 0;
            for (String s : line.split("\\s+")) {
                samples.add(new Sample("" + sample));
                samples.get(sample).addSpecies(Integer.valueOf(s));
                sample++;
            }
        }

        int lineno = 2;
        while ((line = reader.readLine()) != null) {
            if (line.trim().equals("")) {
                continue;
            }
            int sample = 0;
            if (line.split("\\s+").length != numSamples) {
                System.err.println(
                        "Line number " + lineno + " didn't have the expected number of samples (contained "
                                + line.split("\\s+").length + ", expected " + numSamples + ")");
            }

            for (String s : line.split("\\s+")) {
                samples.get(sample).addSpecies(Integer.valueOf(s));
                sample++;
            }

            lineno++;
        }

        processSamples(samples, statCalcs, resultDir, inputFile.getName(), plotter);
    }
}

From source file:de.prozesskraft.ptest.Launch.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from  w  w  w .  j av a2  s  . c o m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ospl = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory with sample input data")
            //            .isRequired()
            .create("spl");

    Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory, default: .] directory where the test will be performed")
            //            .isRequired()
            .create("instancedir");

    Option ocall = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory, default: random call in spl-directory] file with call-string")
            //            .isRequired()
            .create("call");

    Option oaltapp = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription(
                    "[optional] alternative app. this String replaces the first line of the .call-file.")
            //            .isRequired()
            .create("altapp");

    Option oaddopt = OptionBuilder.withArgName("STRING").hasArg()
            .withDescription("[optional] add an option to the call.")
            //            .isRequired()
            .create("addopt");

    Option onolaunch = new Option("nolaunch",
            "only create instance directory, copy all spl files, but do NOT launch the process");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ospl);
    options.addOption(oinstancedir);
    options.addOption(ocall);
    options.addOption(oaltapp);
    options.addOption(oaddopt);
    options.addOption(onolaunch);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("launch", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String spl = null;
    String instancedir = null;
    String call = null;
    String altapp = null;
    ArrayList<String> addopt = new ArrayList<String>();

    // spl initialisieren
    if (commandline.hasOption("spl")) {
        spl = commandline.getOptionValue("spl");
    } else {
        System.err.println("option -spl is mandatory");
        error = true;
    }

    // instancedir initialisieren
    if (commandline.hasOption("instancedir")) {
        instancedir = commandline.getOptionValue("instancedir");
    } else {
        instancedir = System.getProperty("user.dir");
    }

    // call initialisieren
    if (commandline.hasOption("call")) {
        call = commandline.getOptionValue("call");
    }

    // altapp initialisieren
    if (commandline.hasOption("altapp")) {
        altapp = commandline.getOptionValue("altapp");
    }

    // addopt initialisieren
    if (commandline.hasOption("addopt")) {
        for (String actString : commandline.getOptionValues("addopt")) {
            addopt.add(actString);
        }
    }

    // wenn fehler, dann exit
    if (error) {
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // das erste spl-objekt geben lassen
    Spl actSpl = new Splset(spl).getSpl().get(0);

    // den call, result und altapp ueberschreiben
    actSpl.setName("default");

    if (call != null) {
        actSpl.setCall(new java.io.File(call));
    }
    if (actSpl.getCall() == null) {
        System.err.println("error: no call information found");
        System.exit(1);
    }

    if (altapp != null) {
        actSpl.setAltapp(altapp);
    }

    if (addopt.size() > 0) {
        actSpl.setAddopt(addopt);
    }

    actSpl.setResult(null);

    // das instancedir erstellen
    java.io.File actSplInstanceDir = new java.io.File(instancedir);
    System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath());
    actSplInstanceDir.mkdirs();

    // Inputdaten in das InstanceDir exportieren
    actSpl.exportInput(actSplInstanceDir);

    // exit, wenn --nolaunch
    if (commandline.hasOption("nolaunch")) {
        System.err.println("info: exiting, because of -nolaunch");
        System.exit(0);
    }

    // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht)
    String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log";
    String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt";
    String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt";
    String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid";

    // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl
    // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden
    // syscall ersetzt die zeichensequenz wieder zurueck in ein " "
    ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList();
    ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>();
    for (String actString : callFuerSyscall) {
        callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%"));
    }

    try {
        // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten
        // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory'
        ArrayList<String> processSyscallWithArgs = new ArrayList<String>(
                Arrays.asList(ini.get("apps", "pkraft-syscall").split(" ")));

        // die sonstigen argumente hinzufuegen
        processSyscallWithArgs.add("-call");
        processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen));
        //         processSyscallWithArgs.add("\""+call+"\"");
        processSyscallWithArgs.add("-stdout");
        processSyscallWithArgs.add(AbsStdout);
        processSyscallWithArgs.add("-stderr");
        processSyscallWithArgs.add(AbsStderr);
        processSyscallWithArgs.add("-pid");
        processSyscallWithArgs.add(AbsPid);
        processSyscallWithArgs.add("-mylog");
        processSyscallWithArgs.add(AbsLogSyscallWrapper);
        processSyscallWithArgs.add("-maxrun");
        processSyscallWithArgs.add("" + 3000);

        // erstellen prozessbuilder
        ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs);

        // erweitern des PATHs um den prozesseigenen path
        //         Map<String,String> env = pb.environment();
        //         String path = env.get("PATH");
        //         log("debug", "$PATH="+path);
        //         path = this.parent.getAbsPath()+":"+path;
        //         env.put("PATH", path);
        //         log("info", "path: "+path);

        // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll)
        java.io.File directory = new java.io.File(instancedir);
        System.err.println("info: setting execution directory to: " + directory.getCanonicalPath());
        pb.directory(directory);

        // zum debuggen ein paar ausgaben
        //         java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt");
        //         p1.waitFor();
        //         java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt");
        //         p2.waitFor();
        //         java.lang.Process pro = Runtime.getRuntime().exec("nautilus");
        //         java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()]));
        //         p3.waitFor();

        System.err.println("info: calling: " + pb.command());

        // starten des prozesses
        java.lang.Process sysproc = pb.start();

        // einfangen der stdout- und stderr des subprozesses
        InputStream is_stdout = sysproc.getInputStream();
        InputStream is_stderr = sysproc.getErrorStream();

        // Send your InputStream to an InputStreamReader:
        InputStreamReader isr_stdout = new InputStreamReader(is_stdout);
        InputStreamReader isr_stderr = new InputStreamReader(is_stderr);

        // That needs to go to a BufferedReader:
        BufferedReader br_stdout = new BufferedReader(isr_stdout);
        BufferedReader br_stderr = new BufferedReader(isr_stderr);

        //         // oeffnen der OutputStreams zu den Ausgabedateien
        //         FileWriter fw_stdout = new FileWriter(sStdout);
        //         FileWriter fw_stderr = new FileWriter(sStderr);

        // zeilenweise in die files schreiben
        String line_out = new String();
        String line_err = new String();

        while (br_stdout.readLine() != null) {
        }

        //         while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null))
        //         {
        //            if (!(line_out == null))
        //            {
        //               System.out.println(line_out);
        //               System.out.flush();
        //            }
        //            if (!(line_err == null))
        //            {
        //               System.err.println(line_err);
        //               System.err.flush();
        //            }
        //         }

        int exitValue = sysproc.waitFor();

        //         fw_stdout.close();
        //         fw_stderr.close();

        System.err.println("exitvalue: " + exitValue);

        sysproc.destroy();

        System.exit(exitValue);

        //         alternativer aufruf
        //         java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " "));

        //         log("info", "call executed. pid="+sysproc.hashCode());

        // wait 2 seconds for becoming the pid-file visible
        //         Thread.sleep(2000);

        //         int exitValue = sysproc.waitFor();

        //         // der prozess soll bis laengstens
        //         if(exitValue != 0)
        //         {
        //            System.err.println("error: call returned a value indicating an error: "+exitValue);
        //         }
        //         else
        //         {
        //            System.err.println("info: call returned value: "+exitValue);
        //         }

        //         System.err.println("info: "+new Date().toString());
        //         System.err.println("info: bye");
        //
        //         sysproc.destroy();
        //
        //         System.exit(sysproc.exitValue());
    } catch (Exception e2) {
        System.err.println("error: " + e2.getMessage());
        System.exit(1);
    }

}

From source file:com.cohesionforce.dis.BinaryConverter.java

public static void main(String[] args) {

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    options.addOption("i", true, "Input DIS Log file");
    options.addOption("o", true, "Ouput directory for Avro files");
    options.addOption("c", true, "Compression Codec <snappy,deflate,none> Default is snappy");
    options.addOption("p", false, "Write to Parquet format");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//  ww w  .  j  av a2 s.  c om
    String inputFile = null;
    String outputFile = null;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        outputFile = cmd.getOptionValue("o");
        if (inputFile == null || outputFile == null) {
            formatter.printHelp("usage: BinaryConverter", options);
            return;
        }
        if (cmd.hasOption("p")) {
            LogWriter.setParquet(true);
        }
        if (cmd.hasOption("c")) {
            LogWriter.setCodec(cmd.getOptionValue("c"));
        }
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    // Make sure the output directory exists
    File outputDir = new File(outputFile);
    outputDir.mkdirs();

    // Start the logger thread listening
    final BinaryConverter converter = new BinaryConverter();
    if (cmd.hasOption("p")) {
        converter.setExtension("parquet");
    }
    converter.setOutputDirectory(outputFile);
    converter.setInputFile(inputFile);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("Shutting down DIS Logger");
            synchronized (converter) {
                converter.shutdown();
            }
        }
    });
    converter.run();
    converter.shutdown();
}

From source file:edu.kit.dama.util.release.GenerateSourceRelease.java

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

    if (args.length != 3) {
        System.err.println("Usage: GenerateSourceRelease TYPE SOURCE DESTINATION");
        System.err.println("");
        System.err.println("TYPE\tThe release type. Must be one of KITDM, GENERIC_CLIENT or BARE_DEMO");
        System.err.println("SOURCE\tThe source folder containing all sources for the selected release type.");
        System.err.println("DESTINATION\tThe destination folder where all sources of the release are placed.");
        System.exit(1);//from   w w w.  ja  va  2  s.  c om
    }

    String releaseType = args[0];
    RELEASE_TYPE type = RELEASE_TYPE.KITDM;
    try {
        type = RELEASE_TYPE.valueOf(releaseType);
    } catch (IllegalArgumentException ex) {
        System.err.println(
                "Invalid release type. Valid relase types arguments are KITDM, GENERIC_CLIENT or BARE_DEMO");
        System.exit(1);
    }

    String source = args[1];
    String destination = args[2];
    File sourceFile = new File(source);
    File destinationFile = new File(destination);

    if ((sourceFile.exists() && !sourceFile.isDirectory())
            || (destinationFile.exists() && !destinationFile.isDirectory())) {
        System.err.println("Either source or destination are no directories.");
        System.exit(1);
    }

    if (!sourceFile.exists() || !sourceFile.canRead()) {
        System.err.println("Source either does not exist or is not readable.");
        System.exit(1);
    }

    if ((destinationFile.exists() && !sourceFile.canWrite())
            || (!destinationFile.exists() && !destinationFile.mkdirs())) {
        System.err.println("Destination is either not writable or cannot be created.");
        System.exit(1);
    }

    ReleaseConfiguration config = null;
    switch (type) {
    case KITDM:
        config = getKITDMSourceReleaseConfig(source, destination);
        break;
    case GENERIC_CLIENT:
        config = getGenericRepoClientSourceReleaseConfig(source, destination);
        break;
    case BARE_DEMO:
        config = getBaReDemoSourceReleaseConfig(source, destination);
        break;

    }

    generateSourceRelease(config);

    System.out.println("Generating Release finished.");
    System.out.println("Please manually check pom.xml:");
    System.out.println(" - Remove profiles");
    System.out.println(" - Update links to SCM, ciManagement and internal repositories");
}

From source file:edu.oregonstate.eecs.mcplan.domains.cosmic.experiments.CosmicExperiments.java

/**
 * @param args//w ww .j  a  va 2s. c  om
 * @throws IOException
 * @throws FileNotFoundException
 */
public static void main(final String[] args) throws FileNotFoundException, IOException {
    System.out.println("[Es beginnt!]");

    final String experiment_file = args[0];
    final File root_directory;
    if (args.length > 1) {
        root_directory = new File(args[1]);
    } else {
        root_directory = new File(".");
    }
    final CsvConfigurationParser csv_config = new CsvConfigurationParser(new FileReader(experiment_file));
    final String experiment_name = FilenameUtils.getBaseName(experiment_file);

    final File expr_directory = new File(root_directory, experiment_name);
    expr_directory.mkdirs();

    final KeyValueStore expr_config = csv_config.get(0);
    final Configuration config = new Configuration(root_directory.getPath(), experiment_name, expr_config);

    // Configure loggers
    LogAgent.setLevel(Level.valueOf(config.get("log.agent")));
    LogDomain.setLevel(Level.valueOf(config.get("log.domain")));
    LogWorld.setLevel(Level.valueOf(config.get("log.world")));

    LogAgent.warn("log.agent working");
    LogDomain.warn("log.domain working");
    LogWorld.warn("log.world working");

    try (final CosmicMatlabInterface cosmic = new CosmicMatlabInterface()) {
        System.out.println("[Matlab is alive]");

        // Initialize Cosmic
        final CosmicMatlabInterface.Problem cosmic_case = config.createCase(cosmic);
        final CosmicParameters params = cosmic_case.params;
        LogDomain.info("params: {}", cosmic_case.params);
        LogDomain.info("s0: {}", cosmic_case.s0);
        LogDomain.info("s0.ps: {}", cosmic_case.s0.ps);

        try (final WorldTrajectoryConsumer data_out = new WorldTrajectoryConsumer(config, params)) {

            for (int episode = 0; episode < config.getInt("Nepisodes"); ++episode) {
                final CosmicState s = cosmic_case.s0.copy();

                // Simulator
                final RandomGenerator world_rng = new MersenneTwister(config.getInt("seed.world"));
                final CosmicTransitionSimulator world = new CosmicTransitionSimulator("world", params);
                world.addSimulationListener(new SimulationListener<CosmicState, CosmicAction>() {

                    int t = 0;

                    @Override
                    public void onInitialStateSample(final StateNode<CosmicState, CosmicAction> s0) {
                        t = 0;
                        LogWorld.info("world: t  : {}", t);
                        LogWorld.info("world: s  : {}", s0.s);
                        LogWorld.info("world: s.r: {}", s0.r);
                    }

                    @Override
                    public void onTransitionSample(final ActionNode<CosmicState, CosmicAction> trans) {
                        LogWorld.info("world: a  : {}", trans.a);
                        LogWorld.info("world: a.r: {}", trans.r);
                        final StateNode<CosmicState, CosmicAction> sprime = Fn.head(trans.successors());

                        t += 1;
                        LogWorld.info("world: t  : {}", t);
                        LogWorld.debug("world: s  : {}", sprime.s);
                        LogWorld.info("world: s.r: {}", sprime.r);
                        // Note: show_memory() will cause a crash on the cluster!
                        //                     cosmic.show_memory();
                    }
                });

                // Agent
                final RandomGenerator agent_rng = new MersenneTwister(config.getInt("seed.agent"));
                final Policy<CosmicState, CosmicAction> agent = config.createAgent(agent_rng, params);

                // Fault scenario
                final CosmicAction fault_action;
                if (config.branch_set.length > 0) {
                    fault_action = new TripBranchSetAction(config.branch_set);
                } else {
                    fault_action = new CosmicNothingAction();
                }
                // Note: 'Tstable - 1' because we want the agent to start
                // acting at t = Tstable.
                final Policy<CosmicState, CosmicAction> fault = new FaultPolicy(fault_action,
                        config.Tstable - 1);

                // Top-level control policy
                final List<Policy<CosmicState, CosmicAction>> seq = new ArrayList<>();
                seq.add(fault);
                seq.add(agent);
                final int[] switch_times = new int[] { config.Tstable };
                final Policy<CosmicState, CosmicAction> pi = new SequencePolicy<>(seq, switch_times);

                // Do episode
                data_out.beginEpisode(world, episode);
                world.sampleTrajectory(world_rng, s, pi, config.T);
                data_out.endEpisode();

                System.out.println("[Episode " + episode + " ok]");
            } // for each episode
        } // RAII for data_out
    } // RAII for cosmic interface

    System.out.println("[Alles gut!]");
}

From source file:edu.oregonstate.eecs.mcplan.search.fsss.experiments.FsssJairExperiments.java

public static void main(final String[] args) throws Exception {
    final String experiment_file = args[0];
    final File root_directory;
    if (args.length > 1) {
        root_directory = new File(args[1]);
    } else {//from w ww  .  jav a 2s . c  o m
        root_directory = new File(".");
    }
    final CsvConfigurationParser csv_config = new CsvConfigurationParser(new FileReader(experiment_file));
    final String experiment_name = FilenameUtils.getBaseName(experiment_file);

    final File expr_directory = new File(root_directory, experiment_name);
    expr_directory.mkdirs();

    for (int expr = 0; expr < csv_config.size(); ++expr) {
        final KeyValueStore expr_config = csv_config.get(expr);
        final Configuration config = new Configuration(root_directory.getPath(), experiment_name, expr_config);

        LoggerManager.getLogger("log.domain").setLevel(Level.valueOf(config.get("log.domain")));
        LoggerManager.getLogger("log.search").setLevel(Level.valueOf(config.get("log.search")));

        final GsonBuilder gson_builder = new GsonBuilder();
        if (config.getBoolean("log.history.pretty")) {
            gson_builder.setPrettyPrinting();
        }

        if ("advising".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final int max_grade = config.getInt("advising.max_grade");
            final int passing_grade = config.getInt("advising.passing_grade");
            final AdvisingParameters params = AdvisingRddlParser.parse(max_grade, passing_grade, domain,
                    instance);
            final AdvisingFsssModel model = new AdvisingFsssModel(config.rng_world, params);
            runGames(config, model, expr);
        }
        //         else if( "cliffworld".equals( config.domain ) ) {
        //            final CliffWorld.FsssModel model = new CliffWorld.FsssModel( config.rng_world, config );
        //            runGames( config, model, expr );
        //         }
        else if ("crossing".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final IpcCrossingState s0 = IpcCrossingDomains.parse(domain, instance);
            final IpcCrossingFsssModel model = new IpcCrossingFsssModel(config.rng_world, s0);
            runGames(config, model, expr);
        } else if ("elevators".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final IpcElevatorsState s0 = IpcElevatorsDomains.parse(domain, instance);
            final IpcElevatorsFsssModel model = new IpcElevatorsFsssModel(config.rng_world, s0);
            runGames(config, model, expr);
        }
        //         else if( "firegirl".equals( config.domain ) ) {
        //            final int T = config.getInt( "firegirl.T" );
        //            final double discount = config.getDouble( "discount" );
        //            final FactoredRepresenter<FireGirlState, ? extends FactoredRepresentation<FireGirlState>> base_repr;
        //            if( "local".equals( config.get( "firegirl.repr" ) ) ) {
        //               base_repr = new FireGirlLocalFeatureRepresenter();
        //            }
        //            else {
        //               throw new IllegalArgumentException( "firegirl.repr" );
        //            }
        //            final FireGirlParameters params = new FireGirlParameters( T, discount, base_repr );
        //            final FireGirlFsssModel model = new FireGirlFsssModel( params, config.rng_world );
        //            runGames( config, model, expr );
        //         }
        //         else if( "inventory".equals( config.domain ) ) {
        //            final String problem_name = config.get( "inventory.problem" );
        //            final InventoryProblem problem;
        //            if( "Dependent".equals( problem_name ) ) {
        //               problem = InventoryProblem.Dependent();
        //            }
        //            else if( "Geometric".equals( problem_name ) ) {
        //               problem = InventoryProblem.Geometric();
        //            }
        //            else if( "Geometric2".equals( problem_name ) ) {
        //               problem = InventoryProblem.Geometric2();
        //            }
        //            else if( "TwoProducts".equals( problem_name ) ) {
        //               problem = InventoryProblem.TwoProducts();
        //            }
        //            else {
        //               throw new IllegalArgumentException( "inventory.problem" );
        //            }
        //            final InventoryFsssModel model = new InventoryFsssModel( config.rng_world, problem );
        //            runGames( config, model, expr );
        //         }
        else if ("racegrid".equals(config.domain)) {
            final String circuit = config.get("racegrid.circuit");
            final int scale = config.getInt("racegrid.scale");
            final int T = config.getInt("racegrid.T");
            final RacegridState ex;
            if ("bbs_small".equals(circuit)) {
                ex = RacegridCircuits.barto_bradtke_singh_SmallTrack(config.rng_world, T, scale);
            } else if ("bbs_large".equals(circuit)) {
                ex = RacegridCircuits.barto_bradtke_singh_LargeTrack(config.rng_world, T, scale);
            } else {
                throw new IllegalArgumentException("racegrid.circuit");
            }
            final double slip = config.getDouble("racegrid.slip");
            final RacegridFsssModel model = new RacegridFsssModel(config.rng_world, ex, slip);
            runGames(config, model, expr);
        }
        //         else if( "rally".equals( config.domain ) ) {
        //            final RallyWorld.Parameters params = new RallyWorld.Parameters( config.rng_world, config );
        //            final RallyWorld.FsssModel model = new RallyWorld.FsssModel( params );
        //            runGames( config, model, expr );
        //         }
        else if ("relevant_irrelevant".equals(config.domain)) {
            final RelevantIrrelevant.Parameters params = new RelevantIrrelevant.Parameters(config);
            final RelevantIrrelevant.FsssModel model = new RelevantIrrelevant.FsssModel(config.rng_world,
                    params);
            runGames(config, model, expr);
        } else if ("sailing".equals(config.domain)) {
            final String world = config.get("sailing.world");
            final int V = config.getInt("sailing.V");
            final int T = config.getInt("sailing.T");
            final int dim = config.getInt("sailing.dim");
            final SailingState.Factory state_factory;
            if ("empty".equals(world)) {
                state_factory = new SailingWorlds.EmptyRectangleFactory(V, T, dim, dim);
            } else if ("island".equals(world)) {
                state_factory = new SailingWorlds.SquareIslandFactory(V, T, dim, dim / 3);
            } else if ("random".equals(world)) {
                final double p = config.getDouble("sailing.p");
                state_factory = new SailingWorlds.RandomObstaclesFactory(p, V, T, dim);
            } else {
                throw new IllegalArgumentException("sailing.world");
            }
            final SailingFsssModel model = new SailingFsssModel(config.rng_world, state_factory);
            runGames(config, model, expr);
        } else if ("saving".equals(config.domain)) {
            final SavingProblem.Parameters params = new SavingProblem.Parameters(config);
            final SavingProblem.FsssModel model = new SavingProblem.FsssModel(config.rng_world, params);
            runGames(config, model, expr);
        } else if ("spbj".equals(config.domain)) {
            final SpBjFsssModel model = new SpBjFsssModel(config.rng_world);
            runGames(config, model, expr);
        } else if ("tamarisk".equals(config.domain)) {
            final File domain = new File(config.get("rddl.domain") + ".rddl");
            final File instance = new File(config.get("rddl.instance") + ".rddl");
            final IpcTamariskState s0 = IpcTamariskDomains.parse(domain, instance);
            // TODO: Make this a parameter
            final IpcTamariskReachRepresenter base_repr = new IpcTamariskReachRepresenter(s0.params);
            final IpcTamariskFsssModel model = new IpcTamariskFsssModel(config.rng_world, s0.params, s0,
                    base_repr);
            runGames(config, model, expr);
        } else if ("tetris".equals(config.domain)) {
            final int T = config.getInt("tetris.T");
            final int Nrows = config.getInt("tetris.Nrows");
            final TetrisParameters params = new TetrisParameters(T, Nrows);
            final FactoredRepresenter<TetrisState, ? extends FactoredRepresentation<TetrisState>> base_repr;
            if ("ground".equals(config.get("tetris.repr"))) {
                base_repr = new TetrisGroundRepresenter(params);
            } else if ("bertsekas".equals(config.get("tetris.repr"))) {
                base_repr = new TetrisBertsekasRepresenter(params);
            } else {
                throw new IllegalArgumentException("tetris.repr");
            }
            final TetrisFsssModel model = new TetrisFsssModel(config.rng_world, params, base_repr);

            gson_builder.registerTypeAdapter(TetrisState.class, new TetrisState.GsonSerializer());
            gson_builder.registerTypeAdapter(TetrisAction.class, new TetrisAction.GsonSerializer());
            gson = gson_builder.create();

            runGames(config, model, expr);
        } else if ("weinstein_littman".equals(config.domain)) {
            final WeinsteinLittman.Parameters params = new WeinsteinLittman.Parameters(config);
            final WeinsteinLittman.FsssModel model = new WeinsteinLittman.FsssModel(config.rng_world, params);
            runGames(config, model, expr);
        } else {
            throw new IllegalArgumentException("domain = " + config.domain);
        }
    }

    System.out.println("Alles gut!");
}

From source file:edu.oregonstate.eecs.mcplan.abstraction.EvaluateSimilarityFunction.java

/**
 * @param args/*from w w  w  .j a va 2 s.c  o m*/
 * @throws IOException
 * @throws FileNotFoundException
 */
public static void main(final String[] args) throws FileNotFoundException, IOException {
    final String experiment_file = args[0];
    final File root_directory;
    if (args.length > 1) {
        root_directory = new File(args[1]);
    } else {
        root_directory = new File(".");
    }
    final CsvConfigurationParser csv_config = new CsvConfigurationParser(new FileReader(experiment_file));
    final String experiment_name = FilenameUtils.getBaseName(experiment_file);

    final File expr_directory = new File(root_directory, experiment_name);
    expr_directory.mkdirs();

    final Csv.Writer csv = new Csv.Writer(
            new PrintStream(new FileOutputStream(new File(expr_directory, "results.csv"))));
    final String[] parameter_headers = new String[] { "kpca.kernel", "kpca.rbf.sigma",
            "kpca.random_forest.Ntrees", "kpca.random_forest.max_depth", "kpca.Nbases", "multiclass.classifier",
            "multiclass.random_forest.Ntrees", "multiclass.random_forest.max_depth",
            "pairwise_classifier.max_branching", "training.label_noise" };
    csv.cell("domain").cell("abstraction");
    for (final String p : parameter_headers) {
        csv.cell(p);
    }
    csv.cell("Ntrain").cell("Ntest").cell("ami.mean").cell("ami.variance").cell("ami.confidence").newline();

    for (int expr = 0; expr < csv_config.size(); ++expr) {
        try {
            final KeyValueStore expr_config = csv_config.get(expr);
            final Configuration config = new Configuration(root_directory.getPath(), expr_directory.getName(),
                    expr_config);

            System.out.println("[Loading '" + config.training_data_single + "']");
            final Instances single = WekaUtil
                    .readLabeledDataset(new File(root_directory, config.training_data_single + ".arff"));

            final Instances train = new Instances(single, 0);
            final int[] idx = Fn.range(0, single.size());
            int instance_counter = 0;
            Fn.shuffle(config.rng, idx);
            final int Ntrain = config.getInt("Ntrain_games"); // TODO: Rename?
            final double label_noise = config.getDouble("training.label_noise");
            final int Nlabels = train.classAttribute().numValues();
            assert (Nlabels > 0);
            for (int i = 0; i < Ntrain; ++i) {
                final Instance inst = single.get(idx[instance_counter++]);
                if (label_noise > 0 && config.rng.nextDouble() < label_noise) {
                    int noisy_label = 0;
                    do {
                        noisy_label = config.rng.nextInt(Nlabels);
                    } while (noisy_label == (int) inst.classValue());
                    System.out.println("Noisy label (" + inst.classValue() + " -> " + noisy_label + ")");
                    inst.setClassValue(noisy_label);
                }
                train.add(inst);
                inst.setDataset(train);
            }

            final Fn.Function2<Boolean, Instance, Instance> plausible_p = createPlausiblePredicate(config);

            final int Ntest = config.Ntest_games;
            int Ntest_added = 0;
            final ArrayList<Instances> tests = new ArrayList<Instances>();
            while (instance_counter < single.size() && Ntest_added < Ntest) {
                final Instance inst = single.get(idx[instance_counter++]);
                boolean found = false;
                for (final Instances test : tests) {
                    // Note that 'plausible_p' should be transitive
                    if (plausible_p.apply(inst, test.get(0))) {
                        WekaUtil.addInstance(test, inst);
                        if (test.size() == 30) {
                            Ntest_added += test.size();
                        } else if (test.size() > 30) {
                            Ntest_added += 1;
                        }
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    final Instances test = new Instances(single, 0);
                    WekaUtil.addInstance(test, inst);
                    tests.add(test);
                }
            }
            final Iterator<Instances> test_itr = tests.iterator();
            while (test_itr.hasNext()) {
                if (test_itr.next().size() < 30) {
                    test_itr.remove();
                }
            }
            System.out.println("=== tests.size() = " + tests.size());
            System.out.println("=== Ntest_added = " + Ntest_added);

            System.out.println("[Training]");
            final Evaluator evaluator = createEvaluator(config, train);
            //            final Instances transformed_test = evaluator.prepareInstances( test );

            System.out.println("[Evaluating]");

            final int Nxval = evaluator.isSensitiveToOrdering() ? 10 : 1;
            final MeanVarianceAccumulator ami = new MeanVarianceAccumulator();

            final MeanVarianceAccumulator errors = new MeanVarianceAccumulator();
            final MeanVarianceAccumulator relative_error = new MeanVarianceAccumulator();

            int c = 0;
            for (int xval = 0; xval < Nxval; ++xval) {
                for (final Instances test : tests) {
                    // TODO: Debugging
                    WekaUtil.writeDataset(new File(config.root_directory), "test_" + (c++), test);

                    //               transformed_test.randomize( new RandomAdaptor( config.rng ) );
                    //               final ClusterContingencyTable ct = evaluator.evaluate( transformed_test );
                    test.randomize(new RandomAdaptor(config.rng));
                    final ClusterContingencyTable ct = evaluator.evaluate(test);
                    System.out.println(ct);

                    int Nerrors = 0;
                    final MeanVarianceAccumulator mv = new MeanVarianceAccumulator();
                    for (int i = 0; i < ct.R; ++i) {
                        final int max = Fn.max(ct.n[i]);
                        Nerrors += (ct.a[i] - max);
                        mv.add(((double) ct.a[i]) / ct.N * Nerrors / ct.a[i]);
                    }
                    errors.add(Nerrors);
                    relative_error.add(mv.mean());

                    System.out.println("exemplar: " + test.get(0));
                    System.out.println("Nerrors = " + Nerrors);
                    final PrintStream ct_out = new PrintStream(
                            new FileOutputStream(new File(expr_directory, "ct_" + expr + "_" + xval + ".csv")));
                    ct.writeCsv(ct_out);
                    ct_out.close();
                    final double ct_ami = ct.adjustedMutualInformation_max();
                    if (Double.isNaN(ct_ami)) {
                        System.out.println("! ct_ami = NaN");
                    } else {
                        ami.add(ct_ami);
                    }
                    System.out.println();
                }
            }
            System.out.println("errors = " + errors.mean() + " (" + errors.confidence() + ")");
            System.out.println(
                    "relative_error = " + relative_error.mean() + " (" + relative_error.confidence() + ")");
            System.out.println("AMI_max = " + ami.mean() + " (" + ami.confidence() + ")");

            csv.cell(config.domain).cell(config.get("abstraction.discovery"));
            for (final String p : parameter_headers) {
                csv.cell(config.get(p));
            }
            csv.cell(Ntrain).cell(Ntest).cell(ami.mean()).cell(ami.variance()).cell(ami.confidence()).newline();
        } catch (final Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.zimbra.perf.chart.ChartUtil.java

public static void main(String[] args) throws Exception {
    CommandLineParser clParser = new GnuParser();
    Options opts = getOptions();/*from w  w  w .  j  a va2 s.  co  m*/
    try {
        CommandLine cl = clParser.parse(opts, args);

        if (cl.hasOption('h'))
            usage(opts);
        if (!cl.hasOption('s') && !cl.hasOption('d'))
            usage(opts, "-s and -d options are required");
        if (!cl.hasOption('s'))
            usage(opts, "Missing required -s option");

        if (!cl.hasOption('d'))
            usage(opts, "Missing required -d option");

        String[] confs = cl.getOptionValues(OPT_CONF);
        if (confs == null || confs.length == 0)
            usage(opts, "Missing --" + OPT_CONF + " option");
        File[] confFiles = new File[confs.length];
        for (int i = 0; i < confs.length; i++) {
            File conf = new File(confs[i]);
            if (!conf.exists()) {
                System.err.printf("Configuration file %s does not exist\n", conf.getAbsolutePath());
                System.exit(1);
            }
            confFiles[i] = conf;
        }

        String[] srcDirStrs = cl.getOptionValues(OPT_SRCDIR);
        if (srcDirStrs == null || srcDirStrs.length == 0)
            usage(opts, "Missing --" + OPT_SRCDIR + " option");
        List<File> srcDirsList = new ArrayList<File>(srcDirStrs.length);
        for (int i = 0; i < srcDirStrs.length; i++) {
            File srcDir = new File(srcDirStrs[i]);
            if (srcDir.exists())
                srcDirsList.add(srcDir);
            else
                System.err.printf("Source directory %s does not exist\n", srcDir.getAbsolutePath());
        }
        if (srcDirsList.size() < 1)
            usage(opts, "No valid source directory found");
        File[] srcDirs = new File[srcDirsList.size()];
        srcDirsList.toArray(srcDirs);

        String destDirStr = cl.getOptionValue(OPT_DESTDIR);
        if (destDirStr == null)
            usage(opts, "Missing --" + OPT_DESTDIR + " option");
        File destDir = new File(destDirStr);
        if (!destDir.exists()) {
            boolean created = destDir.mkdirs();
            if (!created) {
                System.err.printf("Unable to create destination directory %s\n", destDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!destDir.canWrite()) {
            System.err.printf("Destination directory %s is not writable\n", destDir.getAbsolutePath());
            System.exit(1);
        }

        String title = cl.getOptionValue(OPT_TITLE);
        if (title == null)
            title = srcDirs[0].getAbsoluteFile().getName();

        Date startAt = parseTimestampOption(cl, opts, OPT_START_AT);
        Date endAt = parseTimestampOption(cl, opts, OPT_END_AT);
        Date aggStartAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_START_AT);
        Date aggEndAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_END_AT);

        boolean noSummary = cl.hasOption('n');
        ChartUtil app = new ChartUtil(confFiles, srcDirs, destDir, title, startAt, endAt, aggStartAt, aggEndAt,
                noSummary);
        app.doit();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        usage(opts);
    }
}

From source file:net.massbank.validator.RecordValidator.java

public static void main(String[] args) {
    RequestDummy request;//from  www .ja  v a  2  s . co m

    PrintStream out = System.out;

    Options lvOptions = new Options();
    lvOptions.addOption("h", "help", false, "show this help.");
    lvOptions.addOption("r", "recdata", true,
            "points to the recdata directory containing massbank records. Reads all *.txt files in there.");

    CommandLineParser lvParser = new BasicParser();
    CommandLine lvCmd = null;
    try {
        lvCmd = lvParser.parse(lvOptions, args);
        if (lvCmd.hasOption('h')) {
            printHelp(lvOptions);
            return;
        }
    } catch (org.apache.commons.cli.ParseException pvException) {
        System.out.println(pvException.getMessage());
    }

    String recDataPath = lvCmd.getOptionValue("recdata");

    // ---------------------------------------------
    // ????
    // ---------------------------------------------

    final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL);
    final String dbRootPath = "./";
    final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME);
    final String tomcatTmpPath = ".";
    final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator;
    GetConfig conf = new GetConfig(baseUrl);
    int recVersion = 2;
    String selDbName = "";
    Object up = null; // Was: file Upload
    boolean isResult = true;
    String upFileName = "";
    boolean upResult = false;
    DatabaseAccess db = null;

    try {
        // ----------------------------------------------------
        // ???
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // (new File(tmpPath)).mkdir();
        // String os = System.getProperty("os.name");
        // if (os.indexOf("Windows") == -1) {
        // isResult = FileUtil.changeMode("777", tmpPath);
        // if (!isResult) {
        // out.println(msgErr("[" + tmpPath
        // + "]  chmod failed."));
        // return;
        // }
        // }
        // up = new FileUpload(request, tmpPath);
        // }

        // ----------------------------------------------------
        // ?DB????
        // ----------------------------------------------------
        List<String> dbNameList = Arrays.asList(conf.getDbName());
        ArrayList<String> dbNames = new ArrayList<String>();
        dbNames.add("");
        File[] dbDirs = (new File(dbRootPath)).listFiles();
        if (dbDirs != null) {
            for (File dbDir : dbDirs) {
                if (dbDir.isDirectory()) {
                    int pos = dbDir.getName().lastIndexOf("\\");
                    String dbDirName = dbDir.getName().substring(pos + 1);
                    pos = dbDirName.lastIndexOf("/");
                    dbDirName = dbDirName.substring(pos + 1);
                    if (dbNameList.contains(dbDirName)) {
                        // DB???massbank.conf???DB????
                        dbNames.add(dbDirName);
                    }
                }
            }
        }
        if (dbDirs == null || dbNames.size() == 0) {
            out.println(msgErr("[" + dbRootPath + "] directory not exist."));
            return;
        }
        Collections.sort(dbNames);

        // ----------------------------------------------------
        // ?
        // ----------------------------------------------------
        // if (FileUpload.isMultipartContent(request)) {
        // HashMap<String, String[]> reqParamMap = new HashMap<String,
        // String[]>();
        // reqParamMap = up.getRequestParam();
        // if (reqParamMap != null) {
        // for (Map.Entry<String, String[]> req : reqParamMap
        // .entrySet()) {
        // if (req.getKey().equals("ver")) {
        // try {
        // recVersion = Integer
        // .parseInt(req.getValue()[0]);
        // } catch (NumberFormatException nfe) {
        // }
        // } else if (req.getKey().equals("db")) {
        // selDbName = req.getValue()[0];
        // }
        // }
        // }
        // } else {
        // if (request.getParameter("ver") != null) {
        // try {
        // recVersion = Integer.parseInt(request
        // .getParameter("ver"));
        // } catch (NumberFormatException nfe) {
        // }
        // }
        // selDbName = request.getParameter("db");
        // }
        // if (selDbName == null || selDbName.equals("")
        // || !dbNames.contains(selDbName)) {
        // selDbName = dbNames.get(0);
        // }

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        out.println("Database: ");
        for (int i = 0; i < dbNames.size(); i++) {
            String dbName = dbNames.get(i);
            out.print("dbName");
            if (dbName.equals(selDbName)) {
                out.print(" selected");
            }
            if (i == 0) {
                out.println("------------------");
            } else {
                out.println(dbName);
            }
        }
        out.println("Record Version : ");
        out.println(recVersion);

        out.println("Record Archive :");

        // ---------------------------------------------
        // 
        // ---------------------------------------------
        //         HashMap<String, Boolean> upFileMap = up.doUpload();
        //         if (upFileMap != null) {
        //            for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) {
        //               upFileName = e.getKey();
        //               upResult = e.getValue();
        //               break;
        //            }
        //            if (upFileName.equals("")) {
        //               out.println(msgErr("please select file."));
        //               isResult = false;
        //            } else if (!upResult) {
        //               out.println(msgErr("[" + upFileName
        //                     + "] upload failed."));
        //               isResult = false;
        //            } else if (!upFileName.endsWith(ZIP_EXTENSION)
        //                  && !upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("please select ["
        //                     + UPLOAD_RECDATA_ZIP
        //                     + "] or ["
        //                     + UPLOAD_RECDATA_MSBK + "]."));
        //               up.deleteFile(upFileName);
        //               isResult = false;
        //            }
        //         } else {
        //            out.println(msgErr("server error."));
        //            isResult = false;
        //         }
        //         up.deleteFileItem();
        //         if (!isResult) {
        //            return;
        //         }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        //         final String upFilePath = (new File(tmpPath + File.separator
        //               + upFileName)).getPath();
        //         isResult = FileUtil.unZip(upFilePath, tmpPath);
        //         if (!isResult) {
        //            out.println(msgErr("["
        //                  + upFileName
        //                  + "]  extraction failed. possibility of time-out."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath();
        File tmpRecDir = new File(recDataPath);
        if (!tmpRecDir.isDirectory()) {
            tmpRecDir.mkdirs();
        }

        // ---------------------------------------------
        // ???
        // ---------------------------------------------
        // data?
        //         final String recDataPath = (new File(tmpPath + File.separator
        //               + RECDATA_DIR_NAME)).getPath()
        //               + File.separator;
        //
        //         if (!(new File(recDataPath)).isDirectory()) {
        //            if (upFileName.endsWith(ZIP_EXTENSION)) {
        //               out.println(msgErr("["
        //                     + RECDATA_DIR_NAME
        //                     + "]  directory is not included in the up-loading file."));
        //            } else if (upFileName.endsWith(MSBK_EXTENSION)) {
        //               out.println(msgErr("The uploaded file is not record data."));
        //            }
        //            return;
        //         }

        // ---------------------------------------------
        // DB
        // ---------------------------------------------
        //         db = new DatabaseAccess(dbHostName, selDbName);
        //         isResult = db.open();
        //         if (!isResult) {
        //            db.close();
        //            out.println(msgErr("not connect to database."));
        //            return;
        //         }

        // ---------------------------------------------
        // ??
        // ---------------------------------------------
        TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion);
        if (resultMap.size() == 0) {
            return;
        }

        // ---------------------------------------------
        // ?
        // ---------------------------------------------
        isResult = dispResult(out, resultMap);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
        File tmpDir = new File(tmpPath);
        if (tmpDir.exists()) {
            FileUtil.removeDir(tmpDir.getPath());
        }
    }

}