Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   * http://www.apache.org/licenses/LICENSE-2.0
   * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package freemarker.template.utility;
 
 import java.io.Writer;
 import java.util.Map;
 

A filter that compresses each sequence of consecutive whitespace to a single line break (if the sequence contains a line break) or a single space. In addition, leading and trailing whitespace is completely removed.

Specify the transform parameter single_line = true to always compress to a single space instead of a line break.

The default buffer size can be overridden by specifying a buffer_size transform parameter (in bytes).

Note: The compress tag is implemented using this filter

Usage:
From java:

 SimpleHash root = new SimpleHash();

 root.put( "standardCompress", new freemarker.template.utility.StandardCompress() );

 ...
 

From your FreeMarker template:

 <transform standardCompress>
   <p>This    paragraph will have
       extraneous

 whitespace removed.</p>
 </transform>
 

Output:

 <p>This paragraph will have
 extraneous
 whitespace removed.</p>
 
 
 public class StandardCompress implements TemplateTransformModel {
     private static final String BUFFER_SIZE_KEY = "buffer_size";
     private static final String SINGLE_LINE_KEY = "single_line";
     private int defaultBufferSize;
 
     public static final StandardCompress INSTANCE = new StandardCompress();
     
     public StandardCompress()
     {
         this(2048);
     }

    

Parameters:
defaultBufferSize the default amount of characters to buffer
 
     public StandardCompress(int defaultBufferSize)
     {
         this. = defaultBufferSize;
     }
 
     public Writer getWriter(final Writer outMap args)
     throws TemplateModelException
     {
         int bufferSize = ;
         boolean singleLine = false;
         if (args != null) {
             try {
                 TemplateNumberModel num = (TemplateNumberModel)args.get();
                 if (num != null)
                     bufferSize = num.getAsNumber().intValue();
             } catch (ClassCastException e) {
                throw new TemplateModelException("Expecting numerical argument to " + );
            }
            try {
                TemplateBooleanModel flag = (TemplateBooleanModel)args.get();
                if (flag != null)
                    singleLine = flag.getAsBoolean();
            } catch (ClassCastException e) {
                throw new TemplateModelException("Expecting boolean argument to " + );
            }
        }
        return new StandardCompressWriter(outbufferSizesingleLine);
    }
    private static class StandardCompressWriter extends Writer
    {
        private static final int MAX_EOL_LENGTH = 2; // CRLF is two bytes
        
        private static final int AT_BEGINNING = 0;
        private static final int SINGLE_LINE = 1;
        private static final int INIT = 2;
        private static final int SAW_CR = 3;
        private static final int LINEBREAK_CR = 4;
        private static final int LINEBREAK_CRLF = 5;
        private static final int LINEBREAK_LF = 6;
        private final Writer out;
        private final char[] buf;
        private final boolean singleLine;
    
        private int pos = 0;
        private boolean inWhitespace = true;
        private int lineBreakState = ;
        public StandardCompressWriter(Writer outint bufSizeboolean singleLine) {
            this. = out;
            this. = singleLine;
             = new char[bufSize];
        }
        public void write(char[] cbufint offint lenthrows IOException {
            for (;;) {
                // Need to reserve space for the EOL potentially left in the state machine
                int room = . -  - 
                if (room >= len) {
                    writeHelper(cbufofflen);
                    break;
                } else if (room <= 0) {
                    flushInternal();
                } else {
                    writeHelper(cbufoffroom);
                    flushInternal();
                    off += room;
                    len -= room;
                }
            }
        }
        private void writeHelper(char[] cbufint offint len) {
            for (int i = offend = off + leni < endi++) {
                char c = cbuf[i];
                if (Character.isWhitespace(c)) {
                     = true;
                    updateLineBreakState(c);
                } else if () {
                     = false;
                    writeLineBreakOrSpace();
                    [++] = c;
                } else {
                    [++] = c;
                }
            }
        }
        /*
          \r\n    => CRLF
          \r[^\n] => CR
          \r$     => CR
          [^\r]\n => LF
          ^\n     => LF
        */
        private void updateLineBreakState(char c)
        {
            switch () {
            case :
                if (c == '\r') {
                     = ;
                } else if (c == '\n') {
                     = ;
                }
                break;
            case :
                if (c == '\n') {
                     = ;
                } else {
                     = ;
                }
            }
        }
        private void writeLineBreakOrSpace()
        {
            switch () {
            case :
                // whitespace ended with CR, fall through
            case :
                [++] = '\r';
                break;
            case :
                [++] = '\r';
                // fall through
            case :
                [++] = '\n';
                break;
            case :
                // ignore leading whitespace
                break;
            case :
            case :
                [++] = ' ';
            }
             = () ?  : ;
        }
        private void flushInternal() throws IOException {
            .write(, 0, );
             = 0;
        }
        public void flush() throws IOException {
            flushInternal();
            .flush();
        }
        public void close() throws IOException {
            flushInternal();
        }
    }
New to GrepCode? Check out our FAQ X