Search in sources :

Example 1 with ParseException

use of com.helger.css.parser.ParseException in project ph-css by phax.

the class CSSCompressMojo method _compressCSSFile.

private void _compressCSSFile(@Nonnull final File aChild) {
    // Compress the file only if the compressed file is older than the original
    // file. Note: lastModified on a non-existing file returns 0L
    final File aCompressed = new File(FilenameHelper.getWithoutExtension(aChild.getAbsolutePath()) + targetFileExtension);
    if (aCompressed.lastModified() < aChild.lastModified() || forceCompress) {
        if (verbose)
            getLog().info("Start compressing CSS file " + _getRelativePath(aChild));
        else
            getLog().debug("Start compressing CSS file " + _getRelativePath(aChild));
        final ICSSParseExceptionCallback aExHdl = (@Nonnull final ParseException ex) -> getLog().error("Failed to parse CSS file " + _getRelativePath(aChild), ex);
        final Charset aFallbackCharset = CharsetHelper.getCharsetFromName(sourceEncoding);
        final CSSReaderSettings aSettings = new CSSReaderSettings().setCSSVersion(ECSSVersion.CSS30).setFallbackCharset(aFallbackCharset).setCustomExceptionHandler(aExHdl).setBrowserCompliantMode(browserCompliantMode);
        final CascadingStyleSheet aCSS = CSSReader.readFromFile(aChild, aSettings);
        if (aCSS != null) {
            // We read it!
            final FileSystemResource aDestFile = new FileSystemResource(aCompressed);
            try {
                final CSSWriterSettings aWriterSettings = new CSSWriterSettings(ECSSVersion.CSS30);
                aWriterSettings.setOptimizedOutput(true);
                aWriterSettings.setRemoveUnnecessaryCode(removeUnnecessaryCode);
                aWriterSettings.setNewLineMode(newLineMode);
                aWriterSettings.setQuoteURLs(quoteURLs);
                aWriterSettings.setWriteNamespaceRules(writeNamespaceRules);
                aWriterSettings.setWriteFontFaceRules(writeFontFaceRules);
                aWriterSettings.setWriteKeyframesRules(writeKeyframesRules);
                aWriterSettings.setWriteMediaRules(writeMediaRules);
                aWriterSettings.setWritePageRules(writePageRules);
                aWriterSettings.setWriteViewportRules(writeViewportRules);
                aWriterSettings.setWriteSupportsRules(writeSupportsRules);
                aWriterSettings.setWriteUnknownRules(writeUnknownRules);
                final Charset aTargetCharset = CharsetHelper.getCharsetFromName(targetEncoding);
                new CSSWriter(aWriterSettings).writeCSS(aCSS, aDestFile.getWriter(aTargetCharset, EAppend.TRUNCATE));
            } catch (final IOException ex) {
                getLog().error("Failed to write compressed CSS file '" + aCompressed.toString() + "' to disk", ex);
            }
        }
    } else {
        if (verbose)
            getLog().info("Ignoring already compressed CSS file " + _getRelativePath(aChild));
        else
            getLog().debug("Ignoring already compressed CSS file " + _getRelativePath(aChild));
    }
}
Also used : CascadingStyleSheet(com.helger.css.decl.CascadingStyleSheet) CSSWriterSettings(com.helger.css.writer.CSSWriterSettings) Charset(java.nio.charset.Charset) ParseException(com.helger.css.parser.ParseException) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) CSSWriter(com.helger.css.writer.CSSWriter) IOException(java.io.IOException) CSSReaderSettings(com.helger.css.reader.CSSReaderSettings) File(java.io.File) ICSSParseExceptionCallback(com.helger.css.handler.ICSSParseExceptionCallback)

Example 2 with ParseException

use of com.helger.css.parser.ParseException in project ph-css by phax.

the class CSSReader method getCharsetDeclaredInCSS.

/**
 * Determine the charset to read the CSS file. The logic is as follows:
 * <ol>
 * <li>Determine the charset used to read the @charset from the stream. If a
 * BOM is present and a matching Charset is present, this charset is used. As
 * a fallback the CSS file is initially read with ISO-8859-1.</li>
 * <li>If the CSS content contains a valid @charset rule, the defined charset
 * is returned even if a different BOM is present.</li>
 * <li>If the CSS content does not contain a valid @charset rule than the
 * charset of the BOM is returned (if any).</li>
 * <li>Otherwise <code>null</code> is returned.</li>
 * </ol>
 *
 * @param aISP
 *        The input stream provider to read from. May not be <code>null</code>
 *        .
 * @return <code>null</code> if the input stream could not be opened or if
 *         neither a BOM nor a charset is specified. Otherwise a non-
 *         <code>null</code> Charset is returned.
 * @throws IllegalStateException
 *         if an invalid charset is supplied
 */
@Nullable
public static Charset getCharsetDeclaredInCSS(@Nonnull final IHasInputStream aISP) {
    ValueEnforcer.notNull(aISP, "InputStreamProvider");
    // Try to open input stream
    final InputStream aIS = aISP.getInputStream();
    if (aIS == null)
        return null;
    final InputStreamAndCharset aISAndBOM = CharsetHelper.getInputStreamAndCharsetFromBOM(aIS);
    final Charset aBOMCharset = aISAndBOM.getCharset();
    Charset aStreamCharset = aBOMCharset;
    if (aStreamCharset == null) {
        // Always read as ISO-8859-1 as everything contained in the CSS charset
        // declaration can be handled by this charset
        // A known problem is when the file is UTF-16, UTF-16BE, UTF-16LE etc.
        // encoded. In this case a BOM must be present to read the file correctly!
        aStreamCharset = StandardCharsets.ISO_8859_1;
    }
    final Reader aReader = StreamHelper.createReader(aISAndBOM.getInputStream(), aStreamCharset);
    try {
        // Read with the Stream charset
        final CSSCharStream aCharStream = new CSSCharStream(aReader);
        final ParserCSSCharsetDetectorTokenManager aTokenHdl = new ParserCSSCharsetDetectorTokenManager(aCharStream);
        final ParserCSSCharsetDetector aParser = new ParserCSSCharsetDetector(aTokenHdl);
        final String sCharsetName = aParser.styleSheetCharset().getText();
        if (sCharsetName == null) {
            // No charset specified - use the one from the BOM (may be null)
            return aBOMCharset;
        }
        // Remove leading and trailing quotes from value
        final String sPlainCharsetName = CSSParseHelper.extractStringValue(sCharsetName);
        final Charset aReadCharset = CharsetHelper.getCharsetFromName(sPlainCharsetName);
        if (aBOMCharset != null && !aBOMCharset.equals(aReadCharset)) {
            // BOM charset different from read charset
            s_aLogger.warn("The charset found in the CSS data (" + aReadCharset.name() + ") differs from the charset determined by the BOM (" + aBOMCharset.name() + ") -> Using the read charset");
        }
        return aReadCharset;
    } catch (final ParseException ex) {
        // grammar!
        throw new IllegalStateException("Failed to parse CSS charset definition", ex);
    } catch (final Throwable ex) {
        // As e.g. indicated by https://github.com/phax/ph-css/issues/9
        throw new IllegalStateException("Failed to parse CSS charset definition", ex);
    } finally {
        StreamHelper.close(aReader);
    }
}
Also used : ParserCSSCharsetDetectorTokenManager(com.helger.css.parser.ParserCSSCharsetDetectorTokenManager) InputStreamAndCharset(com.helger.commons.charset.CharsetHelper.InputStreamAndCharset) IHasInputStream(com.helger.commons.io.IHasInputStream) InputStream(java.io.InputStream) CSSCharStream(com.helger.css.parser.CSSCharStream) Charset(java.nio.charset.Charset) InputStreamAndCharset(com.helger.commons.charset.CharsetHelper.InputStreamAndCharset) IHasReader(com.helger.commons.io.IHasReader) NonBlockingStringReader(com.helger.commons.io.stream.NonBlockingStringReader) Reader(java.io.Reader) ParserCSSCharsetDetector(com.helger.css.parser.ParserCSSCharsetDetector) ParseException(com.helger.css.parser.ParseException) Nullable(javax.annotation.Nullable)

Example 3 with ParseException

use of com.helger.css.parser.ParseException in project ph-css by phax.

the class MainReadAllCSSOnDisc method main.

@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
public static void main(final String[] args) {
    int nFilesOK = 0;
    int nFilesError = 0;
    final ICommonsOrderedMap<File, ParseException> aErrors = new CommonsLinkedHashMap<>();
    final Wrapper<File> aCurrentFile = new Wrapper<>();
    final ICSSParseExceptionCallback aHdl = ex -> aErrors.put(aCurrentFile.get(), ex);
    for (final File aFile : new FileSystemRecursiveIterator(new File("/")).withFilter(IFileFilter.filenameEndsWith(".css"))) {
        if (false)
            s_aLogger.info(aFile.getAbsolutePath());
        aCurrentFile.set(aFile);
        final CascadingStyleSheet aCSS = CSSReader.readFromFile(aFile, StandardCharsets.UTF_8, ECSSVersion.CSS30, aHdl);
        if (aCSS == null) {
            nFilesError++;
            s_aLogger.warn("  " + aFile.getAbsolutePath() + " failed!");
        } else
            nFilesOK++;
    }
    s_aLogger.info("Done");
    for (final Map.Entry<File, ParseException> aEntry : aErrors.entrySet()) s_aLogger.info("  " + aEntry.getKey().getAbsolutePath() + ":\n" + aEntry.getValue().getMessage() + "\n");
    s_aLogger.info("OK: " + nFilesOK + "; Error: " + nFilesError);
}
Also used : Logger(org.slf4j.Logger) ICSSParseExceptionCallback(com.helger.css.handler.ICSSParseExceptionCallback) CSSReader(com.helger.css.reader.CSSReader) LoggerFactory(org.slf4j.LoggerFactory) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) ECSSVersion(com.helger.css.ECSSVersion) ParseException(com.helger.css.parser.ParseException) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) FileSystemRecursiveIterator(com.helger.commons.io.file.FileSystemRecursiveIterator) IFileFilter(com.helger.commons.io.file.IFileFilter) Wrapper(com.helger.commons.wrapper.Wrapper) Map(java.util.Map) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) CascadingStyleSheet(com.helger.css.decl.CascadingStyleSheet) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) Wrapper(com.helger.commons.wrapper.Wrapper) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) ICSSParseExceptionCallback(com.helger.css.handler.ICSSParseExceptionCallback) CascadingStyleSheet(com.helger.css.decl.CascadingStyleSheet) FileSystemRecursiveIterator(com.helger.commons.io.file.FileSystemRecursiveIterator) ParseException(com.helger.css.parser.ParseException) File(java.io.File) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) Map(java.util.Map) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

ParseException (com.helger.css.parser.ParseException)3 CascadingStyleSheet (com.helger.css.decl.CascadingStyleSheet)2 ICSSParseExceptionCallback (com.helger.css.handler.ICSSParseExceptionCallback)2 File (java.io.File)2 Charset (java.nio.charset.Charset)2 InputStreamAndCharset (com.helger.commons.charset.CharsetHelper.InputStreamAndCharset)1 CommonsLinkedHashMap (com.helger.commons.collection.impl.CommonsLinkedHashMap)1 ICommonsOrderedMap (com.helger.commons.collection.impl.ICommonsOrderedMap)1 IHasInputStream (com.helger.commons.io.IHasInputStream)1 IHasReader (com.helger.commons.io.IHasReader)1 FileSystemRecursiveIterator (com.helger.commons.io.file.FileSystemRecursiveIterator)1 IFileFilter (com.helger.commons.io.file.IFileFilter)1 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)1 NonBlockingStringReader (com.helger.commons.io.stream.NonBlockingStringReader)1 Wrapper (com.helger.commons.wrapper.Wrapper)1 ECSSVersion (com.helger.css.ECSSVersion)1 CSSCharStream (com.helger.css.parser.CSSCharStream)1 ParserCSSCharsetDetector (com.helger.css.parser.ParserCSSCharsetDetector)1 ParserCSSCharsetDetectorTokenManager (com.helger.css.parser.ParserCSSCharsetDetectorTokenManager)1 CSSReader (com.helger.css.reader.CSSReader)1