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    package org.picocontainer.web;
009    
010    import org.picocontainer.MutablePicoContainer;
011    
012    import javax.servlet.http.HttpServletRequest;
013    
014    /**
015     * Use this to make a request level component that pulls an integer from a named parameter (GET or POST)
016     * of the request.  If a parameter of the supplied name is not available for the current
017     * request path, then an exception will be thrown. An exception will also be thrown, if the number format is bad.
018     */
019    public class IntFromRequest extends StringFromRequest {
020    
021        public IntFromRequest(String paramName) {
022            super(paramName);
023        }
024    
025        @Override
026        public Class getComponentImplementation() {
027            return Integer.class;
028        }
029    
030        @Override
031        public Object provide(HttpServletRequest req) {
032            String num = (String) super.provide(req);
033            try {
034                return Integer.parseInt(num);
035            } catch (NumberFormatException e) {
036                throw new RuntimeException("'" + num + "' cannot be converted to an integer");
037            }
038        }
039    
040        /**
041         * Add a number of IntFromRequest adapters to a container.
042         * @param toContainer the container to add to
043         * @param names the list of names to make adapters from
044         */
045        public static void addIntegerRequestParameters(MutablePicoContainer toContainer, String... names) {
046            for (String name : names) {
047                toContainer.addAdapter(new IntFromRequest(name));
048            }
049        }
050    
051    
052    }