CPD Results

The following document contains the results of PMD's CPD 6.55.0.

Duplications

File Project Line
org/apache/commons/chain/web/jakarta/ChainInit.java Commons Chain :: Web :: Jakarta 88
org/apache/commons/chain/web/javax/ChainInit.java Commons Chain :: Web :: Javax 88
final class ChainInit {

    /**
     * The name of the context init parameter containing the name of the
     * servlet context attribute under which our resulting {@link Catalog}
     * will be stored.
     */
    static final String CONFIG_ATTR =
        "org.apache.commons.chain.CONFIG_ATTR";

    /**
     * The name of the context init parameter containing a comma-delimited
     * list of class loader resources to be scanned.
     */
    static final String CONFIG_CLASS_RESOURCE =
        "org.apache.commons.chain.CONFIG_CLASS_RESOURCE";

    /**
     * The name of the context init parameter containing a comma-delimited
     * list of web application resources to be scanned.
     */
    static final String CONFIG_WEB_RESOURCE =
        "org.apache.commons.chain.CONFIG_WEB_RESOURCE";

    /**
     * The name of the context init parameter containing the fully
     * qualified class name of the {@code RuleSet} implementation
     * for configuring our {@link ConfigParser}.
     */
    static final String RULE_SET =
        "org.apache.commons.chain.RULE_SET";

    /**
     * Remove the configured {@link Catalog} from the servlet context
     * attributes for this web application.
     *
     * @param context the servlet-context
     * @param attr the value of the {@code CONFIG_ATTR}
     */
    static void destroy(ServletContext context, String attr) {
        if (attr != null) {
            context.removeAttribute(attr);
        }
        CatalogFactory.clear();
    }

    /**
     * Private constructor.
     */
    private ChainInit() {
    }

    /**
     * Scan the required chain configuration resources, assemble the
     * configured chains into a {@link Catalog}, and expose it as a
     * servlet context attribute under the specified key.
     *
     * @param context the servlet-context
     * @param attr the value of the {@code CONFIG_ATTR}
     * @param logger to use for logging
     * @param parseJarResources {@code true} to parse resources in jar-files
     */
    @SuppressWarnings("deprecation")
    static void initialize(ServletContext context, String attr, Logger logger, boolean parseJarResources) throws ServletException {
        String classResources = context.getInitParameter(CONFIG_CLASS_RESOURCE);
        String ruleSet = context.getInitParameter(RULE_SET);
        String webResources = context.getInitParameter(CONFIG_WEB_RESOURCE);

        // Retrieve or create the Catalog instance we may be updating
        Catalog<?> catalog = null;
        if (attr != null) {
            catalog = (Catalog<?>) context.getAttribute(attr);
            if (catalog == null) {
                catalog = new CatalogBase<>();
            }
        }

        // Construct the configuration resource parser we will use
        ConfigParser parser = new ConfigParser();
        if (ruleSet != null) {
            try {
                ClassLoader loader =
                    Thread.currentThread().getContextClassLoader();
                if (loader == null) {
                    loader = ChainInit.class.getClassLoader();
                }
                Class<? extends RuleSet> clazz = loader
                        .loadClass(ruleSet)
                        .asSubclass(RuleSet.class);
                parser.setRuleSet(clazz.getDeclaredConstructor().newInstance());
            } catch (Exception e) {
                throw new ServletException("Exception initalizing RuleSet '"
                                           + ruleSet + "' instance ", e);
            }
        }

        // Parse the resources specified in our init parameters (if any)
        final CheckedConsumer<URL, Exception> parse;
        if (attr == null) {
            parse = parser::parse;
        } else {
            final Catalog<?> cat = catalog;
            parse = url -> parser.parse(cat, url);
        }
        if (parseJarResources) {
            parseJarResources(context, parse, logger);
        }
        ChainResources.parseClassResources(classResources, parse);
        ChainResources.parseWebResources(context, webResources, parse);

        // Expose the completed catalog (if requested)
        if (attr != null) {
            context.setAttribute(attr, catalog);
        }
    }

    // --------------------------------------------------------- Private Methods

    /**
     * Parse resources found in JAR files in the {@code /WEB-INF/lib}
     * subdirectory (if any).
     *
     * @param <E> the type of the exception from parse-function
     * @param context {@code ServletContext} for this web application
     * @param parse parse-function to parse the XML document
     * @param logger to use for logging
     */
    private static <E extends Exception> void parseJarResources(ServletContext context,
                CheckedConsumer<URL, E> parse, Logger logger) {

        Set<String> jars = context.getResourcePaths("/WEB-INF/lib");
        if (jars == null) {
            jars = Collections.emptySet();
        }
        String path = null;
        Iterator<String> paths = jars.iterator();
        while (paths.hasNext()) {

            path = paths.next();
            if (!path.endsWith(".jar")) {
                continue;
            }
            URL resourceURL = null;
            try {
                URL jarURL = context.getResource(path);
                path = jarURL.toExternalForm();

                resourceURL = new URL("jar:"
                                      + translate(path)
                                      + "!/META-INF/chain-config.xml");
                path = resourceURL.toExternalForm();

                InputStream is = null;
                try {
                    is = resourceURL.openStream();
                } catch (Exception e) {
                    // means there is no such resource
                    logger.atTrace().setMessage("OpenStream: {}").addArgument(resourceURL).setCause(e).log();
                }
                if (is == null) {
                    logger.debug("Not Found: {}", resourceURL);
                    continue;
                } else {
                    is.close();
                }
                logger.debug("Parsing: {}", resourceURL);
                parse.accept(resourceURL);
            } catch (Exception e) {
                throw new RuntimeException("Exception parsing chain config resource '"
                     + path + "': " + e.getMessage());
            }
        }
    }

    /**
     * Translate space character into {@code %20} to avoid problems
     * with paths that contain spaces on some JVMs.
     *
     * @param value Value to translate
     *
     * @return the translated value
     */
    private static String translate(String value) {
        while (true) {
            int index = value.indexOf(' ');
            if (index < 0) {
                break;
            }
            value = value.substring(0, index) + "%20" + value.substring(index + 1);
        }
        return value;
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/servlet/ServletWebContext.java Commons Chain :: Web :: Jakarta :: Servlet 36
org/apache/commons/chain/web/javax/servlet/ServletWebContext.java Commons Chain :: Web :: Javax :: Servlet 36
public class ServletWebContext extends WebContext {
    private static final long serialVersionUID = 5302874006663111922L;

    // ------------------------------------------------------ Instance Variables

    /**
     * The lazily instantiated {@code Map} of application scope
     * attributes.
     */
    private transient Map<String, Object> applicationScope = null;

    /**
     * The {@code ServletContext} for this web application.
     */
    private transient ServletContext context = null;

    /**
     * The lazily instantiated {@code Map} of header name-value
     * combinations (immutable).
     */
    private transient Map<String, String> header = null;

    /**
     * The lazily instantiated {@code Map} of header name-values
     * combinations (immutable).
     */
    private transient Map<String, String[]> headerValues = null;

    /**
     * The lazily instantiated {@code Map} of context initialization
     * parameters.
     */
    private transient Map<String, String> initParam = null;

    /**
     * The lazily instantiated {@code Map} of cookies.
     */
    private transient Map<String, Cookie> cookieValues = null;

    /**
     * The lazily instantiated {@code Map} of request
     * parameter name-value.
     */
    private transient Map<String, String> param = null;

    /**
     * The lazily instantiated {@code Map} of request
     * parameter name-values.
     */
    private transient Map<String, String[]> paramValues = null;

    /**
     * The {@code HttpServletRequest} for this request.
     */
    private transient HttpServletRequest request = null;

    /**
     * The lazily instantiated {@code Map} of request scope
     * attributes.
     */
    private transient Map<String, Object> requestScope = null;

    /**
     * The {@code HttpServletResponse} for this request.
     */
    private transient HttpServletResponse response = null;

    /**
     * The lazily instantiated {@code Map} of session scope
     * attributes.
     */
    private transient Map<String, Object> sessionScope = null;

    // ------------------------------------------------------------ Constructors

    /**
     * Construct an uninitialized {@link ServletWebContext} instance.
     */
    public ServletWebContext() {
    }

    /**
     * Construct a {@link ServletWebContext} instance that is initialized
     * with the specified Servlet API objects.
     *
     * @param context The {@code ServletContext} for this web application
     * @param request The {@code HttpServletRequest} for this request
     * @param response The {@code HttpServletResponse} for this request
     */
    public ServletWebContext(ServletContext context,
                             HttpServletRequest request,
                             HttpServletResponse response) {

        initialize(context, request, response);
    }

    // ---------------------------------------------------------- Public Methods

    /**
     * Return the {@link ServletContext} for this context.
     *
     * @return The {@code ServletContext} for this context.
     */
    public ServletContext getContext() {
        return this.context;
    }

    /**
     * Return the {@link HttpServletRequest} for this context.
     *
     * @return The {@code HttpServletRequest} for this context.
     */
    public HttpServletRequest getRequest() {
        return this.request;
    }

    /**
     * Return the {@link HttpServletResponse} for this context.
     *
     * @return The {@code HttpServletResponse} for this context.
     */
    public HttpServletResponse getResponse() {
        return this.response;
    }

    /**
     * Initialize (or reinitialize) this {@link ServletWebContext} instance
     * for the specified Servlet API objects.
     *
     * @param context The {@code ServletContext} for this web application
     * @param request The {@code HttpServletRequest} for this request
     * @param response The {@code HttpServletResponse} for this request
     */
    public void initialize(ServletContext context,
                           HttpServletRequest request,
                           HttpServletResponse response) {

        // Save the specified Servlet API object references
        this.context = context;
        this.request = request;
        this.response = response;

        // Perform other setup as needed
    }

    /**
     * Release references to allocated resources acquired in
     * {@code initialize()} of via subsequent processing. After this
     * method is called, subsequent calls to any other method than
     * {@code initialize()} will return undefined results.
     */
    public void release() {
        // Release references to allocated collections
        applicationScope = null;
        header = null;
        headerValues = null;
        initParam = null;
        param = null;
        paramValues = null;
        cookieValues = null;
        requestScope = null;
        sessionScope = null;

        // Release references to Servlet API objects
        context = null;
        request = null;
        response = null;
    }

    // ------------------------------------------------------ WebContext Methods

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Application scope Map.
     */
    @Override
    public Map<String, Object> getApplicationScope() {
        if (applicationScope == null && context != null) {
            applicationScope = new ServletApplicationScopeMap(context);
        }
        return applicationScope;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Header values Map.
     */
    @Override
    public Map<String, String> getHeader() {
        if (header == null && request != null) {
            header = new ServletHeaderMap(request);
        }
        return header;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Header values Map.
     */
    @Override
    public Map<String, String[]> getHeaderValues() {
        if (headerValues == null && request != null) {
            headerValues = new ServletHeaderValuesMap(request);
        }
        return headerValues;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Initialization parameter Map.
     */
    @Override
    public Map<String, String> getInitParam() {
        if (initParam == null && context != null) {
            initParam = new ServletInitParamMap(context);
        }
        return initParam;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Request parameter Map.
     */
    @Override
    public Map<String, String> getParam() {
        if (param == null && request != null) {
            param = new ServletParamMap(request);
        }
        return param;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Request parameter Map.
     */
    @Override
    public Map<String, String[]> getParamValues() {
        if (paramValues == null && request != null) {
            paramValues = new ServletParamValuesMap(request);
        }
        return paramValues;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Map of Cookies.
     * @since Chain 1.1
     */
    @Override
    public Map<String, Cookie> getCookies() {
        if (cookieValues == null && request != null) {
            cookieValues = new ServletCookieMap(request);
        }
        return cookieValues;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Request scope Map.
     */
    @Override
    public Map<String, Object> getRequestScope() {
        if (requestScope == null && request != null) {
            requestScope = new ServletRequestScopeMap(request);
        }
        return requestScope;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Session scope Map.
     */
    @Override
    public Map<String, Object> getSessionScope() {
        if (sessionScope == null && request != null) {
            sessionScope = new ServletSessionScopeMap(request);
        }
        return sessionScope;
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/internal/CookieMap.java Commons Chain :: Web :: Jakarta 41
org/apache/commons/chain/web/javax/internal/CookieMap.java Commons Chain :: Web :: Javax 41
public class CookieMap<P> extends ParameterMap<P, Cookie> {

    /**
     * Supplier to return the {@link Cookie}-Array in this object.
     */
    private final Supplier<Cookie[]> cookiesSupplier;

    /**
     * The constructor for the {@code Map} for cookies.
     *
     * @param request         the request with the cookies
     * @param cookiesSupplier Supplier to return the {@link Cookie}-Array in this
     *                        object
     */
    public CookieMap(final P request, final Supplier<Cookie[]> cookiesSupplier) {
        super(request, null, null);
        this.cookiesSupplier = cookiesSupplier;
    }

    /**
     * Returns {@code true} if this cookie-map contains a mapping
     * for the specified cookie-name.
     *
     * @param key The key whose presence in this cookie-map is to
     *            be tested
     *
     * @return {@code true} if this cookie-map contains a mapping
     *         for the specified cookie-name.
     */
    @Override
    public boolean containsKey(Object key) {
        return get(key) != null;
    }

    /**
     * Returns {@code true} if this cookie-map maps one or more keys
     * to the specified cookie.
     *
     * @param value cookie whose presence in this cookie-map is to be
     *        tested
     *
     * @return {@code true} if this cookie-map maps one or more keys
     *         to the specified cookie
     */
    @Override
    public boolean containsValue(Object value) {
        for (Cookie cookie : values()) {
            if (cookie.equals(value)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns a {@link Set} view of the mappings contained in this
     * cookie-map. The set is not backed by the cookie-map, so
     * changes to the cookie-map are not reflected in the set,
     * and vice-versa.
     *
     * @return a set view of the mappings contained in this cookie-map
     */
    @Override
    public Set<Map.Entry<String, Cookie>> entrySet() {
        final Set<Map.Entry<String, Cookie>> set = new HashSet<>();
        for (Cookie cookie : values()) {
            set.add(new MapEntry<>(cookie.getName(), cookie, false));
        }
        return set;
    }

    /**
     * Returns the cookie to which the specified cookie-name is mapped,
     * or {@code null} if this cookie-map contains no mapping for the
     * cookie-name.
     *
     * @param key the cookie-name whose associated value is to be
     *            returned
     *
     * @return the value to which the specified key is mapped, or
     *         {@code null} if this cookie-map contains no mapping for
     *         the cookie-name
     *
     * @see #put(Object, Object)
     */
    @Override
    public Cookie get(Object key) {
        final Collection<Cookie> cookies = values();
        if (!cookies.isEmpty()) {
            final String skey = key(key);
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(skey)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * Returns {@code true} if this cookie-map contains no cookies.
     *
     * @return {@code true} if this cookie-map contains no cookies
     */
    @Override
    public boolean isEmpty() {
        final Cookie[] cookies = cookiesSupplier.get();
        return cookies == null || cookies.length == 0;
    }

    /**
     * Returns a {@link Set} view of the cookies contained in this
     * cookie-map. The set is not backed by the cookie-map, so
     * changes to the cookie-map are not reflected in the set, and
     * vice-versa.
     *
     * @return a set view of the cookies contained in this cookie-map
     */
    @Override
    public Set<String> keySet() {
        final Collection<Cookie> cookies = values();
        final Set<String> set = new HashSet<String>(Math.max((int) (cookies.size() / .75f) + 1, 16));
        for (Cookie cookie : cookies) {
            set.add(cookie.getName());
        }
        return set;
    }

    /**
     * Returns the number of cookies in this cookie-map.
     *
     * @return the number of cookies in this cookie-map
     */
    @Override
    public int size() {
        final Cookie[] cookies = cookiesSupplier.get();
        return cookies == null ? 0 : cookies.length;
    }

    /**
     * Returns a {@link Collection} view of the cookies contained in
     * this cookie-map. The collection is not backed by the
     * cookie-map, so changes to the cookie-map are not
     * reflected in the collection, and vice-versa.
     *
     * @return a view of the cookies contained in this cookie-map
     */
    @Override
    public Collection<Cookie> values() {
        final Cookie[] cookies = cookiesSupplier.get();
        return cookies == null ? Collections.emptyList() : Arrays.asList(cookies);
    }

    /**
     * Returns the hash code value for this cookie-map. The
     * hash code of a cookie-map is defined to be the sum of
     * the hash codes of each entry in the cookie-map's
     * {@code entrySet()} view. This ensures that {@code m1.equals(m2)}
     * implies that {@code m1.hashCode()==m2.hashCode()} for any two
     * parameter-maps {@code m1} and {@code m2}, as required by the
     * general contract of {@link Object#hashCode}.
     *
     * @implSpec
     * This implementation calls the {@code hashCode()} from the
     * parameter-map.
     *
     * @return the hash code value for this cookie-map
     */
    @Override
    public int hashCode() {
        return super.hashCode();
    }

    /**
     * Compares the specified object with this cookie-map for equality.
     * Returns {@code true} if the given object is also a cookie-map
     * and the two cookie-maps represent the same mappings. More formally,
     * two cookie-maps {@code m1} and {@code m2} represent the same
     * mappings if {@code m1.entrySet().equals(m2.entrySet())}.
     *
     * @param obj object to be compared for equality with this
     *        cookie-map
     *
     * @return {@code true} if the specified object is equal to this
     *         cookie-map
     */
    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/ChainResources.java Commons Chain :: Web :: Jakarta 39
org/apache/commons/chain/web/javax/ChainResources.java Commons Chain :: Web :: Javax 39
final class ChainResources {

    /**
     * This class uses a private constructor because it is a utility class.
     */
    private ChainResources() {
    }

    // ---------------------------------------------------------- Static Methods

    /**
     * Parse the specified class loader resources.
     *
     * @param <E> the type of the exception from parse-function
     * @param resources Comma-delimited list of resources (or {@code null})
     * @param parse parse-function to parse the XML document
     */
    static <E extends Exception> void parseClassResources(String resources,
                                    CheckedConsumer<URL, E> parse) {

        ClassLoader loader =
            Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = ChainResources.class.getClassLoader();
        }
        parseResources(loader::getResource, resources, parse);
    }

    /**
     * Parse the specified web application resources.
     *
     * @param <E> the type of the exception from parse-function
     * @param context {@code ServletContext} for this web application
     * @param resources Comma-delimited list of resources (or {@code null})
     * @param parse parse-function to parse the XML document
     */
    static <E extends Exception> void parseWebResources(ServletContext context,
                                  String resources,
                                  CheckedConsumer<URL, E> parse) {

        parseResources(context::getResource, resources, parse);
    }

    /**
     * Parse the specified resources with a resource-get-function.
     *
     * @param <ER> the type of the exception from resource-function
     * @param <EP> the type of the exception from parse-function
     * @param resourceFunction function to get the {@link URL} from a path
     * @param resources Comma-delimited list of resources (or {@code null})
     * @param parse parse-function to parse the XML document
     */
    private static <ER extends Exception, EP extends Exception> void parseResources(
            CheckedFunction<String, URL, ER> resourceFunction, String resources,
            CheckedConsumer<URL, EP> parse) {

        if (resources == null) {
            return;
        }
        Logger logger = LoggerFactory.getLogger(ChainResources.class);
        String[] paths = getResourcePaths(resources);
        String path = null;
        try {
            for (String path2 : paths) {
                path = path2;
                URL url = resourceFunction.apply(path);
                if (url == null) {
                    throw new IllegalStateException("Missing chain config resource '" + path + "'");
                }
                logger.debug("Loading chain config resource '{}'", path);
                parse.accept(url);
            }
        } catch (Exception e) {
            throw new RuntimeException("Exception parsing chain config resource '" + path + "': "
                 + e.getMessage());
        }
    }

    /**
     * Parse the resource string into an array of paths. Empty entries will
     * be skipped. (That is, all entries in the array are non-empty paths.)
     *
     * @param resources A comma-delimited list of resource paths (or
     *        {@code null}).
     *
     * @return An array of non-empty paths. The array itself may be empty.
     *
     * @since Chain 1.1
     */
    static String[] getResourcePaths(String resources) {
        final List<String> paths = new ArrayList<>();

        if (resources != null) {
            String path;
            int comma;

            int lastComma = 0;
            while ((comma = resources.indexOf(',', lastComma)) >= 0) {
                path = resources.substring(lastComma, comma).trim();
                if (path.length() > 0) {
                    paths.add(path);
                }
                lastComma = comma + 1;
            }
            path = resources.substring(lastComma).trim();
            if (path.length() > 0) {
                paths.add(path);
            }
        }

        return paths.toArray(new String[0]);
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/faces/FacesWebContext.java Commons Chain :: Web :: Jakarta :: Faces 37
org/apache/commons/chain/web/javax/faces/FacesWebContext.java Commons Chain :: Web :: Javax :: Faces 37
public class FacesWebContext extends WebContext {
    private static final long serialVersionUID = -1429681424077509130L;

    // ------------------------------------------------------ Instance Variables

    /**
     * The {@code FacesContext} instance for the request represented
     * by this {@link WebContext}.
     */
    private transient FacesContext context = null;

    /**
     * The lazily instantiated {@code Map} of cookies.
     */
    private transient Map<String, Cookie> cookieValues = null;

    // ------------------------------------------------------------ Constructors

    /**
     * Construct an uninitialized {@link FacesWebContext} instance.
     */
    public FacesWebContext() {
    }

    /**
     * Construct a {@link FacesWebContext} instance that is initialized
     * with the specified JavaServer Faces API objects.
     *
     * @param context The {@code FacesContext} for this request
     */
    public FacesWebContext(FacesContext context) {
        initialize(context);
    }
    // ---------------------------------------------------------- Public Methods

    /**
     * Return the {@code FacesContext} instance for the request
     * associated with this {@link FacesWebContext}.
     *
     * @return The {@code FacesContext} for this request
     */
    public FacesContext getContext() {
        return this.context;
    }

    /**
     * Initialize (or reinitialize) this {@link FacesWebContext} instance
     * for the specified JavaServer Faces API objects.
     *
     * @param context The {@code FacesContext} for this request
     */
    public void initialize(FacesContext context) {
        this.context = context;
    }

    /**
     * Release references to allocated resources acquired in
     * {@code initialize()} of via subsequent processing. After this
     * method is called, subsequent calls to any other method than
     * {@code initialize()} will return undefined results.
     */
    public void release() {
        context = null;
        cookieValues = null;
    }

    // ------------------------------------------------------ WebContext Methods

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Application scope Map.
     */
    @Override
    public Map<String, Object> getApplicationScope() {
        return context.getExternalContext().getApplicationMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Header values Map.
     */
    @Override
    public Map<String, String> getHeader() {
        return context.getExternalContext().getRequestHeaderMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Header values Map.
     */
    @Override
    public Map<String, String[]> getHeaderValues() {
        return context.getExternalContext().getRequestHeaderValuesMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Initialization parameter Map.
     */
    @Override
    public Map<String, String> getInitParam() {
        return context.getExternalContext().getInitParameterMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Request parameter Map.
     */
    @Override
    public Map<String, String> getParam() {
        return context.getExternalContext().getRequestParameterMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Request parameter Map.
     */
    @Override
    public Map<String, String[]> getParamValues() {
        return context.getExternalContext().getRequestParameterValuesMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Map of Cookies.
     * @since Chain 1.1
     */
    @Override
    public Map<String, Cookie> getCookies() {
        if (cookieValues == null) {
            final Map<String, Object> cookiesSrc = context.getExternalContext().getRequestCookieMap();
            final Map<String, Cookie> cookiesDest = new HashMap<>(cookiesSrc.size());

            cookiesSrc.forEach((k, v) -> cookiesDest.put(k, (Cookie) v));

            cookieValues = Collections.unmodifiableMap(cookiesDest);
        }

        return cookieValues;
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Request scope Map.
     */
    @Override
    public Map<String, Object> getRequestScope() {
        return context.getExternalContext().getRequestMap();
    }

    /**
     * See the {@link WebContext}'s Javadoc.
     *
     * @return Session scope Map.
     */
    @Override
    public Map<String, Object> getSessionScope() {
        return context.getExternalContext().getSessionMap();
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/servlet/ChainProcessor.java Commons Chain :: Web :: Jakarta :: Servlet 57
org/apache/commons/chain/web/javax/servlet/ChainProcessor.java Commons Chain :: Web :: Javax :: Servlet 57
public class ChainProcessor extends ChainServlet {
    private static final long serialVersionUID = -6817532768031279260L;

    // ------------------------------------------------------ Manifest Constants

    /**
     * The name of the servlet init parameter containing the name of the
     * {@link Catalog} to use for processing incoming requests.
     */
    public static final String CATALOG =
        "org.apache.commons.chain.CATALOG";

    /**
     * The default request attribute under which we expose the
     * {@link Catalog} being used to subordinate {@link Command}s.
     */
    public static final String CATALOG_DEFAULT =
        "org.apache.commons.chain.CATALOG";

    /**
     * The name of the servlet init parameter containing the name of the
     * {@link Command} (loaded from our configured {@link Catalog} to use
     * for processing each incoming request.
     */
    public static final String COMMAND =
        "org.apache.commons.chain.COMMAND";

    /**
     * The default command name.
     */
    private static final String COMMAND_DEFAULT = "command";

    // ------------------------------------------------------ Instance Variables

    /**
     * The name of the context attribute under which our {@link Catalog}
     * is stored. This value is also used as the name of the context
     * attribute under which the catalog is exposed to commands. If not
     * specified, we will look up commands in the appropriate
     * {@link Catalog} retrieved from our {@link CatalogFactory}
     */
    private String attribute = null;

    /**
     * The name of the {@link Catalog} to retrieve from the
     * {@link CatalogFactory} for this application, or {@code null}
     * to select the default {@link Catalog}.
     */
    private String catalog = null;

    /**
     * The name of the {@link Command} to be executed for each incoming
     * request.
     */
    private String command = null;

    // ------------------------------------------------------------ Constructors

    /**
     * The Default-Constructor for this class.
     */
    public ChainProcessor() {
    }

    // --------------------------------------------------------- Servlet Methods

    /**
     * Clean up as this application is shut down.
     */
    @Override
    public void destroy() {
        super.destroy();
        attribute = null;
        catalog = null;
        command = null;
    }

    /**
     * Cache the name of the command we should execute for each request.
     *
     * @throws ServletException if an initialization error occurs
     */
    @Override
    public void init() throws ServletException {
        super.init();
        attribute = getServletConfig().getInitParameter(CONFIG_ATTR);
        catalog = getServletConfig().getInitParameter(CATALOG);
        command = getServletConfig().getInitParameter(COMMAND);
        if (command == null) {
            command = COMMAND_DEFAULT;
        }
    }

    /**
     * Configure a {@link ServletWebContext} for the current request, and
     * pass it to the {@code execute()} method of the specified
     * {@link Command}, loaded from our configured {@link Catalog}.
     *
     * @param request The request we are processing
     * @param response The response we are creating
     *
     * @throws IOException if an input/output error occurs
     * @throws ServletException if a servlet exception occurs
     */
    @Override
    public void service(HttpServletRequest request,
                        HttpServletResponse response)
        throws IOException, ServletException {

        ServletWebContext context =
            new ServletWebContext(getServletContext(), request, response);
        Catalog<ServletWebContext> theCatalog = null;
        if (attribute != null) {
            @SuppressWarnings("unchecked")
            Catalog<ServletWebContext> catalog = (Catalog<ServletWebContext>)
                    getServletContext().getAttribute(this.attribute);
            theCatalog = catalog;
        } else if (catalog != null) {
            theCatalog = CatalogFactory.<ServletWebContext>getInstance().getCatalog(catalog);
        } else {
            theCatalog = CatalogFactory.<ServletWebContext>getInstance().getCatalog();
        }
        if (attribute == null) {
            request.setAttribute(CATALOG_DEFAULT, theCatalog);
        }
        Command<ServletWebContext> command = theCatalog.getCommand(this.command);
        try {
            command.execute(context);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/ChainServlet.java Commons Chain :: Web :: Jakarta 93
org/apache/commons/chain/web/javax/ChainServlet.java Commons Chain :: Web :: Javax 93
public class ChainServlet extends HttpServlet {
    private static final long serialVersionUID = 4833344945293509188L;

    // ------------------------------------------------------ Manifest Constants

    /**
     * The name of the context init parameter containing the name of the
     * servlet context attribute under which our resulting {@link Catalog}
     * will be stored.
     */
    public static final String CONFIG_ATTR = ChainInit.CONFIG_ATTR;

    /**
     * The name of the context init parameter containing a comma-delimited
     * list of class loader resources to be scanned.
     */
    public static final String CONFIG_CLASS_RESOURCE =
        ChainInit.CONFIG_CLASS_RESOURCE;

    /**
     * The name of the context init parameter containing a comma-delimited
     * list of web application resources to be scanned.
     */
    public static final String CONFIG_WEB_RESOURCE =
        ChainInit.CONFIG_WEB_RESOURCE;

    /**
     * The name of the context init parameter containing the fully
     * qualified class name of the {@code RuleSet} implementation
     * for configuring our {@link ConfigParser}.
     */
    public static final String RULE_SET = ChainInit.RULE_SET;

    // ------------------------------------------------------------ Constructors

    /**
     * The Default-Constructor for this class.
     */
    public ChainServlet() {
    }

    // --------------------------------------------------------- Servlet Methods

    /**
     * Clean up after ourselves as this application shuts down.
     */
    @Override
    public void destroy() {
        final ServletConfig config = getServletConfig();
        final ServletContext context = getServletContext();
        ChainInit.destroy(context, config.getInitParameter(CONFIG_ATTR));
    }

    /**
     * Create (if necessary) and configure a {@link Catalog} from the
     * servlet init parameters that have been specified.
     *
     * @throws ServletException if the servlet could not be initialized
     */
    @Override
    public void init() throws ServletException {
        final Logger logger = LoggerFactory.getLogger(ChainServlet.class);
        final ServletConfig config = getServletConfig();
        final ServletContext context = getServletContext();
        logger.info("Initializing chain servlet '{}'", config.getServletName());

        ChainInit.initialize(context, config.getInitParameter(CONFIG_ATTR), logger, false);
    }

    /**
     * Does nothing; this servlet's only purpose is to initialize a Chain
     * and store it in the servlet context.
     *
     * @param request the request issued by the client
     * @param response the response to be returned to the cliengt
     *
     * @throws ServletException this exception is never thrown
     * @throws IOException this exception is never thrown
     */
    @Override
    public void service(HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {

          // do nothing
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/servlet/RequestParameterMapper.java Commons Chain :: Web :: Jakarta :: Servlet 38
org/apache/commons/chain/web/javax/servlet/RequestParameterMapper.java Commons Chain :: Web :: Javax :: Servlet 38
public class RequestParameterMapper extends LookupCommand<ServletWebContext> {

    // ------------------------------------------------------ Instance Variables

    private String catalogKey = ChainProcessor.CATALOG_DEFAULT;
    private String parameter = "command";

    // ------------------------------------------------------------ Constructors

    /**
     * The Default-Constructor for this class.
     */
    public RequestParameterMapper() {
    }

    // -------------------------------------------------------------- Properties

    /**
     * Return the context key under which our {@link Catalog} has been
     * stored.
     *
     * @return The context key for the Catalog.
     */
    public String getCatalogKey() {
        return this.catalogKey;
    }

    /**
     * Set the context key under which our {@link Catalog} has been
     * stored.
     *
     * @param catalogKey The new catalog key
     *
     * @deprecated Use catalogName to specify the name of the catalog in the
     *  catalog factory
     */
    @Deprecated
    public void setCatalogKey(String catalogKey) {
        this.catalogKey = catalogKey;
    }

    /**
     * Return the name of the request parameter to use for
     * selecting the {@link Command} to be executed.
     *
     * @return The name of the request parameter.
     *
     * @deprecated Use catalogName to specify the name of the catalog in the
     *  catalog factory
     */
    @Deprecated
    public String getParameter() {
        return this.parameter;
    }

    /**
     * Set the name of the request parameter to use for
     * selecting the {@link Command} to be executed.
     *
     * @param parameter The new parameter name
     */
    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    // --------------------------------------------------------- Command Methods

    /**
     * Look up the specified request parameter for this request, and use it
     * to select an appropriate {@link Command} to be executed.
     *
     * @param context Context for the current request
     *
     * @return The name of the {@link Command} instance
     *
     * @since Chain 1.2
     */
    @Override
    protected String getCommandName(ServletWebContext context) {
        // Look up the specified request parameter for this request
        HttpServletRequest request = context.getRequest();
        String value = request.getParameter(getParameter());
        return value;
    }

    /**
     * Return the {@link Catalog} to look up the {@link Command} in.
     *
     * @param context {@link Context} for this request
     *
     * @return The catalog.
     *
     * @throws IllegalArgumentException if no {@link Catalog}
     *         can be found
     *
     * @since Chain 1.2
     */
    @Override
    protected Catalog<ServletWebContext> getCatalog(ServletWebContext context) {
        /* If the object returned from the passed context is not a valid catalog
         * then we use the super class's catalog extraction logic to pull it
         * or to error gracefully.
         */
        Object testCatalog = context.get(getCatalogKey());

        /* Assume that the underlying implementation is following convention and
         * returning a catalog with the current context.
         */
        @SuppressWarnings("unchecked")
        Catalog<ServletWebContext> catalog = testCatalog instanceof Catalog
                    ? (Catalog<ServletWebContext>) testCatalog
                    : super.getCatalog(context);

        return catalog;
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/ChainListener.java Commons Chain :: Web :: Jakarta 91
org/apache/commons/chain/web/javax/ChainListener.java Commons Chain :: Web :: Javax 91
public class ChainListener implements ServletContextListener {

    // ------------------------------------------------------ Manifest Constants

    /**
     * The name of the context init parameter containing the name of the
     * servlet context attribute under which our resulting {@link Catalog}
     * will be stored.
     */
    public static final String CONFIG_ATTR = ChainInit.CONFIG_ATTR;

    /**
     * The name of the context init parameter containing a comma-delimited
     * list of class loader resources to be scanned.
     */
    public static final String CONFIG_CLASS_RESOURCE =
            ChainInit.CONFIG_CLASS_RESOURCE;

    /**
     * The name of the context init parameter containing a comma-delimited
     * list of web application resources to be scanned.
     */
    public static final String CONFIG_WEB_RESOURCE =
            ChainInit.CONFIG_WEB_RESOURCE;

    /**
     * The name of the context init parameter containing the fully
     * qualified class name of the {@code RuleSet} implementation
     * for configuring our {@link ConfigParser}.
     */
    public static final String RULE_SET = ChainInit.RULE_SET;

    // ------------------------------------------------------------ Constructors

    /**
     * The Default-Constructor for this class.
     */
    public ChainListener() {
    }

    // ------------------------------------------ ServletContextListener Methods

    /**
     * Remove the configured {@link Catalog} from the servlet context
     * attributes for this web application.
     *
     * @param event {@code ServletContextEvent} to be processed
     */
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        final ServletContext context = event.getServletContext();
        ChainInit.destroy(context, context.getInitParameter(CONFIG_ATTR));
    }

    /**
     * Scan the required chain configuration resources, assemble the
     * configured chains into a {@link Catalog}, and expose it as a
     * servlet context attribute under the specified key.
     *
     * @param event {@code ServletContextEvent} to be processed
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        final Logger logger = LoggerFactory.getLogger(ChainListener.class);
        logger.info("Initializing chain listener");
        final ServletContext context = event.getServletContext();

        try {
            ChainInit.initialize(context, context.getInitParameter(CONFIG_ATTR), logger, true);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/WebContext.java Commons Chain :: Web :: Jakarta 43
org/apache/commons/chain/web/javax/WebContext.java Commons Chain :: Web :: Javax 43
public abstract class WebContext extends ContextBase {
    private static final long serialVersionUID = 6804961872140299027L;

    /**
     * The Default-Constructor for this class.
     */
    public WebContext() {
    }

    /**
     * Return a mutable {@code Map} that maps application scope
     * attribute names to their values.
     *
     * @return Application scope Map.
     */
    public abstract Map<String, Object> getApplicationScope();

    /**
     * Return an immutable {@code Map} that maps header names to
     * the first (or only) header value (as a String). Header names must
     * be matched in a case-insensitive manner.
     *
     * @return Header values Map.
     */
    public abstract Map<String, String> getHeader();

    /**
     * Return an immutable {@code Map} that maps header names to
     * the set of all values specified in the request (as a String array).
     * Header names must be matched in a case-insensitive manner.
     *
     * @return Header values Map.
     */
    public abstract Map<String, String[]> getHeaderValues();

    /**
     * Return an immutable {@code Map} that maps context application
     * initialization parameters to their values.
     *
     * @return Initialization parameter Map.
     */
    public abstract Map<String, String> getInitParam();

    /**
     * Return an immutable {@code Map} that maps request parameter
     * names to the first (or only) value (as a String).
     *
     * @return Request parameter Map.
     */
    public abstract Map<String, String> getParam();

    /**
     * Return an immutable {@code Map} that maps request parameter
     * names to the set of all values (as a String array).
     *
     * @return Request parameter Map.
     */
    public abstract Map<String, String[]> getParamValues();

    /**
     * Return an immutable {@code Map} that maps cookie names to
     * the set of cookies specified in the request.
     *
     * @return Map of Cookies.
     *
     * @since Chain 1.1
     */
    public abstract Map<String, Cookie> getCookies();

    /**
     * Return a mutable {@code Map} that maps request scope
     * attribute names to their values.
     *
     * @return Request scope Map.
     */
    public abstract Map<String, Object> getRequestScope();

    /**
     * Return a mutable {@code Map} that maps session scope
     * attribute names to their values.
     *
     * @return Session scope Map.
     */
    public abstract Map<String, Object> getSessionScope();
}
File Project Line
org/apache/commons/chain/web/jakarta/SetLocaleCommand.java Commons Chain :: Web :: Jakarta 36
org/apache/commons/chain/web/javax/SetLocaleCommand.java Commons Chain :: Web :: Javax 36
public abstract class SetLocaleCommand<C extends WebContext> implements Command<C> {

    // ----------------------------------------------------- Instance Variables

    /**
     * BiConsumer to set the {@link Locale} into the {@code context}.
     */
    private final BiConsumer<C, Locale> localeBiConsumer;

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new instance to set the locale into the context.
     *
     * @param localeBiConsumer BiConsumer to set the {@link Locale} into
     *                         the {@code context}
     */
    public SetLocaleCommand(final BiConsumer<C, Locale> localeBiConsumer) {
        this.localeBiConsumer = localeBiConsumer;
    }

    // -------------------------------------------------------------- Properties

    /**
     * The context attribute key used to retrieve the {@code Locale}.
     */
    private String localeKey = "locale";

    /**
     * Return the context attribute key under which we will retrieve
     * the response {@code Locale}.
     *
     * @return The context attribute key of the request {@code Locale}.
     */
    public String getLocaleKey() {
        return this.localeKey;
    }

    /**
     * Set the context attribute key under which we will retrieve
     * the response {@code Locale}.
     *
     * @param localeKey The new context attribute key
     */
    public void setLocaleKey(String localeKey) {
        this.localeKey = localeKey;
    }

    // --------------------------------------------------------- Command Methods

    /**
     * Retrieve the {@code Locale} stored under the specified
     * context attribute key, and establish it on this response.
     *
     * @param context The {@link Context} we are operating on
     *
     * @return {@code false} so that processing will continue
     *
     * @throws Exception If an error occurs during execution.
     */
    @Override
    public boolean execute(C context) throws Exception {
        localeBiConsumer.accept(context, (Locale) context.get(getLocaleKey()));
        return false;
    }
}
File Project Line
org/apache/commons/chain/web/jakarta/GetLocaleCommand.java Commons Chain :: Web :: Jakarta 35
org/apache/commons/chain/web/javax/GetLocaleCommand.java Commons Chain :: Web :: Javax 35
public class GetLocaleCommand<C extends WebContext> implements Command<C> {

    // ----------------------------------------------------- Instance Variables

    /**
     * Function to get the {@link Locale} from the {@code context}.
     */
    private final Function<C, Locale> localeFunction;

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new instance to get the locale from the context.
     *
     * @param localeFunction Function to get the {@link Locale} from
     *                       the {@code context}
     */
    public GetLocaleCommand(final Function<C, Locale> localeFunction) {
        this.localeFunction = localeFunction;
    }

    // -------------------------------------------------------------- Properties

    /**
     * The context attribute key used to store the {@code Locale}.
     */
    private String localeKey = "locale";

    /**
     * Return the context attribute key under which we will store
     * the request {@code Locale}.
     *
     * @return The context attribute key of the request {@code Locale}.
     */
    public String getLocaleKey() {
        return this.localeKey;
    }

    /**
     * Set the context attribute key under which we will store
     * the request {@code Locale}.
     *
     * @param localeKey The new context attribute key
     */
    public void setLocaleKey(String localeKey) {
        this.localeKey = localeKey;
    }

    // --------------------------------------------------------- Command Methods

    /**
     * Retrieve the {@code Locale} for this request, and store it
     * under the specified context attribute.
     *
     * @param context The {@link Context} we are operating on
     *
     * @return {@code false} so that processing will continue
     *
     * @throws Exception If an error occurs during execution.
     */
    @Override
    public boolean execute(C context) throws Exception {
        context.put(getLocaleKey(), localeFunction.apply(context));
        return false;
    }
}