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    import org.picocontainer.MutablePicoContainer;
013    
014    import javax.servlet.http.HttpServletRequest;
015    import java.io.Serializable;
016    
017    /**
018     * Use this to make a request level component that pulls an string from a named parameter (GET or POST)
019     * of the request.  If a parameter of the supplied name is not available for the current
020     * request path, then an exception will be thrown.
021     */
022    public class StringFromRequest extends ProviderAdapter implements Serializable {
023        private final String paramName;
024    
025        public StringFromRequest(String paramName) {
026            this.paramName = paramName;
027        }
028    
029        @Override
030        public Class getComponentImplementation() {
031            return String.class;
032        }
033    
034        @Override
035        public Object getComponentKey() {
036            return paramName;
037        }
038    
039        public Object provide(HttpServletRequest req) {
040            String parameter = req.getParameter(paramName);
041            if (parameter == null) {
042                throw new ParameterNotFound(paramName);
043            }
044            return parameter;
045        }
046    
047        /**
048         * Add a number of StringFromRequest adapters to a container.
049         * @param toContainer the container to add to
050         * @param names the list of names to make adapters from
051         */
052        public static void addStringRequestParameters(MutablePicoContainer toContainer, String... names) {
053            for (String name : names) {
054                toContainer.addAdapter(new StringFromRequest(name));
055            }
056        }
057    
058        @SuppressWarnings("serial")
059        public static class ParameterNotFound extends PicoContainerWebException {
060            private ParameterNotFound(String name) {
061                super(name + " not found in request parameters");
062            }
063        }
064    
065    
066    }