2 * Copyright 2005-2011 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.xmlrouter.impl;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
23 import org.wamblee.xmlrouter.common.Id;
24 import org.wamblee.xmlrouter.config.Identifiable;
27 * This proxy factory creates proxies for identifiable objects that add a prefix
30 * @author Erik Brakkee
34 public class IdentifiablePrefixProxyFactory<T> {
36 public static final class IdPrefixInvocationHandler<T> implements
39 private String prefix;
42 public IdPrefixInvocationHandler(String aPrefix, T aService) {
48 public Object invoke(Object aProxy, final Method aMethod,
49 final Object[] aArgs) throws Throwable {
51 if (aMethod.getDeclaringClass().equals(Identifiable.class)) {
52 if (!aMethod.getName().equals("getId")) {
53 throw new RuntimeException(
54 "Programming error, Identifiable interface was modified");
56 Id id = (Id) aMethod.invoke(service, aArgs);
57 return new Id(prefix + id.getId());
59 return aMethod.invoke(service, aArgs);
60 } catch (InvocationTargetException e) {
66 public static <T> T getProxy(String aPrefix, T aService,
67 Class... aInterfaces) {
68 InvocationHandler handler = new IdPrefixInvocationHandler<T>(aPrefix,
70 Class proxyClass = Proxy.getProxyClass(aService.getClass()
71 .getClassLoader(), aInterfaces);
74 proxy = (T) proxyClass.getConstructor(
75 new Class[] { InvocationHandler.class }).newInstance(
76 new Object[] { handler });
78 } catch (Exception e) {
79 throw new RuntimeException("Could not create proxy for " +
80 aService.getClass().getName(), e);