Java tutorial
/* * Copyright 2015 The RPC Project * * The RPC Project licenses this file to you 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. */ package io.flood.rpc.registry; import com.google.common.collect.ImmutableSet; import com.google.common.reflect.ClassPath; import io.flood.common.Resource; import io.flood.common.config.Configuration; import io.flood.registry.api.NotifyListener; import io.flood.registry.api.Registry; import io.flood.registry.api.RegistryAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Optional; public class ResourceRegistry implements Registry { private static final Logger LOG = LoggerFactory.getLogger(ResourceRegistry.class); private final Registry registry; public ResourceRegistry() { registry = getRegistry(); } private synchronized static Registry getRegistry() { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { ImmutableSet<ClassPath.ClassInfo> classes = ClassPath.from(loader).getTopLevelClasses("io.flood"); Optional<ClassPath.ClassInfo> registryClassInfoOp = classes.stream().filter(classInfo -> { if (classInfo.getClass().getAnnotation(RegistryAction.class) != null) { return true; } return false; }).sorted(((cla, clb) -> { RegistryAction aa = cla.getClass().getAnnotation(RegistryAction.class); RegistryAction ab = clb.getClass().getAnnotation(RegistryAction.class); return aa.order() - ab.order(); })).findFirst(); ClassPath.ClassInfo registryClassInfo = registryClassInfoOp.orElseThrow(Exception::new); RegistryAction action = registryClassInfo.getClass().getAnnotation(RegistryAction.class); Registry registry = (Registry) Class.forName(registryClassInfo.getName()).<Registry>newInstance(); Configuration.configObject(registry); LOG.info("instance {} registry", action.value()); return registry; } catch (Exception e) { LOG.error(""); System.exit(-1); } return null; } public void start() { registry.start(); } @Override public void register(Resource resource) { registry.register(resource); } @Override public void unregister(Resource resource) { registry.unregister(resource); } @Override public void subscribe(String name, String group, NotifyListener listener) { registry.subscribe(name, group, listener); } @Override public void unsubscribe(String name, String group, NotifyListener listener) { registry.unsubscribe(name, group, listener); } @Override public List<Resource> lookup(String name, String group) { return registry.lookup(name, group); } }