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:de.juwimm.cms.common.http.HttpClientWrapper.java

protected HttpMethodBase invoke(URL targetURL, String userName, String password) throws URIException {
    HttpMethodBase method = null;/* w w w  .  ja va 2s .c o  m*/
    if (log.isDebugEnabled())
        log.debug(targetURL.toExternalForm());
    method = new GetMethod(targetURL.toExternalForm());
    HttpClient httpClient = getNewHttpClient();
    if (userName != null) {
        // Credentials for destination URL
        Credentials cred = new UsernamePasswordCredentials(userName, password);
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AUTHSCOPE_ANY, cred);
    }
    setHostConfiguration(httpClient, targetURL);
    String returnMessage = null;
    int returnCode = 500;
    try {
        returnCode = httpClient.executeMethod(method);
    } catch (InvalidCredentialsException exe) {
        if (log.isInfoEnabled())
            log.info("Invalid credentials trying to authenticate: " + exe.getMessage());
    } catch (HttpException exe) {
        log.error("while connection to: " + targetURL.getHost() + " an unknown error occured (HttpException): "
                + exe.getMessage());
    } catch (SSLPeerUnverifiedException exe) {
        returnCode = 516;
        returnMessage = exe.getMessage();
    } catch (IOException exe) {
        log.error("while connection to: " + targetURL.getHost() + " using Proxy: " + this.isUsingProxy()
                + " host: " + this.getHttpProxyHost() + " on Port: " + this.httpProxyPort + " together: "
                + this.getProxyServer() + " an unknown error occured (IOException): "
                + targetURL.toExternalForm() + " " + exe.getMessage());
    } catch (Exception exe) {
        log.error("while connection to: " + targetURL.getHost() + " an unknown error occured: "
                + exe.getMessage());
    }

    if ((returnCode > 199) && (returnCode < 300)) {
        // return is OK - so fall through
        if (log.isDebugEnabled())
            log.debug("good return code: " + returnCode);
    } else if (returnCode == 401) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.401_authRequired");
    } else if (returnCode == 404) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.404_notFound");
    } else if (returnCode == 407) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.407_proxyAuthRequired");
    } else if (returnCode == 403) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.403_Forbidden");
    } else if (returnCode == 503) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.503_ServiceUnavailable");
    } else if (returnCode == 504) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.504_ProxyTimeout");
    } else if (returnCode == 516) {
        returnMessage = HttpMessages.getString("HttpClientWrapper.516_SSLPeerUnverified", returnMessage);
    } else {
        returnMessage = "Unknown error with return code " + returnCode;
    }
    if (returnMessage != null) {
        throw new URIException(returnCode, returnMessage);
    }
    return method;
}

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

/**
 * Gets the raw response configured for the request.
 * @param request the request/*from w  w  w  .  j  ava 2  s  .  co m*/
 * @return the raw response
 */
public RawResponseData getRawResponse(final WebRequest request) {
    final URL url = request.getUrl();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Getting response for " + url.toExternalForm());
    }

    lastRequest_ = request;
    requestCount_++;
    requestedUrls_.add(url);

    RawResponseData rawResponse = responseMap_.get(url.toExternalForm());
    if (rawResponse == null) {
        rawResponse = defaultResponse_;
        if (rawResponse == null) {
            throw new IllegalStateException(
                    "No response specified that can handle URL [" + url.toExternalForm() + "]");
        }
    }

    return rawResponse;
}

From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java

@Test
public void testNotAuthorizedResource() throws Exception {
    URL url = new URL(urlStr + "confidentialResource");

    DefaultHttpClient httpclient = null;
    try {/*from w  w  w . j  a  v a 2s .  c  om*/
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        DigestHolder digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(403, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:ch.entwine.weblounge.common.impl.content.page.PageTemplateImpl.java

/**
 * Processes both renderer and editor url by replacing templates in their
 * paths with real values from the actual module.
 * //from   w w  w  . ja  v a2 s  .  c o  m
 * @param environment
 *          the environment
 * 
 * @return <code>false</code> if the paths don't end up being real urls,
 *         <code>true</code> otherwise
 */
private boolean processURLTemplates(Environment environment) {
    if (site == null)
        throw new IllegalStateException("Site cannot be null");

    // Process the renderer URL
    for (Map.Entry<String, URL> entry : renderers.entrySet()) {
        URL renderer = entry.getValue();
        String rendererURL = ConfigurationUtils.processTemplate(renderer.toExternalForm(), site, environment);
        try {
            renderer = new URL(rendererURL);
            renderers.put(entry.getKey(), renderer);
        } catch (MalformedURLException e) {
            logger.error("Renderer url {} of pagelet {} is malformed", rendererURL, this);
        }
    }

    // Process the head elements (scripts and stylesheet includes)
    for (HTMLHeadElement headElement : headers) {
        headElement.setEnvironment(environment);
    }

    return true;
}

From source file:com.intuit.tank.http.BaseRequest.java

/**
 * Execute the POST./*  w w  w. j  a  v a2s  .  c  o m*/
 */
public void doPost(BaseResponse response) {
    PostMethod httppost = null;
    String theUrl = null;
    try {
        URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables);
        theUrl = url.toExternalForm();
        httppost = new PostMethod(url.toString());
        String requestBody = getBody();
        StringRequestEntity entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet);
        httppost.setRequestEntity(entity);

        sendRequest(response, httppost, requestBody);
    } catch (MalformedURLException e) {
        logger.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(e);
    } catch (Exception ex) {
        // logger.error(LogUtil.getLogMessage(ex.toString()), ex);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(ex);
    } finally {
        if (null != httppost) {
            httppost.releaseConnection();
        }
        if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) {
            logger.info(LogUtil.getLogMessage("Response from POST to " + theUrl + " got status code "
                    + response.httpCode + " BODY { " + response.response + " }", LogEventType.Informational));
        }
    }

}

From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private ConnectionFactory createConnectionFactory(boolean profileSql) throws MalformedURLException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();
    URL url = new URL(jdbcDriverClassPath);
    try {/* w w  w .j  a  v a  2s .com*/
        File file = new File(url.toURI());
        if (!file.exists()) {
            throw new IllegalStateException("JDBC driver class path not found: " + file);
        }
    } catch (URISyntaxException e) {
        throw new IllegalStateException(
                "Unable to convert URL " + url.toExternalForm() + " into URI: " + e.getMessage(), e);
    }
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url },
            Thread.currentThread().getContextClassLoader());

    String jdbcDriverClassName = globalConfiguration.getJdbcDriverClassName();
    String connectURI = globalConfiguration.getJdbcConnectionURI(); // + "?initialTimeout=2";
    String userName = globalConfiguration.getJdbcUsername();
    String password = globalConfiguration.getJdbcPassword();

    Class<?> aClass = null;
    try {
        aClass = Class.forName(jdbcDriverClassName, true, urlClassLoader);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Unable to locate class " + jdbcDriverClassName + " in class path '"
                + jdbcDriverClassPath + "'");
    }
    Driver driver = (Driver) aClass.newInstance();
    assertTrue(driver.acceptsURL(connectURI));

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);
    if (profileSql) {
        properties.put("profileSQL", "true"); // MySQL debug option
    }
    return new DriverConnectionFactory(driver, connectURI, properties);
}

From source file:com.apdplat.platform.spring.APDPlatPersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the <code>persistence.xml</code> file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws IOException if the checking failed
 *//*from   ww w. j a  va 2  s.  c  o m*/
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();
    String urlToString = originalURL.toExternalForm();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    else {
        // check META-INF folder
        if (!urlToString.contains(META_INF)) {
            if (logger.isInfoEnabled()) {
                logger.info(resource.getFilename()
                        + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                        + resource);
            }
            return null;
        }
        if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
            if (logger.isInfoEnabled()) {
                logger.info(resource.getFilename()
                        + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                        + resource);
            }
            return null;
        }

        String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
        return new URL(persistenceUnitRoot);
    }
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HtmlArchiver.java

final public String getUrlFileName(String src) {
    if (urlFileMap == null)
        return null;
    URL objectURL = LinkUtils.getLink(pageUrl, src, null, false);
    String url = objectURL == null ? src : objectURL.toExternalForm();
    return urlFileMap.get(url);
}

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected RemoteTask remoteImport(DBAttachment target) throws Exception {
    Reference uri = new Reference(queryService);

    HttpClient client = createHTTPClient(uri.getHostDomain(), uri.getHostPort());
    RemoteTask task = new RemoteTask(client, new URL(String.format("%s/dataset", queryService)),
            "text/uri-list", createPOSTEntity(attachment), HttpPost.METHOD_NAME);

    try {//  www  .  j  a v a2 s.  com
        task = wait(task, System.currentTimeMillis());
        String dataset_uri = "dataset_uri";
        URL dataset = task.getResult();
        if (task.isCompletedOK()) {
            if (!"text/uri-list".equals(attachment.getFormat())) { //was a file
                //now post the dataset uri to get the /R datasets (query table)
                attachment.setFormat("text/uri-list");
                attachment.setDescription(dataset.toExternalForm());
                task = new RemoteTask(client, new URL(String.format("%s/dataset", queryService)),
                        "text/uri-list", createPOSTEntity(attachment), HttpPost.METHOD_NAME);
                task = wait(task, System.currentTimeMillis());
            }

            Form form = new Form();
            form.add(dataset_uri, dataset.toURI().toString());
            for (String algorithm : algorithms) { //just launch tasks and don't wait
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair(dataset_uri, dataset.toURI().toString()));
                HttpEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpClient newclient = createHTTPClient(uri.getHostDomain(), uri.getHostPort());
                try {
                    new RemoteTask(newclient, new URL(String.format("%s%s", queryService, algorithm)),
                            "text/uri-list", entity, HttpPost.METHOD_NAME);

                } catch (Exception x) {
                } finally {
                    try {
                        newclient.getConnectionManager().shutdown();
                    } catch (Exception x) {
                    }
                }
            }
        }

    } catch (Exception x) {
        task.setError(new ResourceException(Status.SERVER_ERROR_BAD_GATEWAY,
                String.format("Error importing chemical structures dataset to %s", uri), x));
    } finally {
        try {
            client.getConnectionManager().shutdown();
        } catch (Exception x) {
        }
    }
    return task;
}

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

private void appendMailingListInfo(final StrBuilder text, final Artifact artifact, final Model artifactPom) {
    boolean first = true;
    for (final Iterator<MailingList> stream = artifactPom.getMailingLists().iterator(); stream.hasNext();) {
        final MailingList mailingList = stream.next();
        if (!first && !stream.hasNext()) {
            text.append(" or ");
        } else if (!first && stream.hasNext()) {
            text.append(", ");
        } else {/*www  .j a va 2s.  c om*/
            first = false;
        }
        text.append(escapeHtml4(mailingList.getName()));
        if (StringUtils.isNotBlank(mailingList.getPost())) {
            text.append(" &lt;").append(escapeHtml4(mailingList.getPost())).append("&gt;");
        }
        final String url = mailingList.getArchive();
        if (isPotentialWebUrl(url)) {
            try {
                final URL archiveUrl = toUrl(url); // parse as URL to avoid surprises
                text.append(" (<a href=\"").append(archiveUrl.toExternalForm())
                        .append("\" target=\"_blank\">archive</a>)");
            } catch (final MalformedURLException e) {
                getLog().debug(e);
                getLog().warn(format("Invalide mailing list archive url '%s' in artifact pom '%s'.", url,
                        artifact.getFile()));
            }
        }
    }
}