    001// Copyright 2006-2014 The Apache Software Foundation
    002//
    003// Licensed under the Apache License, Version 2.0 (the "License");
    004// you may not use this file except in compliance with the License.
    005// You may obtain a copy of the License at
    006//
    007// http://www.apache.org/licenses/LICENSE-2.0
    008//
    009// Unless required by applicable law or agreed to in writing, software
    010// distributed under the License is distributed on an "AS IS" BASIS,
    011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    012// See the License for the specific language governing permissions and
    013// limitations under the License.
    014
    015package org.apache.tapestry5.ioc.modules;
    016
    017import org.apache.tapestry5.func.Flow;
    018import org.apache.tapestry5.ioc.*;
    019import org.apache.tapestry5.ioc.annotations.*;
    020import org.apache.tapestry5.ioc.internal.BasicTypeCoercions;
    021import org.apache.tapestry5.ioc.internal.services.*;
    022import org.apache.tapestry5.ioc.internal.services.cron.PeriodicExecutorImpl;
    023import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
    024import org.apache.tapestry5.ioc.internal.util.InternalUtils;
    025import org.apache.tapestry5.ioc.services.*;
    026import org.apache.tapestry5.ioc.services.cron.PeriodicExecutor;
    027import org.apache.tapestry5.ioc.util.TimeInterval;
    028import org.apache.tapestry5.services.UpdateListenerHub;
    029
    030import java.io.File;
    031import java.lang.reflect.Array;
    032import java.math.BigDecimal;
    033import java.math.BigInteger;
    034import java.util.*;
    035import java.util.concurrent.LinkedBlockingQueue;
    036import java.util.concurrent.ThreadPoolExecutor;
    037import java.util.concurrent.TimeUnit;
    038
    039import static org.apache.tapestry5.ioc.OrderConstraintBuilder.after;
    040import static org.apache.tapestry5.ioc.OrderConstraintBuilder.before;
    041
    042/**
    043 * Defines the base set of services for the Tapestry IOC container.
    044 */
    045@SuppressWarnings("all")
    046@Marker(Builtin.class)
    047public final class TapestryIOCModule
    048{
    049    public static void bind(ServiceBinder binder)
    050    {
    051        binder.bind(LoggingDecorator.class, LoggingDecoratorImpl.class);
    052        binder.bind(ChainBuilder.class, ChainBuilderImpl.class);
    053        binder.bind(PropertyAccess.class, PropertyAccessImpl.class);
    054        binder.bind(StrategyBuilder.class, StrategyBuilderImpl.class);
    055        binder.bind(PropertyShadowBuilder.class, PropertyShadowBuilderImpl.class);
    056        binder.bind(PipelineBuilder.class, PipelineBuilderImpl.class).preventReloading();
    057        binder.bind(DefaultImplementationBuilder.class, DefaultImplementationBuilderImpl.class);
    058        binder.bind(ExceptionTracker.class, ExceptionTrackerImpl.class);
    059        binder.bind(ExceptionAnalyzer.class, ExceptionAnalyzerImpl.class);
    060        binder.bind(TypeCoercer.class, TypeCoercerImpl.class).preventReloading();
    061        binder.bind(ThreadLocale.class, ThreadLocaleImpl.class);
    062        binder.bind(SymbolSource.class, SymbolSourceImpl.class);
    063        binder.bind(SymbolProvider.class, MapSymbolProvider.class).withId("ApplicationDefaults")
    064                .withMarker(ApplicationDefaults.class);
    065        binder.bind(SymbolProvider.class, MapSymbolProvider.class).withId("FactoryDefaults")
    066                .withMarker(FactoryDefaults.class);
    067        binder.bind(Runnable.class, RegistryStartup.class).withSimpleId();
    068        binder.bind(MasterObjectProvider.class, MasterObjectProviderImpl.class).preventReloading();
    069        binder.bind(ClassNameLocator.class, ClassNameLocatorImpl.class);
    070        binder.bind(ClasspathScanner.class, ClasspathScannerImpl.class);
    071        binder.bind(AspectDecorator.class, AspectDecoratorImpl.class);
    072        binder.bind(ClasspathURLConverter.class, ClasspathURLConverterImpl.class);
    073        binder.bind(ServiceOverride.class, ServiceOverrideImpl.class);
    074        binder.bind(LoggingAdvisor.class, LoggingAdvisorImpl.class);
    075        binder.bind(LazyAdvisor.class, LazyAdvisorImpl.class);
    076        binder.bind(ThunkCreator.class, ThunkCreatorImpl.class);
    077        binder.bind(UpdateListenerHub.class, UpdateListenerHubImpl.class).preventReloading();
    078        binder.bind(PeriodicExecutor.class, PeriodicExecutorImpl.class);
    079        binder.bind(OperationAdvisor.class, OperationAdvisorImpl.class);
    080        binder.bind(ServiceConfigurationListenerHub.class);
    081    }
    082
    083    /**
    084     * Provides access to additional service lifecycles. One lifecycle is built in ("singleton") but additional ones are
    085     * accessed via this service (and its mapped configuration). Only proxiable services (those with explicit service
    086     * interfaces) can be managed in terms of a lifecycle.
    087     */
    088    @PreventServiceDecoration
    089    public static ServiceLifecycleSource build(Map<String, ServiceLifecycle> configuration)
    090    {
    091        final Map<String, ServiceLifecycle2> lifecycles = CollectionFactory.newCaseInsensitiveMap();
    092
    093        for (String name : configuration.keySet())
    094        {
    095            lifecycles.put(name, InternalUtils.toServiceLifecycle2(configuration.get(name)));
    096        }
    097
    098        return new ServiceLifecycleSource()
    099        {
    100            @Override
    101            public ServiceLifecycle get(String scope)
    102            {
    103                return lifecycles.get(scope);
    104            }
    105        };
    106    }
    107
    108    /**
    109     * Contributes the "perthread" scope.
    110     */
    111    @Contribute(ServiceLifecycleSource.class)
    112    public static void providePerthreadScope(MappedConfiguration<String, ServiceLifecycle> configuration)
    113    {
    114        configuration.addInstance(ScopeConstants.PERTHREAD, PerThreadServiceLifecycle.class);
    115    }
    116
    117    /**
    118     * <dl>
    119     * <dt>AnnotationBasedContributions</dt>
    120     * <dd>Empty placeholder used to separate annotation-based ObjectProvider contributions (which come before) from
    121     * non-annotation based (such as ServiceOverride) which come after.</dd>
    122     * <dt>Value</dt>
    123     * <dd>Supports the {@link org.apache.tapestry5.ioc.annotations.Value} annotation</dd>
    124     * <dt>Symbol</dt>
    125     * <dd>Supports the {@link org.apache.tapestry5.ioc.annotations.Symbol} annotations</dd>
    126     * <dt>Autobuild</dt>
    127     * <dd>Supports the {@link org.apache.tapestry5.ioc.annotations.Autobuild} annotation</dd>
    128     * <dt>ServiceOverride</dt>
    129     * <dd>Allows simple service overrides via the {@link org.apache.tapestry5.ioc.services.ServiceOverride} service
    130     * (and its configuration)
    131     * </dl>
    132     */
    133    @Contribute(MasterObjectProvider.class)
    134    public static void setupObjectProviders(OrderedConfiguration<ObjectProvider> configuration, @Local
    135    final ServiceOverride serviceOverride)
    136    {
    137        configuration.add("AnnotationBasedContributions", null);
    138
    139        configuration.addInstance("Value", ValueObjectProvider.class, before("AnnotationBasedContributions").build());
    140        configuration.addInstance("Symbol", SymbolObjectProvider.class, before("AnnotationBasedContributions").build());
    141        configuration.add("Autobuild", new AutobuildObjectProvider(), before("AnnotationBasedContributions").build());
    142
    143        ObjectProvider wrapper = new ObjectProvider()
    144        {
    145            @Override
    146            public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider, ObjectLocator locator)
    147            {
    148                return serviceOverride.getServiceOverrideProvider().provide(objectType, annotationProvider, locator);
    149            }
    150        };
    151
    152        configuration.add("ServiceOverride", wrapper, after("AnnotationBasedContributions").build());
    153    }
    154
    155    /**
    156     * Contributes a set of standard type coercions to the {@link TypeCoercer} service:
    157     * <ul>
    158     * <li>Object to String</li>
    159     * <li>Object to Boolean</li>
    160     * <li>String to Double</li>
    161     * <li>String to BigDecimal</li>
    162     * <li>BigDecimal to Double</li>
    163     * <li>Double to BigDecimal</li>
    164     * <li>String to BigInteger</li>
    165     * <li>BigInteger to Long</li>
    166     * <li>String to Long</li>
    167     * <li>Long to Byte</li>
    168     * <li>Long to Short</li>
    169     * <li>Long to Integer</li>
    170     * <li>Double to Long</li>
    171     * <li>Double to Float</li>
    172     * <li>Float to Double</li>
    173     * <li>Long to Double</li>
    174     * <li>String to Boolean ("false" is always false, other non-blank strings are true)</li>
    175     * <li>Number to Boolean (true if number value is non zero)</li>
    176     * <li>Null to Boolean (always false)</li>
    177     * <li>Collection to Boolean (false if empty)</li>
    178     * <li>Object[] to List</li>
    179     * <li>primitive[] to List</li>
    180     * <li>Object to List (by wrapping as a singleton list)</li>
    181     * <li>String to File</li>
    182     * <li>String to {@link org.apache.tapestry5.ioc.util.TimeInterval}</li>
    183     * <li>{@link org.apache.tapestry5.ioc.util.TimeInterval} to Long</li>
    184     * <li>Object to Object[] (wrapping the object as an array)</li>
    185     * <li>Collection to Object[] (via the toArray() method)
    186     * <li>{@link Flow} to List</li>
    187     * <li>{@link Flow} to Boolean (false if empty)</li>
    188     * </ul>
    189     */
    190    @Contribute(TypeCoercer.class)
    191    public static void provideBasicTypeCoercions(Configuration<CoercionTuple> configuration)
    192    {
    193        BasicTypeCoercions.provideBasicTypeCoercions(configuration);
    194    }
    195
    196    /**
    197     * <dl>
    198     * <dt>SystemProperties</dt>
    199     * <dd>Exposes JVM System properties as symbols (currently case-sensitive)</dd>
    200     * <dt>EnvironmentVariables</dt>
    201     * <dd>Exposes environment variables as symbols (adding a "env." prefix)</dd>
    202     * <dt>ApplicationDefaults</dt>
    203     * <dd>Values contributed to @{@link SymbolProvider} @{@link ApplicationDefaults}</dd>
    204     * <dt>FactoryDefaults</dt>
    205     * <dd>Values contributed to @{@link SymbolProvider} @{@link FactoryDefaults}</dd>
    206     * </dl>
    207     */
    208    @Contribute(SymbolSource.class)
    209    public static void setupStandardSymbolProviders(OrderedConfiguration<SymbolProvider> configuration,
    210                                                    @ApplicationDefaults
    211                                                    SymbolProvider applicationDefaults,
    212
    213                                                    @FactoryDefaults
    214                                                    SymbolProvider factoryDefaults)
    215    {
    216        configuration.add("SystemProperties", new SystemPropertiesSymbolProvider(), "before:*");
    217        configuration.add("EnvironmentVariables", new SystemEnvSymbolProvider());
    218        configuration.add("ApplicationDefaults", applicationDefaults);
    219        configuration.add("FactoryDefaults", factoryDefaults);
    220    }
    221
    222    public static ParallelExecutor buildDeferredExecution(@Symbol(IOCSymbols.THREAD_POOL_CORE_SIZE)
    223                                                          int coreSize,
    224
    225                                                          @Symbol(IOCSymbols.THREAD_POOL_MAX_SIZE)
    226                                                          int maxSize,
    227
    228                                                          @Symbol(IOCSymbols.THREAD_POOL_KEEP_ALIVE)
    229                                                          @IntermediateType(TimeInterval.class)
    230                                                          int keepAliveMillis,
    231
    232                                                          @Symbol(IOCSymbols.THREAD_POOL_ENABLED)
    233                                                          boolean threadPoolEnabled,
    234
    235                                                          @Symbol(IOCSymbols.THREAD_POOL_QUEUE_SIZE)
    236                                                          int queueSize,
    237
    238                                                          PerthreadManager perthreadManager,
    239
    240                                                          RegistryShutdownHub shutdownHub,
    241
    242                                                          ThunkCreator thunkCreator)
    243    {
    244
    245        if (!threadPoolEnabled)
    246            return new NonParallelExecutor();
    247
    248        LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(queueSize);
    249
    250        final ThreadPoolExecutor executorService = new ThreadPoolExecutor(coreSize, maxSize, keepAliveMillis,
    251                TimeUnit.MILLISECONDS, workQueue);
    252
    253        shutdownHub.addRegistryShutdownListener(new Runnable()
    254        {
    255            @Override
    256            public void run()
    257            {
    258                executorService.shutdown();
    259            }
    260        });
    261
    262        return new ParallelExecutorImpl(executorService, thunkCreator, perthreadManager);
    263    }
    264
    265    @Contribute(SymbolProvider.class)
    266    @FactoryDefaults
    267    public static void setupDefaultSymbols(MappedConfiguration<String, Object> configuration)
    268    {
    269        configuration.add(IOCSymbols.THREAD_POOL_CORE_SIZE, 3);
    270        configuration.add(IOCSymbols.THREAD_POOL_MAX_SIZE, 20);
    271        configuration.add(IOCSymbols.THREAD_POOL_KEEP_ALIVE, "1 m");
    272        configuration.add(IOCSymbols.THREAD_POOL_ENABLED, true);
    273        configuration.add(IOCSymbols.THREAD_POOL_QUEUE_SIZE, 100);
    274    }
    275}