+++ /dev/null
-/*
- * Copyright 2005-2011 the original author or authors.
- *
- * Licensed 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 org.wamblee.xmlrouter.impl;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-import org.wamblee.xmlrouter.common.Id;
-import org.wamblee.xmlrouter.config.Identifiable;
-
-/**
- * This proxy factory creates proxies for identifiable objects that add a prefix
- * to the ids.
- *
- * @author Erik Brakkee
- *
- * @param <T>
- */
-public class IdentifiablePrefixProxyFactory<T> {
-
- public static final class IdPrefixInvocationHandler<T> implements
- InvocationHandler {
-
- private String prefix;
- private T service;
-
- public IdPrefixInvocationHandler(String aPrefix, T aService) {
- prefix = aPrefix;
- service = aService;
- }
-
- @Override
- public Object invoke(Object aProxy, final Method aMethod,
- final Object[] aArgs) throws Throwable {
- try {
- if (aMethod.getDeclaringClass().equals(Identifiable.class)) {
- if (!aMethod.getName().equals("getId")) {
- throw new RuntimeException(
- "Programming error, Identifiable interface was modified");
- }
- Id id = (Id) aMethod.invoke(service, aArgs);
- return new Id(prefix + id.getId());
- }
- return aMethod.invoke(service, aArgs);
- } catch (InvocationTargetException e) {
- throw e.getCause();
- }
- }
- }
-
- public static <T> T getProxy(String aPrefix, T aService,
- Class... aInterfaces) {
- InvocationHandler handler = new IdPrefixInvocationHandler<T>(aPrefix,
- aService);
- Class proxyClass = Proxy.getProxyClass(aService.getClass()
- .getClassLoader(), aInterfaces);
- T proxy;
- try {
- proxy = (T) proxyClass.getConstructor(
- new Class[] { InvocationHandler.class }).newInstance(
- new Object[] { handler });
- return proxy;
- } catch (Exception e) {
- throw new RuntimeException("Could not create proxy for " +
- aService.getClass().getName(), e);
- }
- }
-}