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 public void run() 047 { 048 lock.lock(); 049 050 // Do we want extra exception catching here? 051 052 for (Runnable r : configuration) 053 { 054 try 055 { 056 r.run(); 057 } catch (RuntimeException ex) 058 { 059 // startup-failure=An exception occurred during startup: %s 060 061 logger.error(String.format("An exception occurred during startup: %s", 062 ExceptionUtils.toMessage(ex)), ex); 063 } 064 } 065 066 // We don't need them any more since this method can only be run once. It's a insignificant 067 // savings, but still a nice thing to do. 068 069 configuration.clear(); 070 } 071 072}