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:coria2015.server.ContentServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final URL url;
    IMAGE_URI = "/recipe/image/";
    if (request.getRequestURI().startsWith(IMAGE_URI)) {

        String recipeName = URLDecoder.decode(request.getRequestURI().substring(IMAGE_URI.length()), "UTF-8")
                .replace(" ", "-");
        String name = recipeImages.get(recipeName);
        File file = new File(imagePath, name);
        url = file.toURI().toURL();/*from w ww . ja  v  a 2  s.  com*/
    } else {
        url = ContentServlet.class.getResource(format("/web%s", request.getRequestURI()));
    }

    if (url != null) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(url.toExternalForm());
        if (file.getType() == FileType.FOLDER) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", format("%sindex.html", request.getRequestURI()));
            return;
        }

        String filename = url.getFile();
        if (filename.endsWith(".html"))
            response.setContentType("text/html");
        else if (filename.endsWith(".png"))
            response.setContentType("image/png");
        else if (filename.endsWith(".css"))
            response.setContentType("text/css");
        response.setStatus(HttpServletResponse.SC_OK);

        final ServletOutputStream out = response.getOutputStream();
        InputStream in = url.openStream();
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        in.close();
        return;
    }

    // Not found
    error404(request, response);

}

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

final private String downloadObject(URL parentUrl, String src, String contentType)
        throws ClientProtocolException, IllegalStateException, IOException, SearchLibException,
        URISyntaxException {/*from   www. j  ava  2 s  . c o m*/
    RecursiveEntry recursiveEntry = recursiveSecurity.enter();
    if (recursiveEntry == null) {
        Logging.warn("Max recursion reached - " + recursiveSecurity + " src: " + src + " url: " + parentUrl);
        return src;
    }
    try {
        src = StringEscapeUtils.unescapeXml(src);
        URL objectURL = LinkUtils.getLink(parentUrl, src, null, false);
        if (objectURL == null)
            return src;
        if (objectURL.equals(pageUrl)) {
            return "index.html";
        }
        String urlString = objectURL.toExternalForm();
        String fileName = urlFileMap.get(urlString);
        if (fileName != null)
            return getLocalPath(parentUrl, fileName);
        DownloadItem downloadItem = null;
        try {
            downloadItem = downloader.get(objectURL.toURI(), null);
        } catch (IOException e) {
            Logging.warn("IO Exception on " + objectURL.toURI(), e);
            return src;
        }
        fileName = downloadItem.getFileName();
        if (fileName == null || fileName.length() == 0)
            return src;
        downloadItem.checkNoErrorRange(200, 300);
        String baseName = FilenameUtils.getBaseName(fileName);
        String extension = FilenameUtils.getExtension(fileName);
        if (contentType == null)
            contentType = downloadItem.getContentBaseType();
        if ("text/html".equalsIgnoreCase(contentType))
            extension = "html";
        else if ("text/javascript".equalsIgnoreCase(contentType))
            extension = "js";
        else if ("text/css".equalsIgnoreCase(contentType))
            extension = "css";
        else if ("application/x-shockwave-flash".equalsIgnoreCase(contentType))
            extension = "swf";
        else if ("image/png".equalsIgnoreCase(contentType))
            extension = "png";
        else if ("image/gif".equalsIgnoreCase(contentType))
            extension = "gif";
        else if ("image/jpeg".equalsIgnoreCase(contentType))
            extension = "jpg";
        else if ("image/jpg".equalsIgnoreCase(contentType))
            extension = "jpg";
        File destFile = getAndRegisterDestFile(urlString, baseName, extension);
        if ("css".equals(extension)) {
            String cssContent = downloadItem.getContentAsString();
            StringBuffer sb = checkCSSContent(objectURL, cssContent);
            if (sb != null && sb.length() > 0)
                cssContent = sb.toString();
            FileUtils.write(destFile, cssContent);
        } else
            downloadItem.writeToFile(destFile);

        return getLocalPath(parentUrl, destFile.getName());
    } catch (HttpHostConnectException e) {
        Logging.warn(e);
        return src;
    } catch (UnknownHostException e) {
        Logging.warn(e);
        return src;
    } catch (WrongStatusCodeException e) {
        Logging.warn(e);
        return src;
    } finally {
        recursiveEntry.release();
    }
}

From source file:org.eclipse.skalli.model.ext.maven.internal.HttpMavenPomResolverBase.java

@Override
public MavenPom getMavenPom(UUID project, String scmLocation, String relativePath) throws IOException {
    URL url = resolvePath(scmLocation, relativePath);
    if (url == null) {
        throw new IOException(MessageFormat.format(
                "Failed to calculate an URL for downloading of a POM based on SCM location \"{0}\" and relative path \"{1}\"",
                scmLocation, relativePath));
    }//from w w w  .ja va 2  s. c o m
    try {
        return parse(url, relativePath, false);
    } catch (Exception e) {
        try {
            parse(url, relativePath, true);
        } catch (Exception e1) {
            LOG.error(MessageFormat.format("Unexpected error occured while logging the response from {0}",
                    url.toExternalForm()), e);
        }

        throw new IOException(MessageFormat.format(
                "Failed to download POM from {0} (scmLocation=\"{1}\", relativePath =\"{2}\")",
                url.toExternalForm(), scmLocation, relativePath), e);
    }
}

From source file:bixo.parser.SimpleParserTest.java

private FetchedDatum makeFetchedDatum(URL path) throws IOException {
    File file = new File(path.getFile());
    byte[] bytes = new byte[(int) file.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(file));
    in.readFully(bytes);//  w w  w . ja v a 2  s.  c  o m

    String url = path.toExternalForm().toString();
    FetchedDatum fetchedDatum = new FetchedDatum(url, url, System.currentTimeMillis(), new HttpHeaders(),
            new ContentBytes(bytes), "text/html", 0);
    return fetchedDatum;
}

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

@Test
@InSequence(20) // put here in order to prevent potential influence for other tests by the standard global valve
@OperateOnDeployment(value = DEPLOYMENT_NAME)
public void authWithStandardValve(@ArquillianResource URL url, @ArquillianResource ManagementClient client)
        throws Exception {
    // as first test in sequence creating valve module
    ValveUtil.createValveModule(client, STANDARD_VALVE_MODULE, getBaseModulePath(STANDARD_VALVE_MODULE),
            STANDARD_VALVE_JAR, VALVE_CLASS);
    String classicValveName = "classicValve";

    // adding valve based on the created module
    ValveUtil.addValve(client, classicValveName, STANDARD_VALVE_MODULE, VALVE_CLASS.getName(), null);

    ValveUtil.reload(client);//from w w  w .  j  a  v a 2  s . c  om
    try {
        String appUrl = url.toExternalForm() + WEB_APP_URL_1;
        log.debug("Testing url " + appUrl
                + " against two valves defined, one standard valve and one global valve authenticator named "
                + CUSTOM_AUTHENTICATOR_1);
        Header[] valveHeaders = ValveUtil.hitValve(new URL(appUrl));
        assertEquals("There was one valve defined - it's missing now", 2, valveHeaders.length);
        //          test if valve headers contain correct values
        assertEquals("Standard valve with not defined param expecting default param value", DEFAULT_PARAM_VALUE,
                valveHeaders[0].getValue());
        assertEquals("Authenticator valve with not defined param expecting default param value",
                AUTH_VALVE_DEFAULT_PARAM_VALUE, valveHeaders[1].getValue());
    } finally {
        ValveUtil.removeValve(client, classicValveName);
    }
}

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

/**
 * Facility to test external form of an URL.
 * @param expectedUrl the string representation of the expected URL
 * @param actualUrl the URL to test//w w  w.  j av  a 2  s .  c o m
 */
protected void assertEquals(final String expectedUrl, final URL actualUrl) {
    Assert.assertEquals(expectedUrl, actualUrl.toExternalForm());
}

From source file:io.github.mmichaelis.selenium.client.provider.AbstractWebDriverProviderTest.java

private void prepareResetTest(final HtmlUnitDriver testedDriver)
        throws InterruptedException, ExecutionException {
    final URL otherPageUrl = Resources.getResource(this.getClass(), "page2.html");
    final URL newPageUrl = Resources.getResource(this.getClass(), "page3.html");
    final WebDriverProvider driverProvider = new NoExceptionWebDriverProvider(testedDriver);
    final ExecutorService executorService = newCachedThreadPool();
    final Future<Void> openWindowResultFuture = executorService.submit(new Callable<Void>() {
        @Nullable//from   www.j a v a2  s.  c o  m
        @Override
        public Void call() {
            final WebDriver driver = driverProvider.get();
            driver.get(otherPageUrl.toExternalForm());
            final JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("window.open(arguments[0])", newPageUrl.toExternalForm());
            final Set<String> windowHandles = driver.getWindowHandles();
            checkState(windowHandles.size() > 1, "Failed to open additional window for driver: %s", driver);
            driverProvider.reset();
            return null;
        }
    });
    openWindowResultFuture.get();
}

From source file:com.boundlessgeo.geoserver.api.controllers.StoreController.java

private String source(URL url) {
    File baseDirectory = dataDir().getResourceLoader().getBaseDirectory();

    if (url.getProtocol().equals("file")) {
        File file = Files.url(baseDirectory, url.toExternalForm());
        if (file != null && !file.isAbsolute()) {
            return Paths.convert(baseDirectory, file);
        }/*  ww  w.  j  a va2  s .  co  m*/
    }
    return url.toExternalForm();
}

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

/**
 * Facility to test external form of an URL.
 * @param message the message to display if assertion fails
 * @param expectedUrl the string representation of the expected URL
 * @param actualUrl the URL to test//from   w w w  .  j a  v  a2 s  .com
 */
protected void assertEquals(final String message, final String expectedUrl, final URL actualUrl) {
    Assert.assertEquals(message, expectedUrl, actualUrl.toExternalForm());
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlAnchor.java

/**
 * Same as {@link #doClickStateUpdate()}, except that it accepts an href suffix, needed when a click is
 * performed on an image map to pass information on the click position.
 *
 * @param hrefSuffix the suffix to add to the anchor's href attribute (for instance coordinates from an image map)
 * @throws IOException if an IO error occurs
 *///  w  w  w . j  a v  a 2  s . c o m
protected void doClickStateUpdate(final String hrefSuffix) throws IOException {
    final String href = (getHrefAttribute() + hrefSuffix).trim();
    if (LOG.isDebugEnabled()) {
        final String w = getPage().getEnclosingWindow().getName();
        LOG.debug("do click action in window '" + w + "', using href '" + href + "'");
    }
    if (ATTRIBUTE_NOT_DEFINED == getHrefAttribute()) {
        return;
    }
    HtmlPage htmlPage = (HtmlPage) getPage();
    if (StringUtils.startsWithIgnoreCase(href, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        final StringBuilder builder = new StringBuilder(href.length());
        builder.append(JavaScriptURLConnection.JAVASCRIPT_PREFIX);
        for (int i = JavaScriptURLConnection.JAVASCRIPT_PREFIX.length(); i < href.length(); i++) {
            final char ch = href.charAt(i);
            if (ch == '%' && i + 2 < href.length()) {
                final char ch1 = Character.toUpperCase(href.charAt(i + 1));
                final char ch2 = Character.toUpperCase(href.charAt(i + 2));
                if ((Character.isDigit(ch1) || ch1 >= 'A' && ch1 <= 'F')
                        && (Character.isDigit(ch2) || ch2 >= 'A' && ch2 <= 'F')) {
                    builder.append((char) Integer.parseInt(href.substring(i + 1, i + 3), 16));
                    i += 2;
                    continue;
                }
            }
            builder.append(ch);
        }

        if (hasFeature(ANCHOR_IGNORE_TARGET_FOR_JS_HREF)) {
            htmlPage.executeJavaScriptIfPossible(builder.toString(), "javascript url", getStartLineNumber());
        } else {
            final WebWindow win = htmlPage.getWebClient().openTargetWindow(htmlPage.getEnclosingWindow(),
                    htmlPage.getResolvedTarget(getTargetAttribute()), "_self");
            final Page page = win.getEnclosedPage();
            if (page != null && page.isHtmlPage()) {
                htmlPage = (HtmlPage) page;
                htmlPage.executeJavaScriptIfPossible(builder.toString(), "javascript url",
                        getStartLineNumber());
            }
        }
        return;
    }

    final URL url = getTargetUrl(href, htmlPage);

    final BrowserVersion browser = htmlPage.getWebClient().getBrowserVersion();
    final WebRequest webRequest = new WebRequest(url, browser.getHtmlAcceptHeader());
    webRequest.setCharset(htmlPage.getPageEncoding());
    webRequest.setAdditionalHeader("Referer", htmlPage.getUrl().toExternalForm());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Getting page for " + url.toExternalForm() + ", derived from href '" + href
                + "', using the originating URL " + htmlPage.getUrl());
    }
    htmlPage.getWebClient().download(htmlPage.getEnclosingWindow(),
            htmlPage.getResolvedTarget(getTargetAttribute()), webRequest, true, false, "Link click");
}