Example usage for java.io File getAbsolutePath

List of usage examples for java.io File getAbsolutePath

Introduction

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

Prototype

public String getAbsolutePath() 

Source Link

Document

Returns the absolute pathname string of this abstract pathname.

Usage

From source file:com.blackducksoftware.tools.nrt.NoticeReportTool.java

/**
 * @param args/* ww w . j a  va  2  s  .c  om*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    System.out.println("Notice Report Tool for Black Duck Suite");
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option applicationOption = new Option(NRTConstants.CL_APPLICATION_TYPE, true,
            "Application type [PROTEX|CODECENTER] (required)");
    applicationOption.setRequired(true);
    options.addOption(applicationOption);

    Option configFileOption = new Option(NRTConstants.CL_CONFIG_FILE, true,
            "Location of configuration file (required)");
    configFileOption.setRequired(true);
    options.addOption(configFileOption);

    Option projectNameOption = new Option(NRTConstants.CL_PROJECT_NAME, true,
            "Name of Protex project (will override configuration file)");
    projectNameOption.setRequired(false);
    options.addOption(projectNameOption);

    File configFile = null;
    APPLICATION applicationType = null;
    String projectName = null;

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            help();
        }

        // Config File
        if (cmd.hasOption(NRTConstants.CL_CONFIG_FILE)) {
            String configFilePath = cmd.getOptionValue(NRTConstants.CL_CONFIG_FILE);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                System.exit(-1);
            }
        } else {
            log.error("Must specify configuration file!");
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_APPLICATION_TYPE)) {
            String bdsApplicationType = cmd.getOptionValue(NRTConstants.CL_APPLICATION_TYPE);

            try {
                applicationType = APPLICATION.valueOf(bdsApplicationType);
            } catch (IllegalArgumentException e) {
                log.error("No such application type recognized: " + bdsApplicationType);
                help();
            }

        } else {
            help();
        }

        if (cmd.hasOption(NRTConstants.CL_PROJECT_NAME)) {
            projectName = cmd.getOptionValue(NRTConstants.CL_PROJECT_NAME);
            log.info("User specified project name: " + projectName);
        }

        NoticeReportProcessor processor = new NoticeReportProcessor(configFile.getAbsolutePath(),
                applicationType, projectName);
        try {
            processor.connect();
        } catch (Exception e) {
            log.error("Connection problems: " + e.getMessage());
            throw new Exception(e);
        }
        processor.processReport();

    } catch (Exception e) {
        log.error("Error: " + e.getMessage());
        help();
    }
}

From source file:com.doculibre.constellio.utils.license.ApplyLicenseUtils.java

/**
 * @param args//from w w w.j  a v a 2  s  .c om
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    URL licenceHeaderURL = ApplyLicenseUtils.class.getResource("LICENSE_HEADER");
    File binDir = ClasspathUtils.getClassesDir();
    File projectDir = binDir.getParentFile();
    //        File dryrunDir = new File(projectDir, "dryrun");
    File licenceFile = new File(licenceHeaderURL.toURI());
    List<String> licenceLines = readLines(licenceFile);
    //        for (int i = 0; i < licenceLines.size(); i++) {
    //            String licenceLine = licenceLines.get(i);
    //            licenceLines.set(i, " * " + licenceLine);
    //        }
    //        licenceLines.add(0, "/**");
    //        licenceLines.add(" */");

    List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(projectDir,
            new String[] { "java" }, true);
    for (File javaFile : javaFiles) {
        if (isValidPackage(javaFile)) {
            List<String> javaFileLines = readLines(javaFile);
            if (!javaFileLines.isEmpty()) {
                boolean modified = false;
                String firstLineTrim = javaFileLines.get(0).trim();
                if (firstLineTrim.startsWith("package")) {
                    modified = true;
                    javaFileLines.addAll(0, licenceLines);
                } else if (firstLineTrim.startsWith("/**")) {
                    int indexOfEndCommentLine = -1;
                    loop2: for (int i = 0; i < javaFileLines.size(); i++) {
                        String javaFileLine = javaFileLines.get(i);
                        if (javaFileLine.indexOf("*/") != -1) {
                            indexOfEndCommentLine = i;
                            break loop2;
                        }
                    }
                    if (indexOfEndCommentLine != -1) {
                        modified = true;
                        int i = 0;
                        loop3: for (Iterator<String> it = javaFileLines.iterator(); it.hasNext();) {
                            it.next();
                            if (i <= indexOfEndCommentLine) {
                                it.remove();
                            } else {
                                break loop3;
                            }
                            i++;
                        }
                        javaFileLines.addAll(0, licenceLines);
                    } else {
                        throw new RuntimeException(
                                "Missing end comment for file " + javaFile.getAbsolutePath());
                    }
                }

                if (modified) {
                    //                        String outputFilePath = javaFile.getPath().substring(projectDir.getPath().length());
                    //                        File outputFile = new File(dryrunDir, outputFilePath);
                    //                        outputFile.getParentFile().mkdirs();
                    //                        System.out.println(outputFile.getPath());
                    //                        FileOutputStream fos = new FileOutputStream(outputFile);
                    System.out.println(javaFile.getPath());
                    FileOutputStream fos = new FileOutputStream(javaFile);
                    IOUtils.writeLines(javaFileLines, "\n", fos);
                    IOUtils.closeQuietly(fos);
                }
            }
        }
    }
}

From source file:fll.scheduler.GreedySolver.java

public static void main(final String[] args) throws InterruptedException {
    LogUtils.initializeLogging();/*from ww  w.  j av  a  2 s .com*/

    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:com.dtolabs.rundeck.ec2.NodeGenerator.java

public static void main(final String[] args) throws IOException, GeneratorException {
    File outfile = null;

    //load generator mapping
    if (args.length < 2) {
        System.err.println(/*from w ww  .  java 2 s. com*/
                "usage: <credentials.properties> <endpoint> [mapping.properties] [outfile] [query parameters, \"a=b\" ...]");
        System.err.println(
                "\t optional arguments can be replaced by \"-\" to use the default, and then query parameters appended");
        System.exit(2);
    }

    final InputStream stream = new FileInputStream(args[0]);
    final String endPoint = args[1];
    final AWSCredentials credentials = new PropertiesCredentials(stream);

    Properties mapping = new Properties();
    if (args.length > 2 && !"-".equals(args[2])) {
        mapping.load(new FileInputStream(args[2]));
    } else {
        mapping.load(NodeGenerator.class.getClassLoader().getResourceAsStream("simplemapping.properties"));
    }

    final ResourceXMLGenerator gen;
    if (args.length > 3 && !"-".equals(args[3])) {
        outfile = new File(args[3]);
        gen = new ResourceXMLGenerator(outfile);
    } else {
        //use stdout
        gen = new ResourceXMLGenerator(System.out);
    }
    ArrayList<String> params = new ArrayList<String>();
    if (args.length > 4) {
        for (int i = 4; i < args.length; i++) {
            params.add(args[i]);
        }
    }

    Set<Instance> instances = performQuery(credentials, endPoint, params);

    for (final Instance inst : instances) {
        final INodeEntry iNodeEntry = instanceToNode(inst, mapping);
        if (null != iNodeEntry) {
            gen.addNode(iNodeEntry);
        }
    }
    gen.generate();
    //
    if (null != outfile) {
        System.out.println("XML Stored: " + outfile.getAbsolutePath());
    }
}

From source file:de.prozesskraft.pramp.parts.PrampPartUi1.java

/**
 * @param args//from  w  w  w. ja  v a2 s .com
 */
public static void main(String[] args) {
    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(PrampPartUi1.class) + "/" + "../etc/pramp-gui.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 help = new Option("help", "print this message");
    Option v = new Option("v", "prints version and build-date");
    /*----------------------------
      create argument options
    ----------------------------*/
    Option dbfile = OptionBuilder.withArgName("dbfile").hasArg().withDescription("[optional] dbfile")
            //            .isRequired()
            .create("dbfile");
    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(help);
    options.addOption(v);
    options.addOption(dbfile);

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

    /*----------------------------
      usage/help
    ----------------------------*/
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        //         formatter.printHelp("checkin --version [% version %]", options);
        formatter.printHelp("pramp-gui", options);
        System.exit(0);
    }

    if (line.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      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);
    }

    // gui
    final Display display = new Display();

    Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
        public void run() {
            try {
                shell = new Shell(display);
                shell.setText("pramp " + "[% version %]");

                // set an icon
                if (this.getClass().getResourceAsStream("/logoSymbol50Transp.png") != null) {
                    shell.setImage(
                            new Image(display, this.getClass().getResourceAsStream("/logoSymbol50Transp.png")));
                } else if ((new java.io.File("logoSymbol50Transp.png")).exists()) {
                    shell.setImage(new Image(display, "logoSymbol50Transp.png"));
                }

                shell.setLayout(new FillLayout());
                shell.setSize(1000, 780);
                Composite composite = new Composite(shell, SWT.NO_FOCUS);
                GridLayout gl_composite = new GridLayout(2, false);
                gl_composite.marginWidth = 0;
                gl_composite.marginHeight = 0;
                new PrampPartUi1(composite);

                try {
                    shell.open();

                    while (!shell.isDisposed()) {
                        if (!display.readAndDispatch()) {
                            display.sleep();
                        }
                    }

                } finally {
                    if (!shell.isDisposed()) {
                        shell.dispose();
                    }
                }

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

From source file:com.mvdb.etl.actions.ExtractDBChanges.java

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

    ActionUtils.setUpInitFileProperty();
    //        boolean success = ActionUtils.markActionChainBroken("Just Testing");        
    //        System.exit(success ? 0 : 1);
    ActionUtils.assertActionChainNotBroken();
    ActionUtils.assertEnvironmentSetupOk();
    ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing.");
    ActionUtils.assertFileExists("~/.mvdb/status.InitCustomerData.complete",
            "300init-customer-data.sh not executed yet. Exiting");
    //This check is not required as data can be modified any number of times
    //ActionUtils.assertFileDoesNotExist("~/.mvdb/status.ModifyCustomerData.complete", "ModifyCustomerData already done. Start with 100init.sh if required. Exiting");

    ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.start", true);

    //String schemaDescription = "{ 'root' : [{'table' : 'orders', 'keyColumn' : 'order_id', 'updateTimeColumn' : 'update_time'}]}";

    String customerName = null;/* ww w.  j ava2  s .c  om*/
    final CommandLineParser cmdLinePosixParser = new PosixParser();
    final Options posixOptions = constructPosixOptions();
    CommandLine commandLine;
    try {
        commandLine = cmdLinePosixParser.parse(posixOptions, args);
        if (commandLine.hasOption("customer")) {
            customerName = commandLine.getOptionValue("customer");
        }
    } catch (ParseException parseException) // checked exception
    {
        System.err.println(
                "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
    }

    if (customerName == null) {
        System.err.println("Could not find customerName. Aborting...");
        System.exit(1);
    }

    ApplicationContext context = Top.getContext();

    final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO");
    final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO");
    final GenericDAO genericDAO = (GenericDAO) context.getBean("genericDAO");
    File snapshotDirectory = getSnapshotDirectory(configurationDAO, customerName);
    try {
        FileUtils.writeStringToFile(new File("/tmp/etl.extractdbchanges.directory.txt"),
                snapshotDirectory.getName(), false);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
        return;
    }
    long currentTime = new Date().getTime();
    Configuration lastRefreshTimeConf = configurationDAO.find(customerName, "last-refresh-time");
    Configuration schemaDescriptionConf = configurationDAO.find(customerName, "schema-description");
    long lastRefreshTime = Long.parseLong(lastRefreshTimeConf.getValue());
    OrderJsonFileConsumer orderJsonFileConsumer = new OrderJsonFileConsumer(snapshotDirectory);
    Map<String, ColumnMetadata> metadataMap = orderDAO.findMetadata();
    //write file schema-orders.dat in snapshotDirectory
    genericDAO.fetchMetadata("orders", snapshotDirectory);
    //writes files: header-orders.dat, data-orders.dat in snapshotDirectory
    JSONObject json = new JSONObject(schemaDescriptionConf.getValue());
    JSONArray rootArray = json.getJSONArray("root");
    int length = rootArray.length();
    for (int i = 0; i < length; i++) {
        JSONObject jsonObject = rootArray.getJSONObject(i);
        String table = jsonObject.getString("table");
        String keyColumnName = jsonObject.getString("keyColumn");
        String updateTimeColumnName = jsonObject.getString("updateTimeColumn");
        System.out.println("table:" + table + ", keyColumn: " + keyColumnName + ", updateTimeColumn: "
                + updateTimeColumnName);
        genericDAO.fetchAll2(snapshotDirectory, new Timestamp(lastRefreshTime), table, keyColumnName,
                updateTimeColumnName);
    }

    //Unlikely failure
    //But Need to factor this into a separate task so that extraction does not have to be repeated. 
    //Extraction is an expensive task. 
    try {
        String sourceDirectoryAbsolutePath = snapshotDirectory.getAbsolutePath();

        File sourceRelativeDirectoryPath = getRelativeSnapShotDirectory(configurationDAO,
                sourceDirectoryAbsolutePath);
        String hdfsRoot = ActionUtils.getConfigurationValue(ConfigurationKeys.GLOBAL_CUSTOMER,
                ConfigurationKeys.GLOBAL_HDFS_ROOT);
        String targetDirectoryFullPath = hdfsRoot + "/data" + sourceRelativeDirectoryPath;

        ActionUtils.copyLocalDirectoryToHdfsDirectory(sourceDirectoryAbsolutePath, targetDirectoryFullPath);
        String dirName = snapshotDirectory.getName();
        ActionUtils.setConfigurationValue(customerName, ConfigurationKeys.LAST_COPY_TO_HDFS_DIRNAME, dirName);
    } catch (Throwable e) {
        e.printStackTrace();
        logger.error("Objects Extracted from database. But copy of snapshot directory<"
                + snapshotDirectory.getAbsolutePath() + "> to hdfs <" + ""
                + ">failed. Fix the problem and redo extract.", e);
        System.exit(1);
    }

    //Unlikely failure
    //But Need to factor this into a separate task so that extraction does not have to be repeated. 
    //Extraction is an expensive task. 
    String targetZip = null;
    try {
        File targetZipDirectory = new File(snapshotDirectory.getParent(), "archives");
        if (!targetZipDirectory.exists()) {
            boolean success = targetZipDirectory.mkdirs();
            if (success == false) {
                logger.error("Objects copied to hdfs. But able to create archive directory <"
                        + targetZipDirectory.getAbsolutePath() + ">. Fix the problem and redo extract.");
                System.exit(1);
            }
        }
        targetZip = new File(targetZipDirectory, snapshotDirectory.getName() + ".zip").getAbsolutePath();
        ActionUtils.zipFullDirectory(snapshotDirectory.getAbsolutePath(), targetZip);
    } catch (Throwable e) {
        e.printStackTrace();
        logger.error("Objects copied to hdfs. But zipping of snapshot directory<"
                + snapshotDirectory.getAbsolutePath() + "> to  <" + targetZip
                + ">failed. Fix the problem and redo extract.", e);
        System.exit(1);
    }

    //orderDAO.findAll(new Timestamp(lastRefreshTime), orderJsonFileConsumer);
    Configuration updateRefreshTimeConf = new Configuration(customerName, "last-refresh-time",
            String.valueOf(currentTime));
    configurationDAO.update(updateRefreshTimeConf, String.valueOf(lastRefreshTimeConf.getValue()));
    ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.complete", true);

}

From source file:com.jug.MoMA.java

/**
 * PROJECT MAIN//w w w.  j  av  a2 s .  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:gov.nasa.ensemble.dictionary.nddl.ParseInterpreter.java

public static void main(String[] args) throws Exception {
    try {/*from w  w w . j av  a2  s  . c  o m*/
        CommandLineArguments cmd = new CommandLineArguments(args);

        // Create a resource set to hold the resources.
        //
        ResourceSet resourceSet = new ResourceSetImpl();

        // Register the package to ensure it is available during loading.
        //
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getPackageRegistry().put(DictionaryPackage.eNS_URI, DictionaryPackage.eINSTANCE);

        // Construct the URI for the instance file.
        // The argument is treated as a file path only if it denotes an
        // existing file.
        // Otherwise, it's directly treated as a URL.
        //

        File file = new File(cmd.getValue(Option.ACTIVITY_DICTIONARY_FILE));
        URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath())
                : URI.createURI(cmd.getValue(Option.ACTIVITY_DICTIONARY_FILE));

        try {
            // Demand load resource for this file.
            //
            Resource resource = resourceSet.getResource(uri, true);
            EActivityDictionary eActivityDictionary = (EActivityDictionary) resource.getContents().get(0);

            ParseInterpreter parseInterpreter = new ParseInterpreter(eActivityDictionary,
                    cmd.getValue(Option.CPU_STATE), cmd.getValue(Option.CPU_VALUE),
                    cmd.getIntValue(Option.BOOT), cmd.getIntValue(Option.SHUTDOWN),
                    cmd.getIntValue(Option.GAP));
            parseInterpreter.interpretAD(false);

            String path = cmd.getValue(Option.OUTPUT_DIRECTORY_PATH);
            path = path + uri.trimFileExtension().lastSegment();

            FileOutputStream objStream = new FileOutputStream(path + "-objects.nddl");
            FileOutputStream modelStream = new FileOutputStream(path + "-model.nddl");
            FileOutputStream initStateStream = new FileOutputStream(path + "-initial-state.nddl");
            objStream.flush();
            modelStream.flush();
            initStateStream.flush();

            parseInterpreter.writeObjects(objStream);
            objStream.close();
            parseInterpreter.writeCompats(modelStream, path + "-objects.nddl");
            modelStream.close();
            parseInterpreter.writeInitialState(initStateStream, path + "-model.nddl");

        } catch (RuntimeException exception) {
            System.out.println("Problem loading " + uri);
            exception.printStackTrace();
        }
    } catch (Exception e) {
        System.out.println(getManPageText());
    }
}

From source file:de.huberlin.cuneiform.main.Main.java

public static void main(String[] args)
        throws ParseException, IOException, NotDerivableException, InterruptedException, JSONException {

    GnuParser gnuParser;//from ww  w . j  a  va  2  s.c o m
    CommandLine cmdline;
    Options opt;
    String value;
    int platform;
    File outputDir;
    String[] fileList;
    StringBuffer buf;
    String line;
    String dagid;
    File logFile;

    opt = new Options();

    opt.addOption("p", "platform", true, "The platform to perform the Cuneiform script's interpretation. "
            + "Possible platforms are: 'dot', 'local', and 'debug'. Default is 'local'.");

    opt.addOption("d", "directory", true,
            "The output directory, to put the interpretation intermediate and output result as well as the default location to store the log.");

    opt.addOption("c", "clean", false,
            "If set, the execution engine ignores all cached results and starts a clean workflow run.");

    opt.addOption("r", "runid", true,
            "If set, a custom id is set for this workflow run. By default a UUID string is used.");

    opt.addOption("f", "file", true,
            "Override the default location of the log file and use the specified filename instead. If the platform is 'dot', this option sets the name of the output dot-file.");

    opt.addOption("h", "help", false, "Print help text.");

    gnuParser = new GnuParser();
    cmdline = gnuParser.parse(opt, args);

    if (cmdline.hasOption("help")) {

        System.out.println("CUNEIFORM - A Functional Workflow Language\n" + LABEL_VERSION);
        new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

        return;
    }

    if (cmdline.hasOption("platform")) {

        value = cmdline.getOptionValue("platform");

        if (value.equals("dot"))
            platform = PLATFORM_DOT;
        else if (value.equals("local"))
            platform = PLATFORM_LOCAL;
        else if (value.equals("debug"))
            platform = PLATFORM_DEBUG;
        else
            throw new RuntimeException("Specified platform '" + value + "' not recognized.");

    } else
        platform = PLATFORM_LOCAL;

    if (cmdline.hasOption('d')) {

        value = cmdline.getOptionValue('d');
    } else
        value = "build";

    outputDir = new File(value);

    if (outputDir.exists()) {

        if (!outputDir.isDirectory())
            throw new IOException(
                    "Output directory '" + outputDir.getAbsolutePath() + "' exists but is not a directory.");

        else if (cmdline.hasOption('c')) {

            FileUtils.deleteDirectory(outputDir);

            if (!outputDir.mkdirs())
                throw new IOException(
                        "Could not create output directory '" + outputDir.getAbsolutePath() + "'");
        }
    } else if (!outputDir.mkdirs())
        throw new IOException("Could not create output directory '" + outputDir.getAbsolutePath() + "'");

    if (cmdline.hasOption('r'))
        dagid = cmdline.getOptionValue('r');
    else
        dagid = UUID.randomUUID().toString();

    if (cmdline.hasOption('f'))
        logFile = new File(cmdline.getOptionValue('f'));
    else
        logFile = null;

    fileList = cmdline.getArgs();
    buf = new StringBuffer();
    if (fileList.length == 0) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {

            while ((line = reader.readLine()) != null)
                buf.append(line).append('\n');
        }

        switch (platform) {

        case PLATFORM_DOT:
            createDot(buf.toString(), outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(buf.toString(), outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(buf.toString(), outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }
    } else

        switch (platform) {

        case PLATFORM_DOT:
            createDot(fileList, outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(fileList, outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(fileList, outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }

}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public static void main(String[] args) {

    String file = args[0];/*from  w w  w.  j  av  a  2  s. co m*/
    String type = args[1];

    if (file == null || type == null || "".equals(file) || "".equals(type)) {
        System.err.println("Usage: java edu.harvard.iq.dataverse.ingest.IngestServiceBean <file> <type>.");
        System.exit(1);
    }

    BufferedInputStream fileInputStream = null;

    try {
        fileInputStream = new BufferedInputStream(new FileInputStream(new File(file)));
    } catch (FileNotFoundException notfoundEx) {
        fileInputStream = null;
    }

    if (fileInputStream == null) {
        System.err.println("Could not open file " + file + ".");
        System.exit(1);
    }

    TabularDataFileReader ingestPlugin = getTabDataReaderByMimeType(type);

    if (ingestPlugin == null) {
        System.err.println("Could not locate an ingest plugin for type " + type + ".");
        System.exit(1);
    }

    TabularDataIngest tabDataIngest = null;

    try {
        tabDataIngest = ingestPlugin.read(fileInputStream, null);
    } catch (IOException ingestEx) {
        System.err.println("Caught an exception trying to ingest file " + file + ".");
        System.exit(1);
    }

    try {
        if (tabDataIngest != null) {
            File tabFile = tabDataIngest.getTabDelimitedFile();

            if (tabDataIngest.getDataTable() != null && tabFile != null && tabFile.exists()) {

                String tabFilename = FileUtil.replaceExtension(file, "tab");

                Files.copy(Paths.get(tabFile.getAbsolutePath()), Paths.get(tabFilename),
                        StandardCopyOption.REPLACE_EXISTING);

                DataTable dataTable = tabDataIngest.getDataTable();

                System.out.println("NVARS: " + dataTable.getVarQuantity());
                System.out.println("NOBS: " + dataTable.getCaseQuantity());
                System.out.println("UNF: " + dataTable.getUnf());

                for (int i = 0; i < dataTable.getVarQuantity(); i++) {
                    String vartype = "";

                    if (dataTable.getDataVariables().get(i).isIntervalContinuous()) {
                        vartype = "numeric-continuous";
                    } else {
                        if (dataTable.getDataVariables().get(i).isTypeNumeric()) {
                            vartype = "numeric-discrete";
                        } else {
                            vartype = "character";
                        }
                    }

                    System.out.print("VAR" + i + " ");
                    System.out.print(dataTable.getDataVariables().get(i).getName() + " ");
                    System.out.print(vartype + " ");
                    System.out.print(dataTable.getDataVariables().get(i).getUnf());
                    System.out.println();

                }

            } else {
                System.err.println("Ingest failed to produce tab file or data table for file " + file + ".");
                System.exit(1);
            }
        } else {
            System.err.println("Ingest resulted in a null tabDataIngest object for file " + file + ".");
            System.exit(1);
        }
    } catch (IOException ex) {
        System.err.println("Caught an exception trying to save ingested data for file " + file + ".");
        System.exit(1);
    }

}