Example usage for java.io File toURI

List of usage examples for java.io File toURI

Introduction

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

Prototype

public URI toURI() 

Source Link

Document

Constructs a file: URI that represents this abstract pathname.

Usage

From source file:me.rgcjonas.portableMinecraftLauncher.Main.java

/**
 * entry point//from ww w  .  j a va  2  s .c  o m
 * @param args
 */
public static void main(String[] args) {
    File workDir = getWorkingDirectory();

    //ensure the working directory exists
    if (!workDir.exists()) {
        workDir.mkdir();
    }
    File launcherJar = new File(workDir, "launcher.jar");

    //download launcher if it doesn't exist
    if (!launcherJar.exists()) {
        try {
            URL launcherurl = new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar");
            FileUtils.copyURLToFile(launcherurl, launcherJar);
        } catch (IOException e) {
            // shouldn't happen
            e.printStackTrace();
        }
    }

    URL[] urls;
    try {
        urls = new URL[] { launcherJar.toURI().toURL() };

        //this class loader mustn't be disposed while the launcher is running
        @SuppressWarnings("resource")
        LauncherClassLoader loader = new LauncherClassLoader(urls);

        //run it      
        Class<?> launcherFrame = loader.loadClass("net.minecraft.LauncherFrame");
        launcherFrame.getMethod("main", String[].class).invoke(null, (Object) args);
    } catch (Exception e) {
        // there's nothing we can do in that case but notify the dev
        e.printStackTrace();
    }
}

From source file:com.msd.gin.halyard.tools.HalyardExport.java

/**
 * Main of the HalyardExport//  w w  w .jav  a  2  s  .c  om
 * @param args String command line arguments
 * @throws Exception throws Exception in case of any problem
 */
public static void main(final String args[]) throws Exception {
    if (conf == null)
        conf = new Configuration();
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(
            newOption("q", "sparql_query", "SPARQL tuple or graph query executed to export the data"));
    options.addOption(newOption("t", "target_url",
            "file://<path>/<file_name>.<ext> or hdfs://<path>/<file_name>.<ext> or jdbc:<jdbc_connection>/<table_name>"));
    options.addOption(newOption("p", "property=value", "JDBC connection properties"));
    options.addOption(newOption("l", "driver_classpath", "JDBC driver classpath delimited by ':'"));
    options.addOption(newOption("c", "driver_class", "JDBC driver class name"));
    options.addOption(newOption("r", null, "Trim target table before export (apply for JDBC only)"));
    try {
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardExport.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Export version " + p.getProperty("version", "unknown"));
            return;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ExportException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sqt".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ExportException("Missing mandatory option: " + c);
        }
        for (char c : "sqtlc".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ExportException("Multiple values for option: " + c);
        }
        StatusLog log = new StatusLog() {
            private final Logger l = Logger.getLogger(HalyardExport.class.getName());

            @Override
            public void tick() {
            }

            @Override
            public void logStatus(String status) {
                l.info(status);
            }
        };
        String driverClasspath = cmd.getOptionValue('l');
        URL driverCP[] = null;
        if (driverClasspath != null) {
            String jars[] = driverClasspath.split(":");
            driverCP = new URL[jars.length];
            for (int j = 0; j < jars.length; j++) {
                File f = new File(jars[j]);
                if (!f.isFile())
                    throw new ExportException("Invalid JDBC driver classpath element: " + jars[j]);
                driverCP[j] = f.toURI().toURL();
            }
        }
        export(conf, log, cmd.getOptionValue('s'), cmd.getOptionValue('q'), cmd.getOptionValue('t'),
                cmd.getOptionValue('c'), driverCP, cmd.getOptionValues('p'), cmd.hasOption('r'));
    } catch (RuntimeException exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }
}

From source file:io.mindmaps.migration.csv.Main.java

public static void main(String[] args) {

    String csvFileName = null;//from  w ww  .  j av  a 2 s.co m
    String csvEntityType = null;
    String engineURL = null;
    String graphName = null;

    for (int i = 0; i < args.length; i++) {
        if ("-file".equals(args[i]))
            csvFileName = args[++i];
        else if ("-graph".equals(args[i]))
            graphName = args[++i];
        else if ("-engine".equals(args[i]))
            engineURL = args[++i];
        else if ("-as".equals(args[i])) {
            csvEntityType = args[++i];
        } else if ("csv".equals(args[0])) {
            continue;
        } else
            die("Unknown option " + args[i]);
    }

    if (csvFileName == null) {
        die("Please specify CSV file using the -csv option");
    }
    File csvFile = new File(csvFileName);
    if (!csvFile.exists()) {
        die("Cannot find file: " + csvFileName);
    }
    if (graphName == null) {
        die("Please provide the name of the graph using -graph");
    }
    if (csvEntityType == null) {
        csvEntityType = csvFile.getName().replaceAll("[^A-Za-z0-9]", "_");
    }

    System.out.println("Migrating " + csvFileName + " using MM Engine "
            + (engineURL == null ? "local" : engineURL) + " into graph " + graphName);

    // perform migration
    CSVSchemaMigrator schemaMigrator = new CSVSchemaMigrator();
    CSVDataMigrator dataMigrator = new CSVDataMigrator();

    //
    try {
        MindmapsGraph graph = engineURL == null ? MindmapsClient.getGraph(graphName)
                : MindmapsClient.getGraph(graphName, engineURL);

        Loader loader = engineURL == null ? new BlockingLoader(graphName)
                : new DistributedLoader(graphName, Lists.newArrayList(engineURL));

        CSVParser csvParser = CSVParser.parse(csvFile.toURI().toURL(), StandardCharsets.UTF_8,
                CSVFormat.DEFAULT.withHeader());

        schemaMigrator.graph(graph).configure(csvEntityType, csvParser).migrate(loader);

        System.out.println("Schema migration successful");

        dataMigrator.graph(graph).configure(csvEntityType, csvParser).migrate(loader);

        System.out.println("DataType migration successful");

    } catch (Throwable throwable) {
        throwable.printStackTrace(System.err);
    }

    System.exit(0);
}

From source file:de.huxhorn.lilith.Lilith.java

public static void main(String[] args) {
    {/*from   ww w. j  av a  2s. c o m*/
        // initialize java.util.logging to use slf4j...
        Handler handler = new Slf4JHandler();
        java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
        rootLogger.addHandler(handler);
        rootLogger.setLevel(java.util.logging.Level.WARNING);
    }

    StringBuilder appTitle = new StringBuilder();
    appTitle.append(APP_NAME).append(" V").append(APP_VERSION);
    if (APP_SNAPSHOT) {
        // always append timestamp for SNAPSHOT
        appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")");
    }

    CommandLineArgs cl = new CommandLineArgs();
    JCommander commander = new JCommander(cl);
    Cat cat = new Cat();
    commander.addCommand(Cat.NAME, cat);
    Tail tail = new Tail();
    commander.addCommand(Tail.NAME, tail);
    Filter filter = new Filter();
    commander.addCommand(Filter.NAME, filter);
    Index index = new Index();
    commander.addCommand(Index.NAME, index);
    Md5 md5 = new Md5();
    commander.addCommand(Md5.NAME, md5);
    Help help = new Help();
    commander.addCommand(Help.NAME, help);

    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        printAppInfo(appTitle.toString(), false);
        System.out.println(ex.getMessage() + "\n");
        printHelp(commander);
        System.exit(-1);
    }
    if (cl.verbose) {
        if (!APP_SNAPSHOT) {
            // timestamp is always appended for SNAPSHOT
            // don't append it twice
            appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")");
        }
        appTitle.append(" - ").append(APP_REVISION);
    }

    String appTitleString = appTitle.toString();
    if (cl.showHelp) {
        printAppInfo(appTitleString, false);
        printHelp(commander);
        System.exit(0);
    }

    String command = commander.getParsedCommand();
    if (!Tail.NAME.equals(command) && !Cat.NAME.equals(command) && !Filter.NAME.equals(command)) // don't print info in case of cat, tail or filter
    {
        printAppInfo(appTitleString, true);
    }

    if (cl.logbackConfig != null) {
        File logbackFile = new File(cl.logbackConfig);
        if (!logbackFile.isFile()) {
            System.out.println(logbackFile.getAbsolutePath() + " is not a valid file.");
            System.exit(-1);
        }
        try {
            initLogbackConfig(logbackFile.toURI().toURL());
        } catch (MalformedURLException e) {
            System.out.println("Failed to convert " + logbackFile.getAbsolutePath() + " to URL. " + e);
            System.exit(-1);
        }
    } else if (cl.verbose) {
        initVerboseLogging();
    }

    if (cl.printBuildTimestamp) {
        System.out.println("Build-Date     : " + APP_TIMESTAMP_DATE);
        System.out.println("Build-Revision : " + APP_REVISION);
        System.out.println("Build-Timestamp: " + APP_TIMESTAMP);
        System.exit(0);
    }

    if (Help.NAME.equals(command)) {
        commander.usage();
        if (help.commands == null || help.commands.size() == 0) {
            commander.usage(Help.NAME);
        } else {
            Map<String, JCommander> commands = commander.getCommands();
            for (String current : help.commands) {
                if (commands.containsKey(current)) {
                    commander.usage(current);
                } else {
                    System.out.println("Unknown command '" + current + "'!");
                }
            }
        }
        System.exit(0);
    }

    if (Md5.NAME.equals(command)) {
        List<String> files = md5.files;
        if (files == null || files.isEmpty()) {
            printHelp(commander);
            System.out.println("Missing files!");
            System.exit(-1);
        }
        boolean error = false;
        for (String current : files) {
            if (!CreateMd5Command.createMd5(new File(current))) {
                error = true;
            }
        }
        if (error) {
            System.exit(-1);
        }
        System.exit(0);
    }

    if (Index.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        List<String> files = index.files;
        if (files == null || files.size() == 0) {
            printHelp(commander);
            System.exit(-1);
        }
        boolean error = false;
        for (String current : files) {
            if (!IndexCommand.indexLogFile(new File(current))) {
                error = true;
            }
        }
        if (error) {
            System.exit(-1);
        }
        System.exit(0);
    }

    if (Cat.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        List<String> files = cat.files;
        if (files == null || files.size() != 1) {
            printHelp(commander);
            System.exit(-1);
        }
        if (CatCommand.catFile(new File(files.get(0)), cat.pattern, cat.numberOfLines)) {
            System.exit(0);
        }
        System.exit(-1);
    }

    if (Tail.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        List<String> files = tail.files;
        if (files == null || files.size() != 1) {
            printHelp(commander);
            System.exit(-1);
        }
        if (TailCommand.tailFile(new File(files.get(0)), tail.pattern, tail.numberOfLines, tail.keepRunning)) {
            System.exit(0);
        }
        System.exit(-1);
    }

    if (Filter.NAME.equals(command)) {
        if (!cl.verbose && cl.logbackConfig == null) {
            initCLILogging();
        }
        if (FilterCommand.filterFile(new File(filter.input), new File(filter.output),
                new File(filter.condition), filter.searchString, filter.pattern, filter.overwrite,
                filter.keepRunning, filter.exclusive)) {
            System.exit(0);
        }
        System.exit(-1);
    }

    if (cl.flushPreferences) {
        flushPreferences();
    }

    if (cl.exportPreferencesFile != null) {
        exportPreferences(cl.exportPreferencesFile);
    }

    if (cl.importPreferencesFile != null) {
        importPreferences(cl.importPreferencesFile);
    }

    if (cl.exportPreferencesFile != null || cl.importPreferencesFile != null) {
        System.exit(0);
    }

    if (cl.flushLicensed) {
        flushLicensed();
    }

    startLilith(appTitleString);
}

From source file:at.co.malli.relpm.RelPM.java

/**
 * @param args the command line arguments
 */// w w w.j a  va  2  s.c  o  m
public static void main(String[] args) {
    //<editor-fold defaultstate="collapsed" desc=" Create config & log directory ">
    String userHome = System.getProperty("user.home");
    File relPm = new File(userHome + "/.RelPM");
    if (!relPm.exists()) {
        boolean worked = relPm.mkdir();
        if (!worked) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not create directory "
                    + relPm.getAbsolutePath() + " to store user-settings and logs"));
            System.exit(-1);
        }
    }
    File userConfig = new File(relPm.getAbsolutePath() + "/RelPM-userconfig.xml"); //should be created...
    if (!userConfig.exists()) {
        try {
            URL resource = RelPM.class.getResource("/at/co/malli/relpm/RelPM-defaults.xml");
            FileUtils.copyURLToFile(resource, userConfig);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not copy default config. Reason:\n"
                    + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    if (!userConfig.canWrite() || !userConfig.canRead()) {
        ExceptionDisplayer.showErrorMessage(new Exception(
                "Can not read or write " + userConfig.getAbsolutePath() + "to store user-settings"));
        System.exit(-1);
    }
    if (System.getProperty("os.name").toLowerCase().contains("win")) {
        Path relPmPath = Paths.get(relPm.toURI());
        try {
            Files.setAttribute(relPmPath, "dos:hidden", true);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not set " + relPm.getAbsolutePath()
                    + " hidden. " + "Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    //</editor-fold>

    logger.trace("Environment setup sucessfull");

    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code ">
    try {
        String wantedLookAndFeel = SettingsProvider.getInstance().getString("gui.lookAndFeel");
        UIManager.LookAndFeelInfo[] installed = UIManager.getInstalledLookAndFeels();
        boolean found = false;
        for (UIManager.LookAndFeelInfo info : installed) {
            if (info.getClassName().equals(wantedLookAndFeel))
                found = true;
        }
        if (found)
            UIManager.setLookAndFeel(wantedLookAndFeel);
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (InstantiationException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (IllegalAccessException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Add GUI start to awt EventQue ">
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainGUI().setVisible(true);
        }
    });
    //</editor-fold>
}

From source file:de.prozesskraft.pkraft.Perlcode.java

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

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

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

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

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

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription(
            "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.")
            //            .isRequired()
            .create("step");

    Option ooutput = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory for generated files. must not exist when calling.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    Option onolist = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.")
            //            .isRequired()
            .create("nolist");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ostep);
    options.addOption(ooutput);
    options.addOption(odefinition);
    options.addOption(onolist);

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

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

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

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

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

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

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

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

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File outputDir = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin");
    java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib");
    boolean nolist = false;
    if (commandline.hasOption("nolist")) {
        nolist = true;
    }

    if (outputDir.exists()) {
        System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath());
        exiter();
    } else {
        outputDir.mkdir();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));
    Process p2 = null;
    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // perlcode generieren fuer einen bestimmten step
    if (commandline.hasOption("step")) {
        outputDirBin.mkdir();
        String stepname = commandline.getOptionValue("step");
        writeStepAsPerlcode(p2, stepname, outputDirBin, nolist);
    }

    // perlcode generieren fuer den gesamten process
    else {
        outputDirBin.mkdir();
        writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist);

        // copy all perllibs from the lib directory
        outputDirLib.mkdir();
        final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib");
        final Path target = Paths.get(outputDirLib.toURI());

        copyDirectoryTree.copyDirectoryTree(source, target);
    }
}

From source file:Main.java

private static String relativize(File base, File absolute) {
    String relative = base.toURI().relativize(absolute.toURI()).getPath();
    return relative;
}

From source file:Main.java

public static URL toUrl(File file) {
    try {/*from  ww  w.  j  a v a  2 s  .  c o  m*/
        return file.toURI().toURL();
    } catch (final MalformedURLException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:Main.java

/**
 * Returns an URL for the given local file.
 *//* w w  w .j  a v a  2s. co m*/
public static String getFileUrl(String localFileName) {
    File file = new File(localFileName);
    return file.toURI().toString();
}

From source file:net.erdfelt.android.sdkfido.util.PathUtil.java

public static String toRelativePath(File basedir, File destpath) {
    URI baseuri = basedir.toURI();
    URI otheruri = destpath.toURI();
    URI reluri = baseuri.relativize(otheruri);
    return FilenameUtils.separatorsToSystem(reluri.toASCIIString());
}