Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you 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 org.apache.sling.engine.impl.parameters;
 
 import java.util.Map;
 
 
 public class Util {
 
     // ISO-8859-1 mapps all characters 0..255 to \u0000..\u00ff directly
     public static final String ENCODING_DIRECT = "ISO-8859-1";
 
     // Default query (and www-form-encoded) parameter encoding as per
     // HTML spec.
     // see http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.1
     public static final String ENCODING_DEFAULT = "UTF-8";
 
     public static final byte[] NO_CONTENT = new byte[0];
 
     // the default encoding used in #fixEncoding if the _charset_ request
     // parameter is not set
     private static String defaultFixEncoding = ;

    
Parse state constant
 
     private static final int BEFORE_NAME =  0;

    
Parse state constant
 
     private static final int INSIDE_NAME =   + 1;

    
Parse state constant
 
     private static final int ESC_NAME =   + 1;

    
Parse state constant
 
     private static final int BEFORE_EQU =   + 1;

    
Parse state constant
 
     private static final int BEFORE_VALUE =   + 1;

    
Parse state constant
 
     private static final int INSIDE_VALUE =   + 1;

    
Parse state constant
 
     private static final int ESC_VALUE =   + 1;

    
Parse state constant
 
     private static final int AFTER_VALUE =   + 1;

    
Parse state constant
 
     private static final int BEFORE_SEP =   + 1;
 
     public static void setDefaultFixEncoding(final String encoding) {
          = validateEncoding(encoding);
     }
 
     static String getDefaultFixEncoding() {
         return ;
     }
 
     static String toIdentityEncodedString(byte[] data) {
         if (data == null) {
             return null;
         }
 
         char[] characters = new char[data.length];
         for (int i = 0; i < characters.lengthi++) {
             characters[i] = (char) (data[i] & 0xff);
         }
         return new String(characters);
     }
 
     static byte[] fromIdentityEncodedString(String string) {
         if (string == null) {
             return ;
         }
 
         byte[] data = new byte[string.length()];
        for (int i = 0; i < data.lengthi++) {
            data[i] = (byte) (string.charAt(i) & 0xff);
        }
        return data;
    }
    static InputStream toInputStream(String source) {
        byte[] data = fromIdentityEncodedString(source);
        return new ByteArrayInputStream(data);
    }
    static void fixEncoding(ParameterMap parameterMap) {
        // default the encoding to defaultFixEncoding
        String formEncoding = getDefaultFixEncoding();
        // check whether a form encoding parameter overwrites this default
        RequestParameter[] feParm = parameterMap.get(.);
        if (feParm != null) {
            // get and check form encoding
            byte[] rawEncoding = feParm[0].get();
            formEncoding = toIdentityEncodedString(rawEncoding);
            formEncoding = validateEncoding(formEncoding);
        }
        // map for rename parameters due to encoding fixes
        LinkedHashMap<StringStringrenameMap = new LinkedHashMap<StringString>();
        // convert the map of lists to a map of arrays
        for (Map.Entry<StringRequestParameter[]> paramEntry : parameterMap.entrySet()) {
            RequestParameter[] params = paramEntry.getValue();
            String parName = null;
            for (int i = 0; i < params.lengthi++) {
                if (params[iinstanceof AbstractRequestParameter) {
                    AbstractRequestParameter param = (AbstractRequestParameterparams[i];
                    // fix encoding if different
                    if (!formEncoding.equalsIgnoreCase(param.getEncoding())) {
                        param.setEncoding(formEncoding);
                        // prepare the parameter for renaming
                        if (parName == null) {
                            parName = paramEntry.getKey();
                            String name = reencode(parNameformEncoding);
                            if (!parName.equals(name)) {
                                renameMap.put(parNamename);
                            }
                        }
                    }
                }
            }
        }
        // apply mappings of deinternationalized names
        if (!renameMap.isEmpty()) {
            for (Map.Entry<StringStringentry : renameMap.entrySet()) {
                parameterMap.renameParameter(entry.getKey(), entry.getValue());
            }
        }
    }
    private static String reencode(String parNameString encoding) {
        // re-encode the parameter to the encoding
        if (!.equalsIgnoreCase(encoding)) {
            try {
                return new String(parName.getBytes(), encoding);
            } catch (UnsupportedEncodingException uee) {
                // unexpected, as the encoding is assumed to have been checked !
            }
        }
        // otherwise just return the name unmodified
        return parName;
    }

    
Checks whether the given encoding is known and supported by the platform or not. If the platform supports the encoding the parameter is returned. Otherwise or if the encoding argument is null or an empty string defaultFixEncoding is returned.

Parameters:
encoding The encoding to validate
Returns:
The encoding if supported or defaultFixEncoding
    private static String validateEncoding(final String encoding) {
        if (encoding != null && encoding.length() > 0) {
            // check for the existence of the encoding
            try {
                "".getBytes(encoding);
                return encoding;
            } catch (UnsupportedEncodingException e) {
                // log.warn("HttpMulitpartPost: Character encoding {0} is not "
                // + "supported, using default {1}", formEncodingParam,
                // DEFAULT_ENCODING);
            }
        }
        // no encoding or unsupported encoding
        return getDefaultFixEncoding();
    }

    
Parse a query string and store entries inside a map

Parameters:
data querystring data
encoding encoding to use for converting bytes to characters
map map to populate
prependNew whether to prepend new values
Throws:
java.lang.IllegalArgumentException if the nv string is malformed
java.io.UnsupportedEncodingException if the encoding is not supported
java.io.IOException if an error occurrs reading from data
    public static void parseQueryString(InputStream dataString encodingParameterMap mapboolean prependNew)
            throws UnsupportedEncodingExceptionIOException {
        parseNVPairString(dataencodingmap'&'falseprependNew);
    }

    
Parse a name/value pair string and populate a map with key -> value[s]

Parameters:
data name value data
encoding encoding to use for converting bytes to characters
map map to populate
separator multi-value separator character
allowSpaces allow spaces inside name/values
prependNew whether to prepend new values
Throws:
java.lang.IllegalArgumentException if the nv string is malformed
java.io.UnsupportedEncodingException if the encoding is not supported
java.io.IOException if an error occurrs reading from data
    private static void parseNVPairString(InputStream dataString encodingParameterMap mapchar separator,
            boolean allowSpacesboolean prependNewthrows UnsupportedEncodingExceptionIOException {
        ByteArrayOutputStream keyBuffer   = new ByteArrayOutputStream(256);
        ByteArrayOutputStream valueBuffer = new ByteArrayOutputStream(256);
        char[] chCode = new char[2];
        int state = ;
        int subState = 0;
        for (int in = data.read(); in >= 0; in = data.read()) {
            char ch = (charin;
            switch (state) {
                case :
                    if (ch == ' ') {
                        continue;
                    } else if (ch == '%') {
                        state = ;
                        subState = 0;
                    } else if (ch == '+' && !allowSpaces) {
                        keyBuffer.write(' ');
                        state = ;
                    } else {
                        keyBuffer.write(ch);
                        state = ;
                    }
                    break;
                case :
                    if (ch == '=') {
                        state = ;
                    } else if (ch == '+' && !allowSpaces) {
                        keyBuffer.write(' ');
                    } else if (ch == '%') {
                        state = ;
                        subState = 0;
                    } else if (ch == '&') {
                        addNVPair(mapkeyBuffervalueBufferencodingprependNew);
                        state = ;
                    } else {
                        keyBuffer.write(ch);
                    }
                    break;
                case :
                    chCode[subState++] = ch;
                    if (subState == chCode.length) {
                        String code = new String(chCode);
                        try {
                            keyBuffer.write(Integer.parseInt(code, 16));
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException(
                                    "Bad escape sequence: %" + code);
                        }
                        state = ;
                    }
                    break;
                case :
                    if (ch == '=') {
                        state = ;
                    }
                    break;
                case :
                    if (ch == ' ') {
                        continue;
                    } else if (ch == '%') {
                        state = ;
                        subState = 0;
                    } else if (ch == '+' && !allowSpaces) {
                        valueBuffer.write(' ');
                        state = ;
                    } else if (ch == separator) {
                        addNVPair(mapkeyBuffervalueBufferencodingprependNew);
                        state = ;
                    } else {
                        valueBuffer.write(ch);
                        state = ;
                    }
                    break;
                case :
                    if (ch == separator) {
                        addNVPair(mapkeyBuffervalueBufferencodingprependNew);
                        state = ;
                    } else if (ch == '+' && !allowSpaces) {
                        valueBuffer.write(' ');
                    } else if (ch == '%') {
                        state = ;
                        subState = 0;
                    } else {
                        valueBuffer.write(ch);
                    }
                    break;
                case :
                    chCode[subState++] = ch;
                    if (subState == chCode.length) {
                        String code = new String(chCode);
                        try {
                            valueBuffer.write(Integer.parseInt(code, 16));
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException(
                                    "Bad escape sequence: %" + code);
                        }
                        state = ;
                    }
                    break;
                case :
                    if (ch == separator) {
                        state = ;
                    }
                    break;
            }
        }
        if (keyBuffer.size() > 0) {
            addNVPair(mapkeyBuffervalueBufferencodingprependNew);
        }
    }
    private static void addNVPair(ParameterMap mapByteArrayOutputStream keyBufferByteArrayOutputStream valueBuffer,
            String encodingboolean prependNewthrows UnsupportedEncodingException {
        final String key = keyBuffer.toString(encoding);
        final String value = valueBuffer.toString(encoding);
        map.addParameter(new ContainerRequestParameter(keyvalueencoding), prependNew);
        keyBuffer.reset();
        valueBuffer.reset();
    }
New to GrepCode? Check out our FAQ X