001    /*******************************************************************************
002     * Copyright (c) PicoContainer Organization. All rights reserved.
003     * ---------------------------------------------------------------------------
004     * The software in this package is published under the terms of the BSD style
005     * license a copy of which has been included with this distribution in the
006     * LICENSE.txt file.
007     ******************************************************************************/
008    
009    package org.picocontainer.web;
010    
011    import org.picocontainer.injectors.ProviderAdapter;
012    
013    import javax.servlet.http.HttpServletRequest;
014    import javax.servlet.http.Cookie;
015    import java.io.Serializable;
016    
017    /**
018     * Use this to make a request level component that pulls information from cookie held on
019     * the browser.  If a cookie of the supplied name is not available for the current
020     * request path, then a NotFound exception will be thrown.
021     */
022    public class StringFromCookie extends ProviderAdapter implements Serializable {
023    
024        private final String name;
025    
026        public StringFromCookie(String name) {
027            this.name = name;
028        }
029    
030        @Override
031        public Class getComponentImplementation() {
032            return String.class;
033        }
034    
035        @Override
036        public Object getComponentKey() {
037            return name;
038        }
039    
040        public String provide(HttpServletRequest req) {
041            Cookie[] cookies = req.getCookies();
042            if (cookies != null) {
043                for (Cookie cookie : cookies) {
044                    if (cookie.getName().equals(name)) {
045                        return cookie.getValue();
046                    }
047                }
048            }
049            throw new CookieNotFound(name);
050        }
051    
052        public static class CookieNotFound extends PicoContainerWebException {
053            private CookieNotFound(String name) {
054                super("'" + name + "' not found in cookies");
055            }
056        }
057    
058    }