Search in sources :

Example 1 with InputSource

use of com.gargoylesoftware.css.parser.InputSource in project htmlunit by HtmlUnit.

the class CSSStyleSheet method loadStylesheet.

/**
 * Loads the stylesheet at the specified link or href.
 * @param element the parent DOM element
 * @param link the stylesheet's link (may be {@code null} if a <tt>url</tt> is specified)
 * @param url the stylesheet's url (may be {@code null} if a <tt>link</tt> is specified)
 * @return the loaded stylesheet
 */
public static CSSStyleSheet loadStylesheet(final HTMLElement element, final HtmlLink link, final String url) {
    final HtmlPage page = (HtmlPage) element.getDomNodeOrDie().getPage();
    String uri = page.getUrl().toExternalForm();
    try {
        // Retrieve the associated content and respect client settings regarding failing HTTP status codes.
        final WebRequest request;
        final WebResponse response;
        final WebClient client = page.getWebClient();
        if (link == null) {
            // Use href.
            final BrowserVersion browser = client.getBrowserVersion();
            request = new WebRequest(new URL(url), browser.getCssAcceptHeader(), browser.getAcceptEncodingHeader());
            request.setRefererlHeader(page.getUrl());
            // our cache is a bit strange;
            // loadWebResponse check the cache for the web response
            // AND also fixes the request url for the following cache lookups
            response = client.loadWebResponse(request);
        } else {
            // Use link.
            request = link.getWebRequest();
            if (element.getBrowserVersion().hasFeature(HTMLLINK_CHECK_TYPE_FOR_STYLESHEET)) {
                final String type = link.getTypeAttribute();
                if (StringUtils.isNotBlank(type) && !MimeType.TEXT_CSS.equals(type)) {
                    return new CSSStyleSheet(element, "", uri);
                }
            }
            // our cache is a bit strange;
            // loadWebResponse check the cache for the web response
            // AND also fixes the request url for the following cache lookups
            response = link.getWebResponse(true, request);
        }
        // now we can look into the cache with the fixed request for
        // a cached script
        final Cache cache = client.getCache();
        final Object fromCache = cache.getCachedObject(request);
        if (fromCache instanceof CSSStyleSheetImpl) {
            uri = request.getUrl().toExternalForm();
            return new CSSStyleSheet(element, element.getWindow(), (CSSStyleSheetImpl) fromCache, uri);
        }
        uri = response.getWebRequest().getUrl().toExternalForm();
        client.printContentIfNecessary(response);
        client.throwFailingHttpStatusCodeExceptionIfNecessary(response);
        // CSS content must have downloaded OK; go ahead and build the corresponding stylesheet.
        final CSSStyleSheet sheet;
        final String contentType = response.getContentType();
        if (StringUtils.isEmpty(contentType) || MimeType.TEXT_CSS.equals(contentType)) {
            final InputStream in = response.getContentAsStreamWithBomIfApplicable();
            if (in == null) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn("Loading stylesheet for url '" + uri + "' returns empty responseData");
                }
                return new CSSStyleSheet(element, "", uri);
            }
            try {
                Charset cssEncoding = Charset.forName("windows-1252");
                final Charset contentCharset = EncodingSniffer.sniffEncodingFromHttpHeaders(response.getResponseHeaders());
                if (contentCharset == null && request.getCharset() != null) {
                    cssEncoding = request.getCharset();
                } else if (contentCharset != null) {
                    cssEncoding = contentCharset;
                }
                if (in instanceof BOMInputStream) {
                    final BOMInputStream bomIn = (BOMInputStream) in;
                    // we have to call this before hasBOM(ByteOrderMark)
                    if (bomIn.hasBOM()) {
                        if (bomIn.hasBOM(ByteOrderMark.UTF_8)) {
                            cssEncoding = UTF_8;
                        } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) {
                            cssEncoding = UTF_16BE;
                        } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) {
                            cssEncoding = UTF_16LE;
                        }
                    }
                }
                try (InputSource source = new InputSource(new InputStreamReader(in, cssEncoding))) {
                    source.setURI(uri);
                    sheet = new CSSStyleSheet(element, source, uri);
                }
            } finally {
                in.close();
            }
        } else {
            sheet = new CSSStyleSheet(element, "", uri);
        }
        // cache the style sheet
        if (!cache.cacheIfPossible(request, response, sheet.getWrappedSheet())) {
            response.cleanUp();
        }
        return sheet;
    } catch (final FailingHttpStatusCodeException e) {
        // Got a 404 response or something like that; behave nicely.
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception loading " + uri, e);
        }
        return new CSSStyleSheet(element, "", uri);
    } catch (final IOException e) {
        // Got a basic IO error; behave nicely.
        if (LOG.isErrorEnabled()) {
            LOG.error("IOException loading " + uri, e);
        }
        return new CSSStyleSheet(element, "", uri);
    } catch (final RuntimeException e) {
        // Got something unexpected; we can throw an exception in this case.
        if (LOG.isErrorEnabled()) {
            LOG.error("RuntimeException loading " + uri, e);
        }
        throw Context.reportRuntimeError("Exception: " + e);
    } catch (final Exception e) {
        // Got something unexpected; we can throw an exception in this case.
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception loading " + uri, e);
        }
        throw Context.reportRuntimeError("Exception: " + e);
    }
}
Also used : InputSource(com.gargoylesoftware.css.parser.InputSource) WebResponse(com.gargoylesoftware.htmlunit.WebResponse) CSSStyleSheetImpl(com.gargoylesoftware.css.dom.CSSStyleSheetImpl) InputStreamReader(java.io.InputStreamReader) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) BOMInputStream(org.apache.commons.io.input.BOMInputStream) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) IOException(java.io.IOException) WebClient(com.gargoylesoftware.htmlunit.WebClient) URL(java.net.URL) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) CSSException(com.gargoylesoftware.css.parser.CSSException) IOException(java.io.IOException) CSSParseException(com.gargoylesoftware.css.parser.CSSParseException) DOMException(org.w3c.dom.DOMException) MalformedURLException(java.net.MalformedURLException) BOMInputStream(org.apache.commons.io.input.BOMInputStream) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) FailingHttpStatusCodeException(com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion) Cache(com.gargoylesoftware.htmlunit.Cache)

Example 2 with InputSource

use of com.gargoylesoftware.css.parser.InputSource in project LoboEvolution by LoboEvolution.

the class CSSUtilities method parseCssExternal.

/**
 * <p>parseCssExternal.</p>
 *
 * @param href a {@link java.lang.String} object.
 * @param scriptURL a {@link java.net.URL} object.
 * @param baseURI a {@link java.lang.String} object.
 * @return a {@link com.gargoylesoftware.css.dom.CSSStyleSheetImpl} object.
 * @throws java.lang.Exception if any.
 */
public static CSSStyleSheetImpl parseCssExternal(String href, URL scriptURL, String baseURI, boolean test) throws Exception {
    CSSOMParser parser = new CSSOMParser();
    String scriptURI = scriptURL == null ? href : scriptURL.toExternalForm();
    String source = !test ? ExternalResourcesStore.getSourceCache(scriptURI, "CSS") : "";
    InputSource is = getCssInputSourceForStyleSheet(source, baseURI);
    return parser.parseStyleSheet(is, null);
}
Also used : InputSource(com.gargoylesoftware.css.parser.InputSource) CSSOMParser(com.gargoylesoftware.css.parser.CSSOMParser)

Example 3 with InputSource

use of com.gargoylesoftware.css.parser.InputSource in project LoboEvolution by LoboEvolution.

the class CSSUtilities method getCssInputSourceForStyleSheet.

/**
 * <p>getCssInputSourceForStyleSheet.</p>
 *
 * @param text a {@link java.lang.String} object.
 * @param scriptURI a {@link java.lang.String} object.
 * @return a {@link com.gargoylesoftware.css.parser.InputSource} object.
 */
public static InputSource getCssInputSourceForStyleSheet(String text, String scriptURI) {
    final Reader reader = new StringReader(text);
    final InputSource is = new InputSource(reader);
    is.setURI(scriptURI);
    return is;
}
Also used : InputSource(com.gargoylesoftware.css.parser.InputSource) StringReader(java.io.StringReader) Reader(java.io.Reader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader)

Example 4 with InputSource

use of com.gargoylesoftware.css.parser.InputSource in project LoboEvolution by LoboEvolution.

the class HTMLStyleElementImpl method processStyle.

/**
 * <p>processStyle.</p>
 */
private void processStyle() {
    this.styleSheet = null;
    final HTMLDocumentImpl doc = (HTMLDocumentImpl) getOwnerDocument();
    if (CSSUtilities.matchesMedia(getMedia(), doc.getDefaultView())) {
        final String text = getRawInnerText(true);
        if (Strings.isNotBlank(text)) {
            final String processedText = CSSUtilities.preProcessCss(text);
            final CSSOMParser parser = new CSSOMParser(new CSS3Parser());
            final String baseURI = doc.getBaseURI();
            final InputSource is = CSSUtilities.getCssInputSourceForStyleSheet(processedText, baseURI);
            try {
                final com.gargoylesoftware.css.dom.CSSStyleSheetImpl sheet = parser.parseStyleSheet(is, null);
                sheet.setHref(baseURI);
                sheet.setDisabled(this.disabled);
                CSSStyleSheetImpl cssStyleSheet = new CSSStyleSheetImpl(sheet);
                cssStyleSheet.setOwnerNode(this);
                doc.addStyleSheet(cssStyleSheet);
                this.styleSheet = cssStyleSheet;
            } catch (final Throwable err) {
                this.warn("Unable to parse style sheet", err);
            }
        }
    }
}
Also used : InputSource(com.gargoylesoftware.css.parser.InputSource) CSSStyleSheetImpl(org.loboevolution.html.js.css.CSSStyleSheetImpl) CSSOMParser(com.gargoylesoftware.css.parser.CSSOMParser) CSS3Parser(com.gargoylesoftware.css.parser.javacc.CSS3Parser)

Aggregations

InputSource (com.gargoylesoftware.css.parser.InputSource)4 CSSOMParser (com.gargoylesoftware.css.parser.CSSOMParser)2 CSSStyleSheetImpl (com.gargoylesoftware.css.dom.CSSStyleSheetImpl)1 CSSException (com.gargoylesoftware.css.parser.CSSException)1 CSSParseException (com.gargoylesoftware.css.parser.CSSParseException)1 CSS3Parser (com.gargoylesoftware.css.parser.javacc.CSS3Parser)1 BrowserVersion (com.gargoylesoftware.htmlunit.BrowserVersion)1 Cache (com.gargoylesoftware.htmlunit.Cache)1 FailingHttpStatusCodeException (com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException)1 WebClient (com.gargoylesoftware.htmlunit.WebClient)1 WebRequest (com.gargoylesoftware.htmlunit.WebRequest)1 WebResponse (com.gargoylesoftware.htmlunit.WebResponse)1 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1 MalformedURLException (java.net.MalformedURLException)1