org.springframework.integration.test.coverage.AbstractChannelCoverageTests.java Source code

Java tutorial

Introduction

Here is the source code for org.springframework.integration.test.coverage.AbstractChannelCoverageTests.java

Source

/*
 * Copyright 2002-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.springframework.integration.test.coverage;

import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.channel.AbstractMessageChannel;
import org.springframework.integration.channel.ChannelInterceptor;
import org.springframework.integration.channel.interceptor.ChannelInterceptorAdapter;
import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.integration.test.coverage.Coverage.CoverageDetails;

/**
 * Abstract class that analyzes message history from all tests to determine
 * channel coverage.
 * @author 
 * @since 2.1
 *
 */
public abstract class AbstractChannelCoverageTests {

    private static final String COVERAGE_FILE = "target/si.coverage";

    protected static ApplicationContext _applicationContext;

    private static boolean ignoreErrorChannel;

    private static String simpleClassName;

    private static Package currentPackage;

    private static Set<String> traversedChannels = Collections.synchronizedSet(new HashSet<String>());

    protected static boolean aggregatePackageTests;

    private static long seekPosition;

    private static RandomAccessFile file;

    static {
        new File(COVERAGE_FILE).delete();
    }

    public AbstractChannelCoverageTests() {
        aggregatePackageTests = false;
    }

    private static Log logger = LogFactory.getLog(AbstractChannelCoverageTests.class);

    @Autowired
    ApplicationContext _ctx;

    @Before
    public void _setUp() {
        _applicationContext = _ctx;
        String theClassName = this.getClass().getSimpleName();
        Package thePackage = this.getClass().getPackage();
        try {
            file = new RandomAccessFile(COVERAGE_FILE, "rw");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        if (aggregatePackageTests ? !thePackage.equals(currentPackage) : !theClassName.equals(simpleClassName)) {
            traversedChannels = Collections.synchronizedSet(new HashSet<String>());
            if (file != null) {
                try {
                    seekPosition = file.length();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        findAndInterceptChannels();
        simpleClassName = theClassName;
        currentPackage = thePackage;
    }

    protected final void captureHistory(Message<?> out) {
    }

    private void findAndInterceptChannels() {
        if (_ctx == null) {
            fail("No application context loaded - be sure to use @ContextConfiguration and @RunWith(SpringJUnit4ClassRunner.class)");
        }
        Map<String, MessageChannel> channels = _ctx.getBeansOfType(MessageChannel.class);
        for (String channelName : channels.keySet()) {
            MessageChannel channel = channels.get(channelName);
            if (channel instanceof AbstractMessageChannel) {
                AbstractMessageChannel abstractChannel = (AbstractMessageChannel) channel;
                DirectFieldAccessor dfa = new DirectFieldAccessor(abstractChannel);
                dfa = new DirectFieldAccessor(dfa.getPropertyValue("interceptors"));
                @SuppressWarnings("unchecked")
                List<ChannelInterceptor> interceptors = (List<ChannelInterceptor>) dfa
                        .getPropertyValue("interceptors");
                if (interceptors.size() < 1
                        || !(interceptors.get(interceptors.size() - 1) instanceof ChannelTraversalInterceptor)) {
                    abstractChannel.addInterceptor(new ChannelTraversalInterceptor());
                }
            }
        }
    }

    @AfterClass
    public static void verifyCoverage() {
        CoverageDetails<String> channelsNotCovered = Coverage.channelsNotCovered(_applicationContext,
                traversedChannels, ignoreErrorChannel);
        System.out.println("Integration Channel Coverage " + channelsNotCovered.getCoverage()
                + "%. Channels not covered:" + channelsNotCovered.getNotCovered());
        try {
            float channelCount = 1f;
            if (channelsNotCovered.getChannelCount() > 0) {
                channelCount = channelsNotCovered.getChannelCount();
                assertCoverage(channelsNotCovered.getCovered(), channelCount);

                file.seek(seekPosition);
                file.setLength(seekPosition);
                String line = String.format("%.2f|%.2f|%s|%s\n", channelsNotCovered.getCovered(), channelCount,
                        aggregatePackageTests ? currentPackage.getName() : simpleClassName,
                        channelsNotCovered.getNotCovered().toString());
                file.write(line.getBytes());
                file.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void assertCoverage(float covered, float channelCount) {
        logger.info("channel-coverage-threshold =" + System.getProperty("channel-coverage-threshold"));
        if (System.getProperty("channel-coverage-threshold") != null) {
            double threshold = Double.parseDouble(System.getProperty("channel-coverage-threshold"));
            double actualCoverage = ((double) covered / (double) channelCount) * 100.0;
            logger.info("********Actual coverage = " + actualCoverage + " covered=" + (double) covered
                    + " channelCount=" + (double) channelCount);
            Assert.assertTrue("Not reached threshold level", actualCoverage > threshold);
        }
    }

    public static void setIgnoreErrorChannel(boolean bool) {
        ignoreErrorChannel = bool;
    }

    private class ChannelTraversalInterceptor extends ChannelInterceptorAdapter {

        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            if (channel instanceof IntegrationObjectSupport) {
                traversedChannels.add(((IntegrationObjectSupport) channel).getComponentName());
            }
            return message;
        }

    }

}