Java Examples for com.googlecode.htmlcompressor.compressor.HtmlCompressor
The following java examples will help you to understand the usage of com.googlecode.htmlcompressor.compressor.HtmlCompressor. These source code samples are taken from different open source projects.
Example 1
| Project: gradle-website-optimizer-master File: HtmlProcessor.java View source code |
public String process(String src) {
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());
return compressor.compress(src);
}Example 2
| Project: trimou-master File: MinifyListenerTest.java View source code |
@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 -->";
}
})));
}Example 3
| Project: winlet-master File: CompressFilter.java View source code |
public void close() throws IOException {
if (closed) {
throw new IOException("This output stream has already been closed");
}
String contentType = response.getContentType();
if (contentType != null && contentType.startsWith("text/html")) {
String html = baos.toString();
// { extract JSON-LD before compression, HtmlCompressor cannot
// handle them
ArrayList<String> jsonLd = new ArrayList<String>();
while (true) {
Matcher m = JSON_LD.matcher(html);
if (!m.find())
break;
jsonLd.add(m.group(2).replace("\n", "").replace("\r", ""));
html = m.replaceFirst("");
}
// }
HtmlCompressor compressor = new HtmlCompressor();
compressor.setCompressJavaScript(true);
compressor.setCompressCss(true);
html = compressor.compress(html);
// insert JSON-LD back to before </head> or </body>
if (jsonLd.size() > 0) {
StringBuffer sb = new StringBuffer();
for (String str : jsonLd) sb.append("<script type=\"application/ld+json\">").append(str).append("</script>");
String lower = html.toLowerCase();
int idx = lower.indexOf("</head>");
if (idx <= 0)
idx = lower.indexOf("</body>");
if (idx > 0)
html = html.substring(0, idx) + sb.toString() + html.substring(idx);
}
output.write(html.getBytes());
} else
output.write(baos.toByteArray());
output.flush();
output.close();
closed = true;
}Example 4
| Project: DynamicCompressor-master File: JavascriptTemplateEngine.java View source code |
public static String compress(String name, String source, Mode mode) {
HtmlCompressor compressor = new HtmlCompressor();
//removes iter-tag whitespace characters
compressor.setRemoveIntertagSpaces(true);
//removes unnecessary tag attribute quotes
compressor.setRemoveQuotes(true);
//simplify existing doctype
compressor.setSimpleDoctype(true);
//remove optional attributes from script tags
compressor.setRemoveScriptAttributes(true);
//remove optional attributes from style tags
compressor.setRemoveStyleAttributes(true);
//remove optional attributes from link tags
compressor.setRemoveLinkAttributes(true);
//remove optional attributes from form tags
compressor.setRemoveFormAttributes(true);
//remove optional attributes from input tags
compressor.setRemoveInputAttributes(true);
//remove values from boolean tag attributes
compressor.setSimpleBooleanAttributes(true);
//remove "javascript:" from inline event handlers
compressor.setRemoveJavaScriptProtocol(true);
//compressor.setRemoveHttpProtocol(true); //replace "http://" with "//" inside tag attributes
// compressor.setRemoveHttpsProtocol(true); //replace "https://" with "//" inside tag attributes
//preserves original line breaks
compressor.setPreserveLineBreaks(false);
//remove spaces around provided tags
compressor.setRemoveSurroundingSpaces(HtmlCompressor.ALL_TAGS);
//compress inline css
compressor.setCompressCss(true);
//compress inline javascript
compressor.setCompressJavaScript(true);
//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
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);
}Example 5
| Project: yui-compressor-ant-task-master File: YuiCompressorTask.java View source code |
private void compressFile(final File inFile, final File outFile, final String fileType) throws EvaluatorException, BuildException {
// always recompress when outFile and inFile are exactly the same file
if (outFile.isFile() && !inFile.getAbsolutePath().equals(outFile.getAbsolutePath())) {
if (outFile.lastModified() >= inFile.lastModified()) {
return;
}
}
try {
// prepare input file
Reader in = openFile(inFile);
// prepare output file
outFile.getParentFile().mkdirs();
Writer out = new OutputStreamWriter(new FileOutputStream(outFile), charset);
if (fileType.equals(FileType.JS_FILE)) {
final JavaScriptCompressor compressor = createJavaScriptCompressor(in);
compressor.compress(out, lineBreakPosition, munge, warn, preserveAllSemiColons, !optimize);
} else if (fileType.equals(FileType.CSS_FILE)) {
final CssCompressor compressor = new CssCompressor(in);
compressor.compress(out, lineBreakPosition);
} else if (fileType.equals(FileType.HTML_FILE) || fileType.equals(FileType.XHTML_FILE)) {
final HtmlCompressor compressor = new HtmlCompressor();
out.write(compressor.compress(readerToString(in)));
} else if (fileType.equals(FileType.XML_FILE)) {
final XmlCompressor compressor = new XmlCompressor();
out.write(compressor.compress(readerToString(in)));
}
// close all streams
in.close();
in = null;
out.close();
out = null;
if (verbose) {
log(stats.getFileStats(inFile, outFile, fileType));
}
} catch (final IOException ioe) {
throw new BuildException("I/O Error when compressing file", ioe);
}
}Example 6
| Project: Greencode-Framework-master File: FileWeb.java View source code |
// TODO: Verificar futuramente para possíveis otimizações.
private static FileWeb loadStructure(File file, FileWeb fileWeb, boolean importCoreJS) throws IOException {
final String ext = FileUtils.getExtension(file.getName());
final boolean isCss = ext.equals("css"), isJs = ext.equals("js"), isView = ext.equals("html") || ext.equals("xhtml") || ext.equals("jsp") || ext.equals("htm");
if (isCss || isJs || isView) {
List<FileWeb> inserted = null;
String content = null, path = null;
Document src = null;
if (isView) {
if (fileWeb == null) {
path = file.toURI().toURL().getPath();
path = path.substring(path.indexOf("WEB-INF/classes/../../") + 22);
fileWeb = files.get(path);
} else
path = fileWeb.pageAnnotation.path();
if (fileWeb != null && !fileWeb.changed())
return fileWeb;
inserted = new ArrayList<FileWeb>();
content = FileUtils.getContentFile(file.toURI().toURL(), GreenCodeConfig.Server.View.charset).replaceAll(Pattern.quote("GREENCODE:{CONTEXT_PATH}"), Core.CONTEXT_PATH);
int lastIndex = 0;
String startString = "GREENCODE:{(";
while ((lastIndex = content.indexOf(startString, lastIndex)) != -1) {
final int listCloseIndex = content.indexOf('}', lastIndex);
final String c = content.substring(lastIndex + startString.length(), listCloseIndex);
try {
int closeIndex = c.indexOf(')');
Class<?> clazz = Class.forName(c.substring(0, closeIndex));
content = content.replaceAll(Pattern.quote(startString + c + '}'), GenericReflection.getValue(clazz, c.substring(closeIndex + 2), null).toString());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
lastIndex = listCloseIndex;
}
src = Jsoup.parse(content, GreenCodeConfig.Server.View.charset);
List<Element> listSelf = src.getElementsByTag("template:import");
if (!listSelf.isEmpty()) {
Element ele = listSelf.get(0);
Document templateImported = null;
String templateName = ele.attr("name");
if (templateName != null && !templateName.isEmpty()) {
File f = Cache.templates.get(templateName);
if (f != null) {
FileWeb template = loadStructure(f);
if (!GreenCodeConfig.Server.View.bootable)
inserted.add(template);
templateImported = template.document;
} else
throw new GreencodeError(LogMessage.getMessage("green-0042", templateName));
} else {
FileWeb template = loadStructure(Cache.defaultTemplate);
templateImported = template.document;
if (!GreenCodeConfig.Server.View.bootable)
inserted.add(template);
}
if (templateImported != null) {
ele.remove();
src.head().replaceWith(templateImported.head().clone());
src.body().replaceWith(templateImported.body().clone().append(src.body().html()));
}
String title = ele.attr("title");
if (title != null && !title.isEmpty()) {
Elements e = src.getElementsByTag("title");
if (!e.isEmpty())
e.get(0).text(title);
}
List<Element> elementsHead = src.getElementsByTag("template:head");
if (!elementsHead.isEmpty()) {
for (Element e : elementsHead) {
src.head().append(e.html());
e.remove();
}
}
List<Element> elementsDefine = src.getElementsByTag("template:define");
if (!elementsDefine.isEmpty()) {
List<Element> elementsInsert = src.getElementsByTag("template:insert");
if (!elementsInsert.isEmpty()) {
for (Element eInsert : elementsInsert) {
for (Element eDefine : elementsDefine) {
if (eInsert.attr("name").equals(eDefine.attr("name"))) {
eInsert.after(eDefine.html()).remove();
eDefine.remove();
}
}
}
}
}
}
List<Element> elementsInclude = src.getElementsByTag("template:include");
for (Element element : elementsInclude) {
String attrSrc = element.attr("src");
if (attrSrc != null && !attrSrc.isEmpty()) {
File f = new File(file.getParentFile().getAbsolutePath() + "/" + attrSrc);
try {
FileWeb fw = loadStructure(f);
if (!GreenCodeConfig.Server.View.bootable)
inserted.add(fw);
if (element.hasAttr("head"))
src.head().append(fw.content);
else
element.after(fw.content);
element.remove();
} catch (IOException e) {
throw new GreencodeError(LogMessage.getMessage("green-0020", attrSrc, "template:include", file.getName()));
}
}
}
List<Element> joins = src.head().getElementsByAttribute("join");
for (Element e : joins) {
String filePath = e.attr("file");
if (filePath.isEmpty())
throw new GreencodeError(LogMessage.getMessage("green-0021", "file", e.tagName(), file.getName()));
String[] filesName = e.attr("join").split(",");
File[] files = new File[filesName.length];
for (int i = -1; ++i < filesName.length; ) {
String name = filesName[i].trim();
File f = FileUtils.getFileInWebContent(name);
if (!f.exists()) {
throw new GreencodeError(LogMessage.getMessage("green-0020", name, e.tagName(), file.getName()));
}
files[i] = f;
}
MergedFile mergedFile = new MergedFile(FileUtils.getFileInWebContent(e.attr("file")).toURI(), files);
Cache.mergedFiles.put(filePath, mergedFile);
e.removeAttr("join").removeAttr("file");
}
if (importCoreJS)
src.head().prepend("<script type=\"text/javascript\" src=\"" + Core.SRC_CORE_JS_FOR_SCRIPT_HTML + "\" charset=\"" + GreenCodeConfig.Server.View.charset + "\"></script>");
content = src.html();
} else
content = FileUtils.getContentFile(file.toURI().toURL());
if (GreenCodeConfig.Server.View.useMinified) {
HtmlCompressor html = new HtmlCompressor();
html.setRemoveIntertagSpaces(true);
content = html.compress(content);
}
if (isView) {
if (fileWeb == null) {
(fileWeb = new FileWeb()).file = file;
files.put(path, fileWeb);
} else
fileWeb.updateModifiedDate();
fileWeb.content = content;
fileWeb.document = src;
if (!inserted.isEmpty())
fileWeb.inserted = inserted;
src = null;
path = null;
return fileWeb;
} else
FileUtils.createFile(content, file);
}
return null;
}Example 7
| Project: jsmart-web-master File: FilterControl.java View source code |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.setCharacterEncoding(ENCODING);
httpResponse.setCharacterEncoding(ENCODING);
// Initiate bean context based on current thread instance
WebContext.initCurrentInstance(httpRequest, httpResponse);
// Instantiate request scoped authentication bean
HANDLER.instantiateAuthBean(httpRequest);
// Instantiate web security for request extra validation
HANDLER.instantiateWebSecurity(httpRequest);
// Anonymous subclass to wrap HTTP response to print output
WebFilterResponseWrapper responseWrapper = new WebFilterResponseWrapper(httpResponse);
Throwable throwable = null;
try {
filterChain.doFilter(request, responseWrapper);
} catch (Throwable thrown) {
throwable = thrown;
thrown.printStackTrace();
}
// Finalize request scoped web and auth beans
HANDLER.finalizeBeans(httpRequest, responseWrapper);
// Check if response was written before closing the WebContext
boolean responseWritten = WebContext.isResponseWritten();
// Close bean context based on current thread instance
WebContext.closeCurrentInstance();
// Case AsyncBean or RequestPath process was started it cannot proceed because it will not provide HTML via framework
if (httpRequest.isAsyncStarted() || responseWritten) {
// Generate response value after flushing the response wrapper buffer
responseWrapper.flushBuffer();
String responseVal = responseWrapper.toString();
// Close current outputStream on responseWrapper
responseWrapper.close();
// Write the response value on real response object
if (!httpResponse.isCommitted()) {
httpResponse.getWriter().write(responseVal);
}
// Case internal server error
if (throwable != null) {
if (throwable instanceof IOException) {
throw new IOException(throwable);
}
throw new ServletException(throwable);
}
return;
}
// Add Ajax headers to control redirect and reset
addAjaxHeaders(httpRequest, responseWrapper);
// Generate HTML after flushing the response wrapper buffer
responseWrapper.flushBuffer();
String html = completeHtml(httpRequest, responseWrapper);
// Close current outputStream on responseWrapper
responseWrapper.close();
// Case internal server error
if (throwable != null) {
responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
if (throwable instanceof IOException) {
throw new IOException(throwable);
}
throw new ServletException(throwable);
}
if (StringUtils.isBlank(html)) {
return;
}
if (CONFIG.getContent().isPrintHtml()) {
LOGGER.log(Level.INFO, html);
}
// Compress html to better load performance
HtmlCompress compressHtml = CONFIG.getContent().getCompressHtml();
if (compressHtml.isCompressHtml()) {
HtmlCompressor compressor = new HtmlCompressor();
compressor.setRemoveComments(!compressHtml.isSkipComments());
html = compressor.compress(html);
}
// Write our modified text to the real response
if (!httpResponse.isCommitted()) {
httpResponse.setContentLength(html.getBytes().length);
httpResponse.getWriter().write(html);
}
}Example 8
| Project: yobi-master File: CreationViaEmail.java View source code |
/**
* Does postprocessing for HTML document.
*
* 1. Replaces cid with attachments.
* 2. Removes newlines between HTML tags which will make the result rendered
* by markdown ugly.
*
* @param contents
* @param relatedAttachments
* @return
*/
private static String postprocessForHTML(String contents, Map<String, Attachment> relatedAttachments) {
return new HtmlCompressor().compress(replaceCidWithAttachments(contents, relatedAttachments));
}