/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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 org.apache.camel.management;

import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.camel.Ordered;
import org.apache.camel.Processor;
import org.apache.camel.management.mbean.ManagedPerformanceCounter;
import org.apache.camel.spi.ManagementInterceptStrategy.InstrumentationProcessor;
import org.apache.camel.support.processor.DelegateAsyncProcessor;
import org.apache.camel.util.StopWatch;

/**
 * JMX enabled processor or advice that uses the {@link org.apache.camel.management.mbean.ManagedCounter} for instrumenting
 * processing of exchanges.
 * <p/>
 * This implementation has been optimised to work in dual mode, either as an advice or as a processor.
 * The former is faster and the latter is required when the error handler has been configured with redelivery enabled.
 */
public class DefaultInstrumentationProcessor extends DelegateAsyncProcessor
        implements InstrumentationProcessor<StopWatch>, Ordered {

    private PerformanceCounter counter;
    private String type;

    public DefaultInstrumentationProcessor(String type, Processor processor) {
        super(processor);
        this.type = type;
    }

    public DefaultInstrumentationProcessor(String type) {
        super(null);
        this.type = type;
    }

    @Override
    public void setCounter(Object counter) {
        ManagedPerformanceCounter mpc = null;
        if (counter instanceof ManagedPerformanceCounter) {
            mpc = (ManagedPerformanceCounter) counter;
        }

        if (this.counter instanceof DelegatePerformanceCounter) {
            ((DelegatePerformanceCounter) this.counter).setCounter(mpc);
        } else if (mpc != null) {
            this.counter = mpc;
        } else if (counter instanceof PerformanceCounter) {
            this.counter = (PerformanceCounter) counter;
        }
    }

    @Override
    public boolean process(final Exchange exchange, final AsyncCallback callback) {
        final StopWatch watch = before(exchange);

        return processor.process(exchange, new AsyncCallback() {
            public void done(boolean doneSync) {
                try {
                    // record end time
                    if (watch != null) {
                        after(exchange, watch);
                    }
                } finally {
                    // and let the original callback know we are done as well
                    callback.done(doneSync);
                }
            }

            @Override
            public String toString() {
                return DefaultInstrumentationProcessor.this.toString();
            }
        });
    }

    protected void beginTime(Exchange exchange) {
        counter.processExchange(exchange);
    }

    protected void recordTime(Exchange exchange, long duration) {
        if (log.isTraceEnabled()) {
            log.trace("{}Recording duration: {} millis for exchange: {}", type != null ? type + ": " : "", duration, exchange);
        }

        if (!exchange.isFailed() && exchange.getException() == null) {
            counter.completedExchange(exchange, duration);
        } else {
            counter.failedExchange(exchange);
        }
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public StopWatch before(Exchange exchange) {
        // only record time if stats is enabled
        StopWatch answer = counter != null && counter.isStatisticsEnabled() ? new StopWatch() : null;
        if (answer != null) {
            beginTime(exchange);
        }
        return answer;
    }

    @Override
    public void after(Exchange exchange, StopWatch watch) {
        // record end time
        if (watch != null) {
            recordTime(exchange, watch.taken());
        }
    }

    @Override
    public String toString() {
        return "InstrumentProcessorAdvice";
    }

    @Override
    public int getOrder() {
        // we want instrumentation before calling the processor (but before tracer/debugger)
        return Ordered.LOWEST - 2;
    }
}

@@ -2812,101 +2812,185 @@
     
-return processor.process(exchange, new AsyncCallback() %7B%0A            public void done(boolean
+// optimize to only create a new callback if needed%0A        AsyncCallback ac = callback;%0A        boolean newCallback = watch != null;%0A        if (newCallback) %7B%0A            ac =
  don
@@ -2994,17 +2994,19 @@
 doneSync
-)
+ -%3E
  %7B%0A     
@@ -3065,53 +3065,8 @@
 ime%0A
-                    if (watch != null) %7B%0A    
     
@@ -3109,30 +3109,8 @@
 h);%0A
-                    %7D%0A
     
@@ -3291,22 +3291,18 @@
    %7D
+;
 %0A
-%0A    
         
 @Ove
@@ -3301,67 +3301,19 @@
     
-@Override%0A            public String toString() %7B%0A  
+%7D%0A%0A
         
     
@@ -3312,93 +3312,45 @@
     
-      
 return 
-DefaultInstrumentationProcessor.this.toString();%0A            %7D%0A        %7D
+processor.process(exchange, ac
 );%0A 

Optimize core