aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java
blob: 9353de662be217977010930241b21e4b9144cd61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.core.factory.impl;


import static org.openecomp.core.utilities.CommonMethods.isEmpty;
import static org.openecomp.core.utilities.CommonMethods.newInstance;

import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.errors.ErrorCategory;
import org.openecomp.sdc.common.errors.ErrorCode;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractFactoryBase {

  /**
   * Temporary registry of default implementations. The map keeps class names rather then class
   * types to allow unloading of those classes from memory by garbage collector if factory is not
   * actually used.
   */
  private static Map<String, String> registry = new ConcurrentHashMap<String, String>();

  /**
   * Cached factory instances.
   */
  private static Map<String, AbstractFactoryBase> factoryMap =
      new ConcurrentHashMap<String, AbstractFactoryBase>();

  /**
   * Registers implementor for an abstract factory. The method accepts Java classes rather then
   * class names to ensure type safety at compilation time.
   *
   * @param <I>     Java interface type instantiated by abstract factory
   * @param <F>     Type specific abstract factory for concrete Java interface
   * @param factory Java class of a type specific abstract factory
   * @param impl    Java class of type specific factory implementor
   */
  public static <I, F extends AbstractFactoryBase> void registerFactory(Class<F> factory,
                                                                        Class<? extends F> impl) {
    if (factory == null) {
      throw new CoreException(
          new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input factory.")
              .withCategory(ErrorCategory.SYSTEM).build());
    }

    if (impl == null) {
      throw new CoreException(
          new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input impl.")
              .withCategory(ErrorCategory.SYSTEM).build());
    }
    if (factoryMap != null && factoryMap.containsKey(factory.getName())) {
      factoryMap.remove(factory.getName());
    }
    registry.put(factory.getName(), impl.getName());
  } // registerFactory

  // TODO: Remove
  protected static void registerFactory(String factoryName, String implName) {
    registry.put(factoryName, implName);
  } // registerFactory

  /**
   * Unregister factory.
   *
   * @param <F>     the type parameter
   * @param factory the factory
   */
  public static <F extends AbstractFactoryBase> void unregisterFactory(Class<F> factory) {
    if (factory == null) {
      throw new CoreException(
          new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input factory.")
              .withCategory(ErrorCategory.SYSTEM).build());
    }
    if (factoryMap != null) {
      factoryMap.remove(factory.getName());
    }
  }

  /**
   * Instantiates the configured implementation of an abstract factory.
   *
   * @param <I>         Java interface type instantiated by abstract factory
   * @param <F>         Type specific abstract factory for concrete Java interface
   * @param factoryType Java class of type specific abstract factory
   * @return Instance of implementation class
   */
  @SuppressWarnings("unchecked")
  public static <I, F extends AbstractFactoryBase> F getInstance(Class<F> factoryType) {
    if (factoryType == null) {
      throw new CoreException(
          new ErrorCode.ErrorCodeBuilder().withId("E0001")
              .withMessage("Mandatory input factory type.").withCategory(ErrorCategory.SYSTEM)
              .build());

    }
    // Pick up factory instance from cache
    F factory = (F) factoryMap.get(factoryType.getName());
    // Check for the first time access
    if (factory == null) {
      // Synchronize factory instantiation
      synchronized (factoryType) {
        // Re-check the factory instance
        factory = (F) factoryMap.get(factoryType.getName());
        if (factory == null) {
          // Get the implementation class name
          String implName = registry.get(factoryType.getName());

          if (isEmpty(implName)) {
            throw new CoreException(
                new ErrorCode.ErrorCodeBuilder().withId("E0001")
                    .withMessage("Mandatory input factory implementation.")
                    .withCategory(ErrorCategory.SYSTEM).build());
          }

          factory = newInstance(implName, factoryType);

          factory.init();

          // Cache the instantiated singleton
          factoryMap.put(factoryType.getName(), factory);
        }
      }
    }

    return factory;

  } // getInstance


  /**
   * Is factory registered boolean.
   *
   * @param <F>         the type parameter
   * @param factoryType the factory type
   * @return the boolean
   */
  public static <F extends AbstractFactoryBase> boolean isFactoryRegistered(Class<F> factoryType) {
    boolean isFactoryRegistered = false;
    if (factoryType == null) {
      throw new CoreException(
          new ErrorCode.ErrorCodeBuilder().withId("E0001")
              .withMessage("Mandatory input factory type.").withCategory(ErrorCategory.SYSTEM)
              .build());
    }
    // Pick up factory instance from cache
    F factory = (F) factoryMap.get(factoryType.getName());
    // Check for the first time access
    if (factory != null) {
      isFactoryRegistered = true;
    } else {
      // Get the implementation class name
      String implName = registry.get(factoryType.getName());
      if (!isEmpty(implName)) {
        isFactoryRegistered = true;
      }
    }
    return isFactoryRegistered;
  }

  /**
   * Stop all.
   */
  public static void stopAll() {
    Collection<AbstractFactoryBase> factorylist = factoryMap.values();
    for (AbstractFactoryBase factory : factorylist) {
      factory.stop();
    }
  }

  protected void init() {
  }

  protected void stop() {
  }

}