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    
016    /**
017     * Use this to make a request level component that pulls information from cookie held on
018     * the browser.  If a cookie of the suplied name is not available for the current
019     * request path, then a NotFound exception will be thrown.
020     */
021    public class StringFromCookie extends ProviderAdapter {
022    
023        private final String name;
024    
025        public StringFromCookie(String name) {
026            this.name = name;
027        }
028    
029        @Override
030        public Class getComponentImplementation() {
031            return String.class;
032        }
033    
034        @Override
035        public Object getComponentKey() {
036            return name;
037        }
038    
039        public String provide(HttpServletRequest req) {
040            Cookie[] cookies = req.getCookies();
041            for (Cookie cookie : cookies) {
042                if (cookie.getName().equals(name)) {
043                    return cookie.getValue();
044                }
045            }
046            throw new CookieNotFound(name);
047        }
048    
049        public static class CookieNotFound extends PicoContainerWebException {
050            private CookieNotFound(String name) {
051                super("'" + name + "' not found in cookies");
052            }
053        }
054    
055    }