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:org.fuin.owndeb.commons.DebUtils.java

/**
 * Downloads content from a source URL to a target file. If the target file
 * already exists, nothing happens. The file is first downloaded to the
 * 'temp' directory. If it already exists in that directory, only a local
 * copy is done./*from  ww  w  . ja  v  a 2 s.  c  om*/
 * 
 * @param url
 *            URL to load.
 * @param dir
 *            Target directory
 * @param cookies
 *            Cookies for the request (Format: "name=value").
 * 
 * @return Downloaded file.
 */
public static File cachedDownload(@NotNull final URL url, @NotNull final File dir, final String... cookies) {
    Contract.requireArgNotNull("url", url);
    Contract.requireArgNotNull("dir", dir);

    LOG.info("cachedDownload: {}", url);

    final File targetFile = new File(dir, FilenameUtils.getName(url.getFile()));
    try {
        if (targetFile.exists()) {
            LOG.info("File already exists in target directory: {}", targetFile);
        } else {
            LOG.info("Downloading: {}", url);
            // Cache the file locally in the temporary directory
            final File tmpFile = new File(Utils4J.getTempDir(), targetFile.getName());
            if (!tmpFile.exists()) {
                download(url, Utils4J.getTempDir(), cookies);
                LOG.info("Downloaded to: {}", tmpFile);
            }
            FileUtils.copyFile(tmpFile, targetFile);
            LOG.info("Copied from '{}' to: {}", tmpFile, targetFile);
        }
    } catch (final IOException ex) {
        throw new RuntimeException("Error downloading: " + url, ex);
    }
    return targetFile;

}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Strictly find the file in the plugin. If the file does not exist, an exception is thrown.
 * /*from  ww w  .  j  a  va  2  s. co m*/
 * An alternative to this method is to use FileLocator.openStream, (preferred) or to call FileUtilities.copyToMetadata and then use paths relative to the metadata.
 * 
 * @param bundle
 * @param filename
 * @return File
 * @throws IOException
 * @deprecated use FileLocator.openStream(bundle, new Path(filename), null) instead
 */
@Deprecated
public static File findFileInPluginBundle(Bundle bundle, String filename) throws IOException {
    Path relativePath = new Path(filename);
    URL pluginRelativeURL = FileLocator.find(bundle, relativePath, null);
    if (pluginRelativeURL == null) {
        throw new FileNotFoundException(
                "File not found: " + filename + " in bundle " + bundle.getSymbolicName());
    }
    URL fileURL = FileLocator.resolve(pluginRelativeURL);
    File file = new File(fileURL.getFile());
    if (file.exists()) {
        return file;
    }
    InputStream inputStream = FileLocator.openStream(bundle, relativePath, false);
    if (inputStream == null) {
        throw new FileNotFoundException(
                "File not found: " + filename + " in bundle " + bundle.getSymbolicName());
    }
    file = createTempFile("bundleFile", "");
    FileOutputStream outputStream = new FileOutputStream(file);
    try {
        byte[] buffer = new byte[1024 * 1024];
        while (true) {
            int len = inputStream.read(buffer);
            if (len <= 0) {
                break;
            }
            outputStream.write(buffer, 0, len);
        }
    } finally {
        inputStream.close();
        outputStream.close();
    }
    return file;
}

From source file:net.jcreate.xkins.XkinsLoader.java

/**
 * Agrega el archivo con su time stamp actual
 * @param url/*from  www  . j a  v  a  2s . c  o m*/
 */
public static void addConfigFilesTimeStamp(URL url) {
    File file = new File(url.getFile());
    getConfigFilesTimeStamp().put(file.getPath(), new Long(file.lastModified()));
}

From source file:org.apache.hadoop.gateway.GatewayAppFuncTest.java

public static void setupGateway() throws Exception {

    File targetDir = new File(System.getProperty("user.dir"), "target");
    File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID());
    gatewayDir.mkdirs();/*from  w  ww . j  a v  a 2  s. co  m*/

    config = new GatewayTestConfig();
    config.setGatewayHomeDir(gatewayDir.getAbsolutePath());

    URL svcsFileUrl = TestUtils.getResourceUrl(DAT, "test-svcs/readme.txt");
    File svcsFile = new File(svcsFileUrl.getFile());
    File svcsDir = svcsFile.getParentFile();
    config.setGatewayServicesDir(svcsDir.getAbsolutePath());

    URL appsFileUrl = TestUtils.getResourceUrl(DAT, "test-apps/readme.txt");
    File appsFile = new File(appsFileUrl.getFile());
    File appsDir = appsFile.getParentFile();
    config.setGatewayApplicationsDir(appsDir.getAbsolutePath());

    File topoDir = new File(config.getGatewayTopologyDir());
    topoDir.mkdirs();

    File deployDir = new File(config.getGatewayDeploymentDir());
    deployDir.mkdirs();

    setupMockServers();
    startGatewayServer();
}

From source file:de.alpharogroup.lang.ClassUtils.java

/**
 * Gets the directories from the given path.
 *
 * @param path//from   www . j a  v a  2 s .  com
 *            the path
 * @param isPackage
 *            If the Flag is true than the given path is a package.
 * @return the directories from resources
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static List<File> getDirectoriesFromResources(String path, final boolean isPackage) throws IOException {
    if (isPackage) {
        path = path.replace('.', '/');
    }
    final List<URL> resources = ClassUtils.getResources(path);
    final List<File> dirs = new ArrayList<>();
    for (final URL resource : resources) {
        dirs.add(new File(URLDecoder.decode(resource.getFile(), "UTF-8")));
    }
    return dirs;
}

From source file:HttpTransactionUtils.java

/**
 * Format a base URL string ( protocol://server[:port][/file-specification] )
 * //from  ww  w  .  j a  v  a  2  s  .co m
 * @param url
 *          URL to format
 * @param preserveFile
 *          Keep the /directory/filename portion of the URL?
 * @return URL string
 */
public static String formatUrl(URL url, boolean preserveFile) throws MalformedURLException {
    StringBuilder result;
    int port;

    result = new StringBuilder(url.getProtocol());

    result.append("://");
    result.append(url.getHost());

    if ((port = url.getPort()) != -1) {
        result.append(":");
        result.append(String.valueOf(port));
    }

    if (preserveFile) {
        String file = url.getFile();

        if (file != null) {
            result.append(file);
        }
    }
    return result.toString();
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java

@BeforeClass
public static void runELServer() throws Exception {
    if (runServer) {
        // Build a temporary EL home folder. Copy config files to it.
        File elHome = elHomeFolder.newFolder("dashbuilder-elasticsearch");
        File elHomeConfig = new File(elHome, EL_CONFIG_DIR);
        URL configFileUrl = Thread.currentThread().getContextClassLoader().getResource(EL_CONFIG_ELASTICSEARCH);
        URL loggingFileUrl = Thread.currentThread().getContextClassLoader().getResource(EL_CONFIG_LOGGING);
        File configFile = new File(configFileUrl.getFile());
        File loggingFile = new File(loggingFileUrl.getFile());

        // Create the configuration files and copy config files.
        if (!elHomeConfig.mkdirs())
            throw new RuntimeException(
                    "Cannot create config directory at [" + elHomeConfig.getAbsolutePath() + "].");
        FileUtils.copyFileToDirectory(configFile, elHomeConfig);
        FileUtils.copyFileToDirectory(loggingFile, elHomeConfig);

        // Set the system properties for running the EL server.
        System.setProperty(EL_PROPERTY_ELASTICSEARCH, "");
        System.setProperty(EL_PROPERTY_FOREGROUND, "yes");
        System.setProperty(EL_PROPERTY_HOME, elHome.getAbsolutePath());

        // Run the EL server.
        new Thread("test_ELserver") {
            @Override//w  w  w  .  j av  a  2  s .  co  m
            public void run() {
                super.run();
                Bootstrap.main(new String[] {});
            }
        }.run();
    }

    if (populateServer) {
        // Create the expensereports example index.
        createIndexELServer();

        // Populate the server with some test content.
        populateELServer(EL_EXAMPLE_DATA);

        // Test mappings and document count.
        testMappingCreated();
        testDocumentsCount();

    }
}

From source file:com.izforge.izpack.util.SelfModifier.java

/**
 * Retrieve the jar file the specified class was loaded from.
 *
 * @return null if file was not loaded from a jar file
 * @throws SecurityException if access to is denied by SecurityManager
 *///ww  w.j a v  a  2 s .  co  m
public static File findJarFile(Class<?> clazz) {
    String resource = clazz.getName().replace('.', '/') + ".class";

    URL url = ClassLoader.getSystemResource(resource);
    if (!"jar".equals(url.getProtocol())) {
        return null;
    }

    String path = url.getFile();
    // starts at "file:..." (use getPath() as of 1.3)
    path = path.substring(0, path.lastIndexOf('!'));

    File file;

    // getSystemResource() returns a valid URL (eg. spaces are %20), but a
    // file
    // Constructed w/ it will expect "%20" in path. URI and File(URI)
    // properly
    file = new File(URI.create(path));

    return file;
}

From source file:org.openflamingo.uploader.util.ResourceUtils.java

/**
 *  ?  ? ? {@link java.io.File} ./*from   ww w  .ja  v  a  2 s  .c om*/
 *
 * @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())) {
        throw new FileNotFoundException(description
                + "?  ?  . ? ? ?    : "
                + resourceUrl);
    }
    return new File(URLDecoder.decode(resourceUrl.getFile()));
}

From source file:org.xmlactions.common.io.ResourceUtils.java

/**
 * Gets a URL getFile replacing all %20 characters with spaces
 *///w ww  .j  a  v a2 s  .c o m
public static File getFile(URL resource) {

    return new File(resource.getFile().replace("%20", " "));
}