<commit_before>/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2012 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.
 * 
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.build.minimaven;

import imagej.build.minimaven.JavaCompiler.CompileError;
import imagej.util.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * This class represents a parsed pom.xml file.
 * 
 * Every pom.xml file is parsed into an instance of this class; the tree of projects shares
 * a {@link BuildEnvironment} instance.
 * 
 * @author <NAME>
 */
@SuppressWarnings("hiding")
public class MavenProject extends DefaultHandler implements Comparable<MavenProject> {
	protected final BuildEnvironment env;
	protected boolean buildFromSource, built;
	protected File directory, target;
	protected String sourceDirectory = "src/main/java";
	protected MavenProject parent;
	protected MavenProject[] children;

	protected Coordinate coordinate = new Coordinate(), parentCoordinate;
	protected Map<String, String> properties = new HashMap<String, String>();
	protected List<String> modules = new ArrayList<String>();
	protected List<Coordinate> dependencies = new ArrayList<Coordinate>();
	protected Set<String> repositories = new TreeSet<String>();
	protected String sourceVersion, targetVersion, mainClass;
	protected boolean includeImplementationBuild;
	protected String packaging = "jar";

	// only used during parsing
	protected String prefix = "";
	protected Coordinate latestDependency = new Coordinate();
	protected boolean isCurrentProfile;
	protected String currentPluginName;

	protected MavenProject addModule(String name) throws IOException, ParserConfigurationException, SAXException {
		return addChild(env.parse(new File(new File(directory, name), "pom.xml"), this));
	}

	protected MavenProject addChild(MavenProject child) {
		MavenProject[] newChildren = new MavenProject[children.length + 1];
		System.arraycopy(children, 0, newChildren, 0, children.length);
		newChildren[children.length] = child;
		children = newChildren;
		return child;
	}

	protected MavenProject(final BuildEnvironment miniMaven, File directory, MavenProject parent) {
		env = miniMaven;
		this.directory = directory;
		this.parent = parent;
		if (parent != null) {
			coordinate.groupId = parent.coordinate.groupId;
			coordinate.version = parent.coordinate.version;
			parentCoordinate = parent.coordinate;
			includeImplementationBuild = parent.includeImplementationBuild;
		}
	}

	public void clean() throws IOException, ParserConfigurationException, SAXException {
		if (!buildFromSource)
			return;
		for (MavenProject child : getDependencies(true, env.downloadAutomatically))
			if (child != null)
				child.clean();
		if (target.isDirectory())
			BuildEnvironment.rmRF(target);
		else if (target.exists())
			target.delete();
		File jar = getTarget();
		if (jar.exists())
			jar.delete();
	}

	public void downloadDependencies() throws IOException, ParserConfigurationException, SAXException {
		getDependencies(true, true, "test");
		download();
	}

	protected void download() throws FileNotFoundException {
		if (buildFromSource || target.exists())
			return;
		download(coordinate, true);
	}

	protected void download(Coordinate dependency, boolean quiet) throws FileNotFoundException {
		for (String url : getRoot().getRepositories()) try {
			if (env.debug) {
				env.err.println("Trying to download from " + url);
			}
			env.downloadAndVerify(url, dependency, quiet);
			return;
		} catch (Exception e) {
			if (env.verbose)
				e.printStackTrace();
		}
		throw new FileNotFoundException("Could not download " + dependency.getJarName());
	}

	public boolean upToDate(boolean includingJar) throws IOException, ParserConfigurationException, SAXException {
		if (!buildFromSource)
			return true;
		for (MavenProject child : getDependencies(true, env.downloadAutomatically, "test"))
			if (child != null && !child.upToDate(includingJar)) {
				if (env.verbose) {
					env.err.println(getArtifactId() + " not up-to-date because of " + child.getArtifactId());
				}
				return false;
			}
<commit_msg>MiniMaven: accelerate repeated upToDate() checks<commit_after>/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2012 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.
 * 
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.build.minimaven;

import imagej.build.minimaven.JavaCompiler.CompileError;
import imagej.util.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * This class represents a parsed pom.xml file.
 * 
 * Every pom.xml file is parsed into an instance of this class; the tree of projects shares
 * a {@link BuildEnvironment} instance.
 * 
 * @author <NAME>
 */
@SuppressWarnings("hiding")
public class MavenProject extends DefaultHandler implements Comparable<MavenProject> {
	protected final BuildEnvironment env;
	protected boolean buildFromSource, built;
	protected File directory, target;
	protected String sourceDirectory = "src/main/java";
	protected MavenProject parent;
	protected MavenProject[] children;

	protected Coordinate coordinate = new Coordinate(), parentCoordinate;
	protected Map<String, String> properties = new HashMap<String, String>();
	protected List<String> modules = new ArrayList<String>();
	protected List<Coordinate> dependencies = new ArrayList<Coordinate>();
	protected Set<String> repositories = new TreeSet<String>();
	protected String sourceVersion, targetVersion, mainClass;
	protected boolean includeImplementationBuild;
	protected String packaging = "jar";

	private static enum BooleanState {
		UNKNOWN, YES, NO
	};
	private BooleanState upToDate = BooleanState.UNKNOWN,
		jarUpToDate = BooleanState.UNKNOWN;

	// only used during parsing
	protected String prefix = "";
	protected Coordinate latestDependency = new Coordinate();
	protected boolean isCurrentProfile;
	protected String currentPluginName;

	protected MavenProject addModule(String name) throws IOException, ParserConfigurationException, SAXException {
		return addChild(env.parse(new File(new File(directory, name), "pom.xml"), this));
	}

	protected MavenProject addChild(MavenProject child) {
		MavenProject[] newChildren = new MavenProject[children.length + 1];
		System.arraycopy(children, 0, newChildren, 0, children.length);
		newChildren[children.length] = child;
		children = newChildren;
		return child;
	}

	protected MavenProject(final BuildEnvironment miniMaven, File directory, MavenProject parent) {
		env = miniMaven;
		this.directory = directory;
		this.parent = parent;
		if (parent != null) {
			coordinate.groupId = parent.coordinate.groupId;
			coordinate.version = parent.coordinate.version;
			parentCoordinate = parent.coordinate;
			includeImplementationBuild = parent.includeImplementationBuild;
		}
	}

	public void clean() throws IOException, ParserConfigurationException, SAXException {
		if (!buildFromSource)
			return;
		for (MavenProject child : getDependencies(true, env.downloadAutomatically))
			if (child != null)
				child.clean();
		if (target.isDirectory())
			BuildEnvironment.rmRF(target);
		else if (target.exists())
			target.delete();
		File jar = getTarget();
		if (jar.exists())
			jar.delete();
	}

	public void downloadDependencies() throws IOException, ParserConfigurationException, SAXException {
		getDependencies(true, true, "test");
		download();
	}

	protected void download() throws FileNotFoundException {
		if (buildFromSource || target.exists())
			return;
		download(coordinate, true);
	}

	protected void download(Coordinate dependency, boolean quiet) throws FileNotFoundException {
		for (String url : getRoot().getRepositories()) try {
			if (env.debug) {
				env.err.println("Trying to download from " + url);
			}
			env.downloadAndVerify(url, dependency, quiet);
			return;
		} catch (Exception e) {
			if (env.verbose)
				e.printStackTrace();
		}
		throw new FileNotFoundException("Could not download " + dependency.getJarName());
	}

	public boolean upToDate(boolean includingJar) throws IOException, ParserConfigurationException, SAXException {
		if (includingJar) {
			if (jarUpToDate == BooleanState.UNKNOWN) {
				jarUpToDate = checkUpToDate(true) ?
					BooleanState.YES : BooleanState.NO;
			}
			return jarUpToDate == BooleanState.YES;
		} else {
			if (upToDate == BooleanState.UNKNOWN) {
				upToDate = checkUpToDate(false) ?
					BooleanState.YES : BooleanState.NO;
			}
			return upToDate == BooleanState.YES;
		}
	}

	public boolean checkUpToDate(boolean includingJar) throws IOException, ParserConfigurationException, SAXException {
		if (!buildFromSource)
			return true;
		for (MavenProject child : getDependencies(true, env.downloadAutomatically, "test"))
			if (child != null && !child.upToDate(includingJar)) {
				if (env.verbose) {
					env.err.println(getArtifactId() + " not up-to-date because of " + child.getArtifactId());
				}
				return false;
			}

{'fraction_non_alphanumeric': 0.08918879272407217, 'fraction_numerical': 0.0019069972128502274, 'mean_word_length': 4.872093023255814, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 14}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7489042', 'n_tokens_mistral': 4014, 'n_tokens_neox': 3615, 'n_words': 1264}