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:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static KeyStore loadPKCS12File(final String pathToP12, final String password) throws IOException,
        NoSuchAlgorithmException, CertificateException, KeyStoreException, NoSuchProviderException {
    addBCProvider();//from   w  ww  .  j  ava 2  s  . c  o  m
    KeyStore keystore = KeyStore.getInstance("PKCS12");

    File p12File = new File(pathToP12);
    if (!p12File.exists()) {
        // try loading it from the classpath
        URL localP12File = PKSigningUtil.class.getClassLoader().getResource(pathToP12);
        if (localP12File == null) {
            throw new FileNotFoundException("File at " + pathToP12 + " not found");
        }
        p12File = new File(localP12File.getFile());
    }
    InputStream streamOfFile = new FileInputStream(p12File);

    keystore.load(streamOfFile, password.toCharArray());
    IOUtils.closeQuietly(streamOfFile);
    return keystore;
}

From source file:io.cloudine.rhq.plugins.worker.ResourceUtils.java

/**
 *  ?  ? ? {@link java.io.File} .//  ww  w .j a va  2s .co  m
 *
 * @param resourceUrl ? 
 * @param description ?  ?  (; ?  )
 * @return ?? {@link java.io.File} ?
 * @throws java.io.FileNotFoundException ?? ?   
 */
@SuppressWarnings({ "deprecation" })
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
    if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
        String message = MessageFormatter
                .format("'{}' is not absolute path because does not exists.", description, resourceUrl)
                .getMessage();
        throw new FileNotFoundException(message);
    }
    return new File(URLDecoder.decode(resourceUrl.getFile()));
}

From source file:autoupdater.DownloadLatestZipFromRepo.java

/**
 * @param artifactURL the url of the artifact, if the url is the actual file archive(zip,tar.gz or jar) to download it will just download,
 * otherwise it will try to first retrieve artifactid-versionnumber.zip/tar.gz
 * and lastly try to retrieve artifactid-versionnumber.jar
 * @return the downloaded file/*w w w  .  jav  a  2  s.c om*/
 * @throws java.io.FileNotFoundException if there is not file to download at the url location
 */
public static File downloadJarFile(URL artifactURL, File destination) throws IOException {

    URL archiveURL;

    // get the archive url
    String folderName;
    if (artifactURL.getPath().contains(".zip")) {
        archiveURL = WebDAO.getUrlOfZippedVersion(artifactURL, ".zip", false);
        folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"),
                archiveURL.getFile().lastIndexOf(".zip"));
    } else {
        archiveURL = WebDAO.getUrlOfZippedVersion(artifactURL, ".tar.gz", false);
        if (archiveURL != null) {
            folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"),
                    archiveURL.getFile().lastIndexOf(".tar.gz"));
        }
    }

    // special fix for tools with separate versions for windows and unix, you don't do special fixes in a generic library
    /*
            if (folderName.endsWith("-windows")) {
    folderName = folderName.substring(0, folderName.indexOf("-windows"));
            } else if (folderName.endsWith("-mac_and_linux")) {
    folderName = folderName.substring(0, folderName.indexOf("-mac_and_linux"));
            }
    */

    if (!destination.exists()) {
        if (!destination.mkdirs()) {
            throw new IOException("could not make the directories needed to download the file in");
        }
    }

    // create an empty dummy file so that progress can be monitored
    downloadedFile = new File(destination,
            archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/")));

    // download and unzip the file
    downloadedFile = fileDAO.writeStreamToDisk(archiveURL.openStream(),
            archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/")), destination);
    return downloadedFile;
}

From source file:net.ontopia.topicmaps.entry.XMLConfigSource.java

/**
 * INTERNAL://from  ww  w.j av a 2  s. com
 */
public static TopicMapRepositoryIF getRepositoryFromClassPath(String resourceName,
        Map<String, String> environ) {

    // look up configuration via classpath
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource(resourceName);
    if (url == null)
        throw new OntopiaRuntimeException("Could not find resource '" + resourceName + "' on CLASSPATH.");

    // build configuration environment
    if (environ == null)
        environ = new HashMap<String, String>(1);
    if ("file".equals(url.getProtocol())) {
        String file = url.getFile();
        environ.put(CWD, file.substring(0, file.lastIndexOf('/')));
    } else
        environ.put(CWD, ".");

    // read configuration and create the repository instance
    try {
        return createRepository(readSources(new InputSource(url.openStream()), environ));
    } catch (IOException e) {
        throw new OntopiaRuntimeException(e);
    }

}

From source file:autoupdater.DownloadLatestZipFromRepo.java

/**
 * Aggregation method for downloading and unzipping.
 *
 * @param mavenJarFile the maven jar file to download update for
 * @return the downloaded {@code MavenJarFile}
 * @throws MalformedURLException/*from   w w  w  .  j a  va 2  s. c  o  m*/
 * @throws IOException
 * @throws XMLStreamException
 */
private static MavenJarFile downloadAndUnzipJar(MavenJarFile mavenJarFile)
        throws MalformedURLException, IOException, XMLStreamException {
    boolean isWindows = false;

    if (System.getProperty("os.name").toLowerCase(new Locale("en")).contains("win")) {
        isWindows = true;
    }
    URL archiveURL;
    String folderName;

    // get the archive url
    if (isWindows) {
        archiveURL = WebDAO.getUrlOfZippedVersion(downloadURL, ".zip", false);
        folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"),
                archiveURL.getFile().lastIndexOf(".zip"));
    } else {
        archiveURL = WebDAO.getUrlOfZippedVersion(downloadURL, ".tar.gz", false);
        if (archiveURL != null) {
            folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"),
                    archiveURL.getFile().lastIndexOf(".tar.gz"));
        } else {
            archiveURL = WebDAO.getUrlOfZippedVersion(downloadURL, ".zip", false);
            folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"),
                    archiveURL.getFile().lastIndexOf(".zip"));
            isWindows = true; // zip file, handling is same as for windows
        }
    }

    // special fix for tools with separate versions for windows and unix
    if (folderName.endsWith("-windows")) {
        folderName = folderName.substring(0, folderName.indexOf("-windows"));
    } else if (folderName.endsWith("-mac_and_linux")) {
        folderName = folderName.substring(0, folderName.indexOf("-mac_and_linux"));
    }

    // set up the folder to save the new download in
    File downloadFolder;
    if (isWindows) {
        downloadFolder = new File(
                fileDAO.getLocationToDownloadOnDisk(new File(mavenJarFile.getAbsoluteFilePath()).getParent()),
                folderName);
    } else {
        downloadFolder = fileDAO
                .getLocationToDownloadOnDisk(new File(mavenJarFile.getAbsoluteFilePath()).getParent());
    }
    if (!downloadFolder.exists()) {
        if (!downloadFolder.mkdirs()) {
            throw new IOException("could not make the directories needed to download the file in");
        }
    }

    // create an empty dummy file so that progress can be monitored
    downloadedFile = new File(downloadFolder,
            archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/")));

    // download and unzip the file
    if (isWindows) {
        downloadedFile = fileDAO.writeStreamToDisk(archiveURL.openStream(),
                archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/")), downloadFolder);
        fileDAO.unzipFile(new ZipFile(downloadedFile), downloadFolder.getParentFile());
    } else {
        fileDAO.unGzipAndUntarFile(new GZIPInputStream(archiveURL.openStream()), downloadedFile);
    }

    // get the new jar file
    MavenJarFile newMavenJar;
    if (isWindows) {
        newMavenJar = fileDAO.getMavenJarFileFromFolderWithArtifactId(downloadFolder,
                mavenJarFile.getArtifactId());
    } else {
        newMavenJar = fileDAO.getMavenJarFileFromFolderWithArtifactId(new File(downloadFolder, folderName),
                mavenJarFile.getArtifactId());
    }

    // delete the downloaded zip file
    if (deletePreviousVersion) {
        if (!downloadedFile.delete()) {
            throw new IOException("could not delete the zip file");
        }
    }

    return newMavenJar;
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static X509Certificate loadDERCertificate(final String filePath)
        throws IOException, CertificateException {
    FileInputStream certificateFileInputStream = null;
    try {//from   w ww  . j  a  v a 2  s. co m
        File certFile = new File(filePath);
        if (!certFile.exists()) {
            // try loading it from the classpath
            URL localCertFile = PKSigningUtil.class.getClassLoader().getResource(filePath);
            if (localCertFile == null) {
                throw new FileNotFoundException("File at " + filePath + " not found");
            }
            certFile = new File(localCertFile.getFile());
        }
        certificateFileInputStream = new FileInputStream(certFile);

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        Certificate certificate = certificateFactory.generateCertificate(certificateFileInputStream);
        if (certificate instanceof X509Certificate) {
            return (X509Certificate) certificate;
        }
        throw new IOException("The key from '" + filePath + "' could not be decrypted");
    } catch (IOException ex) {
        throw new IOException("The key from '" + filePath + "' could not be decrypted", ex);
    } catch (NoSuchProviderException ex) {
        throw new IOException("The key from '" + filePath + "' could not be decrypted", ex);
    } finally {
        IOUtils.closeQuietly(certificateFileInputStream);
    }
}

From source file:com.surenpi.autotest.suite.SuiteRunnerLauncher.java

/**
 * ??//from   www.j  av a 2  s  .co  m
 * @param param
 */
private static void compile(RunnerParam param) {
    URL itemUrl = SuiteRunnerLauncher.class.getResource("/");
    if (itemUrl == null) {
        logger.warn("Can not get base url from root. Try use current dir.");

        try {
            itemUrl = new File(".").toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    logger.debug("Base url : {}", itemUrl);

    String protocol = itemUrl.getProtocol();
    if ("file".equals(protocol)) {
        String file = itemUrl.getFile();
        File[] subFiles = new File(file).listFiles(new PageXmlFilter());

        Generator generator = new DefaultXmlCodeGenerator() {
            @Override
            protected void done() {
                super.done();
            }
        };

        for (File pageFile : subFiles) {
            generator.generate(pageFile.getName(), param.compileDstDir);
        }

        JDTUtils utils = new JDTUtils(param.compileDstDir);
        utils.compileAllFile();

        try {
            logger.info("Compile dest dir: {}.", new File(param.compileDstDir).getAbsolutePath());

            ClassLoader loader = new URLClassLoader(
                    new URL[] { new File(param.compileDstDir).toURI().toURL() }) {
                @Override
                protected Class<?> findClass(String s) throws ClassNotFoundException {
                    return super.findClass(s);
                }
            };

            Thread.currentThread().setContextClassLoader(loader);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.alpharogroup.resourcebundle.properties.PropertiesExtensions.java

/**
 * Load the properties file from the given class object. The filename from the properties file
 * is the same as the simple name from the class object and it looks at the same path as the
 * given class object. If locale is not null than the language will be added to the filename
 * from the properties file./*from   ww  w. j  ava  2  s  . co m*/
 *
 * @param clazz
 *            the clazz
 * @param locale
 *            the locale
 * @return the properties
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Properties loadPropertiesFromClassObject(final Class<?> clazz, final Locale locale)
        throws IOException {
    if (null == clazz) {
        throw new IllegalArgumentException("Class object must not be null!!!");
    }
    StringBuilder propertiesName = new StringBuilder();
    Properties properties = null;
    String language = null;
    String filename = null;
    String pathAndFilename = null;
    File propertiesFile = null;
    String absoluteFilename = null;
    final String packagePath = PackageExtensions.getPackagePathWithSlash(clazz);
    final List<String> missedFiles = new ArrayList<>();
    if (null != locale) {
        propertiesName.append(clazz.getSimpleName());
        language = locale.getLanguage();
        if ((null != language) && !language.isEmpty()) {
            propertiesName.append("_").append(language);
        }

        final String country = locale.getCountry();
        if ((null != country) && !country.isEmpty()) {
            propertiesName.append("_").append(country);
        }
        propertiesName.append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassExtensions.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }

        if ((null != propertiesFile) && propertiesFile.exists()) {
            properties = PropertiesExtensions.loadProperties(pathAndFilename);
        } else {
            propertiesName = new StringBuilder();
            if (null != locale) {
                propertiesName.append(clazz.getSimpleName());
                language = locale.getLanguage();
                if ((null != language) && !language.isEmpty()) {
                    propertiesName.append("_").append(language);
                }
                propertiesName.append(FileExtension.PROPERTIES.getExtension());
                filename = propertiesName.toString().trim();
                pathAndFilename = packagePath + filename;
                url = ClassExtensions.getResource(clazz, filename);

                if (url != null) {
                    absoluteFilename = url.getFile();
                } else {
                    missedFiles.add("File with filename '" + filename + "' does not exists.");
                }
                if (null != absoluteFilename) {
                    propertiesFile = new File(absoluteFilename);
                }
                if ((null != propertiesFile) && propertiesFile.exists()) {
                    properties = PropertiesExtensions.loadProperties(pathAndFilename);
                }
            }
        }
    }

    if (null == properties) {
        propertiesName = new StringBuilder();
        propertiesName.append(clazz.getSimpleName()).append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        final URL url = ClassExtensions.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            properties = PropertiesExtensions.loadProperties(pathAndFilename);
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }
        if ((null != propertiesFile) && propertiesFile.exists()) {
            properties = PropertiesExtensions.loadProperties(pathAndFilename);
        }
    }
    if (properties == null) {
        for (final String string : missedFiles) {
            LOGGER.info(string);
        }
    }

    return properties;
}

From source file:com.cloud.utils.script.Script.java

public static String findScript(String path, String script) {
    s_logger.debug("Looking for " + script + " in the classpath");

    URL url = ClassLoader.getSystemResource(script);
    s_logger.debug("System resource: " + url);
    File file = null;//from  w ww . j a v a  2  s.  c  om
    if (url != null) {
        file = new File(url.getFile());
        s_logger.debug("Absolute path =  " + file.getAbsolutePath());
        return file.getAbsolutePath();
    }

    if (path == null) {
        s_logger.warn("No search path specified, unable to look for " + script);
        return null;
    }
    path = path.replace("/", File.separator);

    /**
     * Look in WEB-INF/classes of the webapp
     * URI workaround the URL encoding of url.getFile
     */
    if (path.endsWith(File.separator)) {
        url = Script.class.getClassLoader().getResource(path + script);
    } else {
        url = Script.class.getClassLoader().getResource(path + File.separator + script);
    }
    s_logger.debug("Classpath resource: " + url);
    if (url != null) {
        try {
            file = new File(new URI(url.toString()).getPath());
            s_logger.debug("Absolute path =  " + file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (URISyntaxException e) {
            s_logger.warn("Unable to convert " + url.toString() + " to a URI");
        }
    }

    if (path.endsWith(File.separator)) {
        path = path.substring(0, path.lastIndexOf(File.separator));
    }

    if (path.startsWith(File.separator)) {
        // Path given was absolute so we assume the caller knows what they want.
        file = new File(path + File.separator + script);
        return file.exists() ? file.getAbsolutePath() : null;
    }

    s_logger.debug("Looking for " + script);
    String search = null;
    for (int i = 0; i < 3; i++) {
        if (i == 0) {
            String cp = Script.class.getResource(Script.class.getSimpleName() + ".class").toExternalForm();
            int begin = cp.indexOf(File.separator);

            // work around with the inconsistency of java classpath and file separator on Windows 7
            if (begin < 0)
                begin = cp.indexOf('/');

            int endBang = cp.lastIndexOf("!");
            int end = cp.lastIndexOf(File.separator, endBang);
            if (end < 0)
                end = cp.lastIndexOf('/', endBang);
            if (end < 0)
                cp = cp.substring(begin);
            else
                cp = cp.substring(begin, end);

            s_logger.debug("Current binaries reside at " + cp);
            search = cp;
        } else if (i == 1) {
            s_logger.debug("Searching in environment.properties");
            try {
                final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
                if (propsFile == null) {
                    s_logger.debug("environment.properties could not be opened");
                } else {
                    final Properties props = PropertiesUtil.loadFromFile(propsFile);
                    search = props.getProperty("paths.script");
                }
            } catch (IOException e) {
                s_logger.debug("environment.properties could not be opened");
                continue;
            }
            s_logger.debug("environment.properties says scripts should be in " + search);
        } else {
            s_logger.debug("Searching in the current directory");
            search = ".";
        }

        search += File.separatorChar + path + File.separator;
        do {
            search = search.substring(0, search.lastIndexOf(File.separator));
            file = new File(search + File.separator + script);
            s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
        } while (!file.exists() && search.lastIndexOf(File.separator) != -1);

        if (file.exists()) {
            return file.getAbsolutePath();
        }

    }

    search = System.getProperty("paths.script");

    search += File.separatorChar + path + File.separator;
    do {
        search = search.substring(0, search.lastIndexOf(File.separator));
        file = new File(search + File.separator + script);
        s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
    } while (!file.exists() && search.lastIndexOf(File.separator) != -1);

    if (file.exists()) {
        return file.getAbsolutePath();
    }

    s_logger.warn("Unable to find script " + script);
    return null;
}

From source file:net.sourceforge.jaulp.lang.PropertiesUtils.java

/**
 * Load the properties file from the given class object. The filename from the properties file
 * is the same as the simple name from the class object and it looks at the same path as the
 * given class object. If locale is not null than the language will be added to the filename
 * from the properties file.//ww w. j  a  v  a 2  s  .c  om
 * 
 * @param clazz
 *            the clazz
 * @param locale
 *            the locale
 * @return the properties
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Properties loadPropertiesFromClassObject(Class<?> clazz, Locale locale) throws IOException {
    if (null == clazz) {
        throw new IllegalArgumentException("Class object must not be null!!!");
    }
    StringBuilder propertiesName = new StringBuilder();
    Properties properties = null;
    String language = null;
    String filename = null;
    String pathAndFilename = null;
    File propertiesFile = null;
    String absoluteFilename = null;
    String packagePath = PackageUtils.getPackagePathWithSlash(clazz);
    List<String> missedFiles = new ArrayList<>();
    if (null != locale) {
        propertiesName.append(clazz.getSimpleName());
        language = locale.getLanguage();
        if (null != language && !language.isEmpty()) {
            propertiesName.append("_").append(language);
        }

        String country = locale.getCountry();
        if (null != country && !country.isEmpty()) {
            propertiesName.append("_").append(country);
        }
        propertiesName.append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassUtils.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }

        if (null != propertiesFile && propertiesFile.exists()) {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
        } else {
            propertiesName = new StringBuilder();
            if (null != locale) {
                propertiesName.append(clazz.getSimpleName());
                language = locale.getLanguage();
                if (null != language && !language.isEmpty()) {
                    propertiesName.append("_").append(language);
                }
                propertiesName.append(FileExtension.PROPERTIES.getExtension());
                filename = propertiesName.toString().trim();
                pathAndFilename = packagePath + filename;
                url = ClassUtils.getResource(clazz, filename);

                if (url != null) {
                    absoluteFilename = url.getFile();
                } else {
                    missedFiles.add("File with filename '" + filename + "' does not exists.");
                }
                if (null != absoluteFilename) {
                    propertiesFile = new File(absoluteFilename);
                }
                if (null != propertiesFile && propertiesFile.exists()) {
                    properties = PropertiesUtils.loadProperties(pathAndFilename);
                }
            }
        }
    }

    if (null == properties) {
        propertiesName = new StringBuilder();
        propertiesName.append(clazz.getSimpleName()).append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassUtils.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }
        if (null != propertiesFile && propertiesFile.exists()) {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
        }
    }
    if (properties == null) {
        for (String string : missedFiles) {
            LOGGER.info(string);
        }
    }

    return properties;
}