com.googlecode.htmlcompressor.compressor.HtmlCompressor Java Examples

The following examples show how to use com.googlecode.htmlcompressor.compressor.HtmlCompressor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MinifyUtil.java    From minifierbeans with Apache License 2.0 6 votes vote down vote up
public void compressHtmlInternal(Reader in, Writer out, MinifyProperty minifyProperty) throws IOException {
    try {
        HtmlCompressor compressor = new HtmlCompressor();
        compressor.setRemoveIntertagSpaces(true);
        compressor.setCompressCss(minifyProperty.isBuildInternalCSSMinify());               //compress inline css
        compressor.setCompressJavaScript(minifyProperty.isBuildInternalJSMinify());
        compressor.setYuiJsNoMunge(!minifyProperty.isJsObfuscate());
        String output = compressor.compress(fromStream(in));//out, minifyProperty.getLineBreakPosition());
        in.close();
        in = null;
        out.write(output);
        out.flush();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}
 
Example #2
Source File: AbstractJudgelsController.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
protected static Result getResult(LazyHtml content, int statusCode) {
    HtmlCompressor htmlCompressor = new HtmlCompressor();
    Html compressedContent = new Html(htmlCompressor.compress(content.render().body()));
    switch (statusCode) {
        case Http.Status.OK:
            return Results.ok(compressedContent);
        case Http.Status.NOT_FOUND:
            return Results.notFound(compressedContent);
        default:
            return Results.badRequest(compressedContent);
    }
}
 
Example #3
Source File: TioHtmlCompressor.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 * @param compressor
 * @author tanyaowu
 */
public TioHtmlCompressor() {
	super();

	HtmlCompressor compressor = new HtmlCompressor();
	compressor.setEnabled(true);
	compressor.setCompressCss(false);
	compressor.setCompressJavaScript(false);

	compressor.setGenerateStatistics(false);

	compressor.setRemoveComments(options.isRemoveComments());
	compressor.setRemoveMultiSpaces(options.isRemoveMutliSpaces());
	compressor.setRemoveIntertagSpaces(options.isRemoveIntertagSpaces());
	compressor.setRemoveQuotes(options.isRemoveQuotes());
	compressor.setSimpleDoctype(options.isSimpleDoctype());
	compressor.setRemoveScriptAttributes(options.isRemoveScriptAttributes());
	compressor.setRemoveStyleAttributes(options.isRemoveStyleAttributes());
	compressor.setRemoveLinkAttributes(options.isRemoveLinkAttributes());
	compressor.setRemoveFormAttributes(options.isRemoveFormAttributes());
	compressor.setRemoveInputAttributes(options.isRemoveInputAttributes());
	compressor.setSimpleBooleanAttributes(options.isSimpleBooleanAttributes());
	compressor.setRemoveJavaScriptProtocol(options.isRemoveJavaScriptProtocol());
	compressor.setRemoveHttpProtocol(options.isRemoveHttpProtocol());
	compressor.setRemoveHttpsProtocol(options.isRemoveHttpsProtocol());
	compressor.setPreserveLineBreaks(options.isPreserveLineBreaks());
	this.compressor = compressor;
}
 
Example #4
Source File: HTMLCompressingConfig.java    From wicket-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void init(WebApplication webApplication) {
	
	HtmlCompressor compressor = new HtmlCompressor();
	setFeatureConfiguration(compressor);
	webApplication.getMarkupSettings().setMarkupFactory(new HtmlCompressingMarkupFactory(compressor));
	
	wicketEndpointRepository.add(new WicketAutoConfig.Builder(this.getClass())
			.withDetail("properties", props)
			.build());
}
 
Example #5
Source File: HTMLCompressingConfig.java    From wicket-spring-boot with Apache License 2.0 5 votes vote down vote up
private void setFeatureConfiguration(HtmlCompressor compressor) {
	for(Entry<String, Boolean> entrySet : props.getFeatures().entrySet()){
		Method method = null;
		String capitalizedKey = StringUtils.capitalize(entrySet.getKey());
		String methodname = "set" + capitalizedKey;
		try {
			method = compressor.getClass().getMethod(methodname, boolean.class);
			method.setAccessible(true);
			ReflectionUtils.invokeMethod(method, compressor, entrySet.getValue());
		} catch (Exception e) {
			logger.warn("failed to invoke method: {} with value {}. Exception: {}", methodname, entrySet.getValue(), e.getMessage());
		}
	}
}
 
Example #6
Source File: HtmlAnalyzer.java    From htmlcompressor with Apache License 2.0 5 votes vote down vote up
private HtmlCompressor getCleanCompressor() {
	HtmlCompressor compressor = new HtmlCompressor();
	compressor.setRemoveComments(false);
	compressor.setRemoveMultiSpaces(false);
	
	return compressor;
}
 
Example #7
Source File: JavaScriptCompressorDirective.java    From htmlcompressor with Apache License 2.0 5 votes vote down vote up
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
	super.init(rs, context, node);
	log = rs.getLog();
	
	//set compressor properties
	enabled = rs.getBoolean("userdirective.compressJs.enabled", true);
	jsCompressor = rs.getString("userdirective.compressHtml.jsCompressor", HtmlCompressor.JS_COMPRESSOR_YUI);
	yuiJsNoMunge = rs.getBoolean("userdirective.compressJs.yuiJsNoMunge", false);
	yuiJsPreserveAllSemiColons = rs.getBoolean("userdirective.compressJs.yuiJsPreserveAllSemiColons", false);
	yuiJsLineBreak = rs.getInt("userdirective.compressJs.yuiJsLineBreak", -1);
	closureOptLevel = rs.getString("userdirective.compressHtml.closureOptLevel", ClosureJavaScriptCompressor.COMPILATION_LEVEL_SIMPLE);
}
 
Example #8
Source File: HtmlCompressorTag.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	
	BodyContent bodyContent = getBodyContent();
	String content = bodyContent.getString();
	
	HtmlCompressor htmlCompressor = new HtmlCompressor();
	htmlCompressor.setEnabled(enabled);
	htmlCompressor.setRemoveComments(removeComments);
	htmlCompressor.setRemoveMultiSpaces(removeMultiSpaces);
	htmlCompressor.setRemoveIntertagSpaces(removeIntertagSpaces);
	htmlCompressor.setRemoveQuotes(removeQuotes);
	htmlCompressor.setPreserveLineBreaks(preserveLineBreaks);
	htmlCompressor.setCompressJavaScript(compressJavaScript);
	htmlCompressor.setCompressCss(compressCss);
	htmlCompressor.setYuiJsNoMunge(yuiJsNoMunge);
	htmlCompressor.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
	htmlCompressor.setYuiJsDisableOptimizations(yuiJsDisableOptimizations);
	htmlCompressor.setYuiJsLineBreak(yuiJsLineBreak);
	htmlCompressor.setYuiCssLineBreak(yuiCssLineBreak);

	htmlCompressor.setSimpleDoctype(simpleDoctype);
	htmlCompressor.setRemoveScriptAttributes(removeScriptAttributes);
	htmlCompressor.setRemoveStyleAttributes(removeStyleAttributes);
	htmlCompressor.setRemoveLinkAttributes(removeLinkAttributes);
	htmlCompressor.setRemoveFormAttributes(removeFormAttributes);
	htmlCompressor.setRemoveInputAttributes(removeInputAttributes);
	htmlCompressor.setSimpleBooleanAttributes(simpleBooleanAttributes);
	htmlCompressor.setRemoveJavaScriptProtocol(removeJavaScriptProtocol);
	htmlCompressor.setRemoveHttpProtocol(removeHttpProtocol);
	htmlCompressor.setRemoveHttpsProtocol(removeHttpsProtocol);
	
	if(compressJavaScript && jsCompressor.equalsIgnoreCase(HtmlCompressor.JS_COMPRESSOR_CLOSURE)) {
		ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
		if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
			closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
		} else if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
			closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
		} else {
			closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
		}
		htmlCompressor.setJavaScriptCompressor(closureCompressor);
	}
	
	try {
		bodyContent.clear();
		bodyContent.append(htmlCompressor.compress(content));
		bodyContent.writeOut(pageContext.getOut());
	} catch (Exception e) {
		throw new JspException("Failed to compress html",e);
	}
	
	return super.doEndTag();
}
 
Example #9
Source File: JavaScriptCompressorTag.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
@Override
public int doEndTag() throws JspException {
	
	BodyContent bodyContent = getBodyContent();
	String content = bodyContent.getString();

	try {
		if(enabled) {
			
			String result = content;
			
			if(jsCompressor.equalsIgnoreCase(HtmlCompressor.JS_COMPRESSOR_CLOSURE)) {
				//call Closure compressor
				ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
				if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
					closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
				} else if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
					closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
				} else {
					closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
				}
				
				result = closureCompressor.compress(content);
				
			} else {
				//call YUICompressor
				YuiJavaScriptCompressor yuiCompressor = new YuiJavaScriptCompressor();
				yuiCompressor.setDisableOptimizations(yuiJsDisableOptimizations);
				yuiCompressor.setLineBreak(yuiJsLineBreak);
				yuiCompressor.setNoMunge(yuiJsNoMunge);
				yuiCompressor.setPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
				
				result = yuiCompressor.compress(content);
			}
			
			bodyContent.clear();
			bodyContent.append(result);
			bodyContent.writeOut(pageContext.getOut());
		} else {
			bodyContent.clear();
			bodyContent.append(content);
			bodyContent.writeOut(pageContext.getOut());
		}

	} catch (Exception e) {
		throw new JspException("Failed to compress javascript",e);
	}
	
	return super.doEndTag();
}
 
Example #10
Source File: HtmlCompressorDirective.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
@Override
public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
	super.init(rs, context, node);
	log = rs.getLog();
	
	boolean compressJavaScript = rs.getBoolean("userdirective.compressHtml.compressJavaScript", false);
	
	//set compressor properties
	htmlCompressor.setEnabled(rs.getBoolean("userdirective.compressHtml.enabled", true));
	htmlCompressor.setRemoveComments(rs.getBoolean("userdirective.compressHtml.removeComments", true));
	htmlCompressor.setRemoveMultiSpaces(rs.getBoolean("userdirective.compressHtml.removeMultiSpaces", true));
	htmlCompressor.setRemoveIntertagSpaces(rs.getBoolean("userdirective.compressHtml.removeIntertagSpaces", false));
	htmlCompressor.setRemoveQuotes(rs.getBoolean("userdirective.compressHtml.removeQuotes", false));
	htmlCompressor.setPreserveLineBreaks(rs.getBoolean("userdirective.compressHtml.preserveLineBreaks", false));
	htmlCompressor.setCompressJavaScript(compressJavaScript);
	htmlCompressor.setCompressCss(rs.getBoolean("userdirective.compressHtml.compressCss", false));
	htmlCompressor.setYuiJsNoMunge(rs.getBoolean("userdirective.compressHtml.yuiJsNoMunge", false));
	htmlCompressor.setYuiJsPreserveAllSemiColons(rs.getBoolean("userdirective.compressHtml.yuiJsPreserveAllSemiColons", false));
	htmlCompressor.setYuiJsLineBreak(rs.getInt("userdirective.compressHtml.yuiJsLineBreak", -1));
	htmlCompressor.setYuiCssLineBreak(rs.getInt("userdirective.compressHtml.yuiCssLineBreak", -1));
	htmlCompressor.setSimpleDoctype(rs.getBoolean("userdirective.compressHtml.simpleDoctype", false));
	htmlCompressor.setRemoveScriptAttributes(rs.getBoolean("userdirective.compressHtml.removeScriptAttributes", false));
	htmlCompressor.setRemoveStyleAttributes(rs.getBoolean("userdirective.compressHtml.removeStyleAttributes", false));
	htmlCompressor.setRemoveLinkAttributes(rs.getBoolean("userdirective.compressHtml.removeLinkAttributes", false));
	htmlCompressor.setRemoveFormAttributes(rs.getBoolean("userdirective.compressHtml.removeFormAttributes", false));
	htmlCompressor.setRemoveInputAttributes(rs.getBoolean("userdirective.compressHtml.removeInputAttributes", false));
	htmlCompressor.setSimpleBooleanAttributes(rs.getBoolean("userdirective.compressHtml.simpleBooleanAttributes", false));
	htmlCompressor.setRemoveJavaScriptProtocol(rs.getBoolean("userdirective.compressHtml.removeJavaScriptProtocol", false));
	htmlCompressor.setRemoveHttpProtocol(rs.getBoolean("userdirective.compressHtml.removeHttpProtocol", false));
	htmlCompressor.setRemoveHttpsProtocol(rs.getBoolean("userdirective.compressHtml.removeHttpsProtocol", false));
	
	
	if(compressJavaScript && rs.getString("userdirective.compressHtml.jsCompressor", HtmlCompressor.JS_COMPRESSOR_YUI).equalsIgnoreCase(HtmlCompressor.JS_COMPRESSOR_CLOSURE)) {
		String closureOptLevel = rs.getString("userdirective.compressHtml.closureOptLevel", ClosureJavaScriptCompressor.COMPILATION_LEVEL_SIMPLE);
		
		ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
		if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
			closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
		} else if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
			closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
		} else {
			closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
		}
		
		htmlCompressor.setJavaScriptCompressor(closureCompressor);
	}
}
 
Example #11
Source File: JavaScriptCompressorDirective.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
public boolean render(InternalContextAdapter context, Writer writer, Node node) 
  		throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  	
  	//render content
  	StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);

//compress
if(enabled) {
	try {
		String result = content.toString();
		
		if(jsCompressor.equalsIgnoreCase(HtmlCompressor.JS_COMPRESSOR_CLOSURE)) {
			//call Closure compressor
			ClosureJavaScriptCompressor closureCompressor = new ClosureJavaScriptCompressor();
			if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_ADVANCED)) {
				closureCompressor.setCompilationLevel(CompilationLevel.ADVANCED_OPTIMIZATIONS);
			} else if(closureOptLevel.equalsIgnoreCase(ClosureJavaScriptCompressor.COMPILATION_LEVEL_WHITESPACE)) {
				closureCompressor.setCompilationLevel(CompilationLevel.WHITESPACE_ONLY);
			} else {
				closureCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);
			}
			
			result = closureCompressor.compress(result);
			
		} else {
			//call YUICompressor
			YuiJavaScriptCompressor yuiCompressor = new YuiJavaScriptCompressor();
			yuiCompressor.setDisableOptimizations(yuiJsDisableOptimizations);
			yuiCompressor.setLineBreak(yuiJsLineBreak);
			yuiCompressor.setNoMunge(yuiJsNoMunge);
			yuiCompressor.setPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
			
			result = yuiCompressor.compress(result);
		}
		
		writer.write(result);
	} catch (Exception e) {
		writer.write(content.toString());
		String msg = "Failed to compress content: "+content.toString();
           log.error(msg, e);
           throw new RuntimeException(msg, e);
           
	}
} else {
	writer.write(content.toString());
}

return true;
  	
  }
 
Example #12
Source File: HtmlCompressorMinifier.java    From trimou with Apache License 2.0 4 votes vote down vote up
public HtmlCompressorMinifier() {
    super(new HtmlCompressor());
}
 
Example #13
Source File: HtmlCompressorMinifier.java    From trimou with Apache License 2.0 4 votes vote down vote up
public HtmlCompressorMinifier(Predicate<String> matchingPredicate) {
    super(new HtmlCompressor(), matchingPredicate);
}
 
Example #14
Source File: MinifyListenerTest.java    From trimou with Apache License 2.0 4 votes vote down vote up
@Test
public void testCustomizedHtmlListener() {

    String contents = "<html><body><!-- My comment --></body></html>";

    MustacheEngine engine = MustacheEngineBuilder
            .newBuilder()
            .addMustacheListener(
                    Minify.customListener(new HtmlCompressorMinifier() {
                        @Override
                        protected void initCompressor(
                                HtmlCompressor compressor,
                                Configuration configuration) {
                            compressor.setEnabled(false);
                        }
                    })).build();
    // Compressor is disabled
    assertEquals(contents,
            engine.compileMustache("minify_html_customized", contents)
                    .render(null));

    engine = MustacheEngineBuilder.newBuilder()
            .addMustacheListener(
                    Minify.customListener(new HtmlCompressorMinifier(
                            mustacheName -> mustacheName.endsWith("html"))))
            .build();
    // Mustache name does not match
    assertEquals(contents,
            engine.compileMustache("minify_html_customized", contents)
                    .render(null));

    // Skip lambdas
    engine = MustacheEngineBuilder.newBuilder()
            .addMustacheListener(
                    Minify.customListener(new HtmlCompressorMinifier(
                            mustacheName -> !mustacheName.startsWith(
                                    Lambda.ONEOFF_LAMBDA_TEMPLATE_PREFIX))))
            .build();
    assertEquals(contents, engine
            .compileMustache("minify_html_customized_skip_lambda",
                    "<html><body>{{{lambda}}}</body></html>")
            .render(ImmutableMap.of("lambda", new InputLiteralLambda() {

                @Override
                public boolean isReturnValueInterpolated() {
                    return true;
                }

                @Override
                public String invoke(String text) {
                    return "<!-- My comment -->";
                }
            })));
}