package com.mindprod.example;

import java.applet.Applet;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Example use of ability of Applet to look at cookies with java.net.CookieHandler
 * <p/>
 * composed with IntelliJ IDEA
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0
 */
public final class TestCookie extends Applet
    {
// -------------------------- PUBLIC INSTANCE  METHODS --------------------------
    /**
     * standard applet Init
     */
    public void init()
        {
        System.out.println( "init called" );

        // fetch cookies from the Browser's cache of cookies
        // Requires signed Applet permission
        CookieHandler ch = CookieHandler.getDefault();
        if ( ch == null )
            {
            System.err.println( "no cookie handler" );
            }
        URI uri = null;
        try
            {
            uri = new URI( "http://mindprod.com" );
            }
        catch ( URISyntaxException e )
            {
            System.err.println( e.getMessage() );
            }

        Map<String, List<String>> requestHeaders =
                new HashMap<String, List<String>>( 200 );

        // I'm not sure what you are supposed to put in the requestHeaders
        // resquestHeaders.put( String, ArrayList<String>) of some sort.

        Map<String, List<String>> results = null;
        try
            {
            // returns an immutable map of cookies
            results = ch.get( uri, requestHeaders );
            }
        catch ( IOException e )
            {
            System.err.println( e.getMessage() );
            }
        // display the results, keys Cookie1 and Cookie2
        for ( String key : results.keySet() )
            {
            System.out.println( key );
            for ( String item : results.get( key ) )
                {
                System.out.println( "   " + item );
                }
            }
        }
    }