Example usage for java.net URL toString

List of usage examples for java.net URL toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:com.mber.client.MberClient.java

public static String baseUrlWithPath(final String url, String path) throws MalformedURLException {
    if (!path.endsWith("/")) {
        path += "/";
    }/*from ww  w  .  j a v  a 2 s . c  om*/
    URL base = new URL(url);
    URL baseUrl = new URL(base.getProtocol() + "://" + base.getAuthority());
    URL resolvedUrl = new URL(baseUrl, path);
    return resolvedUrl.toString();
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all resources beneath a folder. Supports filesystem, JARs and JBoss VFS
 * //from  w w w . j  a  v a 2  s. c  o  m
 * @param folder
 * @return
 * @throws IOException
 */
public static URL[] getResources(String folder) throws IOException {
    List<URL> urls = new ArrayList<URL>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new IOException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(folder);
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            String resProtocol = res.getProtocol();
            if (resProtocol.equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {
                    if (e.getName().startsWith(folder) && !e.getName().endsWith("/")) {
                        urls.add(new URL(
                                joinUrl(res.toString(), "/" + e.getName().substring(folder.length() + 1)))); // FIXME: fully qualified name
                    }
                }
            } else if (resProtocol.equalsIgnoreCase("vfszip") || resProtocol.equalsIgnoreCase("vfs")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method toUrl = null;
                    for (Object o : files) {
                        if (toUrl == null) {
                            toUrl = o.getClass().getMethod("toURL");
                        }
                        urls.add((URL) toUrl.invoke(o));
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else if (resProtocol.equalsIgnoreCase("file")) {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            } else {
                throw new IOException("Unknown protocol for resource: " + res.toString());
            }
        }
    } catch (NullPointerException x) {
        throw new IOException(folder + " does not appear to be a valid folder (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new IOException(folder + " does not appear to be a valid folder (Unsupported encoding)");
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                urls.add(new URL("file:///" + joinPath(directory.getAbsolutePath(), file)));
            }
        } else {
            throw new IOException(
                    folder + " (" + directory.getPath() + ") does not appear to be a valid folder");
        }
    }
    URL[] urlsA = new URL[urls.size()];
    urls.toArray(urlsA);
    return urlsA;
}

From source file:org.acra.util.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * /* w  w w .j  a  va 2s  .c  o m*/
 * @param parameters
 * @param url
 * @throws ClientProtocolException
 * @throws IOException
 */
public static void doPost(Map<?, ?> parameters, URL url, String login, String password)
        throws ClientProtocolException, IOException {

    // Construct data
    final StringBuilder dataBfr = new StringBuilder();
    for (final Object key : parameters.keySet()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        Object value = parameters.get(key);
        if (value == null) {
            value = "";
        }
        dataBfr.append(URLEncoder.encode(key.toString(), "UTF-8")).append('=')
                .append(URLEncoder.encode(value.toString(), "UTF-8"));
    }

    final HttpRequest req = new HttpRequest(isNull(login) ? null : login, isNull(password) ? null : password);
    req.sendPost(url.toString(), dataBfr.toString());
}

From source file:com.discovery.darchrow.net.URIUtil.java

/**
 * ???url, spec ? URL.  URL  URL  spec ?<br>
 * ?,method//from   ww  w .java  2  s.com
 * 
 * <pre>
 * {@code
 * : URIUtil.getUnionUrl("E:\\test", "sanguo")------------->file:/E:/test/sanguo
 * URL url = new URL("http://www.exiaoshuo.com/jinyiyexing/");
 * result = URIUtil.getUnionUrl(url, "/jinyiyexing/1173348/");
 * http://www.exiaoshuo.com/jinyiyexing/1173348/
 * }
 * </pre>
 *
 * @param context
 *            ??
 * @param spec
 *            the <code>String</code> to parse as a URL.
 * @return ???url
 */
public static String getUnionUrl(URL context, String spec) {
    try {
        URL unionUrl = new URL(context, spec);
        return unionUrl.toString();
    } catch (MalformedURLException e) {
        LOGGER.error("MalformedURLException:", e);
        throw new URIParseException(e);
    }
}

From source file:eu.morfeoproject.fast.catalogue.ontologies.OntologyFetcher.java

public static Ontology fetch(URL url) {
    if (log.isInfoEnabled())
        log.info("fetching " + url + "...");
    for (Syntax syntax : syntaxList) {
        try {//from   ww  w  . j a  v  a2s  .  c om
            URLInputSource source = new URLInputSource(url, syntax.getMimeType());
            HttpResponse response = source.getHttpResponse();
            String contentType = response.getFirstHeader("Content-Type").getValue();
            if (contentType.startsWith(syntax.getMimeType())) {
                InputStream in = response.getEntity().getContent();
                if (in != null) {
                    URI oUri = getOntologyUri(in, syntax);
                    if (oUri != null) {
                        return new PublicOntology(oUri, url.toString(), syntax, false);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Error while fetching " + url + "[Accept: " + syntax.getMimeType() + "]");
        }
    }
    return null;
}

From source file:mpimp.assemblxweb.util.J5FileUtils.java

public static String createDownloadUrl(AssemblXWebModel model, String filePath) throws Exception {
    String downloadUrl = "";
    URL url = null;
    String host = model.getHost();
    String protocol = model.getProtocol();
    int serverPort = model.getServerPort();

    if (!filePath.startsWith("/")) {
        filePath = "/" + filePath;
    }//from   ww  w.j a  v a 2 s.  com
    try {
        if (serverPort == 0) {
            url = new URL(protocol, host, filePath);
        } else {
            url = new URL(protocol, host, serverPort, filePath);
        }
    } catch (MalformedURLException me) {
        throw new AssemblXException(me.getMessage(), J5FileUtils.class);
    }
    if (url != null) {
        downloadUrl = url.toString();
    }
    return downloadUrl;
}

From source file:net.mutil.util.HttpUtil.java

public static String connServerForResultPost(String strUrl, HashMap<String, String> entityMap)
        throws ClientProtocolException, IOException {
    String strResult = "";
    URL url = new URL(HttpUtil.getPCURL() + strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    StringBuilder entitySb = new StringBuilder("");

    Object[] entityKeys = entityMap.keySet().toArray();
    for (int i = 0; i < entityKeys.length; i++) {
        String key = (String) entityKeys[i];
        if (i == 0) {
            entitySb.append(key + "=" + entityMap.get(key));
        } else {/*from   www .j  av  a2s .c  om*/
            entitySb.append("&" + key + "=" + entityMap.get(key));
        }
    }
    byte[] entity = entitySb.toString().getBytes("UTF-8");
    System.out.println(url.toString() + entitySb.toString());
    conn.setConnectTimeout(5000);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
    conn.getOutputStream().write(entity);
    if (conn.getResponseCode() == 200) {
        InputStream inputstream = conn.getInputStream();
        StringBuffer buffer = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = inputstream.read(b)) != -1;) {
            buffer.append(new String(b, 0, n));
        }
        strResult = buffer.toString();
    }
    return strResult;
}

From source file:com.neuronrobotics.bowlerstudio.MainController.java

/**
 * Returns the location of the Jar archive or .class file the specified
 * class has been loaded from. <b>Note:</b> this only works if the class is
 * loaded from a jar archive or a .class file on the locale file system.
 *
 * @param cls//  w w w .  j av  a  2s  .c  o m
 *            class to locate
 * @return the location of the Jar archive the specified class comes from
 */
public static File getClassLocation(Class<?> cls) {

    // VParamUtil.throwIfNull(cls);
    String className = cls.getName();
    ClassLoader cl = cls.getClassLoader();
    URL url = cl.getResource(className.replace(".", "/") + ".class");

    String urlString = url.toString().replace("jar:", "");

    if (!urlString.startsWith("file:")) {
        throw new IllegalArgumentException("The specified class\"" + cls.getName()
                + "\" has not been loaded from a location" + "on the local filesystem.");
    }

    urlString = urlString.replace("file:", "");
    urlString = urlString.replace("%20", " ");

    int location = urlString.indexOf(".jar!");

    if (location > 0) {
        urlString = urlString.substring(0, location) + ".jar";
    } else {
        // System.err.println("No Jar File found: " + cls.getName());
    }

    return new File(urlString);
}

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

/**
 * If the given class is in a JAR, WAR or EAR file than the manifest url as String is returned.
 *
 * @param clazz//  w  w  w .java2 s.c  om
 *            The class.
 * @return the manifest url as String if the given class is in a JAR, WAR or EAR file.
 */
public static String getManifestUrl(final Class<?> clazz) {
    String manifestUrl = null;
    final String path = ClassExtensions.getPath(clazz);
    final URL classUrl = ClassExtensions.getResource(path);
    if (classUrl != null) {
        final String classUrlString = classUrl.toString();
        if ((classUrlString.startsWith("jar:") && (classUrlString.indexOf(path) > 0))
                || (classUrlString.startsWith("war:") && (classUrlString.indexOf(path) > 0))
                || (classUrlString.startsWith("ear:") && (classUrlString.indexOf(path) > 0))
                || (classUrlString.startsWith("file:") && (classUrlString.indexOf(path) > 0))) {
            manifestUrl = classUrlString.replace(path, "/META-INF/MANIFEST.MF");
        }
    }
    return manifestUrl;
}

From source file:hu.unideb.inf.rdfizers.rpm.ModelBuilder.java

/**
 * Processes the specified RPM package file.
 *
 * @param url URL of the RPM package file
 * @throws IOException if an I/O error occurs
 * @return an RDF model that stores metadata obtained from the RPM package file
 *//*w w w  . ja  va  2 s .co m*/
public static Model process(URL url) throws IOException {
    return process(url.openStream(), url.toString());
}