01 /*
02 * Copyright 2008-2017 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 private InjectionUnitOfWork() {
34 // prevent instantiation
35 }
36
37 public static void start() {
38 requireState(CONTEXT.get() == null, "There is already an existing InjectionUnitOfWork in process!");
39 CONTEXT.set(new ArrayList<>());
40 }
41
42 @Nonnull
43 public static List<Object> finish() {
44 List<Object> instances = CONTEXT.get();
45 requireState(instances != null, ERROR_NO_UNITOFWORK_IN_PROCESS);
46 CONTEXT.set(null);
47 return instances;
48 }
49
50 public static void track(@Nonnull Object instance) {
51 requireNonNull(instance, "Argument 'instance' must not be null");
52 List<Object> instances = CONTEXT.get();
53 requireState(instances != null, ERROR_NO_UNITOFWORK_IN_PROCESS);
54 instances.add(instance);
55 }
56 }
|