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 = new ThreadLocal<ServiceLoader<RestProperties>>() {
31 protected ServiceLoader<RestProperties> initialValue() {
32 return ServiceLoader.load(RestProperties.class);
35 private RestPropertiesLoader() {
38 private static class Helper {
39 private static final RestPropertiesLoader INSTANCE = new RestPropertiesLoader();
42 public static RestPropertiesLoader getInstance() {
43 return Helper.INSTANCE;
46 public <T> T getNewImpl(Class<? extends RestProperties> clazz) {
47 return this.getImpl(clazz, true);
49 public <T> T getImpl(Class<? extends RestProperties> clazz) {
50 return this.getImpl(clazz, false);
53 private <T> T getImpl(Class<? extends RestProperties> clazz, boolean forceNewInstance) {
55 ServiceLoader<RestProperties> loader = this.services.get();
56 Iterator<RestProperties> propertyImpls = loader.iterator();
58 while (propertyImpls.hasNext()) {
59 item = propertyImpls.next();
60 if (clazz.isAssignableFrom(item.getClass())) {
62 if (forceNewInstance) {
63 result = (T)item.getClass().newInstance();
67 } catch (InstantiationException | IllegalAccessException e) {
68 /* all spi implementations must provide a public
69 * no argument constructor