2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.client;
23 import java.util.Iterator;
24 import java.util.ServiceLoader;
26 public class RestPropertiesLoader {
28 /* required to make ServiceLoader thread safe */
29 private static final ThreadLocal<ServiceLoader<RestProperties>> services =
30 new ThreadLocal<ServiceLoader<RestProperties>>() {
32 protected ServiceLoader<RestProperties> initialValue() {
33 return ServiceLoader.load(RestProperties.class);
37 private RestPropertiesLoader() {}
39 private static class Helper {
40 private static final RestPropertiesLoader INSTANCE = new RestPropertiesLoader();
43 public static RestPropertiesLoader getInstance() {
44 return Helper.INSTANCE;
47 public <T> T getNewImpl(Class<? extends RestProperties> clazz) {
48 return this.getImpl(clazz, true);
51 public <T> T getImpl(Class<? extends RestProperties> clazz) {
52 return this.getImpl(clazz, false);
55 private <T> T getImpl(Class<? extends RestProperties> clazz, boolean forceNewInstance) {
57 ServiceLoader<RestProperties> loader = this.services.get();
58 Iterator<RestProperties> propertyImpls = loader.iterator();
60 while (propertyImpls.hasNext()) {
61 item = propertyImpls.next();
62 if (clazz.isAssignableFrom(item.getClass())) {
64 if (forceNewInstance) {
65 result = (T) item.getClass().newInstance();
69 } catch (InstantiationException | IllegalAccessException e) {
71 * all spi implementations must provide a public no argument constructor