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.gargoylesoftware.htmlunit.html.HtmlImageDownloadTest.java

/**
 * @throws Exception if the test fails//from  w ww.j a  v a  2 s  .c  o m
 */
@Test
public void getWebResponse() throws Exception {
    final HtmlImage htmlimage = getHtmlElementToTest("image1");
    final URL url = htmlimage.getPage().getUrl();
    assertNull(htmlimage.getWebResponse(false));
    final WebResponse resp = htmlimage.getWebResponse(true);
    assertNotNull(resp);
    assertEquals(url.toExternalForm(), resp.getWebRequest().getAdditionalHeaders().get("Referer"));
}

From source file:com.ucu.seguridad.views.AbstractFxmlView.java

void addCSSIfAvailable(Parent parent) {

    URL uri = getClass().getResource(getStyleSheetName());
    if (uri == null) {
        return;//  w ww .ja  va  2  s  .c  o  m
    }

    String uriToCss = uri.toExternalForm();
    parent.getStylesheets().add(uriToCss);
}

From source file:net.siegmar.japtproxy.fetcher.FetcherHttp.java

/**
 * {@inheritDoc}/* w w w . j  ava 2 s  .c  om*/
 */
@Override
public FetchedResourceHttp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final HttpGet httpGet = new HttpGet(targetResource.toExternalForm());

    httpGet.addHeader(HttpHeaderConstants.USER_AGENT,
            StringUtils.trim(StringUtils.defaultString(originalUserAgent) + " " + Util.USER_AGENT));

    if (lastModified != 0) {
        final String lastModifiedSince = Util.getRfc822DateFromTimestamp(lastModified);
        LOG.debug("Setting If-Modified-Since: {}", lastModifiedSince);
        httpGet.setHeader(HttpHeaderConstants.IF_MODIFIED_SINCE, lastModifiedSince);
    }

    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);

        if (LOG.isDebugEnabled()) {
            logResponseHeader(httpResponse.getAllHeaders());
        }

        final int retCode = httpResponse.getStatusLine().getStatusCode();
        if (retCode == HttpServletResponse.SC_NOT_FOUND) {
            httpGet.releaseConnection();
            throw new ResourceUnavailableException("Resource '" + targetResource + " not found");
        }

        if (retCode != HttpServletResponse.SC_OK && retCode != HttpServletResponse.SC_NOT_MODIFIED) {
            throw new IOException("Invalid status code returned: " + httpResponse.getStatusLine());
        }

        final FetchedResourceHttp fetchedResourceHttp = new FetchedResourceHttp(httpResponse);
        fetchedResourceHttp.setModified(lastModified == 0 || retCode != HttpServletResponse.SC_NOT_MODIFIED);

        if (LOG.isDebugEnabled()) {
            final long fetchedTimestamp = fetchedResourceHttp.getLastModified();
            if (fetchedTimestamp != 0) {
                LOG.debug("Response status code: {}, Last modified: {}", retCode,
                        Util.getSimpleDateFromTimestamp(fetchedTimestamp));
            } else {
                LOG.debug("Response status code: {}", retCode);
            }
        }

        return fetchedResourceHttp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceHttp
        if (httpResponse != null) {
            httpResponse.close();
        }

        throw e;
    }
}

From source file:org.apache.juddi.v3.client.mapping.wsdl.WSDLLocatorImpl.java

/**
 * see also {@link #getImportInputSource WSDLLocator.getImportInputSource} 
 * @param parentLocation/*from w ww  .  jav a 2  s  .c  o  m*/
 * @param importLocation
 * @return input source
 */
public InputSource getImportInputSource(String parentLocation, String importLocation) {
    InputSource inputSource = null;
    try {
        URL importUrl = constructImportUrl(parentLocation, importLocation);
        return getImportFromUrl(importUrl.toExternalForm());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        lastException = e;
    }
    return inputSource;
}

From source file:at.newsagg.model.parser.hibernate.Item.java

public void setLinkURL(URL aLink) {
    this.link = aLink.toExternalForm();
}

From source file:org.jasig.portlet.notice.controller.rest.JPANotificationRESTController.java

/**
 * Build the URL for a specific notification.
 *
 * @param request the Http request//from   w ww .  ja va  2 s  . co m
 * @param id the notification id
 * @return the URL to hit that specific id
 */
private String getSingleNotificationRESTUrl(HttpServletRequest request, long id) {
    String path = request.getContextPath() + API_ROOT + REQUEST_ROOT + id;
    try {
        URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), path);
        return url.toExternalForm();

    } catch (MalformedURLException e) {
        // if it fails, just return a relative path.  Not ideal, but better than nothing...
        log.warn("Error building Location header", e);
        return path;
    }
}

From source file:com.thinkberg.moxo.dav.PropPatchHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {/*w  w w . j ava2 s. c o  m*/
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        //      log(propDoc);

        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(SC_MULTI_STATUS);

        if (object.exists()) {
            Document resultDoc = DocumentHelper.createDocument();
            Element multiStatusResponse = resultDoc.addElement("multistatus", "DAV:");
            Element responseEl = multiStatusResponse.addElement("response");
            try {
                URL url = new URL(getBaseUrl(request), URLEncoder.encode(object.getName().getPath(), "UTF-8"));
                log("!! " + url);
                responseEl.addElement("href").addText(url.toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
            }

            Element propstatEl = responseEl.addElement("propstat");
            Element propEl = propstatEl.addElement("prop");

            Element propertyUpdateEl = propDoc.getRootElement();
            for (Object elObject : propertyUpdateEl.elements()) {
                Element el = (Element) elObject;
                if ("set".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        setProperty(propEl, object, (Element) propObject);
                    }
                } else if ("remove".equals(el.getName())) {
                    for (Object propObject : el.elements()) {
                        removeProperty(propEl, object, (Element) propObject);
                    }
                }
            }
            propstatEl.addElement("status").addText(DavResource.STATUS_403);

            //        log(resultDoc);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(resultDoc);
            writer.flush();
            writer.close();
        } else {
            log("!! " + object.getName().getPath() + " NOT FOUND");
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (DocumentException e) {
        log("!! inavlid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:jug.rest.arquillian.SubjectServiceTomEETest.java

@Test
public void checkThereIsSomeOutput() throws Exception {
    final String base = url.toExternalForm();
    WebClient.create(base).path("api/subject/create").accept("application/json")
            .query("name", "SubjectServiceTomEETest").post("SubjectServiceTomEETest");
    for (int i = 0; i < 2; i++) { // we have a dynamic datasource so let it round
        final URL url = new URL(base + "api/subject/list");
        final String output = IOUtils.toString(new BufferedInputStream(url.openStream()));
        if (output.contains("SubjectServiceTomEETest")) {
            return;
        }/*from w  w w  .  j  a v  a 2s .co  m*/
    }
    fail("created entry not found");
}

From source file:eu.openanalytics.rsb.config.PersistedConfigurationAdapter.java

private String getDefaultNodeName() {
    // find something unique about the running node like the location of resource
    final URL resourceUrl = getClass().getResource("/META-INF/spring/core-beans.xml");
    final String uniqueId = Long.toHexString(Math.abs((long) resourceUrl.toExternalForm().hashCode()));
    return StringUtils.lowerCase(Constants.HOST_NAME + "-" + uniqueId);
}

From source file:sh.calaba.driver.server.DriverRegistrationHandler.java

/**
 * Performs actually the registration of the calabash driver node into the grid hub.
 * //from  w w w .ja v  a  2s.c o m
 * @throws Exception On registration errors.
 */
public void performRegsitration() throws Exception {
    String tmp = "http://" + config.getHubHost() + ":" + config.getHubPort() + "/grid/register";

    HttpClient client = HttpClientFactory.getClient();

    URL registration = new URL(tmp);
    if (logger.isDebugEnabled()) {
        logger.debug("Registering the node to hub :" + registration);
    }
    BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
            registration.toExternalForm());
    JSONObject nodeConfig = getNodeConfig();
    r.setEntity(new StringEntity(nodeConfig.toString()));

    HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
    HttpResponse response = client.execute(host, r);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new CalabashException("Error sending the registration request.");
    }
}