<commit_before>package fr.tikione.jacocoverage.plugin.action;

import fr.tikione.jacocoexec.analyzer.JaCoCoReportAnalyzer;
import fr.tikione.jacocoexec.analyzer.JaCoCoXmlReportParser;
import fr.tikione.jacocoexec.analyzer.JavaClass;
import fr.tikione.jacocoverage.plugin.anno.AbstractCoverageAnnotation;
import fr.tikione.jacocoverage.plugin.config.Globals;
import fr.tikione.jacocoverage.plugin.config.ProjectConfig;
import fr.tikione.jacocoverage.plugin.util.NBProjectTypeEnum;
import fr.tikione.jacocoverage.plugin.util.NBUtils;
import fr.tikione.jacocoverage.plugin.util.Utils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.tools.ant.module.api.AntProjectCookie;
import org.apache.tools.ant.module.api.AntTargetExecutor;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.project.Project;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.HtmlBrowser;
import org.openide.execution.ExecutorTask;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.xml.sax.SAXException;

/**
 * A toolkit that launches Ant tasks with the JaCoCo JavaAgent, colorizes Java source files and shows a coverage report.
 * <br/>See <a href="http://wiki.netbeans.org/DevFaqRequestProcessor">DevFaqRequestProcessor</a> for NetBeans threading tweaks.
 * <br/>See <a href="http://wiki.netbeans.org/DevFaqActionContextSensitive">DevFaqActionContextSensitive</a> for context action tweaks.
 * <br/>See <a href="http://wiki.netbeans.org/DevFaqAddGlobalContext">DevFaqAddGlobalContext</a> for global context and project tweaks.
 *
 * @author <NAME>
 * @author <NAME>
 */
@SuppressWarnings("CloneableImplementsClone")
public abstract class ActionJacocoOnAntTaskJ2SE
		extends AbstractAction
		implements ActionListener {

	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = Logger.getLogger(ActionJacocoOnAntTaskJ2SE.class.getName());

	// Will be used in a future release
	//private static final String DEFAULT_EXCLUDES = "com.sun.*:org.apache.*:org.netbeans.*:junit.*:sun.*:org.openide.*:org.junit.*";
	/** The Ant task to launch. */
	private final String antTask;

	/** Additional properties passed to the Ant task. */
	private final Properties addAntTargetProps = new Properties();

	/**
	 * Enable the context action on supported projects only.
	 *
	 * @param antTask additional properties passed to the Ant task.
	 */
	public ActionJacocoOnAntTaskJ2SE(String antTask) {
		this.antTask = antTask;
	}

	@Override
	public void actionPerformed(ActionEvent ae) {
		new RequestProcessor("JaCoCoverage Preparation Task", 3, true).post(new Runnable() {
			@Override
			public void run() {
				try {
					runJacocoJavaagent(NBUtils.getSelectedProject());
				} catch (IllegalArgumentException | IOException ex) {
					Exceptions.printStackTrace(ex);
				}
			}
		});
	}

	/**
	 * Run an Ant task with a JaCoCo Java Agent, collect and display coverage data.
	 *
	 * @param project the project to launch Ant target from.
	 * @throws IOException if an I/O error occurs.
	 */
	private void runJacocoJavaagent(final Project project)
			throws IOException {
		// Retrieve JaCoCoverage preferences.
		final ProjectConfig cfg = ProjectConfig.forFile(new File(NBUtils.getProjectDir(project), Globals.PRJ_CFG));
		final boolean enblHighlight = cfg.isEnblHighlighting();
		final boolean enblConsoleReport = cfg.isEnblConsoleReport();
		final boolean enblHtmlReport = cfg.isEnblHtmlReport();
		final boolean openHtmlReport = cfg.isOpenHtmlReport();

		if (enblHighlight || enblConsoleReport || enblHtmlReport) {
			// Retrieve project properties.
			final String prjDir = NBUtils.getProjectDir(project) + File.separator;
			FileObject prjPropsFo = project.getProjectDirectory().getFileObject("nbproject/project.properties");
			final Properties prjProps = new Properties();
			try (InputStream insPrjProps = prjPropsFo.getInputStream()) {
				prjProps.load(insPrjProps);
			}

			final File xmlreport = Utils.getJacocoXmlReportfile(project);
			final File binreport = Utils.getJacocoBinReportFile(project);
			if (binreport.exists() && !binreport.delete() || xmlreport.exists() && !xmlreport.delete()) {
				String msg = "Cannot delete the previous JaCoCo report files, please delete them manually:\n"
						+ binreport.getAbsolutePath() + " and/or\n"
						+ xmlreport.getAbsolutePath();
				NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE);
				DialogDisplayer.getDefault().notify(nd);
			} else {
				// Apply JaCoCo JavaAgent customization.
				final String antTaskJavaagentParam;
				List<String> excludeList = cfg.getPkgclssExclude();
				StringBuilder exclude = new StringBuilder((excludeList.size() + 1) * 20);
				if (cfg.isOverrideGlobals() && !excludeList.isEmpty()) {
					exclude.append(",excludes=");
					boolean first = true;
					for (String pkg : excludeList) {
						if (!first) {
							exclude.append(':');
						}
						exclude.append(pkg).append(".*");
						first = false;
					}
				}

				// GWI patch: If NetBeans Module Project - use different JavaAgent settings
				final boolean isNBModule = Utils.isProjectSupported(NBUtils.getSelectedProject(), NBProjectTypeEnum.NBMODULE);
				final String jacocoAgentJarAbsPath = NBUtils.getJacocoAgentJar().getAbsolutePath();
				if (isNBModule) {
					String excludes = prjProps.getProperty("jacoco.excludes");
					antTaskJavaagentParam = "\"" + jacocoAgentJarAbsPath
							+ "\"=destfile=\"" + binreport.getAbsolutePath() + "\"" + (excludes == null ? "" : ",excludes=" + excludes);
				} else {
					String packagesToTest = NBUtils.getProjectJavaPackagesAsStr(project, prjProps, ":", ".*");
					if (packagesToTest.length() > 1000) { // GitHub#26: JaCoCo seems to fail if the includes list is too long
						packagesToTest = "*";
					}
					antTaskJavaagentParam = "\"" + jacocoAgentJarAbsPath
							+ "\"=includes=" + packagesToTest
							+ ",destfile=\"" + binreport.getAbsolutePath() + "\"" + exclude.toString();
				}

				FileObject scriptToExecute = project.getProjectDirectory().getFileObject("build", "xml");
				if (scriptToExecute == null) { // Fix for GitHub #16.
					scriptToExecute = project.getProjectDirectory().getFileObject("nbbuild", "xml");<commit_msg>prepare patch for #28<commit_after>package fr.tikione.jacocoverage.plugin.action;

import fr.tikione.jacocoexec.analyzer.JaCoCoReportAnalyzer;
import fr.tikione.jacocoexec.analyzer.JaCoCoXmlReportParser;
import fr.tikione.jacocoexec.analyzer.JavaClass;
import fr.tikione.jacocoverage.plugin.anno.AbstractCoverageAnnotation;
import fr.tikione.jacocoverage.plugin.config.Globals;
import fr.tikione.jacocoverage.plugin.config.ProjectConfig;
import fr.tikione.jacocoverage.plugin.util.NBProjectTypeEnum;
import fr.tikione.jacocoverage.plugin.util.NBUtils;
import fr.tikione.jacocoverage.plugin.util.Utils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.tools.ant.module.api.AntProjectCookie;
import org.apache.tools.ant.module.api.AntTargetExecutor;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.project.Project;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.HtmlBrowser;
import org.openide.execution.ExecutorTask;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.xml.sax.SAXException;

/**
 * A toolkit that launches Ant tasks with the JaCoCo JavaAgent, colorizes Java source files and shows a coverage report.
 * <br/>See <a href="http://wiki.netbeans.org/DevFaqRequestProcessor">DevFaqRequestProcessor</a> for NetBeans threading tweaks.
 * <br/>See <a href="http://wiki.netbeans.org/DevFaqActionContextSensitive">DevFaqActionContextSensitive</a> for context action tweaks.
 * <br/>See <a href="http://wiki.netbeans.org/DevFaqAddGlobalContext">DevFaqAddGlobalContext</a> for global context and project tweaks.
 *
 * @author <NAME>
 * @author <NAME>
 */
@SuppressWarnings("CloneableImplementsClone")
public abstract class ActionJacocoOnAntTaskJ2SE
		extends AbstractAction
		implements ActionListener {

	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = Logger.getLogger(ActionJacocoOnAntTaskJ2SE.class.getName());

	// Will be used in a future release
	//private static final String DEFAULT_EXCLUDES = "com.sun.*:org.apache.*:org.netbeans.*:junit.*:sun.*:org.openide.*:org.junit.*";
	/** The Ant task to launch. */
	private final String antTask;

	/** Additional properties passed to the Ant task. */
	private final Properties addAntTargetProps = new Properties();

	/**
	 * Enable the context action on supported projects only.
	 *
	 * @param antTask additional properties passed to the Ant task.
	 */
	public ActionJacocoOnAntTaskJ2SE(String antTask) {
		this.antTask = antTask;
	}

	@Override
	public void actionPerformed(ActionEvent ae) {
		new RequestProcessor("JaCoCoverage Preparation Task", 3, true).post(new Runnable() {
			@Override
			public void run() {
				try {
					runJacocoJavaagent(NBUtils.getSelectedProject());
				} catch (IllegalArgumentException | IOException ex) {
					Exceptions.printStackTrace(ex);
				}
			}
		});
	}

	/**
	 * Run an Ant task with a JaCoCo Java Agent, collect and display coverage data.
	 *
	 * @param project the project to launch Ant target from.
	 * @throws IOException if an I/O error occurs.
	 */
	private void runJacocoJavaagent(final Project project)
			throws IOException {
		// Retrieve JaCoCoverage preferences.
		final ProjectConfig cfg = ProjectConfig.forFile(new File(NBUtils.getProjectDir(project), Globals.PRJ_CFG));
		final boolean enblHighlight = cfg.isEnblHighlighting();
		final boolean enblConsoleReport = cfg.isEnblConsoleReport();
		final boolean enblHtmlReport = cfg.isEnblHtmlReport();
		final boolean openHtmlReport = cfg.isOpenHtmlReport();

		if (enblHighlight || enblConsoleReport || enblHtmlReport) {
			// Retrieve project properties.
			final String prjDir = NBUtils.getProjectDir(project) + File.separator;
			FileObject prjPropsFo = project.getProjectDirectory().getFileObject("nbproject/project.properties");
			final Properties prjProps = new Properties();
			try (InputStream insPrjProps = prjPropsFo.getInputStream()) {
				prjProps.load(insPrjProps);
			}

			final File xmlreport = Utils.getJacocoXmlReportfile(project);
			final File binreport = Utils.getJacocoBinReportFile(project);
			if (binreport.exists() && !binreport.delete() || xmlreport.exists() && !xmlreport.delete()) {
				String msg = "Cannot delete the previous JaCoCo report files, please delete them manually:\n"
						+ binreport.getAbsolutePath() + " and/or\n"
						+ xmlreport.getAbsolutePath();
				NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE);
				DialogDisplayer.getDefault().notify(nd);
			} else {
				// Apply JaCoCo JavaAgent customization.
				final String antTaskJavaagentParam;
				List<String> excludeList = cfg.getPkgclssExclude();
				StringBuilder exclude = new StringBuilder((excludeList.size() + 1) * 20);
				if (cfg.isOverrideGlobals() && !excludeList.isEmpty()) {
					exclude.append(",excludes=");
					boolean first = true;
					for (String pkg : excludeList) {
						if (!first) {
							exclude.append(':');
						}
						exclude.append(pkg).append(".*");
						first = false;
					}
				}

				// GWI patch: If NetBeans Module Project - use different JavaAgent settings
				final boolean isNBModule = Utils.isProjectSupported(NBUtils.getSelectedProject(), NBProjectTypeEnum.NBMODULE);
				String jacocoAgentJarAbsPath = NBUtils.getJacocoAgentJar().getAbsolutePath();
				
				
				
				if (isNBModule) {
					String excludes = prjProps.getProperty("jacoco.excludes");
					antTaskJavaagentParam = "\"" + jacocoAgentJarAbsPath
							+ "\"=destfile=\"" + binreport.getAbsolutePath() + "\"" + (excludes == null ? "" : ",excludes=" + excludes);
				} else {
					String packagesToTest = NBUtils.getProjectJavaPackagesAsStr(project, prjProps, ":", ".*");
					if (packagesToTest.length() > 1000) { // GitHub#26: JaCoCo seems to fail if the includes list is too long
						packagesToTest = "*";
					}
					antTaskJavaagentParam = "\"" + jacocoAgentJarAbsPath
							+ "\"=includes=" + packagesToTest
							+ ",destfile=\"" + binreport.getAbsolutePath() + "\"" + exclude.toString();
				}

				FileObject scriptToExecute = project.getProjectDirectory().getFileObject("build", "xml");
				if (scriptToExecute == null) { // Fix for GitHub #16.
					scriptToExecute = project.getProjectDirectory().getFileObject("nbbuild", "xml");
{'fraction_non_alphanumeric': 0.11512513601741023, 'fraction_numerical': 0.0024664490388103012, 'mean_word_length': 4.6592775041050905, 'pattern_counts': {'":': 2, '<': 27, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 16}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7064959', 'n_tokens_mistral': 4716, 'n_tokens_neox': 4104, 'n_words': 913}