Example usage for java.io File canRead

List of usage examples for java.io File canRead

Introduction

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

Prototype

public boolean canRead() 

Source Link

Document

Tests whether the application can read the file denoted by this abstract pathname.

Usage

From source file:mondrian.gui.Workbench.java

/**
 * @param args the command line arguments
 *///from w  w  w . j  a  v  a2  s. c  o m
public static void main(String args[]) {
    Workbench w = null;
    try {
        w = new Workbench();
        w.parseArgs(args);
        w.setSize(800, 600);
        // if user specified a file to open, do so now.
        if (w.openFile != null) {
            File f = new File(w.openFile);
            if (f.canRead()) {
                w.openSchemaFrame(f.getAbsoluteFile(),
                        // parameter to indicate this is a new or existing
                        // catalog file
                        false);
            }
        }
        w.setVisible(true);
    } catch (Throwable ex) {
        if (w != null) {
            JOptionPane.showMessageDialog(w,
                    w.getResourceConverter().getFormattedString("workbench.main.uncoverable_error",
                            "Pentaho Schema Workbench has encountered an unrecoverable error. \n{0}",
                            ex.getLocalizedMessage()),
                    w.getResourceConverter().getString("workbench.main.uncoverable_error.title",
                            "PSW Fatal Error"),
                    JOptionPane.ERROR_MESSAGE);
        }
        LOGGER.error("main", ex);
    }
}

From source file:fll.scheduler.GreedySolver.java

public static void main(final String[] args) throws InterruptedException {
    LogUtils.initializeLogging();//from   w w w .  j  a va2s  . c  o  m

    final Options options = buildOptions();

    // parse options
    boolean optimize = false;
    File datafile = null;
    try {
        final CommandLineParser parser = new PosixParser();
        final CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(OPTIMIZE_OPTION)) {
            optimize = true;
        }

        datafile = new File(cmd.getOptionValue(DATA_FILE_OPTION));
    } catch (final org.apache.commons.cli.ParseException pe) {
        LOGGER.error(pe.getMessage());
        usage(options);
        System.exit(1);
    }

    try {
        if (!datafile.canRead()) {
            LOGGER.fatal(datafile.getAbsolutePath() + " is not readable");
            System.exit(4);
        }

        final GreedySolver solver = new GreedySolver(datafile, optimize);
        final long start = System.currentTimeMillis();
        solver.solve(null);
        final long stop = System.currentTimeMillis();
        LOGGER.info("Solve took: " + (stop - start) / 1000.0 + " seconds");

    } catch (final ParseException e) {
        LOGGER.fatal(e, e);
        System.exit(5);
    } catch (final IOException e) {
        LOGGER.fatal("Error reading file", e);
        System.exit(4);
    } catch (final RuntimeException e) {
    } catch (final InvalidParametersException e) {
        LOGGER.fatal(e, e);
        System.exit(6);
    }
}

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();/*from www  .  j av  a  2s.  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:com.jug.MoMA.java

/**
 * PROJECT MAIN//from   w  ww.j av a 2s .  c o m
 *
 * @param args
 */
public static void main(final String[] args) {
    if (showIJ)
        new ImageJ();

    //      // ===== set look and feel ========================================================================
    //      try {
    //         // Set cross-platform Java L&F (also called "Metal")
    //         UIManager.setLookAndFeel(
    //               UIManager.getCrossPlatformLookAndFeelClassName() );
    //      } catch ( final UnsupportedLookAndFeelException e ) {
    //         // handle exception
    //      } catch ( final ClassNotFoundException e ) {
    //         // handle exception
    //      } catch ( final InstantiationException e ) {
    //         // handle exception
    //      } catch ( final IllegalAccessException e ) {
    //         // handle exception
    //      }

    // ===== command line parsing ======================================================================

    // create Options object & the parser
    final Options options = new Options();
    final CommandLineParser parser = new BasicParser();
    // defining command line options
    final Option help = new Option("help", "print this message");

    final Option headless = new Option("h", "headless", false,
            "start without user interface (note: input-folder must be given!)");
    headless.setRequired(false);

    final Option timeFirst = new Option("tmin", "min_time", true, "first time-point to be processed");
    timeFirst.setRequired(false);

    final Option timeLast = new Option("tmax", "max_time", true, "last time-point to be processed");
    timeLast.setRequired(false);

    final Option optRange = new Option("orange", "opt_range", true, "initial optimization range");
    optRange.setRequired(false);

    final Option numChannelsOption = new Option("c", "channels", true,
            "number of channels to be loaded and analyzed.");
    numChannelsOption.setRequired(true);

    final Option minChannelIdxOption = new Option("cmin", "min_channel", true,
            "the smallest channel index (usually 0 or 1, default is 1).");
    minChannelIdxOption.setRequired(false);

    final Option infolder = new Option("i", "infolder", true, "folder to read data from");
    infolder.setRequired(false);

    final Option outfolder = new Option("o", "outfolder", true,
            "folder to write preprocessed data to (equals infolder if not given)");
    outfolder.setRequired(false);

    final Option userProps = new Option("p", "props", true, "properties file to be loaded (mm.properties)");
    userProps.setRequired(false);

    options.addOption(help);
    options.addOption(headless);
    options.addOption(numChannelsOption);
    options.addOption(minChannelIdxOption);
    options.addOption(timeFirst);
    options.addOption(timeLast);
    options.addOption(optRange);
    options.addOption(infolder);
    options.addOption(outfolder);
    options.addOption(userProps);
    // get the commands parsed
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (final ParseException e1) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "... [-p props-file] -i in-folder [-o out-folder] -c <num-channels> [-cmin start-channel-ids] [-tmin idx] [-tmax idx] [-orange num-frames] [-headless]",
                "", options, "Error: " + e1.getMessage());
        System.exit(0);
    }

    if (cmd.hasOption("help")) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("... -i <in-folder> -o [out-folder] [-headless]", options);
        System.exit(0);
    }

    if (cmd.hasOption("h")) {
        System.out.println(">>> Starting MM in headless mode.");
        HEADLESS = true;
        if (!cmd.hasOption("i")) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Headless-mode requires option '-i <in-folder>'...", options);
            System.exit(0);
        }
    }

    File inputFolder = null;
    if (cmd.hasOption("i")) {
        inputFolder = new File(cmd.getOptionValue("i"));

        if (!inputFolder.isDirectory()) {
            System.out.println("Error: Input folder is not a directory!");
            System.exit(2);
        }
        if (!inputFolder.canRead()) {
            System.out.println("Error: Input folder cannot be read!");
            System.exit(2);
        }
    }

    File outputFolder = null;
    if (!cmd.hasOption("o")) {
        if (inputFolder == null) {
            System.out.println(
                    "Error: Output folder would be set to a 'null' input folder! Please check your command line arguments...");
            System.exit(3);
        }
        outputFolder = inputFolder;
        STATS_OUTPUT_PATH = outputFolder.getAbsolutePath();
    } else {
        outputFolder = new File(cmd.getOptionValue("o"));

        if (!outputFolder.isDirectory()) {
            System.out.println("Error: Output folder is not a directory!");
            System.exit(3);
        }
        if (!inputFolder.canWrite()) {
            System.out.println("Error: Output folder cannot be written to!");
            System.exit(3);
        }

        STATS_OUTPUT_PATH = outputFolder.getAbsolutePath();
    }

    fileUserProps = null;
    if (cmd.hasOption("p")) {
        fileUserProps = new File(cmd.getOptionValue("p"));
    }

    if (cmd.hasOption("cmin")) {
        minChannelIdx = Integer.parseInt(cmd.getOptionValue("cmin"));
    }
    if (cmd.hasOption("c")) {
        numChannels = Integer.parseInt(cmd.getOptionValue("c"));
    }

    if (cmd.hasOption("tmin")) {
        minTime = Integer.parseInt(cmd.getOptionValue("tmin"));
    }
    if (cmd.hasOption("tmax")) {
        maxTime = Integer.parseInt(cmd.getOptionValue("tmax"));
    }

    if (cmd.hasOption("orange")) {
        initOptRange = Integer.parseInt(cmd.getOptionValue("orange"));
    }

    // ******** CHECK GUROBI ********* CHECK GUROBI ********* CHECK GUROBI *********
    final String jlp = System.getProperty("java.library.path");
    //      System.out.println( jlp );
    try {
        new GRBEnv("MoMA_gurobi.log");
    } catch (final GRBException e) {
        final String msgs = "Initial Gurobi test threw exception... check your Gruobi setup!\n\nJava library path: "
                + jlp;
        if (HEADLESS) {
            System.out.println(msgs);
        } else {
            JOptionPane.showMessageDialog(MoMA.guiFrame, msgs, "Gurobi Error?", JOptionPane.ERROR_MESSAGE);
        }
        e.printStackTrace();
        System.exit(98);
    } catch (final UnsatisfiedLinkError ulr) {
        final String msgs = "Could initialize Gurobi.\n"
                + "You might not have installed Gurobi properly or you miss a valid license.\n"
                + "Please visit 'www.gurobi.com' for further information.\n\n" + ulr.getMessage()
                + "\nJava library path: " + jlp;
        if (HEADLESS) {
            System.out.println(msgs);
        } else {
            JOptionPane.showMessageDialog(MoMA.guiFrame, msgs, "Gurobi Error?", JOptionPane.ERROR_MESSAGE);
            ulr.printStackTrace();
        }
        System.out.println("\n>>>>> Java library path: " + jlp + "\n");
        System.exit(99);
    }
    // ******* END CHECK GUROBI **** END CHECK GUROBI **** END CHECK GUROBI ********

    final MoMA main = new MoMA();
    if (!HEADLESS) {
        guiFrame = new JFrame();
        main.initMainWindow(guiFrame);
    }

    System.out.println("VERSION: " + VERSION_STRING);

    props = main.loadParams();
    BGREM_TEMPLATE_XMIN = Integer
            .parseInt(props.getProperty("BGREM_TEMPLATE_XMIN", Integer.toString(BGREM_TEMPLATE_XMIN)));
    BGREM_TEMPLATE_XMAX = Integer
            .parseInt(props.getProperty("BGREM_TEMPLATE_XMAX", Integer.toString(BGREM_TEMPLATE_XMAX)));
    BGREM_X_OFFSET = Integer.parseInt(props.getProperty("BGREM_X_OFFSET", Integer.toString(BGREM_X_OFFSET)));
    GL_WIDTH_IN_PIXELS = Integer
            .parseInt(props.getProperty("GL_WIDTH_IN_PIXELS", Integer.toString(GL_WIDTH_IN_PIXELS)));
    MOTHER_CELL_BOTTOM_TRICK_MAX_PIXELS = Integer.parseInt(props.getProperty(
            "MOTHER_CELL_BOTTOM_TRICK_MAX_PIXELS", Integer.toString(MOTHER_CELL_BOTTOM_TRICK_MAX_PIXELS)));
    GL_FLUORESCENCE_COLLECTION_WIDTH_IN_PIXELS = Integer
            .parseInt(props.getProperty("GL_FLUORESCENCE_COLLECTION_WIDTH_IN_PIXELS",
                    Integer.toString(GL_FLUORESCENCE_COLLECTION_WIDTH_IN_PIXELS)));
    GL_OFFSET_BOTTOM = Integer
            .parseInt(props.getProperty("GL_OFFSET_BOTTOM", Integer.toString(GL_OFFSET_BOTTOM)));
    if (GL_OFFSET_BOTTOM == -1) {
        GL_OFFSET_BOTTOM_AUTODETECT = true;
    } else {
        GL_OFFSET_BOTTOM_AUTODETECT = false;
    }
    GL_OFFSET_TOP = Integer.parseInt(props.getProperty("GL_OFFSET_TOP", Integer.toString(GL_OFFSET_TOP)));
    GL_OFFSET_LATERAL = Integer
            .parseInt(props.getProperty("GL_OFFSET_LATERAL", Integer.toString(GL_OFFSET_LATERAL)));
    MIN_CELL_LENGTH = Integer.parseInt(props.getProperty("MIN_CELL_LENGTH", Integer.toString(MIN_CELL_LENGTH)));
    MIN_GAP_CONTRAST = Float
            .parseFloat(props.getProperty("MIN_GAP_CONTRAST", Float.toString(MIN_GAP_CONTRAST)));
    SIGMA_PRE_SEGMENTATION_X = Float.parseFloat(
            props.getProperty("SIGMA_PRE_SEGMENTATION_X", Float.toString(SIGMA_PRE_SEGMENTATION_X)));
    SIGMA_PRE_SEGMENTATION_Y = Float.parseFloat(
            props.getProperty("SIGMA_PRE_SEGMENTATION_Y", Float.toString(SIGMA_PRE_SEGMENTATION_Y)));
    SIGMA_GL_DETECTION_X = Float
            .parseFloat(props.getProperty("SIGMA_GL_DETECTION_X", Float.toString(SIGMA_GL_DETECTION_X)));
    SIGMA_GL_DETECTION_Y = Float
            .parseFloat(props.getProperty("SIGMA_GL_DETECTION_Y", Float.toString(SIGMA_GL_DETECTION_Y)));
    SEGMENTATION_MIX_CT_INTO_PMFRF = Float.parseFloat(props.getProperty("SEGMENTATION_MIX_CT_INTO_PMFRF",
            Float.toString(SEGMENTATION_MIX_CT_INTO_PMFRF)));
    SEGMENTATION_CLASSIFIER_MODEL_FILE = props.getProperty("SEGMENTATION_CLASSIFIER_MODEL_FILE",
            SEGMENTATION_CLASSIFIER_MODEL_FILE);
    CELLSIZE_CLASSIFIER_MODEL_FILE = props.getProperty("CELLSIZE_CLASSIFIER_MODEL_FILE",
            CELLSIZE_CLASSIFIER_MODEL_FILE);
    DEFAULT_PATH = props.getProperty("DEFAULT_PATH", DEFAULT_PATH);

    GUROBI_TIME_LIMIT = Double
            .parseDouble(props.getProperty("GUROBI_TIME_LIMIT", Double.toString(GUROBI_TIME_LIMIT)));
    GUROBI_MAX_OPTIMALITY_GAP = Double.parseDouble(
            props.getProperty("GUROBI_MAX_OPTIMALITY_GAP", Double.toString(GUROBI_MAX_OPTIMALITY_GAP)));

    GUI_POS_X = Integer.parseInt(props.getProperty("GUI_POS_X", Integer.toString(DEFAULT_GUI_POS_X)));
    GUI_POS_Y = Integer.parseInt(props.getProperty("GUI_POS_Y", Integer.toString(DEFAULT_GUI_POS_X)));
    GUI_WIDTH = Integer.parseInt(props.getProperty("GUI_WIDTH", Integer.toString(GUI_WIDTH)));
    GUI_HEIGHT = Integer.parseInt(props.getProperty("GUI_HEIGHT", Integer.toString(GUI_HEIGHT)));
    GUI_CONSOLE_WIDTH = Integer
            .parseInt(props.getProperty("GUI_CONSOLE_WIDTH", Integer.toString(GUI_CONSOLE_WIDTH)));

    if (!HEADLESS) {
        // Iterate over all currently attached monitors and check if sceen
        // position is actually possible,
        // otherwise fall back to the DEFAULT values and ignore the ones
        // coming from the properties-file.
        boolean pos_ok = false;
        final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        final GraphicsDevice[] gs = ge.getScreenDevices();
        for (int i = 0; i < gs.length; i++) {
            if (gs[i].getDefaultConfiguration().getBounds()
                    .contains(new java.awt.Point(GUI_POS_X, GUI_POS_Y))) {
                pos_ok = true;
            }
        }
        // None of the screens contained the top-left window coordinates -->
        // fall back onto default values...
        if (!pos_ok) {
            GUI_POS_X = DEFAULT_GUI_POS_X;
            GUI_POS_Y = DEFAULT_GUI_POS_Y;
        }
    }

    String path = props.getProperty("import_path", System.getProperty("user.home"));
    if (inputFolder == null || inputFolder.equals("")) {
        inputFolder = main.showStartupDialog(guiFrame, path);
    }
    System.out.println("Default filename decoration = " + inputFolder.getName());
    defaultFilenameDecoration = inputFolder.getName();
    path = inputFolder.getAbsolutePath();
    props.setProperty("import_path", path);

    GrowthLineSegmentationMagic.setClassifier(SEGMENTATION_CLASSIFIER_MODEL_FILE, "");

    if (!HEADLESS) {
        // Setting up console window...
        main.initConsoleWindow();
        main.showConsoleWindow(true);
    }

    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------
    final MoMAModel mmm = new MoMAModel(main);
    instance = main;
    try {
        main.processDataFromFolder(path, minTime, maxTime, minChannelIdx, numChannels);
    } catch (final Exception e) {
        e.printStackTrace();
        System.exit(11);
    }
    // ------------------------------------------------------------------------------------------------------
    // ------------------------------------------------------------------------------------------------------

    // show loaded and annotated data
    if (showIJ) {
        new ImageJ();
        ImageJFunctions.show(main.imgRaw, "Rotated & cropped raw data");
        // ImageJFunctions.show( main.imgTemp, "Temporary" );
        // ImageJFunctions.show( main.imgAnnotated, "Annotated ARGB data" );

        // main.getCellSegmentedChannelImgs()
        // ImageJFunctions.show( main.imgClassified, "Classification" );
        // ImageJFunctions.show( main.getCellSegmentedChannelImgs(), "Segmentation" );
    }

    gui = new MoMAGui(mmm);

    if (!HEADLESS) {
        System.out.print("Build GUI...");
        main.showConsoleWindow(false);

        //         final JFrameSnapper snapper = new JFrameSnapper();
        //         snapper.addFrame( main.frameConsoleWindow );
        //         snapper.addFrame( guiFrame );

        gui.setVisible(true);
        guiFrame.add(gui);
        guiFrame.setSize(GUI_WIDTH, GUI_HEIGHT);
        guiFrame.setLocation(GUI_POS_X, GUI_POS_Y);
        guiFrame.setVisible(true);

        //         SwingUtilities.invokeLater( new Runnable() {
        //
        //            @Override
        //            public void run() {
        //               snapper.snapFrames( main.frameConsoleWindow, guiFrame, JFrameSnapper.EAST );
        //            }
        //         } );
        System.out.println(" done!");
    } else {
        //         final String name = inputFolder.getName();

        gui.exportHtmlOverview();
        gui.exportDataFiles();

        instance.saveParams();

        System.exit(0);
    }
}

From source file:de.uniwue.info2.main.CommandLineInterpreter.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    /*-------------------------------------------------------- */
    /*---------------SETTING TARGET LANGUAGE------------------ */
    /*-------------------------------------------------------- */
    LanguageFactory languageFactory = new LanguageFactory();

    CommandLine line = null;//from   w w w .jav  a  2 s .c o  m
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    // options to display in the help page
    Options options_short = new Options();

    // add help option
    Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION);
    options.addOption(help_option);
    options_short.addOption(help_option);
    // add extended help option
    Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION);
    options.addOption(help2_option);
    options_short.addOption(help2_option);
    // add optional operations option
    options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION));
    options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION));
    options.addOption(
            new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION));
    // add optional operations config option
    options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION)
            .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT)
            .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg()
            .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT));
    // add dsl option
    Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT)
            .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT);
    options.addOption(dsl_option);
    options_short.addOption(dsl_option);
    // add output-folder option
    Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT)
            .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT);
    options.addOption(output_option);
    options_short.addOption(output_option);

    // count possible language-specifications
    short optionCounter = 1;

    // get all possible language-specifications from language-factory and iterate through them
    List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_();

    for (LanguageSpecification lSpec : lSpecs) {
        // get all possible unit-specifications for current language and iterate through them
        List<UnitTestLibrarySpecification> uSpecs = languageFactory
                .getAvailableUnitTestLibraries_(lSpec.getOptionName());
        String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName();
        String languageCounter = "s" + INDEX.format(optionCounter++);

        for (UnitTestLibrarySpecification uSpec : uSpecs) {
            // get all possible arithmetic-library-specifications for current language and iterate through
            // them
            List<ArithmeticLibrarySpecification> aSpecs = languageFactory
                    .getAvailableArithmeticLibraries_(lSpec.getOptionName());
            for (ArithmeticLibrarySpecification aSpec : aSpecs) {
                String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*["
                        + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName()
                        + " - " + aSpec.getVersion() + "]";

                // if there is more than one option, generate suitable option-names and add them all to
                // commandline options
                if (uSpecs.size() > 1 || aSpecs.size() > 1) {
                    options.addOption(OptionBuilder
                            .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_"
                                    + aSpec.getOptionName())
                            .withDescription(languageDescription).hasArg(false)
                            .create("s" + INDEX.format(optionCounter++)));
                } else {
                    // if there is only one option, use language-name as option-name
                    languageDescriptionAll = languageDescription;
                }
            }
            // add specifications to options
            options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName())
                    .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter));
        }
    }

    /*-------------------------------------------------------- */
    /*-------------------PARSE USER INPUT--------------------- */
    /*-------------------------------------------------------- */
    try {
        // manual search for help-arguments
        for (String arg : args) {
            arg = arg.trim().replace("-", "");
            if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) {
                printHelp(options_short);
                return;
            }
            if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) {
                printExtendedHelp(options);
                return;
            }
        }

        // parse arguments   
        line = parser.parse(options, args);

        File dsl_file = null;
        File output_folder = null;
        File optional_config = null;
        Properties optional_operations = null;
        Boolean optional = false;
        Boolean little_endian = null;
        ArrayList<String> optional_exceptions = new ArrayList<String>();

        // if help-option found print help
        if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) {
            printExtendedHelp(options);
            return;
        }

        // if help-option found print help
        if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) {
            System.out.println("\n");
            printHelp(options_short);
            return;
        }

        if (line.hasOption(OPTIONAL_OPTION_SHORT)) {
            optional = true;
        }

        if (line.hasOption(LITTLE_ENDIAN_OPTION)) {
            little_endian = true;
        }

        if (line.hasOption(BIG_ENDIAN_OPTION)) {
            little_endian = false;
        }

        // if dsl-option found, check if file exists and is readable
        // print help if error occurs
        if (line.hasOption(DSL_OPTION_SHORT)) {
            dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        // if output-option found, check if folder exists and if write-permission was granted
        // print help if error occurs
        if (line.hasOption(OUTPUT_OPTION_SHORT)) {
            output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT));
            if (!output_folder.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.canWrite() || !output_folder.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) {
            optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            }
        }

        if (optional_config != null) {
            optional_operations = new Properties();
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config));
            optional_operations.load(stream);
            stream.close();
            String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL");
            if (optional_prop != null) {
                if (optional_prop.trim().toLowerCase().equals("true")) {
                    optional = true;
                } else if (optional_prop.trim().toLowerCase().equals("false")) {
                    optional = false;
                } else if (!optional_prop.trim().isEmpty()) {
                    System.err.println("\n" + SEPERATOR + "\n"
                            + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n"
                            + SEPERATOR + "\n");
                    printExtendedHelp(options);
                    return;
                }
            }
            String exceptions = optional_operations.getProperty("EXCLUSIONS");
            if (exceptions != null) {
                for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) {
                    optional_exceptions.add(exc.trim());
                }
            }
        }

        /*-------------------------------------------------------- */
        /*-------------------START GENERATING--------------------- */
        /*-------------------------------------------------------- */

        // instantiate generator for unit-tests
        TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder);

        boolean overrideDefaultSpecs = false;

        // check if user input contains a language-specifications
        // if user specified language, set overrideDefaultSpecs to true, so that only given specifications
        // are used
        for (int i = 1; i <= optionCounter; i++) {
            String opt = "s" + INDEX.format(i);
            if (line.hasOption(opt)) {
                LanguageSpecification targetSpecification = languageFactory
                        .getLanguageSpecification(options.getOption(opt).getLongOpt());
                String output = (GENERATING_DIALOG + targetSpecification.getLanguageName());

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
                overrideDefaultSpecs = true;
            }
        }

        // skip, if user already defined one language-specification
        // if user did not define language-specification, generate unit-tests for all
        // possible language-specifications (default)
        if (!overrideDefaultSpecs) {
            for (int i = 0; i < lSpecs.size(); i++) {
                LanguageSpecification specification = languageFactory
                        .getLanguageSpecification(lSpecs.get(i).getOptionName());

                String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG
                        + specification.getLanguageName();

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(specification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
            }
        }

    } catch (ParseException | IOException p) {
        System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n"
                + SEPERATOR + "\n");
        printHelp(options_short);
        System.out.println("\n");
    }
}

From source file:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);/*w  ww .  j  a  v a 2 s .c om*/
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*from  www.  j  av a 2  s  .  c  om*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:Main.java

public static boolean isProtected(File path) {
    return (!path.canRead() && !path.canWrite());
}

From source file:Main.java

public static boolean isUnzippable(File path) {
    return (path.isFile() && path.canRead() && path.getName().endsWith(".zip"));
}

From source file:Main.java

public static boolean checkFile(File f) {
    if (f != null && f.exists() && f.canRead() && (f.isDirectory() || (f.isFile() && f.length() > 0))) {
        return true;
    }//from   w w  w  .j av  a 2s. c o  m
    return false;
}