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:org.uiautomation.ios.server.grid.RegistrationRequest.java

public void registerToHub() {

    HttpClient client = new DefaultHttpClient();
    try {// w w w. j a  va2  s . c  o m
        URL registration = new URL(hubURL);

        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                registration.toExternalForm());

        String json = getJSONRequest().toString();

        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 WebDriverException("Error sending the registration request.", e);
    }

}

From source file:de.smartics.maven.plugin.jboss.modules.util.classpath.ClassPathContext.java

/**
 * Constructs the URL to the resource.//from   w w w. j ava  2  s. co  m
 *
 * @param resource the resource whose URL is requested.
 * @return the URL to the resource or <code>null</code> if the resource cannot
 *         be found on the class path.
 */
public URL getResource(final String resource) {
    if (archiveRoot == null) {
        return classLoader.getResource(resource);
    }

    // TODO: maybe we should simply construct the URL?
    try {
        for (final Enumeration<URL> en = classLoader.getResources(resource); en.hasMoreElements();) {
            final URL current = en.nextElement();
            final String urlString = current.toExternalForm();
            if (urlString.startsWith(archiveRoot)) {
                return current;
            }
        }
    } catch (final IOException e) {
        // return null
    }
    return null;
}

From source file:org.jboss.as.test.manualmode.web.valve.authenticator.DescriptorValveAuthenticatorTestCase.java

@Test
@InSequence(1)//from  ww  w  .  ja v  a  2  s .  c om
public void testWebDescriptor(@ArquillianResource URL url, @ArquillianResource ManagementClient client)
        throws Exception {
    String appUrl = url.toExternalForm() + WEB_APP_URL;
    log.debug("Testing url " + appUrl + " against one authenticator valve defined in jboss-web.xml descriptor");
    Header[] valveHeaders = ValveUtil.hitValve(new URL(appUrl));
    assertEquals("There was one valve defined - it's missing now", 1, valveHeaders.length);
    assertEquals(WEB_PARAM_VALUE, valveHeaders[0].getValue());
}

From source file:org.jenkinsci.plugins.fortifycloudscan.RulepackResolver.java

/**
 * Download a file from the specified URL and place into a temporary directory.
 * Attempts to guess the filename from the HTTP response. If not successful, the
 * filename will be derived from the URL.
 * @param url the URL to download the file from
 * @return a File object where the downloaded file is saved
 *///from  w ww  .  j av  a2  s  .c  om
private File download(URL url) {
    String urlString = url.toExternalForm();
    File temp = new File(
            tempDir + File.separator + FortifyCloudScanPlugin.PLUGIN_NAME + File.separator + UUID.randomUUID());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(urlString);

    CloseableHttpResponse response;
    File downloadedFile;
    try {
        logger.log("Downloading rulepack from " + urlString);
        response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            if (temp.mkdirs()) {
                logger.log("Created temporary rulepack download directory");
            }
            String suggestedFilename = getSuggestedFilename(response);
            String filename = (suggestedFilename != null) ? suggestedFilename
                    : FilenameUtils.getName(urlString);
            downloadedFile = new File(temp + File.separator + filename);
        } else {
            logger.log("ERROR: Remote file cannot be downloaded");
            logger.log("ERROR: Status Code: " + response.getStatusLine().getStatusCode() + " - "
                    + response.getStatusLine().getReasonPhrase());
            return null;
        }
    } catch (IOException e) {
        logger.log("ERROR: An error occurred while attempting to download rulepack");
        logger.log(e.getMessage());
        return null;
    }
    HttpEntity entity = response.getEntity();
    try {
        if (entity != null) {
            FileOutputStream outstream = new FileOutputStream(downloadedFile);
            entity.writeTo(outstream);
            logger.log("Rulepack saved to " + downloadedFile.getAbsolutePath());
        }
    } catch (FileNotFoundException e) {
        logger.log("ERROR: The download file location cannot be found");
        logger.log(e.getMessage());
    } catch (IOException e) {
        logger.log("ERROR: An error occurred while saving the rulepack");
        logger.log(e.getMessage());
    }
    return downloadedFile;
}

From source file:com.redhat.rcm.version.testutil.HttpTestService.java

public String start() throws Exception {
    final Random rand = new Random();
    int tries = 0;

    String baseUrl = null;/*  w w  w.j a  va2 s .c o  m*/
    while (tries < MAX_TRIES) {
        final int port = (Math.abs(rand.nextInt()) % 63000) + 1024;
        server = new Server(port);
        server.setHandler(new AbstractHandler() {
            @Override
            public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
                    final HttpServletResponse response) throws IOException, ServletException {
                System.out.println("GET: " + target);
                final URL res = paths.get(target);
                if (res != null) {
                    System.out.println(" --> " + res.toExternalForm());
                    InputStream stream = null;
                    try {
                        stream = res.openStream();
                        copy(stream, response.getOutputStream());
                    } finally {
                        closeQuietly(stream);
                    }

                    baseRequest.setHandled(true);
                } else {
                    response.sendError(404);
                }
            }
        });

        try {
            server.start();

            baseUrl = "http://localhost:" + server.getConnectors()[0].getPort();
            System.out.println("HTTP server started on port: " + port);
            break;
        } catch (final Exception e) {
            e.printStackTrace();
        }

        tries++;
    }

    if (tries > MAX_TRIES) {
        throw new IllegalStateException("Cannot start HTTP server.");
    }

    return baseUrl;
}

From source file:com.thinkberg.webdav.PropFindHandler.java

/**
 * Create a multistatus response by requesting all properties and writing a response for each
 * the found and the non-found properties
 *
 * @param object  the context object the propfind request applies to
 * @param propEl  the &lt;prop&gt; element containing the actual properties
 * @param baseUrl the base url of this server
 * @param depth   a depth argument for how deep the find will go
 * @return an XML document that is the response
 * @throws FileSystemException if there was an error executing the propfind request
 *//*from ww w  .jav  a2s  . co  m*/
private Document getMultiStatusResponse(FileObject object, Element propEl, URL baseUrl, int depth)
        throws FileSystemException {
    Document propDoc = DocumentHelper.createDocument();
    propDoc.setXMLEncoding("UTF-8");

    Element multiStatus = propDoc.addElement(TAG_MULTISTATUS, NAMESPACE_DAV);
    FileObject[] children = object.findFiles(new DepthFileSelector(depth));
    for (FileObject child : children) {
        Element responseEl = multiStatus.addElement(TAG_RESPONSE);
        try {
            URL url = new URL(baseUrl, URLEncoder.encode(child.getName().getPath(), "UTF-8"));
            responseEl.addElement(TAG_HREF).addText(url.toExternalForm());
        } catch (Exception e) {
            LOG.error("can't set href in response", e);
        }
        DavResource resource = DavResourceFactory.getInstance().getDavResource(child);
        resource.getPropertyValues(responseEl, propEl);
    }
    return propDoc;
}

From source file:org.jboss.as.test.integration.security.loginmodules.databases.ExternalDatabaseLoginTestCase.java

/**
 * Tests access to a protected servlet./*from  ww w.j a  va  2 s .  c o m*/
 *
 * @param url
 * @throws MalformedURLException
 * @throws ClientProtocolException
 * @throws IOException
 * @throws URISyntaxException
 * @test.objective Test whether user with right name and password is
 * correctly authenticated and authorized. Also test
 * unsuccessful authentication and authorization.
 * <p>
 * It uses web.xml and jboss-web.xml files.
 * @test.expectedResult All asserts are correct and test finishes without
 * any exception.
 */
private void testAccess(URL url) throws IOException, URISyntaxException {
    final URL servletUrl = new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1));
    // successful authentication and authorization
    assertEquals("Response body is not correct.", SimpleSecuredServlet.RESPONSE_BODY,
            Utils.makeCallWithBasicAuthn(servletUrl, ANIL, ANIL, 200));
    // successful authentication and unsuccessful authorization
    Utils.makeCallWithBasicAuthn(servletUrl, MARCUS, MARCUS, 403);
    // unsuccessful authentication
    Utils.makeCallWithBasicAuthn(servletUrl, ANIL, MARCUS, 401);
    Utils.makeCallWithBasicAuthn(servletUrl, ANIL, Utils.hash(ANIL, MD5, Coding.BASE_64), 401);
    Utils.makeCallWithBasicAuthn(servletUrl, ANIL, Utils.hash(ANIL, MD5, Coding.HEX), 401);
}

From source file:org.apache.commons.rdf.integrationtests.JSONLDParsingTest.java

private void jenaParse(URL url) {
    JenaDataset dataset = new JenaRDF().createDataset();
    RDFDataMgr.read(dataset.asJenaDatasetGraph(), url.toExternalForm());
    checkGraph(dataset.getGraph());// w w w  .  java 2s  .co  m
}

From source file:org.jcodec.player.filters.http.HttpMedia.java

public HttpMedia(URL url, File cacheWhere) throws IOException {
    cacheWhere = new File(cacheWhere, url.getHost() + "_" + url.getPath().replace("/", "_"));

    String data = requestInfo(url, getHttpClient(url.toExternalForm()));

    MediaInfo[] mediaInfos = MediaInfoParser.parseMediaInfos(data);
    for (int i = 0; i < mediaInfos.length; i++) {
        if (mediaInfos[i] == null)
            continue;
        try {/*from  www.  j  a  va  2s.c o  m*/
            HttpPacketSource ps = new HttpPacketSource(url.toExternalForm() + "/" + i,
                    new File(cacheWhere + "_" + i), mediaInfos[i]);
            tracks.add(ps);
            if (mediaInfos[i] instanceof VideoInfo)
                videoTrack = ps;
            else
                audioTracks.add(ps);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}