Example usage for java.net URL toExternalForm

List of usage examples for java.net URL toExternalForm

Introduction

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

Prototype

public String toExternalForm() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:com.mothsoft.alexis.util.NetworkingUtil.java

public static HttpClientResponse get(final URL url, final String etag, final Date lastModifiedDate)
        throws IOException {

    final HttpGet get = new HttpGet(url.toExternalForm());

    get.addHeader("Accept-Charset", "UTF-8");

    if (etag != null) {
        get.addHeader("If-None-Match", etag);
    }//from  w w w . j a  va 2s  . co m

    if (lastModifiedDate != null) {
        get.addHeader("If-Modified-Since", DateUtils.formatDate(lastModifiedDate));
    }

    int statusCode = -1;
    String responseEtag = null;
    Date responseLastModifiedDate = null;

    final HttpClient client = getClient();
    HttpResponse response = client.execute(get);
    statusCode = response.getStatusLine().getStatusCode();

    InputStream is = null;
    Charset charset = null;

    if (statusCode == 304) {
        responseEtag = etag;
        responseLastModifiedDate = lastModifiedDate;
    } else {
        final Header responseEtagHeader = response.getFirstHeader("Etag");
        if (responseEtagHeader != null) {
            responseEtag = responseEtagHeader.getValue();
        }

        final Header lastModifiedDateHeader = response.getFirstHeader("Last-Modified");
        if (lastModifiedDateHeader != null) {
            try {
                responseLastModifiedDate = DateUtils.parseDate(lastModifiedDateHeader.getValue());
            } catch (DateParseException e) {
                responseLastModifiedDate = null;
            }
        }

        final HttpEntity entity = response.getEntity();

        // here's where to do intelligent checking of content type, content
        // length, etc.
        if (entity.getContentLength() > MAX_CONTENT_LENGTH) {
            get.abort();
            throw new IOException("Exceeded maximum content length, length is: " + entity.getContentLength());
        }

        is = entity.getContent();
        charset = getCharset(entity);
    }
    return new HttpClientResponse(get, statusCode, responseEtag, responseLastModifiedDate, is, charset);
}

From source file:org.echocat.jomon.net.http.HttpUtils.java

@Nonnull
public static HttpResponse makeGetRequestAndReturnResponseFor(@Nonnull URL url) throws IOException {
    final HttpUriRequest httpUriRequest = new HttpGet(url.toExternalForm());
    return CLIENT.execute(httpUriRequest);
}

From source file:Main.java

public static String getResourceUrlString(String resourceFileName, Class runningClass) {
    URL url = runningClass.getClassLoader().getResource(resourceFileName);
    if (url == null)
        throw new MissingResourceException("Resource not found: " + resourceFileName, runningClass.getName(),
                resourceFileName);//from  w w w. j a v  a 2  s  .  co  m
    return url.toExternalForm();
}

From source file:org.qe4j.web.OpenSeleniumGrid.java

/**
 * Extracts the grid node address from the web driver session
 *
 * @return the address of the grid node web driver is connected to
 * @throws JSONException/* w  ww .  j av a 2  s.  com*/
 * @throws IOException
 * @throws ClientProtocolException
 *
 * @return grid node address
 */
public static String getNodeAddress(OpenWebDriver awd)
        throws JSONException, ClientProtocolException, IOException {
    if (awd.isLocal()) {
        return "127.0.0.1";
    }

    String gridUrl = awd.getGridUrl();

    // splitting up grid url (e.g. http://174.129.55.44:4444/wd/hub)
    String[] address = gridUrl.split("/")[2].split(":");
    String hostname = address[0];
    int port = new Integer(address[1]);
    HttpHost host = new HttpHost(hostname, port);

    // call the test session API to get the node data
    DefaultHttpClient client = new DefaultHttpClient();
    SessionId sessionId = ((RemoteWebDriver) awd.getWebDriver()).getSessionId();
    URL testSessionApi = new URL(
            "http://" + hostname + ":" + port + "/grid/api/testsession?session=" + sessionId);
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
            testSessionApi.toExternalForm());
    HttpResponse response = client.execute(host, request);

    JSONObject object = new JSONObject(EntityUtils.toString(response.getEntity()));
    String proxy = object.getString("proxyId");
    log.debug("found proxy [{}] in selenium grid test session", proxy);
    String gridNodeAddress = proxy.split("//")[1].split(":")[0];

    return gridNodeAddress;
}

From source file:com.net2plan.utils.HTMLUtils.java

private static String prepareImagePath(String html, URL url) {
    final Set<String> list = new TreeSet<String>();
    final ParserDelegator parserDelegator = new ParserDelegator();
    final HTMLEditorKit.ParserCallback parserCallback = new HTMLEditorKit.ParserCallback() {
        @Override/*from   www.  j ava  2  s.  c  om*/
        public void handleText(final char[] data, final int pos) {
        }

        @Override
        public void handleStartTag(HTML.Tag tag, MutableAttributeSet attribute, int pos) {
            if (tag == HTML.Tag.IMG) {
                String address = (String) attribute.getAttribute(HTML.Attribute.SRC);
                list.add(address);
            }
        }

        @Override
        public void handleEndTag(HTML.Tag t, final int pos) {
        }

        @Override
        public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, final int pos) {
            if (t == HTML.Tag.IMG) {
                String address = (String) a.getAttribute(HTML.Attribute.SRC);
                list.add(address);
            }
        }

        @Override
        public void handleComment(final char[] data, final int pos) {
        }

        @Override
        public void handleError(final String errMsg, final int pos) {
        }
    };

    final Reader reader = new StringReader(html);
    try {
        parserDelegator.parse(reader, parserCallback, true);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    for (String item : list) {
        try {
            URL newURL = new URL(url, item);
            html = html.replace(item, newURL.toExternalForm());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    return html;
}

From source file:de.micromata.genome.util.runtime.DynamicClassPath.java

public static URL createClUrl(File f) {
    try {/*from w w  w .j  ava2 s. c  o  m*/
        URL ret;
        if (f.isDirectory() == true) {
            ret = f.toURI().toURL();
        } else {
            // ret = new URL("jar", "", f.getAbsolutePath());
            ret = f.toURI().toURL();
        }
        String s = ret.toExternalForm();
        return ret;
    } catch (MalformedURLException ex) {
        throw new RuntimeException("Cannot extend class oath because of invalid url: " + f.toURI());
    }
}

From source file:org.wso2.carbon.discovery.cxf.util.ClassAnnotationScanner.java

public static AnnotationDB getAnnotatedClasses(StandardContext context) {

    AnnotationDB db = new AnnotationDB();
    //        db.addIgnoredPackages("org.apache");
    db.addIgnoredPackages("org.codehaus");
    db.addIgnoredPackages("org.springframework");

    final String path = context.getRealPath("/WEB-INF/classes");
    URL resourceUrl = null;
    URL[] urls = null;/* www  . j a va  2 s. c  o  m*/

    if (path != null) {
        final File fp = new File(path);
        if (fp.exists()) {
            try {
                resourceUrl = fp.toURI().toURL();
                urls = new URL[] { new URL(resourceUrl.toExternalForm()) };
                db.scanArchives(urls);
                return db;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return db;
}

From source file:WarUtil.java

public static boolean isDirectoryResource(URL resource) {
    return resource.toExternalForm().endsWith(SLASH);
}

From source file:WarUtil.java

public static boolean isFileResource(URL resource) {
    return !resource.toExternalForm().endsWith(SLASH);
}

From source file:edu.uci.ics.crawler4j.url.URLCanonicalizer.java

public static String getCanonicalURL(String href, String context) {

    try {//from   w w  w .java  2s .  c om
        URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href));

        String host = canonicalURL.getHost().toLowerCase();
        if (StringUtils.isBlank(host)) {
            // This is an invalid Url.
            return null;
        }

        String path = canonicalURL.getPath();

        /*
         * Normalize: no empty segments (i.e., "//"), no segments equal to
         * ".", and no segments equal to ".." that are preceded by a segment
         * not equal to "..".
         */
        path = new URI(path).normalize().toString();

        /*
         * Convert '//' -> '/'
         */
        int idx = path.indexOf("//");
        while (idx >= 0) {
            path = path.replace("//", "/");
            idx = path.indexOf("//");
        }

        /*
         * Drop starting '/../'
         */
        while (path.startsWith("/../")) {
            path = path.substring(3);
        }

        /*
         * Trim
         */
        path = path.trim();

        final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery());
        final String queryString;

        if (params != null && params.size() > 0) {
            String canonicalParams = canonicalize(params);
            queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);
        } else {
            queryString = "";
        }

        /*
         * Add starting slash if needed
         */
        if (path.length() == 0) {
            path = "/" + path;
        }

        /*
         * Drop default port: example.com:80 -> example.com
         */
        int port = canonicalURL.getPort();
        if (port == canonicalURL.getDefaultPort()) {
            port = -1;
        }

        String protocol = canonicalURL.getProtocol().toLowerCase();
        String pathAndQueryString = normalizePath(path) + queryString;

        URL result = new URL(protocol, host, port, pathAndQueryString);
        return result.toExternalForm();

    } catch (MalformedURLException ex) {
        return null;
    } catch (URISyntaxException ex) {
        return null;
    }
}