Move BP xml files to standard OSGI-INF/blueprint
[controller.git] / opendaylight / config / netty-event-executor-config / src / main / java / org / opendaylight / controller / config / yang / netty / eventexecutor / AutoCloseableEventExecutor.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.config.yang.netty.eventexecutor;
9
10 import com.google.common.reflect.AbstractInvocationHandler;
11 import com.google.common.reflect.Reflection;
12 import io.netty.util.concurrent.EventExecutor;
13 import io.netty.util.concurrent.GlobalEventExecutor;
14 import io.netty.util.concurrent.ImmediateEventExecutor;
15 import java.lang.reflect.Method;
16 import java.util.concurrent.TimeUnit;
17
18 public interface AutoCloseableEventExecutor extends EventExecutor, AutoCloseable {
19
20     static AutoCloseableEventExecutor globalEventExecutor() {
21         return CloseableEventExecutorMixin.createCloseableProxy(GlobalEventExecutor.INSTANCE);
22     }
23
24     static AutoCloseableEventExecutor immediateEventExecutor() {
25         return CloseableEventExecutorMixin.createCloseableProxy(ImmediateEventExecutor.INSTANCE);
26     }
27
28     class CloseableEventExecutorMixin implements AutoCloseable {
29         public static final int DEFAULT_SHUTDOWN_SECONDS = 1;
30         private final EventExecutor eventExecutor;
31
32         public CloseableEventExecutorMixin(final EventExecutor eventExecutor) {
33             this.eventExecutor = eventExecutor;
34         }
35
36         @Override
37         public void close() throws Exception {
38             eventExecutor.shutdownGracefully(0, DEFAULT_SHUTDOWN_SECONDS, TimeUnit.SECONDS);
39         }
40
41
42         private static AutoCloseableEventExecutor createCloseableProxy(final EventExecutor eventExecutor) {
43             final CloseableEventExecutorMixin closeableEventExecutor = new CloseableEventExecutorMixin(eventExecutor);
44             return Reflection.newProxy(AutoCloseableEventExecutor.class, new AbstractInvocationHandler() {
45                 @Override
46                 protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
47                         throws Throwable {
48                     if (method.getName().equals("close")) {
49                         closeableEventExecutor.close();
50                         return null;
51                     } else {
52                         return method.invoke(closeableEventExecutor.eventExecutor, args);
53                     }
54                 }
55             });
56         }
57     }
58 }