myfaces-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From lu4...@apache.org
Subject svn commit: r959472 - in /myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock: MockRenderKit.java MockResponseStateManager.java _Hex.java
Date Thu, 01 Jul 2010 00:05:33 GMT
Author: lu4242
Date: Thu Jul  1 00:05:32 2010
New Revision: 959472

URL: http://svn.apache.org/viewvc?rev=959472&view=rev
Log:
MYFACESTEST-15 Add new MockResponseStateManager

Added:
    myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockResponseStateManager.java
    myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/_Hex.java
Modified:
    myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockRenderKit.java

Modified: myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockRenderKit.java
URL: http://svn.apache.org/viewvc/myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockRenderKit.java?rev=959472&r1=959471&r2=959472&view=diff
==============================================================================
--- myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockRenderKit.java
(original)
+++ myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockRenderKit.java
Thu Jul  1 00:05:32 2010
@@ -35,105 +35,108 @@ import javax.faces.render.ResponseStateM
  * $Id$
  */
 
-public class MockRenderKit extends RenderKit {
-
+public class MockRenderKit extends RenderKit
+{
 
     // ------------------------------------------------------------ Constructors
 
-
     /**
      * <p>Return a default instance.</p>
      */
-    public MockRenderKit() {
+    public MockRenderKit()
+    {
     }
 
-
     // ----------------------------------------------------- Mock Object Methods
 
+    public void setResponseStateManager(ResponseStateManager rsm)
+    {
+        this.rsm = rsm;
+    }
 
     // ------------------------------------------------------ Instance Variables
 
-
     /**
      * <p>The set of renderers registered here.</p>
      */
     private Map renderers = new HashMap();
-
+    private ResponseStateManager rsm = new MockResponseStateManager();
 
     // ------------------------------------------------------- RenderKit Methods
 
-
     /** {@inheritDoc} */
     public void addRenderer(String family, String rendererType,
-                            Renderer renderer) {
+            Renderer renderer)
+    {
 
-        if ((family == null) || (rendererType == null) || (renderer == null)) {
+        if ((family == null) || (rendererType == null) || (renderer == null))
+        {
             throw new NullPointerException();
         }
         renderers.put(family + "|" + rendererType, renderer);
 
     }
 
-
     /** {@inheritDoc} */
-    public Renderer getRenderer(String family, String rendererType) {
+    public Renderer getRenderer(String family, String rendererType)
+    {
 
-        if ((family == null) || (rendererType == null)) {
+        if ((family == null) || (rendererType == null))
+        {
             throw new NullPointerException();
         }
         return (Renderer) renderers.get(family + "|" + rendererType);
 
     }
 
-
     /** {@inheritDoc} */
     public ResponseWriter createResponseWriter(Writer writer,
-                                               String contentTypeList,
-                                               String characterEncoding) {
+            String contentTypeList, String characterEncoding)
+    {
 
-       return new MockResponseWriter(writer, contentTypeList, characterEncoding);
+        return new MockResponseWriter(writer, contentTypeList,
+                characterEncoding);
 
     }
 
-
     /** {@inheritDoc} */
-    public ResponseStream createResponseStream(OutputStream out) {
+    public ResponseStream createResponseStream(OutputStream out)
+    {
 
         final OutputStream stream = out;
-        return new ResponseStream() {
+        return new ResponseStream()
+        {
 
-            public void close() throws IOException {
+            public void close() throws IOException
+            {
                 stream.close();
             }
 
-            public void flush() throws IOException {
+            public void flush() throws IOException
+            {
                 stream.flush();
             }
 
-            public void write(byte[] b) throws IOException {
+            public void write(byte[] b) throws IOException
+            {
                 stream.write(b);
             }
 
-            public void write(byte[] b, int off, int len) throws IOException {
+            public void write(byte[] b, int off, int len) throws IOException
+            {
                 stream.write(b, off, len);
             }
 
-            public void write(int b) throws IOException {
+            public void write(int b) throws IOException
+            {
                 stream.write(b);
             }
-
         };
-
-
     }
 
-
     /** {@inheritDoc} */
-    public ResponseStateManager getResponseStateManager() {
-
-        throw new UnsupportedOperationException();
-
+    public ResponseStateManager getResponseStateManager()
+    {
+        return rsm;
     }
-
-
 }

Added: myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockResponseStateManager.java
URL: http://svn.apache.org/viewvc/myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockResponseStateManager.java?rev=959472&view=auto
==============================================================================
--- myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockResponseStateManager.java
(added)
+++ myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/MockResponseStateManager.java
Thu Jul  1 00:05:32 2010
@@ -0,0 +1,280 @@
+package org.apache.myfaces.test.mock;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+import javax.faces.application.StateManager.SerializedView;
+import javax.faces.context.FacesContext;
+import javax.faces.context.ResponseWriter;
+import javax.faces.render.RenderKitFactory;
+import javax.faces.render.ResponseStateManager;
+
+/**
+ * Mock class that encode view state in hex format
+ * 
+ * @author Leonardo Uribe (latest modification by $Author: lu4242 $)
+ * @version $Revision: 951803 $ $Date: 2010-06-05 21:13:20 -0500 (Sáb, 05 Jun 2010) $
+ */
+public class MockResponseStateManager extends ResponseStateManager
+{
+    // ------------------------------------------------------------ Constructors
+
+    // ------------------------------------------------------ Instance Variables
+    
+    private static final int TREE_PARAM = 0;
+    private static final int STATE_PARAM = 1;
+    private static final int VIEWID_PARAM = 2;
+    private static final String ZIP_CHARSET = "ISO-8859-1";
+
+    
+    // ----------------------------------------------------- Mock Object Methods
+
+    // -------------------------------------------------- ResponseStateManager Methods
+    
+    public Object getState(FacesContext facesContext, String viewId)
+    {
+        Object[] savedState = getSavedState(facesContext);
+        if (savedState == null)
+        {
+            return null;
+        }
+
+        return new Object[] { savedState[TREE_PARAM], savedState[STATE_PARAM] };
+    }
+
+    public Object getTreeStructureToRestore(FacesContext facesContext, String viewId)
+    {
+        // Although this method won't be called anymore,
+        // it has been kept for backward compatibility.
+        Object[] savedState = getSavedState(facesContext);
+        if (savedState == null)
+        {
+            return null;
+        }
+
+        return savedState[TREE_PARAM];
+    }
+
+    public Object getComponentStateToRestore(FacesContext facesContext)
+    {
+        // Although this method won't be called anymore,
+        // it has been kept for backward compatibility.
+        Object[] savedState = getSavedState(facesContext);
+        if (savedState == null)
+        {
+            return null;
+        }
+
+        return savedState[STATE_PARAM];
+    }
+
+    public boolean isPostback(FacesContext context)
+    {
+        return context.getExternalContext().getRequestParameterMap().containsKey(ResponseStateManager.VIEW_STATE_PARAM);
+    }
+
+    public void writeState(FacesContext facescontext, SerializedView serializedview)
+            throws IOException
+    {
+        ResponseWriter responseWriter = facescontext.getResponseWriter();
+
+        Object[] savedState = new Object[3];
+
+        if (facescontext.getApplication().getStateManager().isSavingStateInClient(facescontext))
+        {
+            Object treeStruct = serializedview.getStructure();
+            Object compStates = serializedview.getState();
+
+            if (treeStruct != null)
+            {
+                savedState[TREE_PARAM] = treeStruct;
+            }
+
+            if (compStates != null)
+            {
+                savedState[STATE_PARAM] = compStates;
+            }
+        }
+        else
+        {
+            // write viewSequence
+            Object treeStruct = serializedview.getStructure();
+            if (treeStruct != null)
+            {
+                if (treeStruct instanceof String)
+                {
+                    savedState[TREE_PARAM] = treeStruct;
+                }
+            }
+        }
+
+        savedState[VIEWID_PARAM] = facescontext.getViewRoot().getViewId();
+
+        // write the view state field
+        writeViewStateField(facescontext, responseWriter, savedState);
+
+        // renderKitId field
+        writeRenderKitIdField(facescontext, responseWriter);
+    }
+
+    private void writeViewStateField(FacesContext facesContext, ResponseWriter responseWriter,
Object savedState)
+    throws IOException
+    {
+        
+        String serializedState = construct(facesContext, savedState);
+        responseWriter.startElement("input", null);
+        responseWriter.writeAttribute("type", "hidden", null);
+        responseWriter.writeAttribute("name", VIEW_STATE_PARAM, null);
+        responseWriter.writeAttribute("value", serializedState, null);
+        responseWriter.endElement("input");
+    }
+    
+
+    private void writeRenderKitIdField(FacesContext facesContext, ResponseWriter responseWriter)
throws IOException
+    {
+    
+        String defaultRenderKitId = facesContext.getApplication().getDefaultRenderKitId();
+        if (defaultRenderKitId != null && !RenderKitFactory.HTML_BASIC_RENDER_KIT.equals(defaultRenderKitId))
+        {
+            responseWriter.startElement("input", null);
+            responseWriter.writeAttribute("type", "hidden", null);
+            responseWriter.writeAttribute("name", ResponseStateManager.RENDER_KIT_ID_PARAM,
null);
+            responseWriter.writeAttribute("value", defaultRenderKitId, null);
+            responseWriter.endElement("input");
+        }
+    }
+    
+    private String construct(FacesContext facesContext, Object savedState) throws IOException
+    {
+        byte[] bytes = null;
+        ByteArrayOutputStream baos = null;
+        ObjectOutputStream oos = null;
+        try
+        {
+            baos = new ByteArrayOutputStream();
+            oos = new ObjectOutputStream(baos);
+            oos.writeObject(savedState);
+            bytes = baos.toByteArray();
+        }
+        finally
+        {
+            if (oos != null)
+            {
+                try
+                {
+                    oos.close();
+                }
+                catch(IOException e)
+                {
+                }
+                finally
+                {
+                    oos = null;
+                }
+            }
+            if (baos != null)
+            {
+                try
+                {
+                    baos.close();
+                }
+                catch(IOException e)
+                {
+                }
+                finally
+                {
+                    baos = null;
+                }
+            }
+        }
+        return new String(new _Hex().encode(bytes), ZIP_CHARSET);
+    }
+    
+    private Object reconstruct(FacesContext facesContext, String encodedState) throws IOException
+    {
+        byte[] bytes = encodedState.getBytes(ZIP_CHARSET);
+        
+        ByteArrayInputStream input = null;
+        ObjectInputStream s = null;
+        Object object = null;
+        
+        try
+        {
+            input = new ByteArrayInputStream(bytes);
+            s = new ObjectInputStream(input); 
+            object = s.readObject();
+        }
+        catch (ClassNotFoundException e)
+        {
+            throw new IOException(e);
+        }
+        finally
+        {
+            if (s != null)
+            {
+                try
+                {
+                    s.close();
+                }
+                catch(IOException e)
+                {
+                }
+                finally
+                {
+                    s = null;
+                }
+            }
+            if (input != null)
+            {
+                try
+                {
+                    input.close();
+                }
+                catch(IOException e)
+                {
+                }
+                finally
+                {
+                    input = null;
+                }
+            }
+        }
+        return object;
+    }
+
+    private Object[] getSavedState(FacesContext facesContext) {
+        Object encodedState = 
+            facesContext.getExternalContext().
+                getRequestParameterMap().get(VIEW_STATE_PARAM);
+        if(encodedState==null || (((String) encodedState).length() == 0)) { 
+            return null;
+        }
+
+        Object[] savedState = null;
+        
+        try
+        {
+            savedState = (Object[])reconstruct(facesContext, (String)encodedState);
+        }
+        catch(IOException e)
+        {
+            facesContext.getExternalContext().log("Cannot reconstruct view state", e);
+        }
+
+        if (savedState == null)
+        {
+            return null;
+        }
+        
+        String restoredViewId = (String)savedState[VIEWID_PARAM];
+
+        if (restoredViewId == null)
+        {
+            return null;
+        }
+        return savedState;
+    }
+}

Added: myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/_Hex.java
URL: http://svn.apache.org/viewvc/myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/_Hex.java?rev=959472&view=auto
==============================================================================
--- myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/_Hex.java (added)
+++ myfaces/test/trunk/test12/src/main/java/org/apache/myfaces/test/mock/_Hex.java Thu Jul
 1 00:05:32 2010
@@ -0,0 +1,310 @@
+/*
+ * 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.myfaces.test.mock;
+
+import java.io.UnsupportedEncodingException;
+
+/**
+ * Hex encoder and decoder. The charset used for certain operation can be set, the default
is set in
+ * {@link #DEFAULT_CHARSET_NAME}
+ * 
+ * @since 1.1
+ * @author Apache Software Foundation
+ * @version $Id: Hex.java 801639 2009-08-06 13:15:10Z niallp $
+ */
+class _Hex {
+
+    /**
+     * Default charset name is {@link CharEncoding#UTF_8}
+     */
+    public static final String DEFAULT_CHARSET_NAME = "UTF-8";
+
+    /**
+     * Used to build output as Hex
+     */
+    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+    /**
+     * Used to build output as Hex
+     */
+    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+    /**
+     * Converts an array of characters representing hexadecimal values into an array of bytes
of those same values. The
+     * returned array will be half the length of the passed array, as it takes two characters
to represent any given
+     * byte. An exception is thrown if the passed char array has an odd number of elements.
+     * 
+     * @param data
+     *            An array of characters containing hexadecimal digits
+     * @return A byte array containing binary data decoded from the supplied char array.
+     * @throws DecoderException
+     *             Thrown if an odd number or illegal of characters is supplied
+     */
+    public static byte[] decodeHex(char[] data) throws Exception {
+
+        int len = data.length;
+
+        if ((len & 0x01) != 0) {
+            throw new Exception("Odd number of characters.");
+        }
+
+        byte[] out = new byte[len >> 1];
+
+        // two characters form the hex value.
+        for (int i = 0, j = 0; j < len; i++) {
+            int f = toDigit(data[j], j) << 4;
+            j++;
+            f = f | toDigit(data[j], j);
+            j++;
+            out[i] = (byte) (f & 0xFF);
+        }
+
+        return out;
+    }
+
+    /**
+     * Converts an array of bytes into an array of characters representing the hexadecimal
values of each byte in order.
+     * The returned array will be double the length of the passed array, as it takes two
characters to represent any
+     * given byte.
+     * 
+     * @param data
+     *            a byte[] to convert to Hex characters
+     * @return A char[] containing hexadecimal characters
+     */
+    public static char[] encodeHex(byte[] data) {
+        return encodeHex(data, true);
+    }
+
+    /**
+     * Converts an array of bytes into an array of characters representing the hexadecimal
values of each byte in order.
+     * The returned array will be double the length of the passed array, as it takes two
characters to represent any
+     * given byte.
+     * 
+     * @param data
+     *            a byte[] to convert to Hex characters
+     * @param toLowerCase
+     *            <code>true</code> converts to lowercase, <code>false</code>
to uppercase
+     * @return A char[] containing hexadecimal characters
+     * @since 1.4
+     */
+    public static char[] encodeHex(byte[] data, boolean toLowerCase) {
+        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
+    }
+
+    /**
+     * Converts an array of bytes into an array of characters representing the hexadecimal
values of each byte in order.
+     * The returned array will be double the length of the passed array, as it takes two
characters to represent any
+     * given byte.
+     * 
+     * @param data
+     *            a byte[] to convert to Hex characters
+     * @param toDigits
+     *            the output alphabet
+     * @return A char[] containing hexadecimal characters
+     * @since 1.4
+     */
+    protected static char[] encodeHex(byte[] data, char[] toDigits) {
+        int l = data.length;
+        char[] out = new char[l << 1];
+        // two characters form the hex value.
+        for (int i = 0, j = 0; i < l; i++) {
+            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
+            out[j++] = toDigits[0x0F & data[i]];
+        }
+        return out;
+    }
+
+    /**
+     * Converts an array of bytes into a String representing the hexadecimal values of each
byte in order. The returned
+     * String will be double the length of the passed array, as it takes two characters to
represent any given byte.
+     * 
+     * @param data
+     *            a byte[] to convert to Hex characters
+     * @return A String containing hexadecimal characters
+     * @since 1.4
+     */
+    public static String encodeHexString(byte[] data) {
+        return new String(encodeHex(data));
+    }
+
+    /**
+     * Converts a hexadecimal character to an integer.
+     * 
+     * @param ch
+     *            A character to convert to an integer digit
+     * @param index
+     *            The index of the character in the source
+     * @return An integer
+     * @throws DecoderException
+     *             Thrown if ch is an illegal hex character
+     */
+    protected static int toDigit(char ch, int index) throws Exception {
+        int digit = Character.digit(ch, 16);
+        if (digit == -1) {
+            throw new Exception("Illegal hexadecimal charcter " + ch + " at index " + index);
+        }
+        return digit;
+    }
+
+    private final String charsetName;
+
+    /**
+     * Creates a new codec with the default charset name {@link #DEFAULT_CHARSET_NAME}
+     */
+    public _Hex() {
+        // use default encoding
+        this.charsetName = DEFAULT_CHARSET_NAME;
+    }
+
+    /**
+     * Creates a new codec with the given charset name.
+     * 
+     * @param csName
+     *            the charset name.
+     * @since 1.4
+     */
+    public _Hex(String csName) {
+        this.charsetName = csName;
+    }
+
+    /**
+     * Converts an array of character bytes representing hexadecimal values into an array
of bytes of those same values.
+     * The returned array will be half the length of the passed array, as it takes two characters
to represent any given
+     * byte. An exception is thrown if the passed char array has an odd number of elements.
+     * 
+     * @param array
+     *            An array of character bytes containing hexadecimal digits
+     * @return A byte array containing binary data decoded from the supplied byte array (representing
characters).
+     * @throws DecoderException
+     *             Thrown if an odd number of characters is supplied to this function
+     * @see #decodeHex(char[])
+     */
+    public byte[] decode(byte[] array) throws Exception {
+        try {
+            return decodeHex(new String(array, getCharsetName()).toCharArray());
+        } catch (UnsupportedEncodingException e) {
+            throw new Exception(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Converts a String or an array of character bytes representing hexadecimal values into
an array of bytes of those
+     * same values. The returned array will be half the length of the passed String or array,
as it takes two characters
+     * to represent any given byte. An exception is thrown if the passed char array has an
odd number of elements.
+     * 
+     * @param object
+     *            A String or, an array of character bytes containing hexadecimal digits
+     * @return A byte array containing binary data decoded from the supplied byte array (representing
characters).
+     * @throws DecoderException
+     *             Thrown if an odd number of characters is supplied to this function or
the object is not a String or
+     *             char[]
+     * @see #decodeHex(char[])
+     */
+    public Object decode(Object object) throws Exception {
+        try {
+            char[] charArray = object instanceof String ? ((String) object).toCharArray()
: (char[]) object;
+            return decodeHex(charArray);
+        } catch (ClassCastException e) {
+            throw new Exception(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Converts an array of bytes into an array of bytes for the characters representing
the hexadecimal values of each
+     * byte in order. The returned array will be double the length of the passed array, as
it takes two characters to
+     * represent any given byte.
+     * <p>
+     * The conversion from hexadecimal characters to the returned bytes is performed with
the charset named by
+     * {@link #getCharsetName()}.
+     * </p>
+     * 
+     * @param array
+     *            a byte[] to convert to Hex characters
+     * @return A byte[] containing the bytes of the hexadecimal characters
+     * @throws IllegalStateException
+     *             if the charsetName is invalid. This API throws {@link IllegalStateException}
instead of
+     *             {@link UnsupportedEncodingException} for backward compatibility.
+     * @see #encodeHex(byte[])
+     */
+    public byte[] encode(byte[] array) {
+        return getBytesUnchecked(encodeHexString(array), getCharsetName());
+    }
+    
+    private static byte[] getBytesUnchecked(String string, String charsetName)
+    {
+        if (string == null)
+        {
+            return null;
+        }
+        try
+        {
+            return string.getBytes(charsetName);
+        }
+        catch (UnsupportedEncodingException e)
+        {
+            throw new IllegalStateException(charsetName, e);
+        }
+    }
+
+
+    /**
+     * Converts a String or an array of bytes into an array of characters representing the
hexadecimal values of each
+     * byte in order. The returned array will be double the length of the passed String or
array, as it takes two
+     * characters to represent any given byte.
+     * <p>
+     * The conversion from hexadecimal characters to bytes to be encoded to performed with
the charset named by
+     * {@link #getCharsetName()}.
+     * </p>
+     * 
+     * @param object
+     *            a String, or byte[] to convert to Hex characters
+     * @return A char[] containing hexadecimal characters
+     * @throws EncoderException
+     *             Thrown if the given object is not a String or byte[]
+     * @see #encodeHex(byte[])
+     */
+    public Object encode(Object object) throws Exception {
+        try {
+            byte[] byteArray = object instanceof String ? ((String) object).getBytes(getCharsetName())
: (byte[]) object;
+            return encodeHex(byteArray);
+        } catch (ClassCastException e) {
+            throw new Exception(e.getMessage(), e);
+        } catch (UnsupportedEncodingException e) {
+            throw new Exception(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Gets the charset name.
+     * 
+     * @return the charset name.
+     * @since 1.4
+     */
+    public String getCharsetName() {
+        return this.charsetName;
+    }
+
+    /**
+     * Returns a string representation of the object, which includes the charset name.
+     * 
+     * @return a string representation of the object.
+     */
+    public String toString() {
+        return super.toString() + "[charsetName=" + this.charsetName + "]";
+    }
+}



Mime
View raw message