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.MockWebConnection.java

/**
 * Indicates if a response has already been configured for this URL.
 * @param url the url/*from  w  w w.j  ava  2  s .  c  o  m*/
 * @return {@code false} if no response has been configured
 */
public boolean hasResponse(final URL url) {
    return responseMap_.containsKey(url.toExternalForm());
}

From source file:com.sketchy.server.HttpServer.java

public void start() throws Exception {
    if (!IMAGE_UPLOAD_DIRECTORY.exists()) {
        if (!IMAGE_UPLOAD_DIRECTORY.mkdir()) {
            throw new Exception(
                    "Error Creating Upload Directory '" + IMAGE_UPLOAD_DIRECTORY.getAbsolutePath() + "!");
        }/*  w  ww.  ja va 2 s . co  m*/
    }

    Server server = new Server(80);

    // File Upload Handler
    ServletHolder imageUploadHolder = new ServletHolder(new ImageUploadServlet());
    MultipartConfigElement multipartConfig = new MultipartConfigElement(FileUtils.getTempDirectory().getPath());
    imageUploadHolder.getRegistration().setMultipartConfig(multipartConfig);

    // File Upgrade Handler
    ServletHolder upgradeUploadHolder = new ServletHolder(new UpgradeUploadServlet());
    multipartConfig = new MultipartConfigElement(FileUtils.getTempDirectory().getPath());
    upgradeUploadHolder.getRegistration().setMultipartConfig(multipartConfig);

    ServletHandler servletHandler = new ServletHandler();
    ServletContextHandler servletContext = new ServletContextHandler();
    servletContext.setHandler(servletHandler);
    servletContext.addServlet(new ServletHolder(new JsonServlet()), "/servlet/*");
    servletContext.addServlet(imageUploadHolder, "/imageUpload/*");
    servletContext.addServlet(upgradeUploadHolder, "/upgradeUpload/*");

    // if we are developing, we shouldn't have the Sketchy.jar file in our classpath.
    // in this case, pull from the filesystem, not the .jar

    ContextHandler resourceContext = new ContextHandler();

    URL url = server.getClass().getClassLoader().getResource("html");
    if (url != null) {
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);
        resourceContext.setWelcomeFiles(new String[] { "index.html" });
        resourceContext.setContextPath("/");
        String resourceBase = url.toExternalForm();
        resourceContext.setResourceBase(resourceBase);
        resourceContext.setHandler(resourceHandler);
    } else {
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);
        resourceContext.setWelcomeFiles(new String[] { "index.html" });
        resourceContext.setContextPath("/");
        resourceContext.setResourceBase(SOURCE_HTML_FILES_DIRECTORY.getCanonicalPath());
        resourceContext.setHandler(resourceHandler);
    }

    ResourceHandler uploadResourceHandler = new ResourceHandler();
    uploadResourceHandler.setDirectoriesListed(true);
    ContextHandler uploadResourceContext = new ContextHandler();
    uploadResourceContext.setContextPath("/upload");
    uploadResourceContext.setResourceBase("./upload");
    uploadResourceContext.setHandler(uploadResourceHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { resourceContext, servletContext, uploadResourceContext });
    server.setHandler(contexts);

    server.start();
    server.join();
}

From source file:net.heroicefforts.viable.android.rep.it.gdata.ProjectHostingService.java

/**
 * Fetches a feed of issue comments.//from  w  ww. j a  v  a2s.c  o  m
 * @param feedUrl a valid Gdata issue URL to issue comments
 * @return a feed of issue comments
 * @throws ServiceException if a service error occurs.
 */
public IssueCommentsFeed getFeed(URL feedUrl) throws ServiceException {
    try {
        String url = feedUrl.toExternalForm();
        if (url.indexOf('?') != -1)
            url += "&";
        else
            url += "?";
        url += "alt=json";
        HttpGet get = new HttpGet(new URI(url));
        HttpResponse response = execute(get);
        JSONObject obj = readJSON(response);
        return loadCommentFeed(obj);
    } catch (Exception e) {
        throw new ServiceException("Error executing query.", e);
    }
}

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

private void checkPrincipal(URL webAppURL, String username)
        throws MalformedURLException, ClientProtocolException, IOException, URISyntaxException, LoginException {

    final URL principalPrintingURL = new URL(
            webAppURL.toExternalForm() + PrincipalPrintingServlet.SERVLET_PATH.substring(1));
    final String principal = Utils.makeCallWithBasicAuthn(principalPrintingURL, username, "theduke", 200);
    assertEquals("Unexpected Principal name", username, principal);
}

From source file:org.apache.jmeter.protocol.http.control.HC4CookieHandler.java

@Override
public String getCookieHeaderForURL(CollectionProperty cookiesCP, URL url, boolean allowVariableCookie) {
    List<org.apache.http.cookie.Cookie> c = getCookiesForUrl(cookiesCP, url, allowVariableCookie);

    boolean debugEnabled = log.isDebugEnabled();
    if (debugEnabled) {
        log.debug("Found " + c.size() + " cookies for " + url.toExternalForm());
    }// www  .  j  ava  2 s .co  m
    if (c.size() <= 0) {
        return null;
    }
    List<Header> lstHdr = cookieSpec.formatCookies(c);

    StringBuilder sbHdr = new StringBuilder();
    for (Header header : lstHdr) {
        sbHdr.append(header.getValue());
    }

    return sbHdr.toString();
}

From source file:net.heroicefforts.viable.android.rep.it.gdata.ProjectHostingService.java

/**
 * Retrieves a single issue based upon an issue entity url.
 * @param feedUrl an issue entity url./* ww  w  .  ja v a2 s  . com*/
 * @return the issue entity or null if the entity was not found.
 * @throws ServiceException if a service error occurs.
 */
public Issue getEntry(URL feedUrl) throws ServiceException {
    try {
        String url = feedUrl.toExternalForm();
        if (url.indexOf('?') != -1)
            url += "&";
        else
            url += "?";
        url += "alt=json";
        HttpGet get = new HttpGet(new URI(url));
        HttpResponse response = execute(get);
        String body = readResponse(response);
        if (!notFound(body)) {
            JSONObject obj = new JSONObject(body);
            if (Config.LOGV)
                Log.v(TAG, "Entry response:  " + obj.toString(4));
            if (obj.has(ENTRY))
                return loadIssue(obj.getJSONObject(ENTRY));
        }

        return null;
    } catch (Exception e) {
        throw new ServiceException("Error executing query.", e);
    }
}

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

/**
 * Calls {@link PrincipalPrintingServlet} and checks if the returned principal name is the expected one.
 * //  w  ww .  ja v  a2  s. c  o m
 * @param url
 * @param expectedPrincipal
 * @return Principal name returned from {@link PrincipalPrintingServlet}
 */
private String assertPrincipal(URL url, String expectedPrincipal) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials creds = new UsernamePasswordCredentials("anyUsername");
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);
    HttpGet httpget = new HttpGet(url.toExternalForm() + PrincipalPrintingServlet.SERVLET_PATH);
    String text;

    try {
        HttpResponse response = httpclient.execute(httpget);
        assertEquals("Unexpected status code", HttpServletResponse.SC_OK,
                response.getStatusLine().getStatusCode());
        text = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        throw new RuntimeException("Servlet response IO exception", e);
    }

    assertEquals("Unexpected principal name assigned by IdentityLoinModule", expectedPrincipal, text);
    return text;
}

From source file:com.digitalpebble.stormcrawler.bolt.SimpleFetcherBolt.java

/** Used for redirections or when discovering sitemap URLs **/
private void handleOutlink(Tuple t, URL sURL, String newUrl, Metadata sourceMetadata, boolean markAsSitemap) {
    // build an absolute URL
    try {/* w  w w . ja v a 2  s  .com*/
        URL tmpURL = URLUtil.resolveURL(sURL, newUrl);
        newUrl = tmpURL.toExternalForm();
    } catch (MalformedURLException e) {
        LOG.debug("MalformedURLException on {} or {}: {}", sURL.toExternalForm(), newUrl, e);
        return;
    }

    // apply URL filters
    newUrl = this.urlFilters.filter(sURL, sourceMetadata, newUrl);

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

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

    if (markAsSitemap) {
        metadata.setValue(SiteMapParserBolt.isSitemapKey, "true");
    }

    _collector.emit(com.digitalpebble.stormcrawler.Constants.StatusStreamName, t,
            new Values(newUrl, metadata, Status.DISCOVERED));
}

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

protected void scanArtifactsManifests(Predicate<Pair<URL, Manifest>> manifestHandler) {
    ClassLoader loader = ExtendedClassUtils.getDefaultClassLoader(getClass());
    try {//from   www.  j  ava  2  s .c o  m
        for (Enumeration<URL> manifests = loader.getResources(JarFile.MANIFEST_NAME); (manifests != null)
                && manifests.hasMoreElements();) {
            URL url = manifests.nextElement();
            try {
                Manifest manifest = ManifestUtils.loadManifest(url);
                if (manifestHandler.evaluate(Pair.of(url, manifest))) {
                    logger.info("Scanning stopped by handler at URL=" + url.toExternalForm());
                    break;
                }
            } catch (Exception e) {
                logger.warn(e.getClass().getSimpleName() + " while handle URL=" + url.toExternalForm() + ": "
                        + e.getMessage());
            }
        }
    } catch (IOException e) {
        logger.warn("Failed (" + e.getClass().getSimpleName() + ") to get manifests URLs: " + e.getMessage());
    }
}