/*
  Copyright 2012 - 2013 Jerome Leleu

   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 org.pac4j.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;

import org.junit.Assert;
import org.pac4j.core.exception.TechnicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.ObjectBuffer;
import com.esotericsoftware.kryo.SerializationException;
import com.gargoylesoftware.htmlunit.WebClient;

/**
 * This class is an helper fo tests : to get a basic web client, parameters from an url, a formatted date or to serialize and deserialize
 * objects.
 * 
 * @author Jerome Leleu
 * @since 1.0.0
 */
public final class TestsHelper {
    
    private static final Logger logger = LoggerFactory.getLogger(TestsHelper.class);
    
    private static final int BUFFERS_INITIAL_CAPACITY = 5 * 1024;
    
    private static final int BUFFERS_MAXIMAL_CAPACITY = 1024 * 20;
    
    public static WebClient newWebClient(final boolean isJavascriptEnabled) {
        final WebClient webClient = new WebClient();
        webClient.setRedirectEnabled(true);
        webClient.setCssEnabled(false);
        webClient.setJavaScriptEnabled(isJavascriptEnabled);
        return webClient;
    }
    
    public static Map<String, String> getParametersFromUrl(String url) {
        final Map<String, String> parameters = new HashMap<String, String>();
        final int pos = url.indexOf("?");
        if (pos > 0) {
            url = url.substring(pos + 1);
        }
        final StringTokenizer st = new StringTokenizer(url, "&");
        while (st.hasMoreTokens()) {
            final String keyValue = st.nextToken();
            final String[] parts = keyValue.split("=");
            if (parts != null && parts.length >= 2) {
                try {
                    parameters.put(parts[0], URLDecoder.decode(parts[1], "UTF-8"));
                } catch (final UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return parameters;
    }
    
    public static String getFormattedDate(final long l, final String format, final Locale locale) {
        final Date d = new Date(l);
        SimpleDateFormat simpleDateFormat;
        if (locale == null) {
            simpleDateFormat = new SimpleDateFormat(format);
        } else {
            simpleDateFormat = new SimpleDateFormat(format, locale);
        }
        return simpleDateFormat.format(d);
    }
    
    public static byte[] serialize(final Object o) {
        byte[] bytes = null;
        try {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final ObjectOutputStream oos = new ObjectOutputStream(baos);
            try {
                oos.writeObject(o);
                oos.flush();
                bytes = baos.toByteArray();
            } finally {
                try {
                    oos.close();
                } finally {
                    baos.close();
                }
            }
        } catch (final IOException e) {
            logger.warn("cannot serialize object", e);
        }
        return bytes;
    }
    
    public static Object unserialize(final byte[] bytes) {
        Object o = null;
        try {
            final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            final ObjectInputStream ois = new ObjectInputStream(bais);
            try {
                o = ois.readObject();
            } finally {
                try {
                    ois.close();
                } finally {
                    bais.close();
                }
            }
        } catch (final IOException e) {
            logger.warn("cannot deserialize object", e);
        } catch (final ClassNotFoundException e) {
            logger.warn("cannot deserialize object", e);
        }
        return o;
    }
    
    public static byte[] serializeKryo(final Kryo kryo, final Object object) {
        final ObjectBuffer buffer = new ObjectBuffer(kryo, BUFFERS_INITIAL_CAPACITY, BUFFERS_MAXIMAL_CAPACITY);
        try {
            return buffer.writeClassAndObject(object);
        } catch (final SerializationException e) {
            logger.error("serialize exception with Kryo on object : {}", object, e);
        }
        return null;
    }
    
    public static Object unserializeKryo(final Kryo kryo, final byte[] bytes) {
        try {
            final ObjectBuffer buffer = new ObjectBuffer(kryo, BUFFERS_INITIAL_CAPACITY, BUFFERS_MAXIMAL_CAPACITY);
            return buffer.readClassAndObject(bytes);
        } catch (final SerializationException e) {
            logger.error("unserialize exception with Kryo", e);
        }
        return null;
    }
    
    public static void initShouldFail(final InitializableObject obj, final String message) {
        try {
            obj.init();
            Assert.fail("init should fail");
        } catch (final TechnicalException e) {
            Assert.assertEquals(message, e.getMessage());
        }
    }
}

@@ -2228,75 +2228,99 @@
     
-f
 in
-al Map%3CString, String%3E parameter
+t pos = url.indexOf(%22?%22);%0A        if (po
 s 
+%3E
 = 
-new HashMap%3CString, String%3E(
+0) %7B%0A            url = url.substring(pos + 1
 );%0A 
@@ -2326,25 +2326,25 @@
         
-final int
+%7D%0A       
  pos = u
@@ -2347,33 +2347,33 @@
  = url.indexOf(%22
-?
+#
 %22);%0A        if (
@@ -2377,16 +2377,17 @@
 f (pos %3E
+=
  0) %7B%0A  
@@ -2408,39 +2408,38 @@
 = url.substring(
+0, 
 pos
- + 1
 );%0A        %7D%0A   
@@ -2427,32 +2427,110 @@
 pos);%0A        %7D%0A
+        final Map%3CString, String%3E parameters = new HashMap%3CString, String%3E();%0A
         final St

update tests behaviour : remove # at the end of the url