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