Example usage for com.google.common.css SourceCode SourceCode

List of usage examples for com.google.common.css SourceCode SourceCode

Introduction

In this page you can find the example usage for com.google.common.css SourceCode SourceCode.

Prototype

public SourceCode(@Nullable String fileName, @Nullable String fileContents) 

Source Link

Document

Constructs a SourceCode .

Usage

From source file:io.bazel.rules.closure.webfiles.compiler.CssParser.java

/** Parses stylesheet. */
public CssTree parse(String path, String content) {
    SourceCode source = new SourceCode(path, content);
    StringCharStream stream = new StringCharStream(source.getFileContents());
    CssBlockNode globalBlock = new CssBlockNode(false /* isEnclosedWithBraces */);
    CssTree tree = new CssTree(source, new CssRootNode(globalBlock));
    GssParserCC parser = new GssParserCC(stream, globalBlock, source, false /* enableErrorRecovery */);
    int endOfLastError = 0;
    while (true) {
        try {//from ww w  . ja v a2s  . c o  m
            parser.parse();
            break;
        } catch (GssParserException e) {
            // TODO(jart): Re-enable when csscomp supports --foo syntax.
            //errorReporter.report(CSS_SYNTAX_ERROR, e.getGssError().format());
            // Generic strategy to retry parsing by getting back to top level
            // NOTE: +1 for end-index because a location is represented as a closed range
            int begin = globalBlock.isEmpty() ? endOfLastError
                    : Math.max(endOfLastError,
                            globalBlock.getLastChild().getSourceCodeLocation().getEndCharacterIndex() + 1);
            endOfLastError = skipCurrentStatement(parser, stream, begin);
        }
    }
    return tree;
}

From source file:com.log4ic.compressor.utils.less.LessEngine.java

/**
 * less// w w w.  j a va  2s.com
 *
 * @param codeList
 * @param conditions
 * @return
 * @throws GssParserException
 */
public static List<SourceCode> parseLess(List<SourceCode> codeList, List<String> conditions)
        throws LessException, CompressionException {
    final List<SourceCode> resultCodeList = new FastList<SourceCode>();
    StringBuilder conditionsBuilder = new StringBuilder();
    if (conditions != null) {
        for (String con : conditions) {
            conditionsBuilder.append("@").append(con).append(":true;");
        }
    }
    for (final SourceCode sourceCode : codeList) {
        if (Compressor.getFileType(sourceCode.getFileName()) != Compressor.FileType.LESS) {
            resultCodeList.add(new SourceCode(sourceCode.getFileName(), sourceCode.getFileContents()));
            continue;
        }
        final Object[] functionArgs = new Object[] {
                conditionsBuilder.toString() + sourceCode.getFileContents() };
        try {
            jsContextFactory.call(new ContextAction() {
                @Override
                public Object run(Context cx) {
                    cx.setLanguageVersion(Context.VERSION_1_8);
                    Object result = parseFn.call(cx, global, fnThisScopeObj, functionArgs);
                    resultCodeList.add(new SourceCode(sourceCode.getFileName(), Context.toString(result)));
                    return null;
                }
            });
        } catch (Exception e) {
            parseLessException(e);
        }
    }
    return resultCodeList;
}

From source file:com.log4ic.compressor.utils.template.JavascriptTemplateEngine.java

public static String compress(String name, String source, Mode mode) {
    HtmlCompressor compressor = new HtmlCompressor();

    compressor.setRemoveIntertagSpaces(true); //removes iter-tag whitespace characters
    compressor.setRemoveQuotes(true); //removes unnecessary tag attribute quotes
    compressor.setSimpleDoctype(true); //simplify existing doctype
    compressor.setRemoveScriptAttributes(true); //remove optional attributes from script tags
    compressor.setRemoveStyleAttributes(true); //remove optional attributes from style tags
    compressor.setRemoveLinkAttributes(true); //remove optional attributes from link tags
    compressor.setRemoveFormAttributes(true); //remove optional attributes from form tags
    compressor.setRemoveInputAttributes(true); //remove optional attributes from input tags
    compressor.setSimpleBooleanAttributes(true); //remove values from boolean tag attributes
    compressor.setRemoveJavaScriptProtocol(true); //remove "javascript:" from inline event handlers
    //compressor.setRemoveHttpProtocol(true);        //replace "http://" with "//" inside tag attributes
    //        compressor.setRemoveHttpsProtocol(true);       //replace "https://" with "//" inside tag attributes
    compressor.setPreserveLineBreaks(false); //preserves original line breaks
    compressor.setRemoveSurroundingSpaces(HtmlCompressor.ALL_TAGS); //remove spaces around provided tags

    compressor.setCompressCss(true); //compress inline css
    compressor.setCompressJavaScript(true); //compress inline javascript

    //use Google Closure Compiler for javascript compression
    compressor.setJavaScriptCompressor(new ClosureJavaScriptCompressor(CompilationLevel.SIMPLE_OPTIMIZATIONS));

    //use your own implementation of css comressor
    compressor.setCssCompressor(new Compressor() {
        @Override//from  w  w w  . j a va 2s.  c  o m
        public String compress(String source) {
            try {
                return com.log4ic.compressor.utils.Compressor
                        .compressGss(new SourceCode("inner-style", source));
            } catch (GssParserException e) {
                e.printStackTrace();
            }
            return null;
        }
    });

    String compressedHtml = compressor.compress(source);

    return parse(name, compressedHtml, mode);
}

From source file:com.google.gwt.resources.converter.GssGenerationVisitor.java

@Override
public boolean visit(CssProperty x, Context ctx) {
    maybePrintOpenBrace();/*from w ww.  ja va2s .  com*/

    StringBuilder propertyBuilder = new StringBuilder();

    if (noFlip) {
        propertyBuilder.append(NO_FLIP);
        propertyBuilder.append(' ');
    }

    propertyBuilder.append(x.getName());
    propertyBuilder.append(": ");

    propertyBuilder.append(printValuesList(x.getValues().getValues()));

    if (x.isImportant()) {
        propertyBuilder.append(IMPORTANT);
    }

    String cssProperty = propertyBuilder.toString();

    if (lenient) {
        // lenient mode: Try to parse the css rule and if an error occurs,
        // print a warning message and don't print the rule.
        try {
            new GssParser(new SourceCode(null, "body{" + cssProperty + "}")).parse();
        } catch (GssParserException e) {
            System.err
                    .println("[WARN] The following property is not valid and will be skipped: " + cssProperty);
            return false;
        }
    }

    out.print(cssProperty);

    semiColon();

    return true;
}

From source file:com.log4ic.compressor.utils.Compressor.java

private static JobDescriptionBuilder buildJobDesBuilder(List<SourceCode> codeList,
        JobDescription.OutputFormat format, List<String> conditions, JobDescription.OptimizeStrategy level) {
    JobDescriptionBuilder builder = new JobDescriptionBuilder();
    builder.setAllowWebkitKeyframes(true);
    builder.setAllowKeyframes(true);// www  .  j  a v  a2 s .  c  o  m
    builder.setAllowUnrecognizedFunctions(true);
    builder.setAllowUnrecognizedProperties(true);
    builder.setProcessDependencies(true);
    builder.setSimplifyCss(true);
    builder.setEliminateDeadStyles(true);
    builder.setOptimizeStrategy(level == null ? JobDescription.OptimizeStrategy.SAFE : level);
    for (SourceCode code : codeList) {
        builder.addInput(new SourceCode(code.getFileName(), fixIE9Hack(code.getFileContents())));
    }
    if (format != null) {
        builder.setOutputFormat(format);
    }
    //
    //builder.setGssFunctionMapProvider(gssFunctionMapProvider);
    //?
    if (conditions != null && conditions.size() > 0) {
        for (String con : conditions) {
            builder.addTrueConditionName(con);
        }
    }
    return builder;
}

From source file:com.log4ic.compressor.utils.Compressor.java

/**
 * ???/* ww w . ja  va2 s  . co  m*/
 *
 * @param fileUrlList
 * @param request
 * @param response
 * @param type
 * @return
 * @throws com.log4ic.compressor.exception.CompressionException
 *
 */
public static List<SourceCode> mergeCode(String[] fileUrlList, HttpServletRequest request,
        HttpServletResponse response, FileType type) throws CompressionException {
    List<SourceCode> codeList = new FastList<SourceCode>();
    ContentResponseWrapper wrapperResponse = null;
    //???
    for (String url : fileUrlList) {
        int index = url.lastIndexOf(".");
        if (index < 0) {
            continue;
        }
        if (type.contains(url.substring(index + 1))) {
            String fragment;
            try {
                url = URLDecoder.decode(url, "utf8");
            } catch (UnsupportedEncodingException e) {
                throw new CompressionException(e);
            }
            try {
                //http/https ??
                if (HttpUtils.isHttpProtocol(url)) {
                    fragment = importCode(HttpUtils.requestFile(url), url, type, request, response);
                } else {
                    //??
                    if (wrapperResponse == null) {
                        wrapperResponse = new ContentResponseWrapper(response);
                    }
                    request.getRequestDispatcher(url).include(request, wrapperResponse);
                    wrapperResponse.flushBuffer();
                    fragment = wrapperResponse.getContent();
                    fragment = importCode(fragment, url, type, request, response);
                    ((ContentResponseStream) wrapperResponse.getOutputStream()).reset();
                }
            } catch (ServletException e) {
                throw new CompressionException("ServletException", e);
            } catch (IOException e) {
                throw new CompressionException(e);
            } catch (GssParserException e) {
                throw new CompressionException(e);
            } catch (LessException e) {
                throw new CompressionException(e);
            }
            if (StringUtils.isNotBlank(fragment)) {
                codeList.add(new SourceCode(url, fragment));
            }
        }
    }

    if (wrapperResponse != null) {
        try {
            wrapperResponse.close();
        } catch (IOException e) {
            throw new CompressionException(e);
        } catch (Throwable throwable) {
            throw new CompressionException("Close Response error", throwable);
        }
    }
    return codeList;
}

From source file:com.google.gwt.resources.rg.GssResourceGenerator.java

private ExtendedCssTree parseResources(List<URL> resources, TreeLogger logger)
        throws UnableToCompleteException {
    List<SourceCode> sourceCodes = new ArrayList<SourceCode>(resources.size());

    // assert that we only support either gss or css on one resource.
    boolean css = ensureEitherCssOrGss(resources, logger);

    if (css && !allowLegacy) {
        // TODO(dankurka): add link explaining the situation in detail.
        logger.log(Type.ERROR,//  ww w.j a v a2  s. c om
                "Your ClientBundle is referencing css files instead of gss. "
                        + "You will need to either convert these files to gss using the "
                        + "converter tool or turn on auto convertion in your gwt.xml file. "
                        + "Note: Autoconversion will be removed after 2.7, you will need to move to gss."
                        + "Add this line to your gwt.xml file to temporary avoid this:"
                        + "<set-configuration-property name=\"CssResource.legacy\" value=\"true\" />");
        throw new UnableToCompleteException();
    }

    if (css) {
        String concatenatedCss = concatCssFiles(resources, logger);
        String gss = convertToGss(concatenatedCss, logger);
        sourceCodes.add(new SourceCode("[auto-converted gss files]", gss));
    } else {
        for (URL stylesheet : resources) {
            TreeLogger branchLogger = logger.branch(TreeLogger.DEBUG,
                    "Parsing GSS stylesheet " + stylesheet.toExternalForm());
            try {
                // TODO : always use UTF-8 to read the file ?
                String fileContent = Resources.asByteSource(stylesheet).asCharSource(Charsets.UTF_8).read();
                sourceCodes.add(new SourceCode(stylesheet.getFile(), fileContent));
                continue;

            } catch (IOException e) {
                branchLogger.log(TreeLogger.ERROR, "Unable to parse CSS", e);
            }
            throw new UnableToCompleteException();

        }
    }

    CssTree tree;

    try {
        tree = new GssParser(sourceCodes).parse();
    } catch (GssParserException e) {
        logger.log(TreeLogger.ERROR, "Unable to parse CSS", e);
        throw new UnableToCompleteException();
    }

    List<String> permutationAxes = finalizeTree(tree);

    checkErrors();

    return new ExtendedCssTree(tree, permutationAxes);
}

From source file:com.log4ic.compressor.utils.Compressor.java

/**
 * ??//from  w  w w  . ja va2  s  .c  o m
 *
 * @param type
 * @param queryString
 * @param cacheManager
 * @param request
 * @param response
 * @param fileDomain
 * @return
 * @throws com.log4ic.compressor.exception.CompressionException
 *
 * @throws com.google.common.css.compiler.ast.GssParserException
 *
 */
private static String buildCode(final FileType type, final String queryString, final CacheManager cacheManager,
        HttpServletRequest request, HttpServletResponse response, String fileDomain)
        throws CompressionException, GssParserException, LessException {
    Cache cache = null;
    try {
        //???
        if (cacheManager != null) {
            byte[] cacheLock;
            //??
            synchronized (progressCacheLock) {
                cacheLock = progressCacheLock.get(queryString);
            }
            if (cacheLock != null) {
                //??
                synchronized (cacheLock) {
                    logger.debug("?");
                    cacheLock.wait();
                }
                //
                cache = cacheManager.get(queryString);
            } else {
                //?queryString?
                cacheLock = new byte[0];
                synchronized (progressCacheLock) {
                    progressCacheLock.put(queryString, cacheLock);
                }
            }
        }
        String code;
        //??cache??
        if (cache == null || cache.isExpired()) {
            //???
            List<SourceCode> codeList = mergeCode(queryString.split("&"), request, response, type);
            List<SourceCode> sourceCodeList = Lists.newArrayList();
            //css?
            for (SourceCode source : codeList) {
                SourceCode s = new SourceCode(source.getFileName(),
                        fixUrlPath(request, source.getFileContents(), source.getFileName(), type, fileDomain));
                sourceCodeList.add(s);
            }
            //
            code = HttpUtils.getBooleanParam(request, "nocompress") ? mergeCode(sourceCodeList, request, type)
                    : compressCode(sourceCodeList, request, type);
            if (cacheManager != null) {
                final String finalCode = code;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            cacheManager.put(queryString, finalCode, type);
                        } catch (Exception e) {
                            logger.error("", e);
                        } finally {
                            byte[] cacheLock;
                            synchronized (progressCacheLock) {
                                cacheLock = progressCacheLock.remove(queryString);
                            }
                            synchronized (cacheLock) {
                                cacheLock.notifyAll();
                            }
                        }
                    }
                }).start();
            }
            return code;
        } else {
            return cache.getContent();
        }
    } catch (Exception e) {
        if (cacheManager != null) {
            byte[] cacheLock;
            synchronized (progressCacheLock) {
                cacheLock = progressCacheLock.remove(queryString);
            }
            synchronized (cacheLock) {
                cacheLock.notifyAll();
            }
        }
        throw new CompressionException(e);
    }
}