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.google.sites.liberation.imprt.EntryUploaderImpl.java

@Override
public BaseContentEntry<?> uploadEntry(BaseContentEntry<?> entry, List<BasePageEntry<?>> ancestors, URL feedUrl,
        SitesService sitesService) {/*from www  .j a v a2  s.  c  o  m*/
    checkNotNull(entry);
    checkNotNull(ancestors);
    checkNotNull(feedUrl);
    checkNotNull(sitesService);
    BaseContentEntry<?> returnedEntry = null;
    if (entry.getId() != null) {
        if (entry.getId().startsWith(feedUrl.toExternalForm() + "/")) {
            returnedEntry = getEntryById(entry, sitesService);
        } else {
            entry.setId(null);
        }
    }
    if (returnedEntry == null) {
        if (isPage(entry) || getType(entry) == ATTACHMENT || getType(entry) == WEB_ATTACHMENT) {
            returnedEntry = getEntryByPath(entry, ancestors, feedUrl, sitesService);
        } else if (getType(entry) == COMMENT) {
            // TODO(gk5885): remove extra cast for
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302214
            if (commentExists((CommentEntry) (BaseContentEntry) entry, feedUrl, sitesService)) {
                return entry;
            }
        } else if (getType(entry) == LIST_ITEM) {
            // TODO(gk5885): remove extra cast for
            // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302214
            if (listItemExists((ListItemEntry) (BaseContentEntry) entry, feedUrl, sitesService)) {
                return entry;
            }
        }
    }
    if (returnedEntry == null) {
        return entryInserter.insertEntry(entry, feedUrl, sitesService);
    } else {
        return entryUpdater.updateEntry(returnedEntry, entry, sitesService);
    }
}

From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java

private void registerToHub(boolean checkPresenceFirst) {
    if (!checkPresenceFirst || !isAlreadyRegistered(nodeConfig)) {
        String tmp = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":"
                + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/register";

        HttpClient client = httpClientFactory.getHttpClient();
        try {/*from  www.  ja v a2 s.c o  m*/
            URL registration = new URL(tmp);
            log.info("Registering the node to hub :" + registration);

            BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                    registration.toExternalForm());
            String json = nodeConfig.toJSON();
            r.setEntity(new StringEntity(json));

            HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
            HttpResponse response = client.execute(host, r);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Error sending the registration request.");
            }
        } catch (Exception e) {
            throw new GridException("Error sending the registration request.", e);
        }
    } else {
        log.fine("The node is already present on the hub. Skipping registration.");
    }

}

From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Test
public void testBasicAuth() throws Exception {
    URL url = new URL(urlStr);

    DefaultHttpClient httpclient = null;
    try {/*  w w w  . ja  v  a  2 s  .  c o  m*/
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm());

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity 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(200, 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:com.nextep.datadesigner.Designer.java

/**
 * Returns the image descriptor with the given relative path.
 */// w  ww  .  j  a v a2  s. com
public String getFullPath(String relativePath) {

    try {
        CorePlugin plugin = CorePlugin.getDefault();
        URL url = plugin.getBundle().getEntry(relativePath); // getDescriptor().getInstallURL();
        url = FileLocator.resolve(url);
        return url.toExternalForm();
    } catch (Exception e) {
        throw new ErrorException(e);
    }
}

From source file:org.wildfly.test.integration.elytron.permissionmappers.ConstantPermissionMapperTestCase.java

/**
 * Makes request to {@link CheckIdentityPermissionServlet}.
 *///from  w ww .jav a2 s.  c  o  m
private String doPermissionCheckPostReq(URL url, String user, String password, String className, String target,
        String action)
        throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException {
    String body;
    final URI uri = new URI(url.toExternalForm() + CheckIdentityPermissionServlet.SERVLET_PATH.substring(1));
    final HttpPost post = new HttpPost(uri);
    List<NameValuePair> nvps = new ArrayList<>();
    setParam(nvps, CheckIdentityPermissionServlet.PARAM_USER, user);
    setParam(nvps, CheckIdentityPermissionServlet.PARAM_PASSWORD, password);
    setParam(nvps, CheckIdentityPermissionServlet.PARAM_CLASS, className);
    setParam(nvps, CheckIdentityPermissionServlet.PARAM_TARGET, target);
    setParam(nvps, CheckIdentityPermissionServlet.PARAM_ACTION, action);
    post.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == SC_FORBIDDEN && user != null) {
                return Boolean.toString(false);
            }
            assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
            body = EntityUtils.toString(response.getEntity());
        }
    }
    return body;
}

From source file:ca.nrc.cadc.sc2pkg.PackageIntTest.java

@Test
public void testMutliID() {
    File tar = null;/*from   ww w  . j a  v  a  2  s .c  o m*/
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("?ID=").append(SINGLE_ARTIFACT);
        sb.append("&ID=").append(SINGLE_ARTIFACT2);
        sb.append("&ID=").append(SINGLE_ARTIFACT3);
        sb.append("&ID=").append(SINGLE_ARTIFACT4);
        URL serviceURL = reg.getServiceURL(URI.create(SERVICE_ID), Standards.PKG_10, AuthMethod.ANON);
        URL url = new URL(serviceURL.toExternalForm() + sb.toString());
        File tmp = new File(System.getProperty("java.io.tmpdir"));

        log.info("testMutliID: " + url + " -> " + tmp.getAbsolutePath());

        HttpDownload get = new HttpDownload(url, tmp);
        get.setOverwrite(true); // file exists from create above
        get.run();
        Assert.assertNull("throwable", get.getThrowable());
        Assert.assertEquals(200, get.getResponseCode());
        tar = get.getFile();
        Assert.assertTrue("tar file exists", tar.exists());

        // validate
        List<String> expectedFiles = new ArrayList<String>();
        expectedFiles.add("IRIS-f212h000-IRAS-12um/I212B1H0.fits");
        expectedFiles.add("IRIS-f212h000-IRAS-25um/I212B2H0.fits");
        expectedFiles.add("IRIS-f212h000-IRAS-60um/I212B3H0.fits");
        expectedFiles.add("IRIS-f212h000-IRAS-100um/I212B4H0.fits");
        expectedFiles.add("IRIS-f212h000-IRAS-12um/README");
        expectedFiles.add("IRIS-f212h000-IRAS-25um/README");
        expectedFiles.add("IRIS-f212h000-IRAS-60um/README");
        expectedFiles.add("IRIS-f212h000-IRAS-100um/README");

        // extract tar file and check all the files vs the md5sum in README?
        FileInputStream fis = new FileInputStream(tar);
        TarArchiveInputStream tis = new TarArchiveInputStream(fis);
        Content c1 = getEntry(tis);
        Content c2 = getEntry(tis);
        Content c3 = getEntry(tis);
        Content c4 = getEntry(tis);
        Content r1 = getEntry(tis);
        Content r2 = getEntry(tis);
        Content r3 = getEntry(tis);
        Content r4 = getEntry(tis);

        ArchiveEntry te = tis.getNextTarEntry();
        Assert.assertNull(te);

        Assert.assertTrue(expectedFiles.contains(c1.name));
        Assert.assertTrue(expectedFiles.contains(c2.name));
        Assert.assertTrue(expectedFiles.contains(c3.name));
        Assert.assertTrue(expectedFiles.contains(c4.name));
        Assert.assertTrue(expectedFiles.contains(r1.name));
        Assert.assertTrue(expectedFiles.contains(r2.name));
        Assert.assertTrue(expectedFiles.contains(r3.name));
        Assert.assertTrue(expectedFiles.contains(r4.name));

        log.debug("testMutliID: " + c1.name + " " + c1.contentMD5);
        log.debug("testMutliID: " + c2.name + " " + c2.contentMD5);
        log.debug("testMutliID: " + c3.name + " " + c3.contentMD5);
        log.debug("testMutliID: " + c4.name + " " + c4.contentMD5);

        // merge md5map(s)
        Map<String, String> md5map = new HashMap<String, String>();
        md5map.putAll(r1.md5map);
        md5map.putAll(r2.md5map);
        md5map.putAll(r3.md5map);
        md5map.putAll(r4.md5map);
        log.debug("testMutliID: " + md5map.size());

        String c1md5 = md5map.get(getFilename(c1.name));
        String c2md5 = md5map.get(getFilename(c2.name));
        String c3md5 = md5map.get(getFilename(c3.name));
        String c4md5 = md5map.get(getFilename(c4.name));

        Assert.assertNotNull(c1md5);
        Assert.assertEquals(c1md5, c1.contentMD5);

        Assert.assertNotNull(c2md5);
        Assert.assertEquals(c2md5, c2.contentMD5);

        Assert.assertNotNull(c3md5);
        Assert.assertEquals(c3md5, c3.contentMD5);

        // cleanup here so we leave file behind on fail
        if (tar.exists())
            tar.delete();
    } catch (Exception unexpected) {
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    }
}

From source file:io.adeptj.runtime.osgi.BundleInstaller.java

private Bundle installBundle(URL bundleUrl, BundleContext systemBundleContext) {
    LOGGER.debug("Installing Bundle from location: [{}]", bundleUrl);
    Bundle bundle = null;/*  w w w. j  a v a  2  s. com*/
    try (JarInputStream jar = new JarInputStream(bundleUrl.openStream(), false)) {
        if (StringUtils.isEmpty(jar.getManifest().getMainAttributes().getValue(BUNDLE_SYMBOLIC_NAME))) {
            LOGGER.warn("Not an OSGi Bundle: {}", bundleUrl);
        } else {
            bundle = systemBundleContext.installBundle(bundleUrl.toExternalForm());
            this.installCount.incrementAndGet();
        }
    } catch (BundleException | IllegalStateException | SecurityException | IOException ex) {
        LOGGER.error("Exception while installing Bundle: [{}]. Cause:", bundleUrl, ex);
    }
    return bundle;
}

From source file:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java

private UriComponents uriComponents() {
    URL url = webRequest.getUrl();
    UriComponentsBuilder uriBldr = UriComponentsBuilder.fromUriString(url.toExternalForm());
    return uriBldr.build();
}

From source file:org.jboss.as.test.integration.web.security.authentication.BasicAuthenticationMechanismPicketboxRemovedTestCase.java

/**
 * Test checks if correct response is returned after the EJB is called from the secured servlet.
 *
 * @param url//from  w  w w  .ja  v a 2  s  . c o m
 * @throws Exception
 */
@Test
public void test(@ArquillianResource URL url) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(USER, PASSWORD));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm() + "SecuredEJBServlet/");
        HttpResponse response = httpclient.execute(httpget);
        assertNotNull("Response is 'null', we expected non-null response!", response);
        String text = Utils.getContent(response);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertTrue("User principal different from what we expected!", text.contains("Principal: " + USER));
        assertTrue("Remote user different from what we expected!", text.contains("Remote User: " + USER));
        assertTrue("Authentication type different from what we expected!",
                text.contains("Authentication Type: BASIC"));
    }
}

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

@Test
public void testDigestAuth() throws Exception {
    URL url = new URL(this.urlStr + "/onlyManagers/");

    DefaultHttpClient httpclient = null;
    try {/*from   ww  w  .  j  a  va  2  s  . 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);
        Digest 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(404, 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();
    }
}