Example usage for java.net URL getFile

List of usage examples for java.net URL getFile

Introduction

In this page you can find the example usage for java.net URL getFile.

Prototype

public String getFile() 

Source Link

Document

Gets the file name of this URL .

Usage

From source file:com.github.rwhogg.git_vcr.App.java

/**
 * main is the entry point for Git-VCR/*  w  w  w.  j a va  2s.co m*/
 * @param args Command-line arguments
 */
public static void main(String[] args) {
    Options options = parseCommandLine(args);

    HierarchicalINIConfiguration configuration = null;
    try {
        configuration = getConfiguration();
    } catch (ConfigurationException e) {
        Util.error("could not parse configuration file!");
    }

    // verify we are in a git folder and then construct the repo
    final File currentFolder = new File(".");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository localRepo = null;
    try {
        localRepo = builder.findGitDir().build();
    } catch (IOException e) {
        Util.error("not in a Git folder!");
    }

    // deal with submodules
    assert localRepo != null;
    if (localRepo.isBare()) {
        FileRepositoryBuilder parentBuilder = new FileRepositoryBuilder();
        Repository parentRepo;
        try {
            parentRepo = parentBuilder.setGitDir(new File("..")).findGitDir().build();
            localRepo = SubmoduleWalk.getSubmoduleRepository(parentRepo, currentFolder.getName());
        } catch (IOException e) {
            Util.error("could not find parent of submodule!");
        }
    }

    // if we need to retrieve the patch file, get it now
    URL patchUrl = options.getPatchUrl();
    String patchPath = patchUrl.getFile();
    File patchFile = null;
    HttpUrl httpUrl = HttpUrl.get(patchUrl);
    if (httpUrl != null) {
        try {
            patchFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".diff");
            Request request = new Request.Builder().url(httpUrl).build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (!response.isSuccessful()) {
                Util.error("could not retrieve diff file from URL " + patchUrl);
            }
            String content = body.string();
            org.apache.commons.io.FileUtils.write(patchFile, content, (Charset) null);
        } catch (IOException ie) {
            Util.error("could not retrieve diff file from URL " + patchUrl);
        }
    } else {
        patchFile = new File(patchPath);
    }

    // find the patch
    //noinspection ConstantConditions
    if (!patchFile.canRead()) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is not readable!");
    }

    final Git git = new Git(localRepo);

    // handle the branch
    String branchName = options.getBranchName();
    String theOldCommit = null;
    try {
        theOldCommit = localRepo.getBranch();
    } catch (IOException e2) {
        Util.error("could not get reference to current branch!");
    }
    final String oldCommit = theOldCommit; // needed to reference from shutdown hook

    if (branchName != null) {
        // switch to the branch
        try {
            git.checkout().setName(branchName).call();
        } catch (RefAlreadyExistsException e) {
            // FIXME Auto-generated catch block
            e.printStackTrace();
        } catch (RefNotFoundException e) {
            Util.error("the branch " + branchName + " was not found!");
        } catch (InvalidRefNameException e) {
            Util.error("the branch name " + branchName + " is invalid!");
        } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
            Util.error("there was a checkout conflict!");
        } catch (GitAPIException e) {
            Util.error("there was an unspecified Git API failure!");
        }
    }

    // ensure there are no changes before we apply the patch
    try {
        if (!git.status().call().isClean()) {
            Util.error("cannot run git-vcr while there are uncommitted changes!");
        }
    } catch (NoWorkTreeException e1) {
        // won't happen
        assert false;
    } catch (GitAPIException e1) {
        Util.error("call to git status failed!");
    }

    // list all the files changed
    String patchName = patchFile.getName();
    Patch patch = new Patch();
    try {
        patch.parse(new FileInputStream(patchFile));
    } catch (FileNotFoundException e) {
        assert false;
    } catch (IOException e) {
        Util.error("could not parse the patch file!");
    }

    ReviewResults oldResults = new ReviewResults(patchName, patch, configuration, false);
    try {
        oldResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // we're about to change the repo, so register a shutdown hook to clean it up
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            cleanupGit(git, oldCommit);
        }
    });

    // apply the patch
    try {
        git.apply().setPatch(new FileInputStream(patchFile)).call();
    } catch (PatchFormatException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " is malformatted!");
    } catch (PatchApplyException e) {
        Util.error("patch file " + patchFile.getAbsolutePath() + " did not apply correctly!");
    } catch (FileNotFoundException e) {
        assert false;
    } catch (GitAPIException e) {
        Util.error(e.getLocalizedMessage());
    }

    ReviewResults newResults = new ReviewResults(patchName, patch, configuration, true);
    try {
        newResults.review();
    } catch (InstantiationException e1) {
        Util.error("could not instantiate a review tool class!");
    } catch (IllegalAccessException e1) {
        Util.error("illegal access to a class");
    } catch (ClassNotFoundException e1) {
        Util.error("could not find a review tool class");
    } catch (ReviewFailedException e1) {
        e1.printStackTrace();
        Util.error("Review failed!");
    }

    // generate and show the report
    VelocityReport report = new VelocityReport(patch, oldResults, newResults);
    File reportFile = null;
    try {
        reportFile = com.twitter.common.io.FileUtils.SYSTEM_TMP.createFile(".html");
        org.apache.commons.io.FileUtils.write(reportFile, report.toString(), (String) null);
    } catch (IOException e) {
        Util.error("could not generate the results page!");
    }

    try {
        assert reportFile != null;
        Desktop.getDesktop().open(reportFile);
    } catch (IOException e) {
        Util.error("could not open the results page!");
    }
}

From source file:ch.sdi.core.impl.ftp.FTPClientExample.java

public static void main(String[] aArgs) throws UnknownHostException {
    List<String> args = new ArrayList<String>(Arrays.asList(aArgs));

    args.add("-s"); // store file on sesrver
    args.add("-b"); // binary transfer mode
    args.add("-#");

    args.add("192.168.99.1");
    args.add("heri"); // user
    args.add("heri"); // pw
    args.add("/var/www/log4j2.xml");

    URL url = ClassLoader.getSystemResource("sdimain_test.properties");
    // URL url = ClassLoader.getSystemResource( "log4j2.xml" );
    args.add(url.getFile());

    FTPClientExample example = new FTPClientExample();
    try {/*from w  ww . j  a va  2 s  .  c  om*/
        example.init(args.toArray(new String[args.size()]));
        example.run();
    } catch (Throwable t) {
        myLog.error("Exception caught", t);
        myLog.info(USAGE);
        System.exit(1);
    }

}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();//  w w w .  jav a 2  s  .c  o  m
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:MainClass.java

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

    URL u = new URL("http://www.java2s.com/binary.dat");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
        throw new IOException("This is not a binary file.");
    }//from   w  ww  . j a  v a  2s . com
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
        bytesRead = in.read(data, offset, data.length - offset);
        if (bytesRead == -1)
            break;
        offset += bytesRead;
    }
    in.close();

    if (offset != contentLength) {
        throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    }

    String filename = u.getFile().substring(filename.lastIndexOf('/') + 1);
    FileOutputStream out = new FileOutputStream(filename);
    out.write(data);
    out.flush();
    out.close();
}

From source file:Main.java

public static String getFileName(URL url) {
    File f = new File(url.getFile());
    return f.getName();
}

From source file:Main.java

public static String makeGETrequest(String url) throws MalformedURLException {
    String result = "";
    URL requestURL = new URL(url);
    result += "GET " + requestURL.getFile() + " HTTP/1.1";
    result += NEWLINE;/*from  ww  w  .  j  a v  a 2 s.c om*/
    result += "Host: " + requestURL.getHost() + ":" + (requestURL.getPort() > 0 ? requestURL.getPort() : 80);
    result += NEWLINE;
    result += "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
    result += NEWLINE;
    result += "Connection: close";
    result += NEWLINE;
    result += NEWLINE;

    return result;
}

From source file:com.base2.kagura.services.camel.utils.TestUtils.java

public static String getResourcePath(String path) {
    URL dir_url = ClassLoader.getSystemResource(path);
    return dir_url.getFile();
}

From source file:javarestart.WebClassLoaderRegistry.java

private static URL normalizeURL(URL url) {
    try {/*from  www  . j  a  va 2  s  .c o  m*/
        return url.getFile().endsWith("/") ? url : new URL(url.toExternalForm() + "/");
    } catch (MalformedURLException e) {
        return url;
    }
}

From source file:eu.seaclouds.platform.dashboard.utils.TestUtils.java

public static String getStringFromPath(String filePath) throws IOException {
    URL resource = Resources.getResource(filePath);
    return FileUtils.readFileToString(new File(resource.getFile()));
}

From source file:Main.java

private static List<Class> getClasses(String packageName) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = null;
    try {/*from w  w w  .j  ava 2  s .  c om*/
        resources = classLoader.getResources(path);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    List<File> dirs = new ArrayList<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class> classes = new ArrayList<Class>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes;
}