001/*
002 * Copyright 2006-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.sample.jmx;
018
019import org.aspectj.lang.JoinPoint;
020import org.springframework.batch.core.StepExecution;
021import org.springframework.context.ApplicationEventPublisher;
022import org.springframework.context.ApplicationEventPublisherAware;
023
024/**
025 * Wraps calls for methods taking {@link StepExecution} as an argument and
026 * publishes notifications in the form of {@link org.springframework.context.ApplicationEvent}.
027 * 
028 * @author Dave Syer
029 */
030public class StepExecutionApplicationEventAdvice implements ApplicationEventPublisherAware {
031
032        private ApplicationEventPublisher applicationEventPublisher;
033
034        /*
035         * (non-Javadoc)
036         * @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher)
037         */
038        @Override
039        public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
040                this.applicationEventPublisher = applicationEventPublisher;
041        }
042
043        public void before(JoinPoint jp, StepExecution stepExecution) {
044                String msg = "Before: " + jp.toShortString() + " with: " + stepExecution;
045                publish(jp.getTarget(), msg);
046        }
047
048        public void after(JoinPoint jp, StepExecution stepExecution) {
049                String msg = "After: " + jp.toShortString() + " with: " + stepExecution;
050                publish(jp.getTarget(), msg);
051        }
052
053        public void onError(JoinPoint jp, StepExecution stepExecution, Throwable t) {
054                String msg = "Error in: " + jp.toShortString() + " with: " + stepExecution + " (" + t.getClass() + ":" + t.getMessage() + ")";
055                publish(jp.getTarget(), msg);
056        }
057
058        /*
059         * Publish a {@link SimpleMessageApplicationEvent} with the given
060         * parameters.
061         */
062        private void publish(Object source, String message) {
063                applicationEventPublisher.publishEvent(new SimpleMessageApplicationEvent(source, message));
064        }
065}