/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2014 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package org.scijava.annotations;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;

import org.junit.Test;

/**
 * Verifies that the {@link EclipseHelper} does its job correctly.
 * 
 * @author Johannes Schindelin
 */
public class EclipseHelperTest {

	@Test
	public void testIndexing() throws Exception {
		final File dir = createTempDirectory();
		copyClasses(dir, Complex.class, Simple.class, Fruit.class,
			AnnotatedA.class, AnnotatedB.class, AnnotatedC.class);
		final File jsonDir = new File(dir, Index.INDEX_PREFIX);
		for (final Class<?> clazz : new Class<?>[] { Complex.class, Simple.class })
		{
			assertFalse(new File(jsonDir, clazz.getName()).exists());
		}
		final URLClassLoader loader =
			new URLClassLoader(new URL[] { dir.toURI().toURL() }, getClass()
				.getClassLoader().getParent())
			{

				@Override
				public Class<?> loadClass(final String className)
					throws ClassNotFoundException
				{
					if (className.equals(Indexable.class.getName())) {
						return Indexable.class;
					}
					return super.loadClass(className);
				}
			};
		EclipseHelper.indexed.clear();
		EclipseHelper.updateAnnotationIndex(loader);
		for (final Class<?> clazz : new Class<?>[] { Complex.class, Simple.class })
		{
			assertTrue(new File(jsonDir, clazz.getName()).exists());
		}
		assertEquals(2, jsonDir.list().length);

		// delete the .class files and verify that the annotation indexes are
		// deleted
		jsonDir.setLastModified(123456789);
		for (final Class<?> clazz : new Class<?>[] { AnnotatedA.class,
			AnnotatedB.class, AnnotatedC.class })
		{
			assertTrue(new File(dir, DirectoryIndexerTest.getResourcePath(clazz))
				.delete());
		}
		long now = System.currentTimeMillis();
		EclipseHelper.indexed.clear();
		EclipseHelper.updateAnnotationIndex(loader);
		assertEquals(0, jsonDir.list().length);
		/*
		 * Most file systems provide the mtime at second granularity, not
		 * milli-second granularity. Hence "now" might be as much as 999
		 * milliseconds ahead of the stored mtime.
		 */
		assertTrue(jsonDir.lastModified() >= now - 999);
	}

	private void copyClasses(final File dir, final Class<?>... classes)
		throws IOException
	{
		final byte[] buffer = new byte[16384];
		for (final Class<?> clazz : classes) {
			final String classPath = DirectoryIndexerTest.getResourcePath(clazz);
			final InputStream in =
				getClass().getResource("/" + classPath).openStream();
			final File outFile = new File(dir, classPath);
			final File parent = outFile.getParentFile();
			assertTrue(parent.isDirectory() || parent.mkdirs());
			final OutputStream out = new FileOutputStream(outFile);
			for (;;) {
				int count = in.read(buffer);
				if (count < 0) {
					break;
				}
				out.write(buffer, 0, count);
			}
			in.close();
			out.close();
		}
	}

	private File createTempDirectory() throws IOException {
		// if running from .../target/test-classes/, let's make a directory next to
		// it
		final String classPath =
			"/" + DirectoryIndexerTest.getResourcePath(getClass());
		final String url = getClass().getResource(classPath).toString();
		if (url.startsWith("file:") && url.endsWith(classPath)) {
			final String directory =
				url.substring(5, url.length() - classPath.length());
			if (directory.endsWith("/target/test-classes")) {
				final File testClassesDirectory = new File(directory);
				if (testClassesDirectory.isDirectory()) {
					final File result =
						new File(testClassesDirectory.getParentFile(), "eclipse-test");
					if (result.exists()) {
						rmRF(result);
					}
					return result;
				}
			}
		}
		// fall back to /tmp/
		final File result = File.createTempFile("eclipse-test", "");
		result.delete();
		result.mkdir();
		return result;
	}

	private static boolean rmRF(final File directory) {
		final File[] list = directory.listFiles();
		if (list != null) {
			for (final File file : list) {
				if (file.isFile() && !file.delete()) {
					return false;
				}
				else if (file.isDirectory() && !rmRF(file)) {
					return false;
				}
			}
		}
		return directory.delete();
	}
}

@@ -2108,16 +2108,516 @@
 Test %7B%0A%0A
+%09@Test%0A%09public void testSkipIndexGeneration() throws Exception %7B%0A%09%09final File dir = createTempDirectory();%0A%09%09copyClasses(dir, Complex.class, Simple.class);%0A%09%09final File jsonDir = new File(dir, Index.INDEX_PREFIX);%0A%09%09assertFalse(jsonDir.exists());%0A%09%09final URLClassLoader loader =%0A%09%09%09new URLClassLoader(new URL%5B%5D %7B dir.toURI().toURL() %7D, getClass()%0A%09%09%09%09.getClassLoader().getParent());%0A%09%09EclipseHelper.indexed.clear();%0A%09%09EclipseHelper.updateAnnotationIndex(loader);%0A%09%09assertFalse(jsonDir.exists());%0A%09%7D%0A%0A
 %09@Test%0A%09

Add a test for the EclipseHelper avoiding to write META-INF/json/