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:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * //from   w w w .  j  av  a2  s  .co m
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:org.opencastproject.util.IoSupport.java

/**
 * Convenience method to read in a file from either a remote or local source.
 *
 * @param url/*w w w  .ja  v a  2  s  . com*/
 *         The {@code URL} to read the source data from.
 * @param trustedClient
 *         The {@code TrustedHttpClient} which should be used to communicate with the remote server. This can be null
 *         for local file reads.
 * @return A String containing the source data or null in the case of an error.
 * @deprecated this method doesn't support UTF8 or handle HTTP response codes
 */
public static String readFileFromURL(URL url, TrustedHttpClient trustedClient) {
    StringBuilder sb = new StringBuilder();
    DataInputStream in = null;
    HttpResponse response = null;
    try {
        // Do different things depending on what we're reading...
        if ("file".equals(url.getProtocol())) {
            in = new DataInputStream(url.openStream());
        } else {
            if (trustedClient == null) {
                logger.error("Unable to read from remote source {} because trusted client is null!",
                        url.getFile());
                return null;
            }
            HttpGet get = new HttpGet(url.toURI());
            try {
                response = trustedClient.execute(get);
            } catch (TrustedHttpClientException e) {
                logger.warn("Unable to fetch file from {}.", url, e);
                trustedClient.close(response);
                return null;
            }
            in = new DataInputStream(response.getEntity().getContent());
        }
        int c = 0;
        while ((c = in.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        logger.warn("IOException attempting to get file from {}.", url);
        return null;
    } catch (URISyntaxException e) {
        logger.warn("URI error attempting to get file from {}.", url);
        return null;
    } catch (NullPointerException e) {
        logger.warn("Nullpointer attempting to get file from {}.", url);
        return null;
    } finally {
        IOUtils.closeQuietly(in);

        if (response != null && trustedClient != null) {
            trustedClient.close(response);
            response = null;
        }
    }

    return sb.toString();
}

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

/**
 * This method is used to extract a configdir from a jar archive.
 * Given a URL this method will extract the jar contents to a temp dir and return that path.
 * It also adds a shutdown hook to cleanup the tmp dir on normal jvm completion.
 * If the given URL does not appear to be a path into a jar archive, this method returns
 * a new File object initialized with <code>dataURL.getFile()</code>.
 *
 * @return A temporary directory to be used as a configdir
 *//*w ww  .  j  a v  a 2  s.co m*/
private static File extractJarDataURL(URL dataURL) {
    // TODO: Extract to a temp location
    // atg.core.util.JarUtils.extractEntry(arg0, arg1, arg2)

    int endIndex = dataURL.getFile().lastIndexOf('!');
    if (endIndex == -1) {
        // Not a jar file url
        return new File(dataURL.getFile());
    }
    logger.info(EXTRACT_TEMP_JAR_FILE_FOR_PATH + dataURL.getFile());
    File configDir = null;
    try {
        final File tempFile = FileUtil.newTempFile();
        final File tmpDir = new File(tempFile.getParentFile(), DYNUNIT_CONFIG + System.currentTimeMillis());

        String jarPath = dataURL.getFile().substring(0, endIndex);
        // Strip leading file:
        int fileColonIndex = jarPath.indexOf(FILE) + FILE.length();
        jarPath = jarPath.substring(fileColonIndex, jarPath.length());
        JarUtils.unJar(new File(jarPath), tmpDir, false);
        // Now get the configpath dir relative to this temp dir
        String relativePath = dataURL.getFile().substring(endIndex + 1, dataURL.getFile().length());
        FileUtils.forceDeleteOnExit(tmpDir);
        configDir = new File(tmpDir, relativePath);
    } catch (IOException e) {
        logger.catching(e);
    }
    return configDir;
}

From source file:org.argouml.application.Main.java

/**
 * Parse command line args. The assumption is that all options precede the
 * name of a project file to load. Sets static fields that can be referenced
 * later./*from   www. jav  a 2  s. c  o  m*/
 * 
 * @param args command line args
 */
private static void parseCommandLine(String[] args) {
    doSplash = Configuration.getBoolean(Argo.KEY_SPLASH, true);
    reloadRecent = Configuration.getBoolean(Argo.KEY_RELOAD_RECENT_PROJECT, false);
    commands = new ArrayList<String>();
    theTheme = null;

    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            String themeName = LookAndFeelMgr.getInstance().getThemeClassNameFromArg(args[i]);
            if (themeName != null) {
                theTheme = themeName;
            } else if (args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")
                    || args[i].equalsIgnoreCase("--help") || args[i].equalsIgnoreCase("/?")) {
                printUsage();
                System.exit(0);
            } else if (args[i].equalsIgnoreCase("-nosplash")) {
                doSplash = false;
            } else if (args[i].equalsIgnoreCase("-norecentfile")) {
                reloadRecent = false;

                // Gateinformationen ber Parameter der JNLP in Variablen
                // schreiben
            } else if (args[i].equalsIgnoreCase("-taskid") && i + 1 < args.length) {
                taskID = args[++i];
            } else if (args[i].equalsIgnoreCase("-sessionid") && i + 1 < args.length) {
                sessionID = args[++i];
            } else if (args[i].equalsIgnoreCase("-srvpath") && i + 1 < args.length) {
                servletPath = args[++i];
            } else if (args[i].equalsIgnoreCase("-command") && i + 1 < args.length) {
                commands.add(args[i + 1]);
                i++;
            } else if (args[i].equalsIgnoreCase("-locale") && i + 1 < args.length) {
                Translator.setLocale(args[i + 1]);
                i++;
            } else if (args[i].equalsIgnoreCase("-batch")) {
                batch = true;
            } else if (args[i].equalsIgnoreCase("-open") && i + 1 < args.length) {
                projectName = args[++i];
            } else if (args[i].equalsIgnoreCase("-print") && i + 1 < args.length) {
                // TODO: Huge side effect.  Hoist out of parse - tfm
                // let's load the project
                String projectToBePrinted = PersistenceManager.getInstance().fixExtension(args[++i]);
                URL urlToBePrinted = projectUrl(projectToBePrinted, null);
                ProjectBrowser.getInstance().loadProject(new File(urlToBePrinted.getFile()), true, null);
                // now, let's print it
                PrintManager.getInstance().print();
                // nothing else to do (?)
                System.exit(0);
            } else if (args[i].equalsIgnoreCase("-nouml2warning")) { // Andreas: just temporary for the 
                showUml2warning = false; // uml2 pre-alpha versions!
            } else {
                System.err.println("Ignoring unknown/incomplete option '" + args[i] + "'");
            }
        } else {
            if (projectName == null) {
                System.out.println("Setting projectName to '" + args[i] + "'");
                projectName = args[i];
            }
        }
    }
    firstGATEDownload();
}

From source file:edu.duke.cabig.c3pr.rules.repository.RepositoryCleaner.java

public RepositoryCleaner(String path) {
    log.debug("Going to delete the contents inside the local rules repository [" + path + "]");
    // run this only once per JVM/classloader
    if (lock == null) {
        try {//  w  w w .  j ava  2  s  .  c  om
            URL url = new URL(path);
            File f = new File(url.getFile());
            RepositoryCleaner.deleteDirectoryContents(f);
        } catch (Exception e) {
            // ignore
            log.debug("Error while emptying the contents of rules repository [" + path + "]", e);
        } finally {
            lock = new Object();
        }
    }
    log.debug("Completed deletion of conents #*#");
}

From source file:com.fengduo.bee.commons.core.utilities.ClassPathScanner.java

public File getJarFile(URL url) {
    String file = url.getFile();
    if (file.startsWith(PREFIX_FILE))
        file = file.substring(PREFIX_FILE.length());
    int end = file.indexOf(JAR_URL_SEPERATOR);
    if (end != (-1))
        file = file.substring(0, end);//from  w ww . j a  v a 2 s  .  c  om
    return new File(file);
}

From source file:fr.eolya.utils.http.HttpUtils.java

public static String urlNormalize(String url, String preferedHost) {

    String ret_url = url.trim();//from  ww  w.jav a  2s.  c  o m

    // Perform some url nomalizations described here : http://en.wikipedia.org/wiki/URL_normalization

    try {
        // Remove last "/" - NO !!!
        //if (ret_url.lastIndexOf("/") == ret_url.length()-1)
        //   ret_url = ret_url.substring(0, ret_url.length()-1); 

        // Remove final "?" if unique in url -     http://www.example.com/display? -> http://www.example.com/display 
        if (ret_url.lastIndexOf("?") == ret_url.length() - 1)
            ret_url = ret_url.substring(0, ret_url.length() - 1);

        // Fix "?&"
        int index = ret_url.indexOf("?&");
        //int l = ret_url.length()-2;
        if (index != -1) {
            if (index != ret_url.length() - 2) {
                ret_url = ret_url.substring(0, index + 1) + ret_url.substring(index + 2);
            } else {
                ret_url = ret_url.substring(0, ret_url.length() - 2);
            }
        }

        // Replace "&amp;" by "&"
        ret_url = StringEscapeUtils.unescapeHtml4(ret_url);

        // Replace " " by "%20"
        ret_url = ret_url.replace(" ", "%20");

        // Replace "'" by "%27"
        ret_url = ret_url.replace("'", "%27");

        // Replace "%5F" by "_"
        ret_url = ret_url.replace("%5f", "_");
        ret_url = ret_url.replace("%5F", "_");

        // Remove dot-segments.
        // http://www.example.com/../a/b/../c/./d.html => http://www.example.com/a/c/d.html           
        URI uri = new URI(ret_url);
        uri = uri.normalize();
        ret_url = uri.toURL().toExternalForm();

        // Remove dot-segments at the beginning of the path
        // http://www.example.com/../a/d.html => http://www.example.com/a/d.html           
        URL tempUrl = new URL(ret_url);
        String path = tempUrl.getFile();
        String pattern = "";
        while (path.startsWith("/../")) {
            path = path.substring(3);
            pattern += "/..";
        }
        if (!pattern.equals("")) {
            index = ret_url.indexOf(pattern);
            ret_url = ret_url.substring(0, index) + ret_url.substring(index + pattern.length());
        }

        // Remove default port
        if (ret_url.indexOf("http://" + uri.getHost() + ":80") != -1) {
            ret_url = ret_url.replace("//" + uri.getHost() + ":80", "//" + uri.getHost());
        }
        if (ret_url.indexOf("https://" + uri.getHost() + ":443") != -1) {
            ret_url = ret_url.replace("//" + uri.getHost() + ":443", "//" + uri.getHost());
        }

        // translate to prefered host (www.site.com vs site.com)
        if (preferedHost != null && !"".equals(preferedHost)) {
            if (uri.getHost().equals("www." + preferedHost) || ("www." + uri.getHost()).equals(preferedHost)) {
                ret_url = ret_url.replace("//" + uri.getHost(), "//" + preferedHost);
            }
        }

        // Remove the fragment.
        // http://www.example.com/bar.html#section1 => http://www.example.com/bar.html 
        if (ret_url.indexOf("#") != -1)
            ret_url = ret_url.substring(0, ret_url.indexOf("#"));

        // Reorder parameters in query string
        //ret_url = urlReorderParameters (ret_url);

        return ret_url;
    } catch (Exception e) {
    }

    return ret_url;
}

From source file:main.okapi.cf.annotations.AnnotationsInfo.java

private Iterable<Class> getClasses(String packageName) throws ClassNotFoundException, IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }/*from   w w w. ja  va2  s.  c om*/
    List<Class> classes = new ArrayList<Class>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }

    return classes;
}

From source file:FileLocator.java

/**
 * Locate the specific file.//from   w w  w.j  av a 2 s.c o  m
 * Return the (URL decoded) abolute pathname to the file or null.
 */
public static String locateFile(String findFile) throws FileNotFoundException {
    URL url;
    String fullPathName;
    StringBuffer decodedPathName;
    int pos, len, start;

    if (findFile == null)
        throw new FileNotFoundException("locateFile: null file name");

    if (findFile.startsWith(absolutePath))
        return findFile.substring(absolutePath.length());

    if ((fullPathName = locateByProperty(findFile)) != null)
        return fullPathName;

    if ((url = locateByResource(findFile)) != null) {
        /*
         * The URL that we receive from getResource /might/ have ' '
         * (space) characters converted to "%20" strings.  However,
         * it doesn't have other URL encoding (e.g '+' characters are
         * kept intact), so we'll just convert all "%20" strings to
         * ' ' characters and hope for the best.
         */
        fullPathName = url.getFile();
        pos = 0;
        len = fullPathName.length();
        start = 0;
        decodedPathName = new StringBuffer();

        while ((pos = fullPathName.indexOf(pct20, start)) != -1) {
            decodedPathName.append(fullPathName.substring(start, pos));
            decodedPathName.append(' ');
            start = pos + pct20len;
        }

        if (start < len)
            decodedPathName.append(fullPathName.substring(start, len));

        fullPathName = decodedPathName.toString();

        if (platformIsWindows())
            fullPathName = fullPathName.substring(1, fullPathName.length());

        return fullPathName;
    }

    throw new FileNotFoundException("locateFile: file not found: " + findFile);
}

From source file:funnycats.TestUtils.java

@Test
public void testGettingFunnyCatsFromDirectoryReturnsAListOfCats() throws ConfigurationException {
    Configuration configuration = new PropertiesConfiguration("funnycats.properties");
    String path = configuration.getString("cats.pictures");
    URL url = getClass().getClassLoader().getResource(path);
    File directory = new File(url.getFile());
    List<FunnyCat> funnyCats = Utils.getFunnyCats(directory);
    Assert.assertTrue(funnyCats.size() > 0);
}