All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ehoffman.test.aspects.FileSystemAdvice Maven / Gradle / Ivy

package org.ehoffman.test.aspects;

import java.io.File;
import java.io.IOException;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.ehoffman.resources.ResourceUtils;
import org.ehoffman.test.FileSystem;

/**
 * 
 * @author rex
 */
public class FileSystemAdvice implements MethodInterceptor {

    private File defaultFile = null;
    private IOException defaultIOException = null;

    private File buildTempFolder(final String temp) throws IOException {
        final File file = File.createTempFile(temp, "temp");
        file.deleteOnExit();
        final File newFile = new File(file.getAbsoluteFile().getParent(), temp + Math.random() + File.separator);
        if (!newFile.mkdirs()) {
            throw new IOException("Could not make directory :" + file.toString());
        }
        newFile.deleteOnExit();
        return newFile;
    }

    public FileSystemAdvice() {
        try {
            defaultFile = buildTempFolder("testRunRootFile");
        } catch (final IOException ioe) {
            defaultIOException = ioe;
        }
    }

    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        final FileSystem annotation = invocation.getMethod().getAnnotation(FileSystem.class);
        if (annotation != null) {
            File rootDir = defaultFile;
            IOException rootDirIoe = defaultIOException;
            if (annotation.dirtiesData()) {
                try {
                    rootDir = buildTempFolder("forSingleTest");
                    rootDirIoe = null;
                } catch (final IOException ioe) {
                    rootDirIoe = ioe;
                }
            }
            if (rootDirIoe != null) {
                throw new SkipException(defaultIOException, this);
            }
            for (String resource : annotation.resourceLocations()) {
                if (!ResourceUtils.copyResourcesRecursively(rootDir.toURI().toURL(), new File(resource).getAbsoluteFile(), true)) {
                    throw new SkipException(this);
                }
            }
            FileSystemAccessor.setFile(rootDir);
        }
        return invocation.proceed();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy