001    /*****************************************************************************
002     * Copyright (c) PicoContainer Organization. All rights reserved.            *
003     * ------------------------------------------------------------------------- *
004     * The software in this package is published under the terms of the BSD      *
005     * style license a copy of which has been included with this distribution in *
006     * the LICENSE.txt file.                                                     *
007     *****************************************************************************/
008    package org.picocontainer.composers;
009    
010    import org.picocontainer.ComponentAdapter;
011    import org.picocontainer.PicoContainer;
012    import org.picocontainer.monitors.ComposingMonitor;
013    
014    import java.util.ArrayList;
015    import java.util.Collection;
016    import java.util.List;
017    import java.util.regex.Matcher;
018    import java.util.regex.Pattern;
019    
020    /**
021     * Subsets components in a container, the keys for which match a regular expression.
022     */
023    public class RegexComposer implements ComposingMonitor.Composer {
024    
025        private final Pattern pattern;
026        private final String forNamedComponent;
027    
028        public RegexComposer(String pattern, String forNamedComponent) {
029            this.pattern = Pattern.compile(pattern);
030            this.forNamedComponent = forNamedComponent;
031        }
032    
033        public RegexComposer() {
034            pattern = null;
035            forNamedComponent = null;
036        }
037    
038        public Object compose(PicoContainer container, Object componentKey) {
039            if (componentKey instanceof String
040                    && (forNamedComponent == null || forNamedComponent.equals(componentKey))) {
041                Pattern pat = null;
042                if (pattern == null) {
043                    pat = Pattern.compile((String) componentKey);
044                } else {
045                    pat = pattern;
046                }
047                Collection<ComponentAdapter<?>> cas = container.getComponentAdapters();
048                List retVal = new ArrayList();
049                for (ComponentAdapter<?> componentAdapter : cas) {
050                    Object key = componentAdapter.getComponentKey();
051                    if (key instanceof String) {
052                        Matcher matcher = pat.matcher((String) key);
053                        if (matcher != null && matcher.find()) {
054                            retVal.add(componentAdapter.getComponentInstance(container, ComponentAdapter.NOTHING.class));
055                        }
056                    }
057                }
058                return retVal;
059            }
060            return null;
061        }
062    }