001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.maven.doxia.sink.impl;
020
021import java.lang.reflect.InvocationHandler;
022import java.lang.reflect.InvocationTargetException;
023import java.lang.reflect.Method;
024import java.util.List;
025
026import org.apache.maven.doxia.sink.Sink;
027
028/**
029 * A proxy for a Sink which captures all event/method names called on it.
030 */
031public class EventCapturingSinkProxy implements InvocationHandler {
032
033    private final Sink sink;
034    private final List<String> capturedEventNames;
035
036    /**
037     *
038     * @param sink
039     * @param capturedEventNames the list to receive the captured event/method names
040     * @return a new, proxied sink
041     */
042    public static Sink newInstance(Sink sink, List<String> capturedEventNames) {
043        return (Sink) java.lang.reflect.Proxy.newProxyInstance(
044                sink.getClass().getClassLoader(),
045                new Class<?>[] {Sink.class},
046                new EventCapturingSinkProxy(sink, capturedEventNames));
047    }
048
049    private EventCapturingSinkProxy(Sink sink, List<String> capturedEventNames) {
050        this.sink = sink;
051        this.capturedEventNames = capturedEventNames;
052    }
053
054    @Override
055    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
056        Object result;
057        try {
058            capturedEventNames.add(method.getName());
059            result = method.invoke(sink, args);
060        } catch (InvocationTargetException e) {
061            throw e.getTargetException();
062        }
063        return result;
064    }
065}