    001// Copyright 2007-2013 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.internal.services;
    016
    017import org.apache.tapestry5.ioc.Registry;
    018import org.apache.tapestry5.ioc.internal.util.OneShotLock;
    019import org.apache.tapestry5.ioc.util.ExceptionUtils;
    020import org.slf4j.Logger;
    021
    022import java.util.List;
    023
    024/**
    025 * Startup service for Tapestry IoC: automatically invoked at {@linkplain Registry#performRegistryStartup() registry
    026 * startup} to execute a series of operations, via its ordered configuration of Runnable objects.
    027 */
    028public class RegistryStartup implements Runnable
    029{
    030    private final Logger logger;
    031
    032    private final List<Runnable> configuration;
    033
    034    private final OneShotLock lock = new OneShotLock();
    035
    036    public RegistryStartup(Logger logger, final List<Runnable> configuration)
    037    {
    038        this.logger = logger;
    039        this.configuration = configuration;
    040    }
    041
    042    /**
    043     * Invokes run() on each contributed object. If the object throws a runtime exception, it is logged but startup
    044     * continues anyway. This method may only be {@linkplain OneShotLock invoked once}.
    045     */
    046    @Override
    047    public void run()
    048    {
    049        lock.lock();
    050
    051        // Do we want extra exception catching here?
    052
    053        for (Runnable r : configuration)
    054        {
    055            try
    056            {
    057                r.run();
    058            } catch (RuntimeException ex)
    059            {
    060                // startup-failure=An exception occurred during startup: %s
    061
    062                logger.error(String.format("An exception occurred during startup: %s",
    063                        ExceptionUtils.toMessage(ex)), ex);
    064            }
    065        }
    066
    067        // We don't need them any more since this method can only be run once. It's a insignificant
    068        // savings, but still a nice thing to do.
    069
    070        configuration.clear();
    071    }
    072
    073}