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:Main.java

/**
 * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the
 * UI thread. Android does not allow it.
 *
 * @param urlString Url to the ressource to download.
 * @param file      file to be written to.
 * @param overwrite if file exists, overwrite?
 * @return flase if download was not successful. If successful, true.
 *//*w  w w  .j  a  v a2 s.  c om*/
private static Boolean fileDownloadHttp(String urlString, File file, Boolean overwrite) {
    HashMap<String, String> result = null;
    URL url = null;
    //        File temp;

    try {
        url = new URL(urlString);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(200000);
        urlConnection.connect();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        FileOutputStream outputStream = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        in.close();
        outputStream.close();
        urlConnection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    Log.d(TAG, "File download: " + file.getAbsolutePath() + url.getFile() + "overwrite " + overwrite
            + "exists? " + file.exists());
    return true;
}

From source file:io.neba.core.resourcemodels.factory.ModelFactory.java

private String urlToClassName(URL url) {
    String file = url.getFile();
    final String classFileName = file.substring(1, file.length() - ".class".length());
    return classFileName.replace('/', '.');
}

From source file:atg.tools.dynunit.nucleus.NucleusUtils.java

/**
 * A convenience method for returning the configpath for a test.
 * pConfigDirectory is the top level name to be used for the configpath.
 * Returns a file in the baseConfigDirectory (or baseConfigDirectory +
 * "data") subdirectory of the the passed in class's location.<P>
 * <p/>/*from   w  w w. jav a2  s.c o  m*/
 * The directory location is calculated as (in psuedo-code):
 * <code>
 * (classRelativeTo's package location) + "/" + (pConfigDirectory or "data") + "/config"
 * </code>
 *
 * @param classRelativeTo
 *         the class whose package the config/data
 *         (or baseConfigDirectory/data) should be relative in.
 * @param baseConfigDirectory
 *         the base configuration directory If null,
 *         uses "config".
 * @param createDirectory
 *         whether to create the config/data subdirectory if
 *         it does not exist.
 *
 * @return The calculated configuration path.
 */
public static File getConfigPath(Class classRelativeTo, String baseConfigDirectory, boolean createDirectory) {
    Map<String, File> baseConfigToFile = configPath.get(classRelativeTo);
    if (baseConfigToFile == null) {
        baseConfigToFile = new ConcurrentHashMap<String, File>();
        configPath.put(classRelativeTo, baseConfigToFile);
    }

    File fileFound = baseConfigToFile.get(baseConfigDirectory);

    if (!baseConfigToFile.containsKey(baseConfigDirectory)) {
        String configdirname = "config";
        String packageName = StringUtils.replaceChars(classRelativeTo.getPackage().getName(), '.', '/');
        if (baseConfigDirectory != null) {
            configdirname = baseConfigDirectory;
        }

        String configFolder = packageName + "/data/" + configdirname;
        URL dataURL = classRelativeTo.getClassLoader().getResource(configFolder);

        // Mkdir
        if (dataURL == null) {
            URL root = classRelativeTo.getClassLoader().getResource(packageName);

            File f = null;
            if (root != null) {
                f = new File(root.getFile());
            }
            File f2 = new File(f, "/data/" + configdirname);
            if (createDirectory) {
                f2.mkdirs();
            }
            dataURL = NucleusUtils.class.getClassLoader().getResource(configFolder);
            if (dataURL == null) {
                System.err.println("Warning: Could not find resource \"" + configFolder + "\" in CLASSPATH");
            }
        }
        if (dataURL != null) {// check if this URL is contained within a jar file
            // if so, extract to a temp dir, otherwise just return
            // the directory
            fileFound = extractJarDataURL(dataURL);
            baseConfigToFile.put(baseConfigDirectory, fileFound);
        }
    }
    if (fileFound != null) {
        System.setProperty("atg.configpath", fileFound.getAbsolutePath());
    }
    return fileFound;
}

From source file:co.cask.cdap.security.server.ExternalAuthenticationServerSSLTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    URL certUrl = ExternalAuthenticationServerSSLTest.class.getClassLoader().getResource("cert.jks");
    Assert.assertNotNull(certUrl);//  w  w w  .  j  ava 2  s  .  co  m

    String authHandlerConfigBase = Constants.Security.AUTH_HANDLER_CONFIG_BASE;

    CConfiguration cConf = CConfiguration.create();
    SConfiguration sConf = SConfiguration.create();
    cConf.set(Constants.Security.AUTH_SERVER_BIND_ADDRESS, "127.0.0.1");
    cConf.set(Constants.Security.SSL_ENABLED, "true");
    cConf.set(Constants.Security.AuthenticationServer.SSL_PORT, "0");
    cConf.set(authHandlerConfigBase.concat("useLdaps"), "true");
    cConf.set(authHandlerConfigBase.concat("ldapsVerifyCertificate"), "false");
    sConf.set(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PATH, certUrl.getPath());
    configuration = cConf;
    sConfiguration = sConf;

    String keystorePassword = sConf.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PASSWORD);
    KeyStoreKeyManager keyManager = new KeyStoreKeyManager(certUrl.getFile(), keystorePassword.toCharArray());
    SSLUtil sslUtil = new SSLUtil(keyManager, new TrustAllTrustManager());
    ldapListenerConfig = InMemoryListenerConfig.createLDAPSConfig("LDAP", InetAddress.getByName("127.0.0.1"),
            ldapPort, sslUtil.createSSLServerSocketFactory(), sslUtil.createSSLSocketFactory());

    setup();
}

From source file:org.fuin.owndeb.commons.DebUtils.java

/**
 * Downloads a file from an URL to a file and outputs progress in the log
 * (level 'info') every 1000 bytes.//from  w ww  . jav  a  2s.  c  o m
 * 
 * @param url
 *            URL to download.
 * @param dir
 *            Target directory.
 * @param cookies
 *            Cookies for the request (Format: "name=value").
 */
public static void download(@NotNull final URL url, @NotNull final File dir, final String... cookies) {
    Contract.requireArgNotNull("url", url);
    Contract.requireArgNotNull("dir", dir);

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

    try {
        final Request request = Request.Get(url.toURI());
        if (cookies != null) {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cookies.length; i++) {
                if (i > 0) {
                    sb.append(";");
                }
                sb.append(cookies[i]);
            }
            request.addHeader("Cookie", sb.toString());
        }
        final File file = new File(dir, FilenameUtils.getName(url.getFile()));
        request.execute().saveContent(file);
    } catch (final IOException | URISyntaxException ex) {
        throw new RuntimeException("Error downloading: " + url, ex);
    }
}

From source file:ch.bfh.iam.oauth.init.Config.java

protected void initialize() throws ConfigurationException {
    if (!isInitilized) {
        URL url = Config.class.getResource("/properties/authorization-server.properties");
        config = new PropertiesConfiguration(url.getFile());
        isInitilized = true;//from w ww. j a  v a 2 s  .c  o m
    }
}

From source file:bixo.fetcher.LoggingFetcher.java

private FetchedDatum makeFetchedDatum(String url, String htmlContent, Payload payload)
        throws MalformedURLException, HttpFetchException, UnsupportedEncodingException {
    URL theUrl = new URL(url);
    if (theUrl.getFile().equals("/robots.txt")) {
        throw new HttpFetchException(url, "Never return robots.txt from LoggingFetcher",
                HttpStatus.SC_NOT_FOUND, null);
    }/*from   w  ww . j a v  a  2 s .c  om*/

    byte[] content = htmlContent.getBytes("UTF-8");
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaderNames.CONTENT_LENGTH, "" + content.length);
    headers.add(HttpHeaderNames.CONTENT_TYPE, "text/html");

    // Set the location to a fixed value, so that when we're processing entries from
    // the URL DB that might have been set using fake content, we know to ignore the
    // refetch time if we're doing a real fetch.
    headers.add(HttpHeaderNames.CONTENT_LOCATION, FAKE_CONTENT_LOCATION);
    FetchedDatum result = new FetchedDatum(url, url, System.currentTimeMillis(), headers,
            new ContentBytes(content), "text/html", 100000);
    result.setPayload(payload);
    return result;
}

From source file:eu.delving.sip.TestLuceneSpatial.java

@Test
public void validateList() throws IOException {
    URL url = getClass().getResource("/geo/latlong.txt");
    List<String> lines = FileUtils.readLines(new File(url.getFile()));
    for (String latlong : lines) {
        try {//from  ww  w  .  ja v a 2s  .  com
            DistanceUtils.parseLatitudeLongitude(latlong);
        } catch (InvalidGeoException e) {
            Assert.assertEquals("Unexpected exception", "624.3020535333326,76.0872380450499", latlong);
        }
    }
}

From source file:com.microsoft.azure.hdinsight.common.StreamUtil.java

public static File getResourceFile(String resource) throws IOException {
    File file = null;//from  w w w . j a v a  2 s.  c  o  m
    URL res = streamUtil.getClass().getResource(resource);

    if (res.toString().startsWith("jar:")) {
        InputStream input = null;
        OutputStream out = null;

        try {
            input = streamUtil.getClass().getResourceAsStream(resource);
            file = File.createTempFile(String.valueOf(new Date().getTime()), ".tmp");
            out = new FileOutputStream(file);

            int read;
            byte[] bytes = new byte[1024];

            while ((read = input.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
        } finally {
            if (input != null) {
                input.close();
            }

            if (out != null) {
                out.flush();
                out.close();
            }

            if (file != null) {
                file.deleteOnExit();
            }
        }

    } else {
        file = new File(res.getFile());
    }

    return file;
}

From source file:com.cognifide.cq.cqsm.core.actions.scanner.ClassScanner.java

private String toClassName(URL url) {
    final String f = url.getFile();
    final String cn = f.substring(1, f.length() - ".class".length());
    return cn.replace('/', '.');
}