01 /*
02 * Copyright 2008-2016 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.codehaus.griffon.runtime.core.injection;
17
18 import javax.annotation.Nonnull;
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import static griffon.util.GriffonClassUtils.requireState;
23 import static java.util.Objects.requireNonNull;
24
25 /**
26 * @author Andres Almiray
27 * @since 2.6.0
28 */
29 public class InjectionUnitOfWork {
30 private static final ThreadLocal<List<Object>> CONTEXT = new ThreadLocal<>();
31 private static final String ERROR_NO_UNITOFWORK_IN_PROCESS = "There is no InjectionUnitOfWork in process!";
32
33 public static void start() {
34 requireState(CONTEXT.get() == null, "There is already an existing InjectionUnitOfWork in process!");
35 CONTEXT.set(new ArrayList<>());
36 }
37
38 @Nonnull
39 public static List<Object> finish() {
40 List<Object> instances = CONTEXT.get();
41 requireState(instances != null, ERROR_NO_UNITOFWORK_IN_PROCESS);
42 CONTEXT.set(null);
43 return instances;
44 }
45
46 public static void track(@Nonnull Object instance) {
47 requireNonNull(instance, "Argument 'instance' must not be null");
48 List<Object> instances = CONTEXT.get();
49 requireState(instances != null, ERROR_NO_UNITOFWORK_IN_PROCESS);
50 instances.add(instance);
51 }
52 }
|