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:io.github.thred.climatetray.mnet.request.AbstractMNetRequest.java

@Override
public final void execute(URL url, String... additionalProxyExcludes) throws MNetRequestException {
    try {//from  w w  w  .ja va2s. c o m
        String content = buildRequest();
        StringEntity body = new StringEntity(content);
        CloseableHttpClient client = ClimateTray.PREFERENCES.getProxySettings()
                .createHttpClient(additionalProxyExcludes);
        HttpPost post = new HttpPost(url.toURI());

        post.setHeader("content-type", "text/xml");
        post.setEntity(body);

        LOG.debug("Sending request to \"%s\". The request is:\n%s", url.toExternalForm(), content);

        CloseableHttpResponse response;

        try {
            response = client.execute(post);
        } catch (IOException e) {
            throw new MNetRequestException("Failed to send request to \"%s\".", e, url.toExternalForm())
                    .hint(Message.error(
                            "Could not contact the centralized controller.\n\nThis usually indicates, that the value of the field \"Controller Address\" is wrong. "
                                    + "If you are sure, that the value is correct, there may be a firewall or a proxy in the way. "
                                    + "Try to call the URL \"%s\" in a browser.",
                            url.toExternalForm()));
        }

        try {
            int status = response.getStatusLine().getStatusCode();

            if ((status >= 200) && (status < 300)) {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    try {
                        InputStream in = entity.getContent();

                        try {
                            if (LOG.isDebugEnabled()) {
                                byte[] bytes = Utils.toByteArray(in);

                                LOG.debug("Reading response from \"%s\". The response is:\n%s",
                                        url.toExternalForm(), new String(bytes, "UTF-8"));

                                in = new ByteArrayInputStream(bytes);
                            }

                            parseResponse(in);
                        } finally {
                            in.close();
                        }
                    } catch (MNetRequestException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new MNetRequestException("Failed to parse response from \"%s\".", e,
                                url.toExternalForm())
                                        .hint(Message.error("The parsing of the response failed.\n\n"
                                                + "The request hit a server, but it may be the wrong one (the log may contain a more detailed description). "
                                                + "Check the contents of the field \"Controller Address\" or try to call the URL \"%s\" in a browser.",
                                                url.toExternalForm()));
                    }
                }
            } else {
                throw new MNetRequestException("Request to \"%s\" failed with error %d.", url.toExternalForm(),
                        status).hint(
                                Message.error("The request failed with error %d.\n\n"
                                        + "The request hit a server, but it may be the wrong one. "
                                        + "Check the contents of the field \"Controller Address\" again or try to call the URL \"%s\" in a browser.",
                                        status, url.toExternalForm()));
            }
        } finally {
            response.close();
        }
    } catch (MNetRequestException e) {
        throw e;
    } catch (Exception e) {
        throw new MNetRequestException("Sending an request to \"%s\" failed with an unhandled error: %s.", e,
                url.toExternalForm(), e.toString())
                        .hint(Message.error(
                                "The request failed for some unknown reason.\n\nYou can check the log for the detailed exception."));
    }
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

private String getOriginInfo(final Artifact artifact, final Model artifactPom) {
    final StrBuilder originInfo = new StrBuilder();
    {/*  w  w w  .j  av  a2s.com*/
        final String url = artifactPom.getUrl();
        if (isPotentialWebUrl(url)) {
            try {
                final URL organizationUrl = toUrl(url); // parse as URL to avoid surprises
                originInfo.append(escapeHtml4(artifactPom.getName()))
                        .append(" including its source is available from ");
                originInfo.append("<a href=\"").append(organizationUrl.toExternalForm())
                        .append("\" target=\"_blank\">");
                originInfo.append(escapeHtml4(removeWebProtocols(url)));
                originInfo.append("</a>.");
            } catch (final MalformedURLException e) {
                getLog().debug(e);
                getLog().warn(
                        format("Invalide project url '%s' in artifact pom '%s'.", url, artifact.getFile()));
            }
        } else if (StringUtils.isNotBlank(url)) {
            originInfo.append(escapeHtml4(artifactPom.getName()))
                    .append(" including its source is available from ");
            originInfo.append(escapeHtml4(url)).append('.');
        }
    }
    // fall-back to Maven coordinates
    if (originInfo.isEmpty()) {
        getLog().warn(format(
                "No project origin information is available for artifact '%s:%s:%s'. Please fill in manually.",
                artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
        originInfo.append(escapeHtml4(artifactPom.getName())).append(" is available from Maven as ");
        originInfo.append(escapeHtml4(artifact.getGroupId())).append(':')
                .append(escapeHtml4(artifact.getArtifactId())).append(':')
                .append(escapeHtml4(artifact.getVersion())).append('.');
    }

    // include additional contact information if available
    if (null != artifactPom.getIssueManagement()) {
        originInfo.append(' ');
        appendIssueTrackingInfo(originInfo, artifact, artifactPom);
    }

    if (!artifactPom.getMailingLists().isEmpty()) {
        originInfo.append(" The following");
        if (artifactPom.getMailingLists().size() == 1) {
            originInfo.append(" mailing list");
        } else {
            originInfo.append(" mailing lists");
        }
        originInfo.append(" can be used to communicate with the project communities: ");
        appendMailingListInfo(originInfo, artifact, artifactPom);
        originInfo.append(".");
    }
    return originInfo.toString();
}

From source file:com.digitalpebble.storm.crawler.bolt.FetcherBolt.java

private void handleRedirect(Tuple t, String sourceUrl, String newUrl, Metadata sourceMetadata) {

    // build an absolute URL
    URL sURL;// w  w  w  .  j av  a 2s . c om
    try {
        sURL = new URL(sourceUrl);
        URL tmpURL = URLUtil.resolveURL(sURL, newUrl);
        newUrl = tmpURL.toExternalForm();
    } catch (MalformedURLException e) {
        LOG.debug("MalformedURLException on {} or {}: {}", sourceUrl, newUrl, e);
        return;
    }

    // apply URL filters
    if (this.urlFilters != null) {
        newUrl = this.urlFilters.filter(sURL, sourceMetadata, newUrl);
    }

    // filtered
    if (newUrl == null) {
        return;
    }

    Metadata metadata = metadataTransfer.getMetaForOutlink(newUrl, sourceUrl, sourceMetadata);

    // TODO check that hasn't exceeded max number of redirections

    emitQueue.add(new Object[] { com.digitalpebble.storm.crawler.Constants.StatusStreamName, t,
            new Values(newUrl, metadata, Status.DISCOVERED) });
}

From source file:de.mpg.escidoc.pubman.util.InternationalizationHelper.java

private String getContent(URL url) throws Exception {

    HttpClient httpClient = new HttpClient();
    GetMethod getMethod = new GetMethod(url.toExternalForm());

    httpClient.executeMethod(getMethod);

    if (getMethod.getStatusCode() == 200) {

        BufferedReader in = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));

        String inputLine = "";
        String content = "";

        while (inputLine != null) {
            inputLine = in.readLine();/*from w w w . jav a  2  s.  c o m*/
            if (inputLine != null) {
                content += inputLine + "  ";
            }
        }

        in.close();

        return content;
    } else {
        return null;
    }

}

From source file:com.gargoylesoftware.htmlunit.WebRequestSettings.java

/**
 * Sets the target URL. The URL may be simplified if needed (for instance eliminating
 * irrelevant path portions like "/./").
 * @param url the target URL//from   w w  w . ja v a 2 s  . com
 */
public void setUrl(URL url) {
    if (url != null) {
        final String path = url.getPath();
        if (path.length() == 0) {
            url = buildUrlWithNewFile(url, "/" + url.getFile());
        } else if (path.contains("./")) {
            final String query = (url.getQuery() != null) ? "?" + url.getQuery() : "";
            url = buildUrlWithNewFile(url, removeDots(path) + query);
        }
        url_ = url.toExternalForm();
    } else {
        url_ = null;
    }
}

From source file:org.apache.servicemix.platform.testing.support.SmxPlatform.java

/**
 * Loads Felix config.properties.//from ww w  .ja  v  a  2 s.  c om
 *
 * <strong>Note</strong> the current implementation uses Felix's Main class
 * to resolve placeholders as opposed to loading the properties manually
 * (through JDK's Properties class or Spring's PropertiesFactoryBean).
 *
 * @return
 */
// TODO: this method should be removed once Felix 1.0.2 is released
private Properties getFelixConfiguration() {
    String location = "/".concat(ClassUtils.classPackageAsResourcePath(getClass())).concat("/")
            .concat(FELIX_CONF_FILE);
    URL url = getClass().getResource(location);
    if (url == null)
        throw new RuntimeException("cannot find felix configuration properties file:" + location);

    // used with Main
    System.getProperties().setProperty(FELIX_CONFIG_PROPERTY, url.toExternalForm());

    // load config.properties (use Felix's Main for resolving placeholders)
    Properties props = new Properties();
    InputStream is = null;
    try {
        is = url.openConnection().getInputStream();
        props.load(is);
        is.close();
    } catch (FileNotFoundException ex) {
        // Ignore file not found.
    } catch (Exception ex) {
        System.err.println("Main: Error loading system properties from " + url);
        System.err.println("Main: " + ex);
        try {
            if (is != null)
                is.close();
        } catch (IOException ex2) {
            // Nothing we can do.
        }
        return null;
    }
    // Perform variable substitution for system properties.
    for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        props.setProperty(name, substVars(props.getProperty(name), name, null, props));
    }
    return props;
}

From source file:com.gargoylesoftware.htmlunit.MockWebConnection.java

/**
 * Sets the response that will be returned when the specified URL is requested.
 * @param url the URL that will return the given response
 * @param content the content to return//from w  w w. j a  va 2  s .  c o m
 * @param statusCode the status code to return
 * @param statusMessage the status message to return
 * @param contentType the content type to return
 * @param charset the name of a supported charset
 * @param headers the response headers to return
 */
public void setResponse(final URL url, final String content, final int statusCode, final String statusMessage,
        final String contentType, final String charset, final List<NameValuePair> headers) {

    final RawResponseData responseEntry = buildRawResponseData(content, charset, statusCode, statusMessage,
            contentType, headers);
    responseMap_.put(url.toExternalForm(), responseEntry);
}