file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
ProductInstr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ProductInstr.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter; import com.sun.tdk.jcov.instrument.asm.ClassMorph; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.InstrumentationParams; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.RuntimeUtils; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Andrey Titov */ public class ProductInstr extends JCovCMDTool { // instrumentation filters (include/exclude, fields, abstract, ...); removing temporary directory static final Logger logger; static { Utils.initLogger(); logger = Logger.getLogger(ProductInstr.class.getName()); } private File instrProductDir; private File instrOutputDir; private String template = MiscConstants.JcovTemplateFileNameXML; private String tempPath; private File rtLibFile; private String[] rtClassDirTargets; private InstrumentationOptions.InstrumentationMode mode = InstrumentationOptions.InstrumentationMode.BRANCH; private String[] include = new String[]{".*"}; private String[] exclude = new String[]{""}; private String[] m_include = new String[]{".*"}; private String[] m_exclude = new String[]{""}; private String[] callerInclude; private String[] callerExclude; public void instrumentProduct() throws IOException { logger.log(Level.INFO, " - Instrumenting product"); logger.log(Level.CONFIG, "Product location: ''{0}'', target location: ''{1}''", new Object[]{instrProductDir.getPath(), instrOutputDir.getPath()}); tempPath = instrProductDir.getPath() + RuntimeUtils.genSuffix(); createTempDir(); AbstractUniversalInstrumenter instrumenter = setupInstrumenter(); instrOutputDir.mkdir(); instrumenter.instrument(instrProductDir, instrOutputDir, rtLibFile.getAbsolutePath(), rtClassDirTargets == null ? null : new ArrayList(Arrays.asList(rtClassDirTargets)), true); instrumenter.finishWork(); removeTempDir(); } private AbstractUniversalInstrumenter setupInstrumenter() { InstrumentationParams params = new InstrumentationParams(true, false, false, false, false, false, InstrumentationOptions.ABSTRACTMODE.NONE, include, exclude, callerInclude, callerExclude, m_include, m_exclude, mode, null, null) .setInstrumentAnonymous(true) .setInstrumentSynthetic(false); final ClassMorph morph = new ClassMorph(params, null); return new AbstractUniversalInstrumenter(true) { @Override protected byte[] instrument(byte[] classData, int classLength) throws IOException { return morph.morph(classBuf, null, tempPath); } @Override public void finishWork() { morph.saveData(template, null, InstrumentationOptions.MERGE.OVERWRITE); } }; } private void createTempDir() { new File(tempPath).mkdir(); logger.log(Level.INFO, "Temp directory for storing instrumented classes created: ''{0}''. Automatic removal is not implemented yet so please remove it manually after all is done.", tempPath); } private void removeTempDir() { File tempFile = new File(tempPath); if (tempFile.isDirectory()) { Utils.deleteDirectory(tempFile); } else { tempFile.delete(); } logger.log(Level.INFO, "Temp directory for storing instrumented classes deleted: ''{0}''.", tempPath); } @Override protected int run() throws Exception { instrumentProduct(); return SUCCESS_EXIT_CODE; } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TYPE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CALLER_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CALLER_EXCLUDE, DSC_INSTRUMENT, DSC_INSTRUMENT_TO, Instr.DSC_INCLUDE_RT, DSC_RT_TO,}, this); } @Override protected int handleEnv(EnvHandler envHandler) throws EnvHandlingException { instrProductDir = Utils.checkFileCanBeNull(envHandler.getValue(ProductInstr.DSC_INSTRUMENT), "product directory", Utils.CheckOptions.FILE_ISDIR, Utils.CheckOptions.FILE_CANREAD); instrOutputDir = Utils.checkFileCanBeNull(envHandler.getValue(ProductInstr.DSC_INSTRUMENT_TO), "directory for instrumented product", Utils.CheckOptions.FILE_NOTEXISTS, Utils.CheckOptions.FILE_CANWRITE); if (instrProductDir != null && instrOutputDir == null) { throw new EnvHandlingException("Output directory for instrumented files should be specified in '-instrOutput'"); } rtLibFile = Utils.checkFileCanBeNull(envHandler.getValue(Instr.DSC_INCLUDE_RT), "JCov RT Saver path", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_ISFILE, Utils.CheckOptions.FILE_CANREAD); if (rtLibFile == null) { throw new EnvHandlingException("Please specify saver location with '-rt' option"); } rtClassDirTargets = envHandler.getValues(ProductInstr.DSC_RT_TO); if (envHandler.getValue(InstrumentationOptions.DSC_TYPE) != null) { mode = InstrumentationOptions.InstrumentationMode.fromString(envHandler.getValue(InstrumentationOptions.DSC_TYPE)); } include = InstrumentationOptions.handleInclude(envHandler); exclude = InstrumentationOptions.handleExclude(envHandler); m_include = InstrumentationOptions.handleMInclude(envHandler); m_exclude = InstrumentationOptions.handleMExclude(envHandler); callerInclude = envHandler.getValues(InstrumentationOptions.DSC_CALLER_INCLUDE); callerExclude = envHandler.getValues(InstrumentationOptions.DSC_CALLER_EXCLUDE); return SUCCESS_EXIT_CODE; } @Override protected String getDescr() { return ""; } @Override protected String usageString() { return ""; } @Override protected String exampleString() { return ""; } public final static OptionDescr DSC_INSTRUMENT = new OptionDescr("product", "", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_INSTRUMENT_TO = new OptionDescr("productOutput", "", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_RT_TO = new OptionDescr("rtTo", "", OptionDescr.VAL_MULTI, ""); }
8,859
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JREInstr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/JREInstr.java
/* * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.runtime.JCovSESocketSaver; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.*; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Objects; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import static com.sun.tdk.jcov.util.Utils.CheckOptions.*; import static com.sun.tdk.jcov.util.Utils.getListFiles; /** * <p> A tool to statically instrument JRE. </p> <p> There are 2 coverage * collection modes: static and dynamic. In static mode JCov reads and modifies * classes bytecode inserting there some instructions which will use JCov RT * libraries. In dynamic mode (aka Agent mode) a VM agent is used ("java * -javaagent") that instruments bytecode just at loadtime. </p> * * @author Andrey Titov * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class JREInstr extends JCovCMDTool { private Instr instr; private File toInstrument; private File[] addJars; private File[] addJimages; private File[] addTests; private File implant; private static final Logger logger; private String host = null; private Integer port = null; static { Utils.initLogger(); logger = Logger.getLogger(Instr.class.getName()); } /** * tries to find class in the specified jars */ public static class StaticJREInstrClassLoader extends URLClassLoader { StaticJREInstrClassLoader(URL[] urls) { super(urls); } @Override public InputStream getResourceAsStream(String s) { InputStream in = null; try { in = findResource(s).openStream(); } catch (IOException ignore) { //nothing to do } if (in != null) { return in; } return super.getResourceAsStream(s); } } @Override protected int run() throws Exception { final String[] toInstr = new String[]{toInstrument.getAbsolutePath()}; Utils.addToClasspath(toInstr); instr.startWorking(); StaticJREInstrClassLoader cl = new StaticJREInstrClassLoader(new URL[]{toInstrument.toURI().toURL()}); instr.setClassLoader(cl); instr.fixJavaBase(); if (toInstrument.getName().equals("jmods")) { logger.log(Level.INFO, "working with jmods"); File jdk = new File(toInstrument.getParentFile(), "jdk"); if (!jdk.exists()) { jdk = toInstrument.getParentFile(); } File jmodsTemp = new File(toInstrument.getParentFile(), "jmod_temp"); ArrayList<URL> urls = new ArrayList<>(); for (File mod : getListFiles(toInstrument)) { File jmodDir = extractJMod(jdk, mod.getAbsoluteFile(), jmodsTemp); urls.add(new File(jmodDir, "classes").toURI().toURL()); } urls.add(toInstrument.toURI().toURL()); cl = new StaticJREInstrClassLoader(urls.toArray(new URL[0])); instr.setClassLoader(cl); try { for (File mod : getListFiles(jmodsTemp)) { if (mod != null && mod.isDirectory()) { File modClasses = new File(mod, "classes"); instr.instrumentFile(modClasses.getAbsolutePath(), null, null, mod.getName()); createJMod(mod, jdk, implant.getAbsolutePath(), (instr.getPlugin() != null && instr.getPlugin().runtime() != null) ? instr.getPlugin().runtime().toString() : null); } } File newJdkDir = runJLink(jmodsTemp, jdk); if (newJdkDir != null) { String jimage_path = File.separator + "lib" + File.separator + "modules" + File.separator + "bootmodules.jimage"; File orig_jimage = new File(jdk.getCanonicalPath() + jimage_path); File instr_jimage = new File(newJdkDir.getCanonicalPath() + jimage_path); if (!orig_jimage.exists()) { jimage_path = File.separator + "lib" + File.separator + "modules"; orig_jimage = new File(jdk.getCanonicalPath() + jimage_path); instr_jimage = new File(newJdkDir.getCanonicalPath() + jimage_path); } Utils.copyFile(orig_jimage, new File(orig_jimage.getParent(), orig_jimage.getName() + ".bak")); if (!orig_jimage.delete()) { Utils.copyFile(instr_jimage, new File(orig_jimage.getParent(), orig_jimage.getName() + ".instr")); logger.log(Level.SEVERE, "please, delete original jimage manually: " + orig_jimage); } else { Utils.copyFile(instr_jimage, orig_jimage); } if (!Utils.deleteDirectory(newJdkDir)) { logger.log(Level.SEVERE, "please, delete " + newJdkDir + " new instumented jdk dir manually"); } if (!Utils.deleteDirectory(jmodsTemp)) { logger.log(Level.SEVERE, "please, delete " + jmodsTemp + " temp jmod dir manually"); } } else { logger.log(Level.SEVERE, "failed to link modules. Please, run jlink for " + jmodsTemp + " temp jmod dir manually"); } } catch (Exception e) { logger.log(Level.SEVERE, "exception while creating mods, e = " + e); } } else if (toInstrument.getAbsolutePath().endsWith("bootmodules.jimage")) { throw new RuntimeException("This functionality has not yet been implemented"); // ArrayList<File> jdkImages = new ArrayList<>(); // jdkImages.add(toInstrument); // if (addJimages != null) { // Collections.addAll(jdkImages, addJimages); // } // // for (File jimageInstr : jdkImages) { // String tempDirName = jimageInstr.getName().substring(0, jimageInstr.getName().indexOf(".jimage")); // // expandJimage(jimageInstr, tempDirName); // // File dirtoInstrument = new File(jimageInstr.getParent(), tempDirName); //// still need it // Utils.addToClasspath(new String[]{dirtoInstrument.getAbsolutePath()}); // for (File file : getListFiles(dirtoInstrument)) { // if (file.isDirectory()) { // Utils.addToClasspath(new String[]{file.getAbsolutePath()}); // } // } // // if (jimageInstr.equals(toInstrument)) { // for (File mod : getListFiles(dirtoInstrument)) { // if (mod != null && mod.isDirectory()) { // // if ("java.base".equals(mod.getName())) { // instr.instrumentFile(mod.getAbsolutePath(), null, implant.getAbsolutePath(), mod.getName()); // } else { // instr.instrumentFile(mod.getAbsolutePath(), null, null, mod.getName()); // } // } // } // } else { // for (File mod : getListFiles(dirtoInstrument)) { // if (mod != null && mod.isDirectory()) { // instr.instrumentFile(mod.getAbsolutePath(), null, null, mod.getName()); // } // } // } // createJimage(dirtoInstrument, jimageInstr.getAbsolutePath() + "i"); // } // for (File jimageInstr : jdkImages) { // // String tempDirName = jimageInstr.getName().substring(0, jimageInstr.getName().indexOf(".jimage")); // File dirtoInstrument = new File(jimageInstr.getParent(), tempDirName); // if (!Utils.deleteDirectory(dirtoInstrument)) { // logger.log(Level.SEVERE, "please, delete " + tempDirName + " jimage dir manually"); // } // // Utils.copyFile(jimageInstr, new File(jimageInstr.getParent(), jimageInstr.getName() + ".bak")); // // if (!jimageInstr.delete()) { // logger.log(Level.SEVERE, "please, delete original jimage manually: " + jimageInstr); // } else { // Utils.copyFile(new File(jimageInstr.getAbsolutePath() + "i"), jimageInstr); // new File(jimageInstr.getAbsolutePath() + "i").delete(); // } // // } } else { throw new RuntimeException("This functionality has not yet been implemented"); // instr.instrumentFile(toInstrument.getAbsolutePath(), null, implant.getAbsolutePath()); } ArrayList<String> srcs = null; if (addJars != null) { srcs = new ArrayList<>(); for (File addJar : addJars) { srcs.add(addJar.getAbsolutePath()); } } if (srcs != null) { Utils.addToClasspath(srcs.toArray(new String[0])); instr.instrumentFiles(srcs.toArray(new String[0]), null, null); } if (addTests != null) { ArrayList<String> tests = new ArrayList<>(); for (File addTest : addTests) { tests.add(addTest.getAbsolutePath()); } instr.instrumentTests(tests.toArray(new String[0]), null, null); } instr.finishWork(); return SUCCESS_EXIT_CODE; } private boolean doCommand(String command, File where, String msg) throws IOException, InterruptedException { Objects.requireNonNull(command); Objects.requireNonNull(msg); boolean success; StringBuilder sb = new StringBuilder(msg + command); ProcessBuilder pb = new ProcessBuilder(command.split("\\s+")).directory(where).redirectErrorStream(true); Process p = null; try { p = pb.start(); try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String s; while ((s = br.readLine()) != null) { sb.append(System.lineSeparator()).append('\t').append(s); } success = p.waitFor() == 0; } if (!success) { logger.log(Level.SEVERE, sb.toString()); } } finally { if (p != null) { p.destroy(); } } return success; } private File extractJMod(File jdk, File from, File to) { try { String name = from.getName(); if (name.contains(".jmod")) { name = name.substring(0, name.indexOf(".jmod")); } File modDir = new File(to, name); modDir.mkdirs(); String command = jdk.getAbsolutePath() + File.separator + "bin" + File.separator + "jar xf " + from.getAbsolutePath(); if (!doCommand(command, modDir, "wrong command for unjar jmod: ")) { return null; } return modDir; } catch (Exception e) { logger.log(Level.SEVERE, "exception in process(unjar jmod)", e); return null; } } private File runJLink(File jmodDir, File jdk) { try { String command = jdk.getAbsolutePath() + File.separator + "bin" + File.separator + "jlink --module-path " + jmodDir.getCanonicalPath() + " --add-modules "; StringBuilder sb = new StringBuilder(); for (File subDir : getListFiles(jmodDir)) { if (subDir.isDirectory()) { sb.append(subDir.getName()).append(","); } } String mods = sb.substring(0, sb.toString().length() - 1); command += mods + " --output instr_jimage_dir"; if (!doCommand(command, jmodDir.getParentFile(), "wrong command for jlink mods: ")) { return null; } } catch (Exception e) { logger.log(Level.SEVERE, "exception in process(jlink mods)", e); return null; } return new File(jmodDir.getParentFile(), "instr_jimage_dir"); } private void createJMod(File jmodDir, File jdk, String rt_path, String pluginPath) { try { File modsDir = jmodDir.getParentFile(); StringBuilder command = new StringBuilder(); command.append(jdk.getAbsolutePath()).append(File.separator).append("bin").append(File.separator). append("jmod create "). append("--module-path ").append(modsDir.getCanonicalPath()).append(" "); for (File subDir : getListFiles(jmodDir)) { if (subDir.getName().equals("classes")) { if ("java.base".equals(jmodDir.getName())) { command.append("--class-path " + rt_path); if(pluginPath != null) { command.append(File.pathSeparator + pluginPath); } command.append(File.pathSeparator + jmodDir.getName() + File.separator + "classes "); } else { command.append("--class-path " + jmodDir.getName() + File.separator + "classes "); } } if (subDir.getName().equals("bin")) { command.append("--cmds " + jmodDir.getName() + File.separator + "bin "); } if (subDir.getName().equals("conf")) { command.append("--config " + jmodDir.getName() + File.separator + "conf "); } if (subDir.getName().equals("lib")) { command.append("--libs " + jmodDir.getName() + File.separator + "lib "); } if (subDir.getName().equals("include")) { command.append("--header-files " + jmodDir.getName() + File.separator + "include "); } if (subDir.getName().equals("legal")) { command.append("--legal-notices " + jmodDir.getName() + File.separator + "legal "); } if (subDir.getName().equals("man")) { command.append("--man-pages " + jmodDir.getName() + File.separator + "man "); } } command.append(" " + jmodDir.getName() + ".jmod"); doCommand(command.toString(),modsDir,"wrong command for create jmod: "); } catch (Exception e) { logger.log(Level.SEVERE, "exception in process(create jmod)", e); } } private void expandJimage(File jimage, String tempDirName) { try { String command = jimage.getParentFile().getParentFile().getParent() + File.separator + "bin" + File.separator + "jimage extract --dir " + jimage.getParent() + File.separator + tempDirName + " " + jimage.getAbsolutePath(); doCommand(command, null, "wrong command for expand jimage: "); } catch (Exception e) { logger.log(Level.SEVERE, "exception in process(expanding jimage)", e); } } private boolean createJimage(File dir, String new_jimage_path) { try { String command = dir.getParentFile().getParentFile().getParent() + File.separator + "bin" + File.separator + "jimage recreate --dir " + dir + " " + new_jimage_path; return doCommand(command, null, "wrong command for create jimage: "); } catch (Exception e) { logger.log(Level.SEVERE, "exception in process(expanding jimage)", e); return false; } } @Override protected EnvHandler defineHandler() { Instr.DSC_INCLUDE_RT.usage = "To run instrumented JRE you should implant JCov runtime library both into rt.jar " + "and into 'lib/endorsed' directory.\nWhen instrumenting whole JRE dir with jreinstr tool - " + "these 2 actions will be done automatically."; return new EnvHandler(new OptionDescr[]{ Instr.DSC_INCLUDE_RT, Instr.DSC_VERBOSE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TYPE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CALLER_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_CALLER_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TEMPLATE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ABSTRACT, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_NATIVE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FIELD, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_SYNTHETIC, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ANONYM, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INNERINVOCATION, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INNER_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INNER_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INSTR_PLUGIN, Instr.DSC_SUBSEQUENT, DSC_JAVAC_HACK, DCS_ADD_JAR, DCS_ADD_JIMAGE, DCS_ADD_TESTS, DSC_HOST, DSC_PORT }, this); } @Override protected int handleEnv(EnvHandler envHandler) throws EnvHandlingException { instr = new Instr(); String[] tail = envHandler.getTail(); if (tail == null || tail.length == 0) { throw new EnvHandlingException("JRE dir is not specified"); } if (tail.length > 1) { logger.log(Level.WARNING, "Only first argument ({0}) will be used", tail[0]); } if (!envHandler.isSet(Instr.DSC_INCLUDE_RT)) { throw new EnvHandlingException("Runtime should be always implanted when instrumenting rt.jar (e.g. '-rt jcov_j2se_rt.jar')"); } implant = new File(envHandler.getValue(Instr.DSC_INCLUDE_RT)); Utils.checkFile(implant, "JCovRT library jarfile", FILE_ISFILE, FILE_EXISTS, FILE_CANREAD); if (envHandler.isSet(DCS_ADD_JAR)) { String[] jars = envHandler.getValues(DCS_ADD_JAR); addJars = new File[jars.length]; for (int i = 0; i < addJars.length; ++i) { addJars[i] = new File(jars[i]); if (!addJars[i].exists()) { throw new EnvHandlingException("Additional jar " + jars[i] + " doesn't exist"); } if (!addJars[i].canRead()) { throw new EnvHandlingException("Can't read additional jar " + jars[i]); } } } if (envHandler.isSet(DCS_ADD_JIMAGE)) { String[] images = envHandler.getValues(DCS_ADD_JIMAGE); addJimages = new File[images.length]; for (int i = 0; i < addJimages.length; ++i) { addJimages[i] = new File(images[i]); if (!addJimages[i].exists()) { throw new EnvHandlingException("Additional jimage " + images[i] + " doesn't exist"); } if (!addJimages[i].canRead()) { throw new EnvHandlingException("Can't read additional jimage " + images[i]); } } } if (envHandler.isSet(DCS_ADD_TESTS)) { String[] files = envHandler.getValues(DCS_ADD_TESTS); addTests = new File[files.length]; for (int i = 0; i < addTests.length; ++i) { addTests[i] = new File(files[i]); if (!addTests[i].exists()) { throw new EnvHandlingException("Test file " + files[i] + " doesn't exist"); } if (!addTests[i].canRead()) { throw new EnvHandlingException("Can't read test file " + files[i]); } } } File f = new File(tail[0]); Utils.checkFile(f, "JRE directory", FILE_EXISTS, FILE_ISDIR, FILE_CANREAD); if (envHandler.isSet(DSC_HOST)) { host = envHandler.getValue(DSC_HOST); } if (envHandler.isSet(DSC_PORT)) { try { port = Integer.valueOf(envHandler.getValue(DSC_PORT)); } catch (NumberFormatException nfe) { throw new EnvHandlingException("Specify correct port number"); } } if (envHandler.isSet(DSC_JAVAC_HACK)) { String javacPath = envHandler.getValue(DSC_JAVAC_HACK); File javac = new File(javacPath); File newJavac; boolean isWin = false; if (javacPath.endsWith(".exe") && System.getProperty("os.name").toLowerCase().contains("win")) { newJavac = new File(javac.getParent() + File.separator + "javac_real.exe"); isWin = true; } else { newJavac = new File(javac.getParent() + File.separator + "javac_real"); } if (newJavac.exists()) { if (javac.exists()) { logger.log(Level.INFO, "javac seems to be already hacked: {0} exists", newJavac.getPath()); } else { try { if (!isWin) { File newFile = new File(javacPath); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(newFile), StandardCharsets.UTF_8); out.write(newJavac.getAbsolutePath() + " -J-Xms30m \"$@\""); out.flush(); out.close(); try { newFile.setExecutable(true); } catch (Exception e) { logger.log(Level.WARNING, "Can't make new hacked javac file executable: {0}", e.getMessage()); } } else { File newFile = new File(javacPath.replaceAll(".exe", ".bat")); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(newFile), StandardCharsets.UTF_8); out.write(newJavac.getAbsolutePath() + " -J-Xms30m %*"); out.flush(); out.close(); } } catch (IOException ex) { Logger.getLogger(JREInstr.class.getName()).log(Level.SEVERE, null, ex); } } } else { if (!javac.exists()) { throw new EnvHandlingException("Specified javac doesn't exist (" + javacPath + ")"); } if (!javac.isFile()) { throw new EnvHandlingException("Specified javac is not a file (" + javacPath + ")"); } if (!javac.canWrite()) { throw new EnvHandlingException("Can't modify specified javac (" + javacPath + ")"); } if (!javac.renameTo(newJavac)) { throw new EnvHandlingException("Can't move specified javac to new location" + " (" + javacPath + " to " + newJavac.getPath() + ")"); } try { if (!isWin) { File newFile = new File(javacPath); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(newFile), StandardCharsets.UTF_8); out.write(newJavac.getAbsolutePath() + " $@ -J-Xms30m"); out.flush(); out.close(); try { newFile.setExecutable(true); } catch (Exception e) { logger.log(Level.WARNING, "Can't make new hacked javac file executable: {0}", e.getMessage()); } } else { File newFile = new File(javacPath.replaceAll(".exe", ".bat")); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(newFile), StandardCharsets.UTF_8); out.write(newJavac.getAbsolutePath() + " -J-Xms30m %*"); out.flush(); out.close(); } } catch (IOException ex) { Logger.getLogger(JREInstr.class.getName()).log(Level.SEVERE, null, ex); } } } if (!f.isDirectory()) { throw new EnvHandlingException("Specified JRE is not a directory: " + f.getPath()); } else { // instrumenting JRE dir - check ${JRE}/lib/rt.jar, move ${JRE}/lib/rt.jar to ${JRE}/lib/rt.jar.bak (if not exist), // add copy ${JRE}/lib/endorsed/${implant.jar} File lib = new File(f, "lib"); if (!lib.exists()) { throw new EnvHandlingException("lib directory was not found in JRE directory"); } String template = envHandler.getValue(InstrumentationOptions.DSC_TEMPLATE); if (template != null) { instr.setTemplate(template); } File mods = new File(f.getParentFile(), "jmods"); if (mods.exists()) { toInstrument = mods; createPropertyFile(f); } else if (new File(f, "jmods").exists()){ toInstrument = new File(f, "jmods"); createPropertyFile(toInstrument.getParentFile()); } else { toInstrument = new File(lib, "modules"); if (!toInstrument.exists()) { toInstrument = new File(lib, "rt.jar"); if (!toInstrument.exists()) { throw new EnvHandlingException("rt.jar directory was not found in lib directory"); } if (!toInstrument.isFile() || !toInstrument.canRead() || !toInstrument.canWrite()) { throw new EnvHandlingException("Can't read/write rt.jar (or not a file)"); } File bak = new File(lib, "rt.jar.bak"); if (!bak.exists()) { try { Utils.copyFile(toInstrument, bak); } catch (FileNotFoundException ex) { throw new EnvHandlingException("Error while backuping rt.jar: file not found", ex); } catch (IOException ex) { throw new EnvHandlingException("Error while backuping rt.jar", ex); } } else { if (!envHandler.isSet(Instr.DSC_SUBSEQUENT)) { throw new EnvHandlingException("Backup rt.jar.bak file exists.\n" + "It can mean that JRE is already instrumented - nothing to do.\n" + "Restore initial rt.jar or delete bak file."); } } File endorsed = new File(lib, "endorsed"); if (!endorsed.exists()) { endorsed.mkdir(); } else { if (!endorsed.isDirectory()) { throw new EnvHandlingException("JRE/lib/endorsed is not a directory"); } } File implantcopy = new File(endorsed, implant.getName()); try { // copy rt to endorsed dir Utils.copyFile(implant, implantcopy); createPropertyFile(endorsed); } catch (FileNotFoundException ex) { throw new EnvHandlingException("Error while copying implant file to endorsed dir: file not found", ex); } catch (IOException ex) { throw new EnvHandlingException("Error while copying implant file to endorsed dir", ex); } } else { toInstrument = new File(toInstrument, "bootmodules.jimage"); if (!toInstrument.exists()) { throw new EnvHandlingException("bootmodules.jimage was not found in modules directory"); } if (!toInstrument.isFile() || !toInstrument.canRead() || !toInstrument.canWrite()) { throw new EnvHandlingException("Can't read/write bootmodules.jimage"); } File bak = new File(toInstrument.getParent(), "bootmodules.jimage.bak"); if (!bak.exists()) { try { Utils.copyFile(toInstrument, bak); } catch (FileNotFoundException ex) { throw new EnvHandlingException("Error while backing up bootmodules.jimage: file not found", ex); } catch (IOException ex) { throw new EnvHandlingException("Error while backing up bootmodules.jimage", ex); } } else { if (!envHandler.isSet(Instr.DSC_SUBSEQUENT)) { throw new EnvHandlingException("Backup bootmodules.jimage.bak file exists.\n" + "It can mean that JRE is already instrumented - nothing to do.\n" + "Restore initial bootmodules.jimage or delete bak file."); } } } } } // check that java/lang/Shutdown is not excluded String[] excludes = com.sun.tdk.jcov.instrument.InstrumentationOptions.handleExclude(envHandler); String[] includes = com.sun.tdk.jcov.instrument.InstrumentationOptions.handleInclude(envHandler); Utils.Pattern pats[] = Utils.concatFilters(includes, excludes); String[] m_excludes = com.sun.tdk.jcov.instrument.InstrumentationOptions.handleMExclude(envHandler); String[] m_includes = com.sun.tdk.jcov.instrument.InstrumentationOptions.handleMInclude(envHandler); String[] callerInclude = envHandler.getValues(InstrumentationOptions.DSC_CALLER_INCLUDE); String[] callerExclude = envHandler.getValues(InstrumentationOptions.DSC_CALLER_EXCLUDE); String[] innerInclude = InstrumentationOptions.handleInnerInclude(envHandler); String[] innerExclude = InstrumentationOptions.handleInnerExclude(envHandler); if (!Utils.accept(pats, null, "/java/lang/Shutdown", null)) { // Shutdown was excluded with some filtering mechanism. No need to remove it from excludes as inclusion has more priority logger.log(Level.WARNING, "java.lang.Shutdown automatically included to instrumentation (it can't be excluded in jreinstr)"); if (includes.length > 0) { // if something else is already included - just including Shutdown includes = Utils.copyOf(includes, includes.length + 1); includes[includes.length - 1] = "/java/lang/Shutdown"; } else { includes = new String[]{"/java/lang/Shutdown", "/*"}; } } if (!Utils.accept(pats, null, "/java/lang/invoke/LambdaForm", null)) { logger.log(Level.WARNING, "java.lang.invoke.LambdaForm automatically included to instrumentation (it can't be excluded in jreinstr)"); if (includes.length > 0) { // if something else is already included - just including Shutdown includes = Utils.copyOf(includes, includes.length + 1); includes[includes.length - 1] = "/java/lang/invoke/LambdaForm"; } else { includes = new String[]{"/java/lang/invoke/LambdaForm", "/*"}; } } int ret = instr.handleEnv(envHandler); instr.setSave_end(new String[]{"java/lang/Shutdown.runHooks"}); instr.setInclude(includes); instr.setExclude(excludes); instr.setMInclude(m_includes); instr.setMExclude(m_excludes); instr.setCallerInclude(callerInclude); instr.setCallerExclude(callerExclude); instr.setInnerInclude(innerInclude); instr.setInnerExclude(innerExclude); return ret; } private void createPropertyFile(File dir){ if (host != null || port != null) { Properties prop = new Properties(); try { if (host != null) { prop.setProperty(JCovSESocketSaver.HOST_PROPERTIES_NAME, host); } if (port != null) { prop.setProperty(JCovSESocketSaver.PORT_PROPERTIES_NAME, Integer.toString(port)); } prop.store(new FileOutputStream(dir.getAbsolutePath() + File.separator + JCovSESocketSaver.NETWORK_DEF_PROPERTIES_FILENAME), null); } catch (IOException ex) { logger.log(Level.WARNING, "Cannot create property file to save host and port: {0}", ex); } } } @Override protected String getDescr() { return "instrumenter designed for instumenting rt.jar"; } @Override protected String usageString() { return "java -jar jcov.jar jreinstr -implantrt <runtime_to_implant> <jre_dir>"; } @Override protected String exampleString() { return "To instrument JRE: \"java -jar jcov.jar jreinstr -implantrt jcov_j2se_rt.jar JDK1.7.0/jre\""; } public static final OptionDescr DSC_JAVAC_HACK = new OptionDescr("javac", "hack javac", OptionDescr.VAL_SINGLE, "Hack javac to increase minimum VM memory used on initialization. Should be used on Solaris platform or should be done manually. "); public static final OptionDescr DCS_ADD_JAR = new OptionDescr("addjar", new String[]{"add"}, "instrument additional jars", OptionDescr.VAL_MULTI, "Instrument additional jars within JRE or JDK. Only jar files are allowed."); public static final OptionDescr DCS_ADD_JIMAGE = new OptionDescr("addjimage", new String[]{"addjimage"}, "instrument additional jimages", OptionDescr.VAL_MULTI, "Instrument additional jimages within JRE or JDK. Only jimage files are allowed."); public static final OptionDescr DCS_ADD_TESTS = new OptionDescr("addtests", new String[]{"tests"}, "instrument tests", OptionDescr.VAL_MULTI, "Instrument tests files (classes and jars)."); final static OptionDescr DSC_HOST = new OptionDescr("host", new String[]{"host"}, "sets default host", OptionDescr.VAL_SINGLE, "set the default host for sending jcov data. needed only in network mode"); final static OptionDescr DSC_PORT = new OptionDescr("port", new String[]{"port"}, "sets default port", OptionDescr.VAL_SINGLE, "set the default port for sending jcov data. needed only in network mode"); }
38,005
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
TmplGen.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/TmplGen.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter; import com.sun.tdk.jcov.instrument.asm.ClassMorph; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.InstrumentationOptions.InstrumentationMode; import com.sun.tdk.jcov.instrument.InstrumentationParams; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.*; /** * <p> Template generation. </p> <p> JCov Template file should be used to merge * dynamic data and to save static data. Template could be created while * statically instrumenting classes or with TmplGen tool. </p> * * @author Andrey Titov */ public class TmplGen extends JCovCMDTool { private String[] files; private AbstractUniversalInstrumenter instrumenter; private String flushPath; private String template; private String[] include; private String[] exclude; private String[] m_include; private String[] m_exclude; private boolean instrumentAbstract = false; private boolean instrumentNative = true; private boolean instrumentField = false; private boolean instrumentAnonymous = true; private boolean instrumentSynthetic = true; private InstrumentationOptions.InstrumentationMode mode; private String currentModule = null; /** * Legacy CMD line entry poiny (use 'java -jar jcov.jar TmplGen' from cmd * instead of 'java -cp jcov.jar com.sun.tdk.jcov.TmplGen') * * @param args */ public static void main(String args[]) { TmplGen tool = new TmplGen(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } protected String usageString() { return "java com.sun.tdk.jcov.TmplGen [options] filename"; } protected String exampleString() { return "java -cp jcov.jar com.sun.tdk.jcov.TmplGen -include java.lang.* -type method -template template.xml classes"; } protected String getDescr() { return "generates the jcov template.xml"; } @Override protected int run() throws Exception { try { generateAndSave(files); } catch (IOException ioe) { throw new Exception("Unexpected error during instrumentation", ioe); } return SUCCESS_EXIT_CODE; } private boolean expandJimage(File jimage, String tempDirName, boolean isModulesDir){ try { String command = ""; if (isModulesDir) { command = jimage.getParentFile().getParentFile().getParent() + File.separator + "bin" + File.separator + "jimage extract --dir " + jimage.getParent() + File.separator + tempDirName + " " + jimage.getAbsolutePath(); } else{ command = jimage.getParentFile().getParentFile() + File.separator + "bin" + File.separator + "jimage extract --dir " + jimage.getParent() + File.separator + tempDirName + " " + jimage.getAbsolutePath(); } Process process = Runtime.getRuntime().exec(command); process.waitFor(); if (process.exitValue() != 0) { //logger.log(Level.SEVERE, "wrong command for expand jimage: "+command); return false; } } catch (Exception e) { //logger.log(Level.SEVERE, "exception in process(expanding jimage)", e); return false; } return true; } public void generateAndSave(String[] files) throws IOException { setDefaultInstrumenter(); for (String root : files) { if (root.endsWith(".jimage")){ readJImage(new File(root), true); } else if (root.endsWith("modules") && (new File(root).isFile())) { readJImage(new File(root), false); } else{ instrumenter.instrument(new File(root), null); } } for (String root : files) { if (root.endsWith(".jimage")) { File rootFile = new File(root); Utils.deleteDirectory(new File(rootFile.getParentFile().getAbsolutePath() + File.separator + "temp_" + getJImageName(rootFile))); } if (root.endsWith("modules")){ File rootFile = new File(root); if (rootFile.isFile()){ Utils.deleteDirectory(new File(rootFile.getParentFile().getAbsolutePath() + File.separator + "temp_modules")); } } } instrumenter.finishWork(); instrumenter = null; } private void readJImage(File rootFile, boolean isModulesDir) throws IOException{ String jimagename = "modules"; if (isModulesDir) { jimagename = getJImageName(rootFile); } expandJimage(rootFile, "temp_"+jimagename, isModulesDir); File tempJimage = new File(rootFile.getParentFile().getAbsolutePath()+File.separator+"temp_"+jimagename); //still need it Utils.addToClasspath(new String[]{tempJimage.getAbsolutePath()}); for (File file:tempJimage.listFiles()){ if (file.isDirectory()){ Utils.addToClasspath(new String[]{file.getAbsolutePath()}); } } for (File file:tempJimage.listFiles()){ if (file.isDirectory()){ currentModule = file.getName(); instrumenter.instrument(file, null); } } } private String getJImageName(File jimage){ String jimagename = jimage.getName(); int pos = jimagename.lastIndexOf("."); if (pos > 0) { jimagename = jimagename.substring(0, pos); } return jimagename; } public void generateTemplate(String[] files) throws IOException { if (instrumenter == null) { setDefaultInstrumenter(); } for (String root : files) { instrumenter.instrument(new File(root), null); } } public void finishWork() { if (instrumenter == null) { throw new IllegalStateException("Instrumenter is not ready"); } instrumenter.finishWork(); instrumenter = null; } public void setDefaultInstrumenter() { if (instrumenter == null) { instrumenter = new AbstractUniversalInstrumenter(true, true) { ClassMorph morph = new ClassMorph( new InstrumentationParams(instrumentNative, instrumentField, instrumentAbstract, include, exclude, m_include, m_exclude, mode) .setInstrumentAnonymous(instrumentAnonymous) .setInstrumentSynthetic(instrumentSynthetic), template); protected byte[] instrument(byte[] classData, int classLen) throws IOException { // byte[] res = Arrays.copyOf(classData, classLen); byte[] res = new byte[classLen]; System.arraycopy(classData, 0, res, 0, classLen); morph.setCurrentModuleName(currentModule); morph.morph(res, null, flushPath); // jdk1.5 support return res; } public void finishWork() { morph.saveData(template, InstrumentationOptions.MERGE.MERGE); } }; } } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ // DSC_OUTPUT, DSC_VERBOSE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TEMPLATE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TYPE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ABSTRACT, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_NATIVE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FIELD, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_SYNTHETIC, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ANONYM, ClassMorph.DSC_FLUSH_CLASSES,}, this); } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { files = opts.getTail(); if (files == null) { throw new EnvHandlingException("No input files specified"); } if (opts.isSet(DSC_VERBOSE)) { Utils.setLoggingLevel(Level.INFO); } Utils.addToClasspath(files); flushPath = opts.getValue(ClassMorph.DSC_FLUSH_CLASSES); if ("none".equals(flushPath)) { flushPath = null; } String abstractValue = opts.getValue(InstrumentationOptions.DSC_ABSTRACT); if (abstractValue.equals("off")) { instrumentAbstract = false; } else if (abstractValue.equals("on")) { instrumentAbstract = true; } else { throw new EnvHandlingException("'" + InstrumentationOptions.DSC_ABSTRACT.name + "' parameter value error: expected 'on' or 'off'; found: '" + abstractValue + "'"); } String nativeValue = opts.getValue(InstrumentationOptions.DSC_NATIVE); if (nativeValue.equals("on")) { instrumentNative = true; } else if (nativeValue.equals("off")) { instrumentNative = false; } else { throw new EnvHandlingException("'" + InstrumentationOptions.DSC_NATIVE.name + "' parameter value error: expected 'on' or 'off'; found: '" + nativeValue + "'"); } String fieldValue = opts.getValue(InstrumentationOptions.DSC_FIELD); if (fieldValue.equals("on")) { instrumentField = true; } else if (fieldValue.equals("off")) { instrumentField = false; } else { throw new EnvHandlingException("'" + InstrumentationOptions.DSC_FIELD.name + "' parameter value error: expected 'on' or 'off'; found: '" + fieldValue + "'"); } String anonym = opts.getValue(InstrumentationOptions.DSC_ANONYM); if (anonym.equals("on")) { instrumentAnonymous = true; } else { // off instrumentAnonymous = false; } String synth = opts.getValue(InstrumentationOptions.DSC_SYNTHETIC); if (synth.equals("on")) { instrumentSynthetic = true; } else { // off instrumentSynthetic = false; } mode = InstrumentationOptions.InstrumentationMode.fromString(opts.getValue(InstrumentationOptions.DSC_TYPE)); template = opts.getValue(InstrumentationOptions.DSC_TEMPLATE); File tmpl = new File(template); if (tmpl.isDirectory()) { throw new EnvHandlingException("'" + template + "' is a directory while expected template filename"); } if (tmpl.getParentFile() != null && !tmpl.getParentFile().exists()) { throw new EnvHandlingException("Template parent directory '" + tmpl.getParentFile() + "' doesn't exits"); } include = InstrumentationOptions.handleInclude(opts); exclude = InstrumentationOptions.handleExclude(opts); m_exclude = com.sun.tdk.jcov.instrument.InstrumentationOptions.handleMExclude(opts); m_include = com.sun.tdk.jcov.instrument.InstrumentationOptions.handleMInclude(opts); com.sun.tdk.jcov.runtime.CollectDetect.enableInvokeCounts(); return SUCCESS_EXIT_CODE; } public String[] getExclude() { return exclude; } public void setExclude(String[] exclude) { this.exclude = exclude; } public String[] getMExclude() { return m_exclude; } public void setMExclude(String[] m_exclude) { this.m_exclude = exclude; } public String getFlushPath() { return flushPath; } public void setFlushPath(String flushPath) { this.flushPath = flushPath; } public String[] getInclude() { return include; } public void setInclude(String[] include) { this.include = include; } public String[] getMInclude() { return m_include; } public void setMInclude(String[] m_include) { this.m_include = m_include; } public boolean isInstrumentAbstract() { return instrumentAbstract; } public void setInstrumentAbstract(boolean instrumentAbstract) { this.instrumentAbstract = instrumentAbstract; } public boolean isInstrumentField() { return instrumentField; } public void setInstrumentField(boolean instrumentField) { this.instrumentField = instrumentField; } public boolean isInstrumentNative() { return instrumentNative; } public void setInstrumentNative(boolean instrumentNative) { this.instrumentNative = instrumentNative; } public InstrumentationMode getMode() { return mode; } public void setMode(InstrumentationMode mode) { this.mode = mode; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", "Verbosity", "Enables verbose mode."); }
15,630
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
RepGen.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/RepGen.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataField; import com.sun.tdk.jcov.processing.DataProcessorSPI; import com.sun.tdk.jcov.report.AncFilter; import com.sun.tdk.jcov.report.ParameterizedAncFilter; import com.sun.tdk.jcov.report.AncFilterFactory; import com.sun.tdk.jcov.util.Utils; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.processing.ProcessingException; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.filter.ConveyerFilter; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.filter.FilterFactory; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.io.ClassSignatureFilter; import com.sun.tdk.jcov.processing.DefaultDataProcessorSPI; import com.sun.tdk.jcov.processing.StubSpi; import com.sun.tdk.jcov.report.DefaultReportGeneratorSPI; import com.sun.tdk.jcov.report.ProductCoverage; import com.sun.tdk.jcov.report.ReportGenerator; import com.sun.tdk.jcov.report.ReportGeneratorSPI; import com.sun.tdk.jcov.report.SmartTestService; import com.sun.tdk.jcov.report.javap.JavapClass; import com.sun.tdk.jcov.report.javap.JavapRepGen; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.SPIDescr; import java.io.IOException; import java.util.ArrayList; import java.util.ServiceLoader; import java.util.logging.Level; import java.util.logging.Logger; import static com.sun.tdk.jcov.tools.OptionDescr.*; import java.io.File; import java.util.Arrays; import java.util.List; /** * <p> Report generation. </p> * * @author Andrey Titov * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class RepGen extends JCovCMDTool { final static String CUSTOM_REPORT_GENERATOR_SPI = "customreport.spi"; final static String DATA_PROCESSOR_SPI = "dataprocessor.spi"; private static final String ANC_FILTER_PARAMETER_SEPARATOR = ":"; // logger initialization static { Utils.initLogger(); logger = Logger.getLogger(RepGen.class.getName()); } private final static Logger logger; /** * Consider or not enums. true - means ignore enum classes. */ private boolean noEnums = false; /** * Whether show or not field coverage in the report (false by default). */ private boolean showFields = false; private ReportGeneratorSPI reportGeneratorSPIs[]; private DataProcessorSPI dataProcessorSPIs[]; private String[] include = new String[]{".*"}; private String[] exclude = new String[]{""}; private String[] m_include = new String[]{".*"}; private String[] m_exclude = new String[]{""}; private String[] fms = null; private String filter = null; private String[] ancfilters = null; private String[] ancdeffilters = null; private boolean noAbstract = false; private boolean syntheticOn = false; private boolean isPublicAPI = false; private String[] filenames; private String name; private String outputDir; private String testlist; private String srcRootPath; private boolean anonym = false; private boolean withTestsInfo = false; //path to the jar, dir or .class for javap repgen private String classesPath; private AncFilter[] ancfiltersClasses = null; private String mainReportTitle = null; private String overviewListTitle = null; private String entitiesTitle = null; public RepGen() { readPlugins = true; } /** * Generate report using default (html) report generator * * @param output * @param jcovResult * @throws ProcessingException * @throws FileFormatException * @throws Exception */ public void generateReport(String output, Result jcovResult) throws ProcessingException, FileFormatException, Exception { generateReport(getDefaultReportGenerator(), output, jcovResult, null); } /** * Generate report using specified format * * @param format * @param output * @param jcovResult * @throws ProcessingException * @throws FileFormatException * @throws Exception */ public void generateReport(String format, String output, Result jcovResult) throws ProcessingException, FileFormatException, Exception { generateReport(format, output, jcovResult, null); } /** * Generate report using specified format * * @param format * @param output * @param jcovResult * @param srcRootPath * @throws ProcessingException * @throws FileFormatException * @throws Exception */ public void generateReport(String format, String output, Result jcovResult, String srcRootPath) throws ProcessingException, FileFormatException, Exception { ReportGenerator rg = null; if (format != null) { rg = findReportGenerator(format); } else { rg = getDefaultReportGenerator(); } if (rg == null) { throw new Exception("Specified ReportGenerator name (" + format + ") was not found"); } generateReport(rg, output, jcovResult, srcRootPath); } /** * Generate report using specified report generator * * @param rg * @param output * @param jcovResult * @param srcRootPath * @throws ProcessingException * @throws FileFormatException * @throws Exception */ public void generateReport(ReportGenerator rg, String output, Result jcovResult, String srcRootPath) throws ProcessingException, FileFormatException, Exception { generateReport(rg, output, jcovResult, srcRootPath, null); } /** * Generate report using specified report generator * * @param rg * @param output * @param jcovResult * @param srcRootPath * @param classes parsed javap classes * @throws ProcessingException * @throws FileFormatException * @throws Exception */ public void generateReport(ReportGenerator rg, String output, Result jcovResult, String srcRootPath, List<JavapClass> classes) throws ProcessingException, FileFormatException, Exception { try { logger.log(Level.INFO, "-- Writing report to {0}", output); rg.init(output); logger.fine("OK"); } catch (Throwable ex) { logger.log(Level.SEVERE, "Error while reading output file by ReportGenerator " + rg.getClass().getName(), ex); return; } logger.log(Level.INFO, "-- Reading data from {0}", jcovResult.getResultPath()); DataRoot file_image = readDataRootFile(jcovResult.getResultPath(), jcovResult.isTestListSet(), include, exclude, fms); if (!syntheticOn) { file_image.applyFilter(new ANC_FILTER()); } MemberFilter customFilter = null; if (filter != null) { logger.fine("-- Initializing custom filter"); customFilter = initCustomFilter(filter, null); logger.fine("OK"); } if (customFilter != null) { logger.log(Level.INFO, "-- Applying filter {0}", customFilter.getClass().getName()); file_image.applyFilter(customFilter); logger.fine("OK"); } if (ancfilters != null){ ancfiltersClasses = new AncFilter[ancfilters.length]; for (int i = 0; i < ancfilters.length; i++) { try { String ancfilter = ancfilters[i]; Class ancFilteClass = Class.forName(ancfilter); ancfiltersClasses[i] = (AncFilter) ancFilteClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new Error("Cannot create an instance of " + "AncFilter: ", e); } } } if (ancdeffilters != null) { ServiceLoader<AncFilterFactory> loader = ServiceLoader.load(AncFilterFactory.class); List<AncFilter> defaultANCFiltersList = new ArrayList<AncFilter>(); if (ancfiltersClasses != null && ancfiltersClasses.length > 0) { defaultANCFiltersList.addAll(Arrays.asList(ancfiltersClasses)); } if (ancdeffilters.length == 1 && ancdeffilters[0].equals("all")) { for (AncFilterFactory factory : loader) { defaultANCFiltersList.addAll(factory.instantiateAll()); } } else { for (String defaulAncFilter : ancdeffilters) { boolean found = false; String filterName, filterParameters; int separatorPosition = defaulAncFilter.indexOf(ANC_FILTER_PARAMETER_SEPARATOR); if (separatorPosition > -1) { filterName = defaulAncFilter.substring(0, separatorPosition); filterParameters = defaulAncFilter.substring(separatorPosition + ANC_FILTER_PARAMETER_SEPARATOR.length()); } else { filterName = defaulAncFilter; filterParameters = null; } for (AncFilterFactory factory : loader) { AncFilter filter = factory.instantiate(filterName); if (filter != null) { if (filterParameters != null) { if (filter instanceof ParameterizedAncFilter) { try { ((ParameterizedAncFilter) filter).setParameter(filterParameters); } catch (Exception e) { throw new RuntimeException("Unable to set parameter for filter " + filterName + ":" + e.getMessage()); } } else { throw new RuntimeException(filterName + " filter does not accept parameters: " + filter); } } found = true; defaultANCFiltersList.add(filter); break; } } if (!found) { throw new RuntimeException("There is no ANC filter for \"" + defaulAncFilter + "\" value"); } } } ancfiltersClasses = defaultANCFiltersList.toArray(new AncFilter[defaultANCFiltersList.size()]); } if (dataProcessorSPIs != null) { for (DataProcessorSPI spi : dataProcessorSPIs) { logger.log(Level.INFO, "-- Applying data processor {0}", spi.getClass()); file_image = spi.getDataProcessor().process(file_image); } } logger.fine("OK"); SmartTestService sts = null; if (jcovResult.isTestListSet()) { logger.fine("-- Initializing test list"); sts = new SmartTestService(jcovResult.getTestList()); if (file_image.getScaleOpts().getScaleSize() != sts.getTestCount()) { logger.log(Level.SEVERE, "The sizes of tests in JCov file and in test list differ.\n" + "Datafile {0} contains {1} item(s).\nThe test list contains {2} item(s).", new Object[]{jcovResult.getResultPath(), file_image.getScaleOpts().getScaleSize(), sts.getTestCount()}); throw new Exception("The sizes of tests in JCov file and in test list differ"); } logger.fine("OK"); } ReportGenerator.Options options = new ReportGenerator.Options(srcRootPath, sts, classes, withTestsInfo, false, mainReportTitle, overviewListTitle, entitiesTitle); options.setInstrMode(file_image.getParams().getMode()); options.setAnonymOn(anonym); try { ProductCoverage coverage = new ProductCoverage(file_image, options.getSrcRootPaths(), options.getJavapClasses(), isPublicAPI, noAbstract, anonym, ancfiltersClasses); logger.log(Level.INFO, "-- Starting ReportGenerator {0}", rg.getClass().getName()); rg.generateReport(coverage, options); } catch (Throwable e) { throw e; } logger.log(Level.INFO, "-- Report generation done"); return; } /** * Get default (html) report generator * * @return default (html) report generator */ public ReportGenerator getDefaultReportGenerator() { return findReportGenerator("html"); } private ReportGenerator findReportGenerator(String name) { ReportGenerator rg = null; if (reportGeneratorSPIs != null) { for (ReportGeneratorSPI reportGeneratorSPI : reportGeneratorSPIs) { rg = reportGeneratorSPI.getReportGenerator(name); if (rg != null) { return rg; } } } return new DefaultReportGeneratorSPI().getReportGenerator(name); // can be null } protected DataRoot readDataRootFile(String filename, boolean readScales, String[] include, String[] exclude, String[] modif) throws FileFormatException { ClassSignatureFilter acceptor = new ClassSignatureFilter(include, exclude, m_include, m_exclude, modif); DataRoot file_image = Reader.readXML(filename, readScales, acceptor); return file_image; } /** * Legacy CMD line entry poiny (use 'java -jar jcov.jar Merger' from cmd * instead of 'java -cp jcov.jar com.sun.tdk.jcov.Merger') * * @param args */ public static void main(String args[]) { RepGen tool = new RepGen(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } protected String usageString() { return "java com.sun.tdk.jcov.RepGen [options] filename"; } protected String exampleString() { return "java -cp jcov.jar com.sun.tdk.jcov.RepGen -include java.lang.* -format html -output out result.xml"; } protected String getDescr() { return "generates text or HTML (or custom) reports"; } private MemberFilter createCustomFilter(String spiName) { return FilterFactory. getInstance(spiName).getMemberFilter(); } private MemberFilter initCustomFilter(String filter, String sig) { MemberFilter customPlugin = null; MemberFilter sigFilter = null; if (filter != null) { customPlugin = createCustomFilter(filter); } if (customPlugin == null && sigFilter == null) { return null; } else if (customPlugin != null && sigFilter != null) { ConveyerFilter f = new ConveyerFilter(); f.add(sigFilter); f.add(customPlugin); return f; } else { return sigFilter != null ? sigFilter : customPlugin; } } public void setReportGeneratorSPIs(ReportGeneratorSPI reportGeneratorSPI[]) { this.reportGeneratorSPIs = reportGeneratorSPI; } public ReportGeneratorSPI[] getReportGeneratorSPIs() { return reportGeneratorSPIs; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public String[] getFms() { return fms; } public void setFms(String[] fms) { this.fms = fms; } public String[] getInclude() { return include; } public void setInclude(String[] include) { this.include = include; } public boolean isIsPublicAPI() { return isPublicAPI; } public void setIsPublicAPI(boolean isPublicAPI) { this.isPublicAPI = isPublicAPI; } public boolean isNoAbstract() { return noAbstract; } public void setNoAbstract(boolean noAbstract) { this.noAbstract = noAbstract; } public boolean isSyntheticOn() { return syntheticOn; } public void setNoANC(boolean syntheticOn) { this.syntheticOn = syntheticOn; } public boolean isWithTestsInfo() { return withTestsInfo; } public void setWithTestsInfo(boolean withTestsInfo) { this.withTestsInfo = withTestsInfo; } public boolean isNoEnums() { return noEnums; } public void setNoEnums(boolean noEnums) { this.noEnums = noEnums; } public boolean isShowFields() { return showFields; } public void setShowFields(boolean showFields) { // this.showFields = showFields; } public String[] getExclude() { return exclude; } public void setExclude(String[] exclude) { this.exclude = exclude; } public String getSrcRootPath() { return srcRootPath; } public void setDataProcessorsSPIs(DataProcessorSPI[] dataProcessorSPIs){ this.dataProcessorSPIs = dataProcessorSPIs; } /** * Reset all properties to defaults. reportGeneratorSPI = null; include = * new String[] {".*"}; exclude = new String[] {""}; fms = null; filter = * null; generateShortFormat = false; noAbstract = false; isPublicAPI = * false; showMethods = true; showBlocks = true; showBranches = true; * showLines = true; */ public void resetDefaults() { try { handleEnv_(defineHandler()); reportGeneratorSPIs = null; //setFilters(new String[]{".*"}, new String[]{""}, null); setNoAbstract(false); setIsPublicAPI(false); } catch (EnvHandlingException ex) { // should not happen } } /** * Set all properties (except custorm report service provider) * * @param include patterns for including data. Set null for default value - * {".*"} (include all) * @param exclude patterns for excluding data. Set null for default value - * {""} (exclude nothing) * @param classModifiers modifiers that should have a class to be included * @param filter custom filter classname * @param generateShortFormat should generate short format * @param publicAPI should generate only public API (public and protected) * @param hideAbstract should hide abstract data * @param hideMethods should hide methods * @param hideBlocks should hide blocks * @param hideBranches should hide branches * @param hideLines should hide lines */ public void configure(String[] include, String[] exclude, String[] classModifiers, String filter, boolean generateShortFormat, boolean publicAPI, boolean hideAbstract, boolean hideMethods, boolean hideBlocks, boolean hideBranches, boolean hideLines, boolean hideFields) { setFilters(include, exclude, classModifiers); setFilter(filter); this.isPublicAPI = publicAPI; // this.showFields = !hideFields; } /** * Set filtering properties for the report * * @param include patterns for including data. Set null for default value - * {".*"} (include all) * @param exclude patterns for excluding data. Set null for default value - * {""} (exclude nothing) * @param classModifiers modifiers that should have a class to be included */ public void setFilters(String[] include, String[] exclude, String[] classModifiers) { if (include == null) { include = new String[]{".*"}; } this.include = include; if (exclude == null) { exclude = new String[]{""}; } this.exclude = exclude; this.fms = classModifiers; } @Override protected int run() throws Exception { Result r; boolean srcZipped = false; if (srcRootPath != null) { File srcRootPathFile = new File(srcRootPath); if (srcRootPathFile.exists() && srcRootPathFile.isFile() && (srcRootPath.endsWith(".zip") || srcRootPath.endsWith(".jar"))) { srcZipped = true; srcRootPath = outputDir + File.separator + srcRootPathFile.getName().replace(".zip", "").replace(".jar", ""); Utils.unzipFolder(srcRootPathFile, srcRootPath); } } try { logger.log(Level.INFO, "-- Reading test list"); if (filenames.length == 1) { r = new Result(filenames[0], testlist); } else { Merger merger = new Merger(); Result[] results = Merger.initResults(filenames, true); Merger.Merge merge = new Merger.Merge(results, null); merger.setAddMissing(true); merger.setRead_scales(true); merger.setDefaultReadingFilter(include, exclude, m_include, m_exclude, fms); merger.merge(merge, outputDir, true); ReportGenerator rg; if (name != null) { rg = findReportGenerator(name); } else { rg = getDefaultReportGenerator(); } if (rg == null) { throw new Exception("Specified ReportGenerator name (" + name + ") was not found"); } rg.init(outputDir); String[] tl = testlist != null ? Utils.readLines(testlist) : merge.getResultTestList(); SmartTestService sts = new SmartTestService(tl); ReportGenerator.Options options = new ReportGenerator.Options(srcRootPath, sts, null, true, true, mainReportTitle, overviewListTitle, entitiesTitle); try { DataRoot mergedResult = merge.getResult(); if (!syntheticOn) { mergedResult.applyFilter(new ANC_FILTER()); } if (dataProcessorSPIs != null) { for (DataProcessorSPI spi : dataProcessorSPIs) { logger.log(Level.INFO, "-- Applying data processor {0}", spi.getClass()); mergedResult = spi.getDataProcessor().process(mergedResult); } } ProductCoverage coverage = new ProductCoverage(mergedResult, options.getSrcRootPaths(), null, isPublicAPI, noAbstract, ancfiltersClasses); rg.generateReport(coverage, options); if (srcZipped) { Utils.deleteDirectory(new File(srcRootPath)); } } catch (Throwable ex) { if (ex.getMessage() != null) { throw new Exception("ReportGenerator produced exception " + ex.getMessage(), ex); } else { throw new Exception("ReportGenerator produced exception " + ex, ex); } } return SUCCESS_EXIT_CODE; } } catch (IOException ex) { logger.log(Level.SEVERE, "Error while reading testlist", ex); return ERROR_CMDLINE_EXIT_CODE; } if (classesPath != null) { try { logger.log(Level.INFO, "-- Creating javap report"); setDataProcessorsSPIs(null); new JavapRepGen(this).run(filenames[0], classesPath, outputDir); return SUCCESS_EXIT_CODE; } catch (Exception ex) { logger.log(Level.SEVERE, "Error while creating javap report", ex); return ERROR_CMDLINE_EXIT_CODE; } } try { generateReport(name, outputDir, r, srcRootPath); if (srcZipped) { Utils.deleteDirectory(new File(srcRootPath)); } return 0; } catch (FileFormatException e) { logger.log(Level.SEVERE, e.getMessage(), Arrays.toString(filenames)); } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } return SUCCESS_EXIT_CODE; } @Override protected EnvHandler defineHandler() { EnvHandler envHandler = new EnvHandler(new OptionDescr[]{ DSC_FMT, DSC_OUTPUT, // DSC_STDOUT, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MINCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_MEXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FM, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FM_LIST, DSC_NO_ABSTRACT, DSC_SYNTHETIC_ON, DSC_PUBLIC_API, DSC_SRC_ROOT, DSC_VERBOSE, DSC_FILTER_PLUGIN, DSC_ANC_FILTER_PLUGINS, DSC_ANC_DEFAULT_FILTERS, DSC_TEST_LIST, DSC_ANONYM, DSC_JAVAP, DSC_TESTS_INFO, DSC_REPORT_TITLE_MAIN, DSC_REPORT_TITLE_OVERVIEW, DSC_REPORT_TITLE_ENTITIES,}, this); SPIDescr spiDescr = new SPIDescr(CUSTOM_REPORT_GENERATOR_SPI, ReportGeneratorSPI.class); spiDescr.setDefaultSPI(new DefaultReportGeneratorSPI()); envHandler.registerSPI(spiDescr); spiDescr = new SPIDescr(DATA_PROCESSOR_SPI, DataProcessorSPI.class); spiDescr.addPreset("none", new StubSpi()); spiDescr.setDefaultSPI(new DefaultDataProcessorSPI()); envHandler.registerSPI(spiDescr); return envHandler; } private int handleEnv_(EnvHandler opts) throws EnvHandlingException { if (opts.isSet(DSC_VERBOSE)) { // LoggingFormatter.printStackTrace = true; // by default logger doesn't print stacktrace logger.setLevel(Level.INFO); } else { logger.setLevel(Level.SEVERE); } name = opts.getValue(DSC_FMT); outputDir = opts.getValue(DSC_OUTPUT); // no check for output filter = opts.getValue(DSC_FILTER_PLUGIN); ancfilters = opts.getValues(DSC_ANC_FILTER_PLUGINS); ancdeffilters = opts.getValues(DSC_ANC_DEFAULT_FILTERS); noAbstract = opts.isSet(DSC_NO_ABSTRACT); isPublicAPI = opts.isSet(DSC_PUBLIC_API); anonym = opts.isSet(DSC_ANONYM); syntheticOn = opts.isSet(DSC_SYNTHETIC_ON); include = InstrumentationOptions.handleInclude(opts); exclude = InstrumentationOptions.handleExclude(opts); fms = InstrumentationOptions.handleFM(opts); m_include = InstrumentationOptions.handleMInclude(opts); m_exclude = InstrumentationOptions.handleMExclude(opts); testlist = opts.getValue(DSC_TEST_LIST); Utils.checkFileCanBeNull(testlist, "testlist filename", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_CANREAD, Utils.CheckOptions.FILE_ISFILE); withTestsInfo = opts.isSet(DSC_TESTS_INFO); srcRootPath = null; if (opts.isSet(DSC_SRC_ROOT)) { srcRootPath = opts.getValue(DSC_SRC_ROOT); } if (opts.isSet(DSC_REPORT_TITLE_MAIN)){ mainReportTitle = opts.getValue(DSC_REPORT_TITLE_MAIN); } if (opts.isSet(DSC_REPORT_TITLE_OVERVIEW)){ overviewListTitle = opts.getValue(DSC_REPORT_TITLE_OVERVIEW); } if (opts.isSet(DSC_REPORT_TITLE_ENTITIES)){ entitiesTitle = opts.getValue(DSC_REPORT_TITLE_ENTITIES); } ArrayList<ReportGeneratorSPI> reportGenerators = opts.getSPIs(ReportGeneratorSPI.class); if (reportGenerators != null) { reportGeneratorSPIs = reportGenerators.toArray(new ReportGeneratorSPI[reportGenerators.size()]); } ArrayList<DataProcessorSPI> dataProcessors = opts.getSPIs(DataProcessorSPI.class); if (dataProcessors != null) { dataProcessorSPIs = dataProcessors.toArray(new DataProcessorSPI[dataProcessors.size()]); } classesPath = opts.getValue(DSC_JAVAP); return SUCCESS_EXIT_CODE; } @Override protected int handleEnv(EnvHandler opts) throws EnvHandlingException { String[] srcs = opts.getTail(); if (srcs == null) { throw new EnvHandlingException("no input files specified"); } filenames = srcs; Utils.checkFileNotNull(filenames[0], "JCov datafile", Utils.CheckOptions.FILE_EXISTS, Utils.CheckOptions.FILE_CANREAD, Utils.CheckOptions.FILE_ISFILE); /*if (srcs.length > 1) { logger.log(Level.WARNING,"only \"{0}\" will be processed, the rest of the files will be ignored\n" + "\tto generate report for all files, merge them into one using the merger utility", filename); }*/ return handleEnv_(opts); } public static class ANC_FILTER implements MemberFilter { @Override public boolean accept(DataClass clz) { return true; } @Override public boolean accept(DataClass clz, DataMethod m) { boolean ancMethod; //Synthetic method (and Bridge method) ancMethod = m.getModifiers().isSynthetic(); //Enum method ancMethod = ancMethod || (clz.getSuperName().equals("java/lang/Enum") && (m.getName().equals("valueOf") || m.getName().equals("values"))); return !ancMethod || m.getName().startsWith("lambda$"); } @Override public boolean accept(DataClass clz, DataField f) { return true; } } final static OptionDescr DSC_FMT = new OptionDescr("format", new String[]{"fmt"}, "Report generation output.", VAL_SINGLE, "Specifies the format of the report.\n" + "Use \"text\" for generate text report and \"html\" for generate HTML report\n" + "Text report in one file which contains method/block/branch coverage information.\n" + "HTML report contains coverage information with marked-up sources.\n\n" + "Custom reports can be specified with ReportGeneratorSPI interface.", "html"); /** * */ public final static OptionDescr DSC_OUTPUT = new OptionDescr("repgen.output", new String[]{"output", "o"}, "", OptionDescr.VAL_SINGLE, "Output directory for generating text and HTML reports.", "report"); /** * */ public final static OptionDescr DSC_TEST_LIST = new OptionDescr("tests", "Test list", OptionDescr.VAL_SINGLE, "Specify the path to the file containing test list. File should contain a list of tests\n" + "with one name per line."); final static OptionDescr DSC_FILTER_PLUGIN = new OptionDescr("filter", "", OptionDescr.VAL_SINGLE, "Custom filtering plugin class"); final static OptionDescr DSC_ANC_FILTER_PLUGINS = new OptionDescr("ancfilter", new String[]{"ancf"}, "Custom anc filtering plugin classes", OptionDescr.VAL_MULTI, ""); final static OptionDescr DSC_ANC_DEFAULT_FILTERS = new OptionDescr("ancdeffilters", new String[]{"ancdf"}, "Default ANC filter name to use in report", OptionDescr.VAL_MULTI, ""); /** * */ public final static OptionDescr DSC_SRC_ROOT = new OptionDescr("sourcepath", new String[]{"source", "src"}, "The source files.", OptionDescr.VAL_SINGLE, ""); final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", "Verbosity.", "Enable verbose mode."); /** * */ public final static OptionDescr DSC_NO_ABSTRACT = new OptionDescr("noabstract", "Additional filtering", "Do not count abstract methods"); public final static OptionDescr DSC_SYNTHETIC_ON = new OptionDescr("syntheticon", "Additional filtering", "Count coverage for synthetic methods"); /** * */ public final static OptionDescr DSC_PUBLIC_API = new OptionDescr("publicapi", "", "Count only public and protected members"); public final static OptionDescr DSC_ANONYM = new OptionDescr("anonym", "", "include methods from anonymous classes into the report"); public final static OptionDescr DSC_JAVAP = new OptionDescr("javap", new String[]{"javap"}, "Path to the class files of the product to use javap", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_TESTS_INFO = new OptionDescr("testsinfo", "Additional information about for specified tests' list", "Show covererage for all tests in test list"); public final static OptionDescr DSC_REPORT_TITLE_MAIN = new OptionDescr("mainReportTitle", new String[]{"mainReportTitle", "mrtitle"}, "The main report title", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_REPORT_TITLE_OVERVIEW = new OptionDescr("overviewReportTitle", new String[]{"overviewReportTitle", "ortitle"}, "The overview list report title", OptionDescr.VAL_SINGLE, ""); public final static OptionDescr DSC_REPORT_TITLE_ENTITIES = new OptionDescr("entitiesReportTitle", new String[]{"entitiesReportTitle", "ertitle"}, "Entities report title (for modules, packages, subpackages)", OptionDescr.VAL_SINGLE, ""); }
35,819
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Instr2.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/Instr2.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov; import com.sun.tdk.jcov.insert.AbstractUniversalInstrumenter; import com.sun.tdk.jcov.instrument.asm.ClassMorph; import com.sun.tdk.jcov.instrument.asm.ClassMorph2; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.InstrumentationParams; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.JCovCMDTool; import com.sun.tdk.jcov.tools.OptionDescr; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <p> A tool to statically instrument classfiles to collect coverage. </p> <p> * There are 2 coverage collection modes: static and dynamic. In static mode * JCov reads and modifies classes bytecode inserting there some instructions * which will use JCov RT libraries. In dynamic mode (aka Agent mode) a VM agent * is used ("java -javaagent") that instruments bytecode just at loadtime. </p> * * @author Andrey Titov */ public class Instr2 extends JCovCMDTool { private boolean genabstract; private boolean genfield; private boolean gennative; private boolean gensynthetic; private boolean genanonymous; private String template; private String flushPath; private String[] include; private String[] exclude; private static final Logger logger; private String[] srcs; private File outDir; static { Utils.initLogger(); logger = Logger.getLogger(Instr2.class.getName()); } /** * entry point. Parses options, constructs appropriate context, class name * filter, then invoces UniversalInstrumenter to do the job */ public static void main(String[] args) { Instr2 tool = new Instr2(); try { int res = tool.run(args); System.exit(res); } catch (Exception ex) { System.exit(1); } } protected String usageString() { return "java com.sun.tdk.jcov.Instr2 [-option [value]]"; } protected String exampleString() { return "java -cp jcov.jar com.sun.tdk.jcov.Instr2 -include java.lang.* -abstract on -native on -field on -template mytemplate.xml instrumented_classes"; } protected String getDescr() { return "instrumenter designed for abstract, native methods and fields"; } @Override protected int run() throws Exception { Utils.addToClasspath(srcs); AbstractUniversalInstrumenter instrumenter = new AbstractUniversalInstrumenter(true) { ClassMorph2 morph = new ClassMorph2( new InstrumentationParams(gennative, genfield, genabstract, include, exclude, InstrumentationOptions.InstrumentationMode.BLOCK) .setInstrumentAnonymous(genanonymous) .setInstrumentSynthetic(gensynthetic), template); protected byte[] instrument(byte[] classData, int classLen) throws IOException { return morph.morph(classData, flushPath); } public void finishWork() { } }; //instrumenter.setPrintStats(opts.isSet(DSC_STATS)); // com.sun.tdk.jcov.instrument.Options.instrumentAbstract = com.sun.tdk.jcov.instrument.Options.instrumentAbstract.NONE; for (String root : srcs) { instrumenter.instrument(new File(root), outDir); } /* if ((opts.isSet(JcovInstrContext.OPT_SAVE_BEFORE) || opts.isSet(JcovInstrContext.OPT_SAVE_AFTER) || opts.isSet(JcovInstrContext.OPT_SAVE_BEGIN) || opts.isSet(JcovInstrContext.OPT_SAVE_AT_END)) && instrumenter.getSavePointCount() < 1) { log.warning("no coverage data savepoints have been inserted"); } */ instrumenter.finishWork(); return SUCCESS_EXIT_CODE; } @Override protected EnvHandler defineHandler() { return new EnvHandler(new OptionDescr[]{ DSC_OUTPUT, DSC_VERBOSE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_INCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_EXCLUDE_LIST, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_TEMPLATE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ABSTRACT, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_NATIVE, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_FIELD, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_SYNTHETIC, com.sun.tdk.jcov.instrument.InstrumentationOptions.DSC_ANONYM, ClassMorph.DSC_FLUSH_CLASSES }, this); } @Override protected int handleEnv(EnvHandler envHandler) throws EnvHandlingException { srcs = envHandler.getTail(); if (srcs == null) { throw new EnvHandlingException("No input files specified"); } if (envHandler.isSet(DSC_VERBOSE)) { logger.setLevel(Level.INFO); } outDir = null; if (envHandler.isSet(DSC_OUTPUT)) { outDir = new File(envHandler.getValue(DSC_OUTPUT)); if (!outDir.exists()) { outDir.mkdirs(); logger.log(Level.INFO, "The directory {0} was created.", outDir.getAbsolutePath()); } } String abstractValue = envHandler.getValue(InstrumentationOptions.DSC_ABSTRACT); if (abstractValue.equals("off")) { genabstract = false; } else if (abstractValue.equals("on")) { genabstract = true; } else { throw new EnvHandlingException("'" + InstrumentationOptions.DSC_ABSTRACT.name + "' parameter value error: expected 'on' or 'off'; found: '" + abstractValue + "'"); } String nativeValue = envHandler.getValue(InstrumentationOptions.DSC_NATIVE); if (nativeValue.equals("on")) { gennative = true; } else if (nativeValue.equals("off")) { gennative = false; } else { throw new EnvHandlingException("'" + InstrumentationOptions.DSC_NATIVE.name + "' parameter value error: expected 'on' or 'off'; found: '" + nativeValue + "'"); } String fieldValue = envHandler.getValue(InstrumentationOptions.DSC_FIELD); if (fieldValue.equals("on")) { genfield = true; } else if (fieldValue.equals("off")) { genfield = false; } else { throw new EnvHandlingException("'" + InstrumentationOptions.DSC_FIELD.name + "' parameter value error: expected 'on' or 'off'; found: '" + fieldValue + "'"); } String anonym = envHandler.getValue(InstrumentationOptions.DSC_ANONYM); if (anonym.equals("on")) { genanonymous = true; } else { // off genanonymous = false; } String syntheticField = envHandler.getValue(InstrumentationOptions.DSC_SYNTHETIC); if (syntheticField.equals("on")) { gensynthetic = true; } else { // if (fieldValue.equals("off")) gensynthetic = false; } template = envHandler.getValue(InstrumentationOptions.DSC_TEMPLATE); Utils.checkFileNotNull(template, "template filename", Utils.CheckOptions.FILE_NOTISDIR, Utils.CheckOptions.FILE_PARENTEXISTS); include = InstrumentationOptions.handleInclude(envHandler); exclude = InstrumentationOptions.handleExclude(envHandler); flushPath = envHandler.getValue(ClassMorph.DSC_FLUSH_CLASSES); if ("none".equals(flushPath)) { flushPath = null; } return SUCCESS_EXIT_CODE; } final static OptionDescr DSC_OUTPUT = new OptionDescr("instr2.output", new String[]{"output", "o"}, "Output directory", OptionDescr.VAL_SINGLE, "Specifies output file or directory, default directory is current."); final static OptionDescr DSC_VERBOSE = new OptionDescr("verbose", "Verbose mode", "Enable verbose mode."); }
9,656
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FileFormatException.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/data/FileFormatException.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.data; /** * Signals an error during reading/parsing a data file * * @author Dmitry Fazunenko */ public class FileFormatException extends Exception { /** * Default constructor */ public FileFormatException() { super(); } /** * Constructs a new FileFormatException with the specified detail message * * @param message the detail message */ public FileFormatException(String message) { super(message); } /** * Constructs a FileFormatException exception with the specified cause * * @param cause reason of the exception */ public FileFormatException(Throwable cause) { super(cause); } /** * Constructs a FileFormatException exception with the specified reason and * cause * * @param message * @param cause */ public FileFormatException(String message, Throwable cause) { super(message, cause); } }
2,195
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Result.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/data/Result.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.data; import com.sun.tdk.jcov.util.Utils; import java.io.IOException; /** * Result class contains path to JCov datafile and it's testlist * * @author Andrey Titov */ public class Result { private String resultPath; private String[] testList; /** * Default empty constructor */ public Result() { } /** * Constructor for Result without testname * * @param resultPath path to the result file */ public Result(String resultPath) { this.resultPath = resultPath; } /** * Constructor for Result * * @param resultPath path to the result file * @param testList tests associated with this result file */ public Result(String resultPath, String[] testList) { this.resultPath = resultPath; this.testList = testList; } /** * Constructor for Result that reads testlist from the file * * @param resultPath path to the result file * @param testListPath path to the test list file associated with this * result file */ public Result(String resultPath, String testListPath) throws IOException { this.resultPath = resultPath; if (testListPath != null) { testList = Utils.readLines(testListPath); } else { testList = null; } } /** * Constructor for Result that reads a part of testlist from the file * * @param resultPath path to the result file * @param testListPath path to the test list file associated with this * result file * @param start first line to be read * @param end last line to be read */ public Result(String resultPath, String testListPath, int start, int end) throws IOException { this.resultPath = resultPath; testList = Utils.readLines(testListPath, start, end); } /** * Get path of result file * * @return path of result file */ public String getResultPath() { return resultPath; } /** * Set path of result file * * @param resultPath */ public void setResultPath(String resultPath) { this.resultPath = resultPath; } /** * Get tests list * * @return Testlist array of test names associated with this result file */ public String[] getTestList() { return testList; } /** * Set tests list * * @param testList array of test names associated with this result file */ public void setTestList(String[] testList) { this.testList = testList; } /** * Set tests list reading it from a file * * @param testListPath path to the test list file associated with this * result file */ public void readTestList(String testListPath) throws IOException { testList = Utils.readLines(testListPath); } /** * Set tests list reading it from a file * * @param testListPath path to the test list file associated with this * result file * @param start first line to be read * @param end last line to be read */ public void readTestList(String testListPath, int start, int end) throws IOException { testList = Utils.readLines(testListPath, start, end); } /** * Set single testname to the test list * * @param testname name of the test associated with this result file */ public void setTestName(String testname) { testList = new String[]{testname}; } /** * Set testname equal to result file name */ public void setDefaultName() { testList = new String[]{resultPath}; } public boolean isTestListSet() { return testList != null; } }
4,991
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Scale.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/data/Scale.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.data; import com.sun.tdk.jcov.tools.ScaleCompressor; import com.sun.tdk.jcov.util.Utils; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; /** * <p> This class represents the so-called 'test scale'. Lets assume that N * tests have been run against the code under test and some tests have covered a * particular item (method, block, branch) and some - have not. It can be * written as a sequence of '0' and '1', where the position of '0' or '1' equals * the test number and the value '0' means that the test has *not* covered the * item, '1' - the test *has* covered the item. This sequence is the test scale * (TS) for this item. Jcov file format allows to keep TSs for every item of all * classes. Using only '1' and '0' would lead to too long TSs, so jcov file * format uses the following method for keeping *uncompressed* TSs: </p> <p> Let * TS be * <code>0100 1011 1001 101</code>. Then it is broken into 4-s of '0' and '1'-s * so that each quadruple represents a value between 0 and 15 (inclusive), and * therefore unambiguously corresponds to a hexadecimal digit with this value. * Thus given binary sequence is transformed into "4b95" hex character sequence * (last triple is left-padded with zero : 101 -> 0101). Such character forms of * TSs are kept in jcov data files. They can be either compressed or not. If the * TS is compressed, Jcov uses some compressor (now it is only * SimpleScaleCompressor) to decompress it and convert to the internal form * which is straightforward: test number N corresponds to N'th bit in a byte * array. Again, if Jcov is instructed to compress test scales it uses a * compressor, which converts a byte array into a sequence of characters (since * jcov data file must be a plain ascii file). </p> <p> For example, when * merging two data files (A.xml and B.xml), Jcov also merges TSs of the * corresponding items. Lets assume, that file A.xml has compressed TSs, file * B.xml - uncompressed TSs. Then to merge two test scales the following is done * : </p> * <pre> * 1. the sequence S1 of chars (corresponding to TS1) is read from A.xml * 2. S1 is decompressed by a compressor into a sequence of bits (byte array), e.g. : * <code> * byte1 | byte0 byte index in the byte array * __01 | 0100 1001 Test scale (as stored in memory) * 98 | 7654 3210 Test number (bit number) * </code> 3. other actions 4. the sequence S2 of chars (corresponding to TS2) * is read from B.xml 5. S2 is straightforwardly transformed into a sequence of * bits, e.g. : * <code> * 01 0110 Test scale (as stored in memory) * 54 3210 Test number (bit number) * </code> 6. other actions 7. TS1 and TS2 are merged : * <code> * byte1 byte0 byte index in resulting byte array * ... ..98 7654 3210 test number (bit number) * 10 0100 1001 "+" 01 0110 "=" 0101 1010 0100 1001 resulting TS * |-TS2-||--- TS1---| * </code> * </pre> * * @see com.sun.tdk.jcov.tools.ScaleCompressor * @see com.sun.tdk.jcov.tools.SimpleScaleCompressor * @author Konstantin Bobrovsky */ public class Scale { public final static String sccsVersion = "%I% $LastChangedDate: 2012-06-20 12:45:52 +0400 (Wed, 20 Jun 2012) $"; private static Scale buf_scale; static { buf_scale = new Scale(); buf_scale.bytes = new byte[1024]; } /** * keeps the internal (always uncompressed) form of the TS */ protected byte[] bytes; /** * number of tests represented by this scale */ protected int size; /** * default constructor */ private Scale() { } /** * Constructs new Scale object * * @param scale TS in character form * @param len number of characters in the TS * @param size TS size (number of tests) * @param compressor scale compressor that can decompress the TS if it is * compressed * @param compressed whether the TS is compressed * @exception JcovFileFormatException if compressor is unable to decompress * the TS */ public Scale(char[] scale, int len, int size, ScaleCompressor compressor, boolean compressed) throws FileFormatException { this.size = size; bytes = new byte[bytesRequiredFor(size)]; if (compressed) { try { compressor.decompress(scale, len, bytes, size); } catch (Exception e) { throw new FileFormatException(e); } } else { int l = (size + 7) / 8; for (int i = 0; i < l; i++) { int ind = 2 * i; char val = scale[ind]; byte b1 = val >= 'a' ? (byte) (10 + val - 'a') : (byte) (val - '0'); if (ind + 1 < scale.length) { val = scale[ind + 1]; byte b2 = val >= 'a' ? (byte) (10 + val - 'a') : (byte) (val - '0'); bytes[i] = (byte) (b1 | (b2 << 4)); } else { bytes[i] = b1; } } if (1 <= size % 8 && size % 8 <= 4) { int lastByte = bytes.length - 1; bytes[lastByte] = (byte) (bytes[lastByte] & 15); } } } /** * Returns size of this scale. Size of the scale equals the number of merged * tests * * @return size of this scale. Size of the scale equals the number of merged * tests */ public int size() { return size; } /** * Returns count of "1" in this scale. This number equals the number of * tests that hit this block * * @return count of "1" in this scale. This number equals the number of * tests that hit this block */ public int getSetBitsCount() { int res = 0; for (int i = 0; i < size; i++) { if (isBitSet(i)) { res++; } } return res; } /** * Checks whether pos's bit in the scale is set * * @return true if pos's bit in the scale is set, false otherwise. True * means that test #pos made hit on this block. */ public boolean isBitSet(int pos) { if (pos < 0 || pos >= size) { return false; } int ind = pos / 8; int sft = pos % 8; byte val = bytes[ind]; byte mask = (byte) (1 << sft); return (val & mask) != 0; } /** * Set scale value on test #pos * * @param pos bit to set * @param to_one value to set (1 or 0) */ public void setBit(int pos, boolean to_one) { if (pos < 0 || pos >= size) { return; } int ind = pos / 8; int sft = pos % 8; byte val = bytes[ind]; byte mask = (byte) (1 << sft); if (to_one) { bytes[ind] = (byte) ((val | mask) & 0xFF); } else { bytes[ind] = (byte) ((val & ~mask) & 0xFF); } } /** * @param scale_size TS size * @return number of bytes required to keep TS of given size */ static int bytesRequiredFor(int scale_size) { return (scale_size + 8 - 1) / 8; } public static Scale createZeroScale(int size) { Scale res = new Scale(); res.size = size; res.bytes = new byte[bytesRequiredFor(size)]; return res; } void addZeroes(int num, boolean add_before) { int new_size = num + size; int new_len = bytesRequiredFor(new_size); int bytes_extra = new_len - bytes.length; byte[] sav = bytes; if (bytes_extra > 0) { bytes = new byte[sav.length + bytes_extra]; } if (add_before) { if (buf_scale.bytes.length < sav.length) { buf_scale.bytes = new byte[sav.length]; } System.arraycopy(sav, 0, buf_scale.bytes, 0, sav.length); buf_scale.size = size; for (int i = 0; i < bytes.length; bytes[i++] = (byte) 0); this.size = num; merge(this, buf_scale); } else { if (bytes_extra > 0) { System.arraycopy(sav, 0, bytes, 0, sav.length); } int len = bytesRequiredFor(size); int rmndr = len * 8 - size; if (rmndr > 0) { byte mask = (byte) ((1 << (8 - rmndr)) - 1); bytes[len - 1] &= mask; } for (int i = len; i < new_len; bytes[i++] = (byte) 0); size = new_size; } } /** * Merges two scales and returns the result scale (new object) * * @param s1 scale information in block1. Can be null. * @param s2 scale information in block2. Can be null. * @param count1 count of hits in block1 * @param count2 count of hits in block2 * @return Merged (or created) Scale */ public static Scale merge(Scale s1, Scale s2, long count1, long count2) { Scale res; if (s1 == null) { if (s2 == null) { res = Scale.merge(count1, count2); } else { res = Scale.merge(count1, s2); } } else { if (s2 == null) { Scale.merge(s1, count2); } else { Scale.merge(s1, s2); } res = s1; } return res; } /** * Given 2 exec counters of a jcov item (obtained from 2 testruns), creates * TS of size 2 for it. * * @param count0 execution counter of a jcov item obtained from the 1st * testrun * @param count1 execution counter of a jcov item obtained from the 2nd * testrun */ static Scale merge(long count0, long count1) { Scale res = new Scale(); res.bytes = new byte[1]; res.size = 2; if (count0 > 0) { count0 = 1; } if (count1 > 0) { count1 = 1; } res.bytes[0] = (byte) (count0 | (count1 << 1)); return res; } /** * Creates new test scale by merging a test scale of size 1 represented only * by an execution counter with another (normal) test scale */ static Scale merge(long count, Scale scale) { Scale res = new Scale(); res.bytes = new byte[bytesRequiredFor(scale.size + 1)]; res.size = 1; if (count > 0) { res.bytes[0] = 1; } merge(res, scale); return res; } /** * Merges a test scale with another test scale of size 1 represented only by * an execution counter, and writes the result to the 1st test scale */ static void merge(Scale scale, long count) { int i = scale.size / 8; int j = scale.size % 8; scale.size++; if (i >= scale.bytes.length) { byte[] sav = scale.bytes; scale.bytes = new byte[i + 1]; System.arraycopy(sav, 0, scale.bytes, 0, i); sav = null; } if (count == 0) { return; } scale.bytes[i] |= (byte) (1 << j); } /** * Merges two test scales, writing the result to the 1st * * @see Scale */ static void merge(Scale dst, Scale src) { // both dst.bytes and src.bytes can be longer than // it is necessary to hold actual scales int old_dst_len = bytesRequiredFor(dst.size); int new_dst_len = bytesRequiredFor(dst.size + src.size); int src_len = bytesRequiredFor(src.size); // does dst have enough space to accomodate both scales? if (dst.bytes.length * 8 < dst.size + src.size) { byte[] sav = dst.bytes; // no - create minimum space required dst.bytes = new byte[new_dst_len]; System.arraycopy(sav, 0, dst.bytes, 0, old_dst_len); sav = null; // should now be gc'ed } byte[] dst_bytes = dst.bytes; byte[] src_bytes = src.bytes; if (dst.size % 8 == 0) { // dst scale occupied exactly old_dst_len * 8 bits System.arraycopy(src_bytes, 0, dst_bytes, old_dst_len, src_len); dst.size += src.size; } else { int dst_rmndr = dst.size % 8; int src_rmndr = src.size % 8; byte dst_mask = (byte) ((1 << dst_rmndr) - 1); // copy src scale to dst shifting it (8 - dst_rmndr) // bits right int i, j; for (i = old_dst_len - 1, j = 0; j < src_len - 1; i++, j++) { dst_bytes[i] = (byte) (((dst_bytes[i] & dst_mask) | (src_bytes[j] << dst_rmndr)) & 0xFF); dst_bytes[i + 1] = (byte) ((src_bytes[j] >>> (8 - dst_rmndr)) & 0xFF); } // copy last byte dst_bytes[i] = (byte) ((dst_bytes[i] & dst_mask) | (src_bytes[j] << dst_rmndr)); if (i < dst_bytes.length - 1) { int src_mask = (int) ((src_rmndr == 0) ? 0xFF : (1 << src_rmndr) - 1); dst_bytes[i + 1] = (byte) (((src_bytes[j] & src_mask) >>> (8 - dst_rmndr)) & 0xFF); } dst.size += src.size; } } /** * <p> Converts this scale to character form </p> <p> Character * representation of a Scale is encoded 16-bit mask: 0123456789abcdef. </p> * * @param compress whether the character form will be compressed * @param buf a StringBuffer that will keep the character form * @param compressor compressor used to compress the TS * @return number of characters representing the TS * (compressed/uncompressed) */ public int convertToChars(boolean compress, StringBuffer buf, ScaleCompressor compressor) { if (compress) { return compressor.compress(bytes, buf, size); } else { int res = Utils.halfBytesRequiredFor(size); for (int i = res - 1; i >= 0; i--) { buf.setCharAt(i, Utils.int2HexChar(Utils.getHalfByteAt(i, bytes))); } return res; } } @Override public String toString() { StringBuffer buf = new StringBuffer(size + size / 4); for (int i = 0; i < size; i++) { if (i % 4 == 0 && i != 0 && i <= size - 1) { buf.append('_'); } char ch = isBitSet(i) ? '1' : '0'; buf.append(ch); } return buf.toString(); } public static Scale illuminateDuplicates(Scale scale, int new_size, ArrayList pairs) { if (scale == null) { return null; } // Merge values for duplicates for (Iterator it = pairs.iterator(); it.hasNext();) { Utils.Pair p = (Utils.Pair) (it.next()); scale.setBit(p.a, scale.isBitSet(p.a) | scale.isBitSet(p.b)); } Scale old = scale; scale = Scale.createZeroScale(new_size); /** * Moving forward simultaneously in new and old scales, skipping * duplicated indexes into old (p.b) and writing data into new scale */ Iterator<Utils.Pair> it = pairs.iterator(); int iremove = it.hasNext() ? it.next().b : new_size; int old_size = old.size; for (int inew = 0, iold = 0; inew < new_size && iold < old_size; inew++, iold++) { while (iold == iremove) { if (it.hasNext()) { iremove = it.next().b; } else { iremove = old_size; } iold++; } scale.setBit(inew, old.isBitSet(iold)); } return scale; } public static Scale expandScale(Scale scale, int new_size, boolean add_before, long dataCount) { if (scale == null) { scale = Scale.createZeroScale(new_size); if (dataCount > 0) { int pos = add_before ? new_size - 1 : 0; scale.setBit(pos, true); } } else if (new_size > scale.size) { scale.addZeroes(new_size - scale.size, add_before); if (dataCount > 0) { int pos = add_before ? 0 : new_size - 1; scale.setBit(pos, true); } } return scale; } /** * Writes this scale data to stream * * @param out * @throws IOException */ public void writeObject(DataOutput out) throws IOException { out.writeShort(bytes.length); out.write(bytes); } /** * Creates Scale instance reading it from the stream * * @param in * @throws IOException */ public Scale(DataInput in) throws IOException { int len = in.readShort(); bytes = new byte[len]; in.readFully(bytes); } }
18,217
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ScaleOptions.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/data/ScaleOptions.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.data; import com.sun.tdk.jcov.tools.ScaleCompressor; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * * @author Sergey Borodin */ public final class ScaleOptions { public ScaleOptions() { } public ScaleOptions(boolean read_scales, int scale_size, ScaleCompressor compressor) { setReadScales(read_scales); setScaleSize(scale_size); setScaleCompressor(compressor); } private boolean read_scales; private int scale_size; private boolean scales_compressed; private ScaleCompressor compressor; private String[] testIDs; private String outTestList; public void setReadScales(boolean read_scales) { this.read_scales = read_scales; } public boolean needReadScales() { return read_scales; } public void setScaleSize(int scale_size) { this.scale_size = scale_size; } public int getScaleSize() { return scale_size; } public void setScalesCompressed(boolean scales_compressed) { this.scales_compressed = scales_compressed; } public boolean scalesCompressed() { return scales_compressed; } public void setScaleCompressor(ScaleCompressor compressor) { this.compressor = compressor; } public ScaleCompressor getScaleCompressor() { return compressor; } public boolean hasCompressor() { return compressor != null; } public void setTestList(String[] testIDs) { this.testIDs = testIDs; } public String[] getTestList() { return testIDs; } public void setOutTestList(String outTestList) { this.outTestList = outTestList; } public String getOutTestList() { return outTestList; } public void writeObject(DataOutput out) throws IOException { out.writeBoolean(read_scales); out.writeShort(scale_size); out.writeBoolean(scales_compressed); if (compressor != null) { out.writeBoolean(true); out.writeUTF(compressor.getClass().getName()); } else { out.writeBoolean(false); } if (testIDs != null) { out.writeShort(testIDs.length); for (int i = 0; i < testIDs.length; ++i) { out.writeUTF(testIDs[i]); } } else { out.writeShort(Short.MAX_VALUE); } if (outTestList != null) { out.writeBoolean(true); out.writeUTF(outTestList); } else { out.writeBoolean(false); } } public ScaleOptions(DataInput in) throws IOException { read_scales = in.readBoolean(); scale_size = in.readShort(); scales_compressed = in.readBoolean(); if (in.readBoolean()) { in.readUTF(); // compressor name } int len = in.readShort(); if (len != Short.MAX_VALUE) { testIDs = new String[len]; for (int i = 0; i < len; ++i) { testIDs[i] = in.readUTF(); } } else { testIDs = null; } if (in.readBoolean()) { outTestList = in.readUTF(); } } }
4,468
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ClassSignatureFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/io/ClassSignatureFilter.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.io; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.DataField; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.util.Utils; import com.sun.tdk.jcov.util.Utils.Pattern; /** * An acceptor able to filter classes by their names and modifiers. All filters * for this acceptor are specified in the format understandable by * WildCardStringFilter class * * @see com.sun.tdk.jcov.tools.Acceptor * @see com.sun.tdk.jcov.tools.WildCardStringFilter * @see com.sun.tdk.jcov.filedata.Clazz * @author Konstantin Bobrovsky */ public class ClassSignatureFilter implements MemberFilter { /** * class modifiers acceptable by this acceptor */ private String[] modifs; private String[] includes; private String[] excludes; private Pattern[] alls; private Pattern[] all_modules; /** * Constructs new ClassSignatureAcceptor with the specified * inclusion/exclusion masks and acceptable modifiers * * @param incl_masks string masks specifying acceptable class names * @param excl_masks string masks specifying unacceptable class names * @param modifs acceptable modifiers */ public ClassSignatureFilter(String[] incl_masks, String[] excl_masks, String[] modifs) { this(incl_masks, excl_masks, null , null, modifs); } public ClassSignatureFilter(String[] incl_masks, String[] excl_masks, String[] m_includes, String[] m_excludes, String[] modifs) { this.modifs = modifs; this.includes = incl_masks; this.excludes = excl_masks; this.alls = Utils.concatFilters(incl_masks, excl_masks); this.all_modules = Utils.concatModuleFilters(m_includes, m_excludes); } public boolean accept(DataClass c) { return Utils.accept(all_modules, modifs, c.getModuleName(), null) && Utils.accept(alls, modifs, "/" + c.getFullname(), c.getSignature()); } public boolean accept(DataClass clz, DataMethod m) { return true; } public boolean accept(DataClass clz, DataField f) { return true; } public String[] getModifs() { return modifs; } public String[] getExcludes() { return excludes; } public String[] getIncludes() { return includes; } }
3,595
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Reader.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/io/Reader.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.io; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.data.ScaleOptions; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.reader.ReaderFactory; import com.sun.tdk.jcov.tools.SimpleScaleCompressor; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class Reader { /** * buffer size for BufferedReaders used here */ protected final static int IO_BUF_SIZE = 524288; /** * @param filename filename * @return BufferedReader associated with the file specified by the filename */ public static BufferedReader openFile4Reading(String filename) throws IOException { return new BufferedReader(new InputStreamReader(new FileInputStream(filename), Charset.forName("UTF-8")), IO_BUF_SIZE); } public static DataRoot readXML(String fileName) throws FileFormatException { return readXML(fileName, true, null); } public static DataRoot readXML(InputStream is) throws FileFormatException { return readXML(is, true, null); } public static DataRoot readXML(String fileName, boolean read_scales, MemberFilter filter) throws FileFormatException { FileInputStream in = null; try { File f = new File(fileName); if (!f.exists()) { throw new FileFormatException("File " + fileName + " doesn''t exist"); } in = new FileInputStream(f); DataRoot dataRoot = readXML(in, read_scales, filter); dataRoot.setStorageFileName(fileName); in.close(); in = null; return dataRoot; } catch (Exception e) { if (!(e instanceof FileFormatException)) { throw new FileFormatException(e.getMessage(), e); } else { throw (FileFormatException) e; } } finally { if (in != null) { try { in.close(); } catch (IOException ex) {/*do nothing*/ } } } } public static DataRoot readXML(InputStream input, boolean read_scales, MemberFilter filter) throws FileFormatException { DataRoot root = new DataRoot("", false); ScaleOptions scaleOpts = new ScaleOptions(read_scales, 0, new SimpleScaleCompressor()); root.setScaleOpts(scaleOpts); root.setAcceptor(filter); ReaderFactory rf = ReaderFactory.newInstance(Utils.getJavaVersion(), input); root.setReaderFactory(rf); root.readDataFrom(); if (read_scales && scaleOpts.getScaleSize() == 0) { root.createScales(); } return root; } public static DataRoot readXMLHeader(String fileName) throws FileFormatException { try { return readXMLHeader(new FileInputStream(fileName)); } catch (FileNotFoundException ex) { throw new FileFormatException(ex.getMessage()); } } public static DataRoot readXMLHeader(InputStream input) throws FileFormatException { DataRoot root = new DataRoot("", false); ReaderFactory rf = ReaderFactory.newInstance(Utils.getJavaVersion(), input); root.setReaderFactory(rf); root.readHeader(); return root; } }
4,914
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
CollectDetect.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/CollectDetect.java
/* * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class CollectDetect extends Collect { /** * Used when it's needed to control concurrency: if there is 2 threads both * instrumenting (agent mode only) and collecting hits - this class allows * to block only that thread which is actually instrumenting and the other * can continue to collect hits. Also used to concurrent control of * CallerInclude/CallerExclude */ private static class ThreadInfo { private static int INFO_LENGTH = 100; long id; // thread id int instLevel; // not-zero instLevel means that this thread entered into instrumentation (agent) or // saving code when it shouldn't collect hits int expected = 0; // used for CallerInclude/CallerExclude - caller() method is instrumented with setExpected() method int clinitValue = 0; /* * In comparison with expected, contains hash of full signature = object * runtime type + name + vmsig * */ int expectedFull; // used for CallerInclude/CallerExclude - caller() method is instrumented with setExpected() method ThreadInfo next; ThreadInfo(long id) { this.id = id; } private boolean enabled() { return instLevel == 0; } private boolean enabled(int i) { return ((expected == i && i != -1) || (expected == 0 && i == -1 && isInitialized)) && instLevel == 0; } private boolean enabledFull(int i) { return (expectedFull == i) && instLevel == 0; } } static ThreadInfo[] info; static ThreadInfo prevInfo; static ThreadInfo underConstruction; static { // CollectDetect.init(); CollectDetect.enableInvokeCounts(); } static void initInfo() { if (info == null) { // do initialization underConstruction = new ThreadInfo(0L); underConstruction.instLevel++; try { if (Thread.currentThread() != null) { info = new ThreadInfo[ThreadInfo.INFO_LENGTH]; long id = Thread.currentThread().getId(); prevInfo = infoForThread(id); } } catch (Throwable t) {} } } public static void enableInvokeCounts() { invokeCounts = new long[MAX_SLOTS]; } public static void enableDetectInternal() { initInfo(); if (info == null) { // do initialization underConstruction = new ThreadInfo(0L); underConstruction.instLevel++; info = new ThreadInfo[ThreadInfo.INFO_LENGTH]; long id = Thread.currentThread().getId(); prevInfo = infoForThread(id); } } private static ThreadInfo infoForThread(long id) { ThreadInfo ti; if( info == null ) { info = new ThreadInfo[ThreadInfo.INFO_LENGTH]; } int hash = (int) (id % ThreadInfo.INFO_LENGTH); for (ti = info[hash]; ti != null; ti = ti.next) { if (ti.id == id) { prevInfo = ti; return ti; } } if (underConstruction != null) { synchronized (underConstruction) { // set up a placeholder to protect us underConstruction.id = id; underConstruction.next = info[hash]; info[hash] = underConstruction; prevInfo = underConstruction; // we are now protected, safe to create the real one ti = new ThreadInfo(id); // the new will trigger a track ti.next = underConstruction.next; info[hash] = ti; prevInfo = ti; } } return ti; } public static void hit(int slot) { if (Collect.isVMReady || Collect.isVMReady()) { Thread t = Thread.currentThread(); if (t != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if (ti == null || ti.enabled()) { Collect.hit(slot); } } } } public static void hit(int slot, int hash, int fullHash) { if (Collect.isVMReady || Collect.isVMReady()) { Thread t = Thread.currentThread(); if (t != null) { long id = t.getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if ( ti == null ) { Collect.hit(slot); } else { if (ti.enabled(hash)) { ti.expected = 0; Collect.hit(slot); } if (ti.enabledFull(fullHash)) { ti.expectedFull = 0; Collect.hit(slot); } } } } } public static void enterInstrumentationCode() { if (prevInfo != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if( ti != null ) ti.instLevel++; } } public static void setExpected(int hash) { if (prevInfo != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if( ti != null ) ti.expected = hash; } } public static void enterClinit() { if (prevInfo != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if( ti != null ) ti.clinitValue = ti.expected; } } public static void leaveClinit() { if (prevInfo != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if( ti != null ) ti.expected = ti.clinitValue; } } public static void setExpectedFull(int fullHash) { if (prevInfo != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti == null || ti.id != id) { ti = infoForThread(id); } if( ti != null ) ti.expectedFull = fullHash; } } public static void leaveInstrumentationCode() { if (prevInfo != null) { long id = Thread.currentThread().getId(); ThreadInfo ti = prevInfo; if (ti.id != id) { ti = infoForThread(id); } ti.instLevel--; } } private static long[] invokeCounts; public static void invokeHit(int id) { invokeCounts[id]++; } public static boolean wasInvokeHit(int id) { return invokeCounts[id] != 0; } public static long invokeCountFor(int id) { return invokeCounts[id]; } public static void setInvokeCountFor(int id, long count) { invokeCounts[id] = count; } }
9,036
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AgentSocketSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/AgentSocketSaver.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import com.sun.tdk.jcov.instrument.DataRoot; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; /** * * @author Andrey Titov */ public class AgentSocketSaver extends JCovSocketSaver { private DataRoot root; private String file; public AgentSocketSaver(DataRoot root, String file) { this.root = root; this.file = file; if (this.file == null) { this.file = "result.xml"; } } public AgentSocketSaver(DataRoot root, String file, String host, int port) { super(host, port); this.root = root; this.file = file; } @Override public synchronized void saveResults() { try { if (host == null) { host = detectHost(); } if (port == -1) { port = detectPort(); } String testname = PropertyFinder.findValue("testname", null); if (testname == null) { testname = PropertyFinder.findValue("file", file); } else { if ("<jcov.ignore>".equals(testname)) { return; // ignoring this test data } } Socket s = null; for (int i = 0; i < 3; ++i) { try { s = new Socket(host, port); break; } catch (UnknownHostException e) { System.err.println("JCovRT: Can't resolve hostname " + host + " - unknown host. Exiting."); return; } catch (IOException e) { System.err.println("JCovRT: Attempt to connect to " + host + ":" + port + " failed: "); System.err.println(e.getMessage()); } Thread.sleep(3000); } if (s == null) { return; } DataOutputStream out = new DataOutputStream(new BufferedOutputStream(s.getOutputStream())); out.writeBytes("JCOV"); // magicword - 8bytes out.write(SOCKET_SAVER_VERSION); // version - 1byte out.writeUTF(System.getProperty("user.name")); // testername - 1+?bytes out.writeUTF(testname); // testname - 1+?bytes out.writeUTF(PropertyFinder.findValue("product", "")); // productname - 1+?bytes out.writeBoolean(root.getParams().isDynamicCollect()); // dynamic - 1byte root.writeObject(out); out.close(); s.close(); } catch (InterruptedException ignored) { } catch (IOException ex) { System.err.println("JCovRT: " + ex); } } }
4,168
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovServerSocketSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/JCovServerSocketSaver.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; /** * * @author Sergey Borodin */ class JCovServerSocketSaver implements JCovSaver { protected static final int DEFAULT_PORT = 3335; protected static final String PORT = "server.port"; protected int port; static int detectPort() { String p = null; try { p = PropertyFinder.findValue(PORT, String.valueOf(DEFAULT_PORT)); return Integer.parseInt(p); } catch (NumberFormatException e) { System.err.println("JCovRT: Port parse error (not a number) " + p); } catch (Throwable ignore) { } return DEFAULT_PORT; } public JCovServerSocketSaver() { port = detectPort(); } public JCovServerSocketSaver(int port) { this.port = port; } protected void startServer(Thread server) { server.start(); } public void saveResults() { //throw new UnsupportedOperationException("Not supported yet."); } }
2,207
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovSESocketSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/JCovSESocketSaver.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.util.Properties; /** * * @author Sergey Borodin */ public class JCovSESocketSaver extends JCovSocketSaver { public static final String NETWORK_DEF_PROPERTIES_FILENAME = "jcov_network_default.properties"; public static final String PORT_PROPERTIES_NAME = "port"; public static final String HOST_PROPERTIES_NAME = "host"; static { URL url = null; File file = null; String urlString = ""; try { url = ClassLoader.getSystemClassLoader().getResource( JCovSESocketSaver.class. getCanonicalName(). replace('.', '/') + ".class"); } catch( Exception ignore ) { } if (url != null) { urlString = url.toString(); if (urlString.contains("file:") && urlString.contains("!")) { urlString = urlString.substring(urlString.indexOf("file:"), urlString.indexOf('!')); } urlString = urlString.replaceAll("jrt:", "file:"); try { url = new URL(urlString); file = new File(url.toURI()); } catch (Exception e) { System.err.println("Error while finding " + urlString + " file: " + e); } } if (file == null) { try { file = new File(System.getProperty("java.home") + File.separator + NETWORK_DEF_PROPERTIES_FILENAME); } catch( Exception ignore ) { } } if (file != null && file.exists()) { File defProperties = new File(file.getParent() + File.separator + NETWORK_DEF_PROPERTIES_FILENAME); if (defProperties.exists()) { Properties prop = new Properties(); try { prop.load(new FileInputStream(defProperties)); if (prop.getProperty(PORT_PROPERTIES_NAME) != null) { setDefaultPort(Integer.valueOf(prop.getProperty(PORT_PROPERTIES_NAME))); } if (prop.getProperty(HOST_PROPERTIES_NAME) != null) { setDefaultHost(prop.getProperty(HOST_PROPERTIES_NAME)); } } catch (Exception e) { System.err.println("Error while reading " + defProperties.getAbsolutePath() + " file: " + e); } } } } public synchronized void saveResults() { try { host = detectHost(); port = detectPort(); String testname = PropertyFinder.findValue("testname", null); if (testname == null) { testname = PropertyFinder.findValue("file", "result.xml"); } else { if ("<jcov.ignore>".equals(testname)) { return; // ignoring this test data } } int count = 0; final long[] data = Collect.counts(); final long[] dataVal = new long[data.length]; final int[] dataIdx = new int[data.length]; int lastIndex = 0; for (int i = 0; i < Collect.MAX_SLOTS; i++) { if (data[i] != 0) { dataIdx[count] = i; dataVal[count] = data[i]; lastIndex = i; count++; } } Socket s = null; /* Make 3 attempts to connect with JCOV server */ for (int i = 0; i < 3; i++) { try { s = new Socket(host, port); } catch (UnknownHostException e) { System.err.println("JCovRT: Can't resolve hostname " + host + " - unknown host. Exiting. "); return; } catch (Throwable e) { System.err.println("Attempt to connect to " + host + ":" + port + " failed: "); System.err.println(e.getMessage()); } if (s != null) { break; } Thread.sleep(3000); } if (s == null) { return; } //System.out.println("Connected to " + host + ":" + port); DataOutputStream out = new DataOutputStream(s.getOutputStream()); out.write(new byte[]{'J', 'C', 'O', 'V'}); // magicword - 8bytes out.write(SOCKET_SAVER_VERSION); // version - 1byte out.writeUTF(System.getProperty("user.name")); // testername - 1+?bytes out.writeUTF(testname); // testname - 1+?bytes out.writeUTF(PropertyFinder.findValue("product", "")); // productname - 1+?bytes out.writeBoolean(false); // static - 1byte out.writeUTF("NIY"); out.writeInt(count); out.writeInt(lastIndex); for (int j = 0; j < count; ++j) { out.writeInt(dataIdx[j]); out.writeLong(dataVal[j]); } out.close(); s.close(); } catch (InterruptedException e) { } catch (Exception e) { e.printStackTrace(); } } }
6,889
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FileSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/FileSaver.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.InstrumentationOptions.MERGE; import com.sun.tdk.jcov.util.RuntimeUtils; import java.io.File; import java.io.IOException; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public abstract class FileSaver implements JCovSaver { static final int LOCK_REPEAT = 50; static final int LOCK_SLEEP = 50000; protected String filename; // filename to write data to protected String template; // template protected MERGE mergeMode; // GEN_SUFF - generate suffics to the file when exists; MERGE - merge if exists; SCALE - MERGE + write scales; OVERWRITE - remove and write if exists; protected boolean insertOnly; // do not change initial hit values when merging into protected DataRoot root; // coverage data + product template protected boolean scales; private static boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); protected static String genUniqFileName(String filename) { for (int i = 1; i < Integer.MAX_VALUE; i++) { if (!new File(filename + "." + i).exists()) { return filename + "." + i; } } throw new Error("It\'s impossible..."); } /** * This constructor configures file saver using Option's values * * @param root */ protected FileSaver(DataRoot root, MERGE merge) { filename = MiscConstants.JcovSaveFileNameXML; template = MiscConstants.JcovTemplateFileNameXML; mergeMode = merge; this.root = root; this.scales = merge == MERGE.SCALE; } /** * This constructor configures file saver with passed parameters * * @param root * @param filename * @param template * @param merge */ protected FileSaver(DataRoot root, String filename, String template, MERGE merge, boolean scales) { this.filename = filename; this.template = template; mergeMode = merge; this.root = root; this.scales = scales; } public abstract void saveResults(String filename) throws Exception; abstract void mergeResults(String dest, String src, boolean scale) throws Exception; public void saveResults() { if (root.getParams().isDynamicCollect() && Collect.enabled) { CollectDetect.enterInstrumentationCode(); } try { if (mergeMode.equals(MERGE.GEN_SUFF)) { try2MergeAndSave(filename + RuntimeUtils.genSuffix(), template, scales || mergeMode == MERGE.SCALE); return; } if (new File(filename).exists() && !mergeMode.equals(MERGE.OVERWRITE)) { try2MergeAndSave(filename, filename, scales || mergeMode == MERGE.SCALE); return; } else { try2MergeAndSave(filename, template, scales || mergeMode == MERGE.SCALE); } } catch (Exception e) { e.printStackTrace(); } finally { if (root.getParams().isDynamicCollect() && Collect.enabled) { CollectDetect.leaveInstrumentationCode(); } } } private void try2MergeAndSave(String filename, String mergeSrc, boolean scales) throws Exception { boolean srcExists = mergeSrc != null && new File(mergeSrc).exists(); if (srcExists) { mergeResults(filename, mergeSrc, scales); } else { saveResults(filename); } } // public static FileSaver getFileSaver(DataRoot root, MERGE merge, boolean insertOnly) { // // return getFileSaver(root, MiscConstants.JcovSaveFileNameXML, MiscConstants.JcovTemplateFileNameXML, merge, insertOnly, false); // } // public static FileSaver getFileSaver(DataRoot root, String filename, String template, MERGE merge) { return getFileSaver(root, filename, template, merge, false, false); } protected boolean agentdata = false; public void setAgentData(boolean agentdata) { this.agentdata = agentdata; } public static FileSaver getFileSaver(DataRoot root, String filename, String template, MERGE merge, boolean agentData) { FileSaver fileSaver = getFileSaver(root, filename, template, merge, false, false); fileSaver.agentdata = agentData; return fileSaver; } public static FileSaver getFileSaver(DataRoot root, boolean insertOnly) { return getFileSaver(root, MiscConstants.JcovSaveFileNameXML, MiscConstants.JcovTemplateFileNameXML, MERGE.MERGE, insertOnly, false); } public static FileSaver getFileSaver(DataRoot root, String filename, String template, MERGE merge, boolean insertOnly, boolean scales) { FileSaver saver = new JCovXMLFileSaver(root, filename, template, merge, scales); saver.insertOnly = insertOnly; return saver; } public static void setDisableAutoSave(boolean flag) { Collect.saveAtShutdownEnabled = !flag; } public static void addAutoShutdownSave() { PropertyFinder.addAutoShutdownSave(); } }
6,480
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SaverDecorator.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/SaverDecorator.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; /** * * @author Andrey Titov */ public interface SaverDecorator extends JCovSaver { public void init(JCovSaver saver); }
1,371
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovSEServerSocketSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/JCovSEServerSocketSaver.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * * @author Sergey Borodin */ public class JCovSEServerSocketSaver extends JCovServerSocketSaver { public JCovSEServerSocketSaver() { super(); SEServer server = new SEServer(); server.setDaemon(true); startServer(server); } public JCovSEServerSocketSaver(int port) { super(port); SEServer server = new SEServer(); server.setDaemon(true); startServer(server); } class SEServer extends Thread { public void run() { try { ServerSocket ssock = new ServerSocket(port); System.out.println("JCov server saver started on port: " + port); Socket sock = ssock.accept(); System.out.println("Remote request accepted"); ByteArrayOutputStream bo = new ByteArrayOutputStream(Collect.MAX_SLOTS * 4); DataOutputStream os = new DataOutputStream(bo); for (int j = 0; j < Collect.counts().length; j++) { os.writeLong(Collect.counts()[j]); } OutputStream oss = sock.getOutputStream(); oss.write(bo.toByteArray()); oss.close(); os.close(); sock.close(); ssock.close(); } catch (Throwable t) { System.err.println("Problem during server saver run: " + t.getMessage()); //throw new Error("Unexpected error during saving: " + e.getMessage()); } } } }
2,952
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovXMLFileSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/JCovXMLFileSaver.java
/* * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import com.sun.tdk.jcov.Merger; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.XmlContext; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.util.RuntimeUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.List; /** * * @author Sergey Borodin */ public class JCovXMLFileSaver extends FileSaver { // private final static boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); public JCovXMLFileSaver(DataRoot root, InstrumentationOptions.MERGE mergeMode) { super(root, mergeMode); } public JCovXMLFileSaver(DataRoot root, String filename, String template, InstrumentationOptions.MERGE merge, boolean scales) { super(root, filename, template, merge, scales); } public void saveResults(String filename) throws Exception { //if (isWindows) { File file = new File(filename); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); for (int i = LOCK_REPEAT; i != 0; i--) { try { FileLock lock = channel.tryLock(); ByteArrayOutputStream os = new ByteArrayOutputStream(); XmlContext ctx = new XmlContext(os, root.getParams()); ctx.setSkipNotCoveredClasses(agentdata); root.xmlGen(ctx); ctx.close(); channel.truncate(0); channel.write(ByteBuffer.wrap(os.toByteArray())); lock.release(); channel.close(); return; } catch (OverlappingFileLockException e) { Thread.sleep(LOCK_SLEEP); } } /*} else { XmlContext ctx = new XmlContext(filename, root.getParams()); ctx.setSkipNotCoveredClasses(agentdata); root.xmlGen(ctx); ctx.close(); }*/ } void mergeResults(String dest, String src, boolean scale) throws Exception { if (insertOnly) { String tmpname = dest + ".tmp"; saveResults(tmpname); try { root = Reader.readXML(src, scale, null); DataRoot templRoot = Reader.readXML(tmpname, scale, null); List<DataPackage> packs = root.getPackages(); for (DataPackage templPack : templRoot.getPackages()) { boolean pInserted = false; for (DataPackage pack : packs) { if (!pack.getName().equals(templPack.getName())) { continue; } for (DataClass clazzNew : templPack.getClasses()) { boolean cInserted = false; for (DataClass clazz : pack.getClasses()) { if (clazz.getName().equals(clazzNew.getName())) { cInserted = true; break; } } if (!cInserted) { pack.getClasses().add(clazzNew); } } pInserted = true; break; // there can't be 2 similar packages } if (!pInserted) { root.addPackage(templPack); } } root.setCount(templRoot.getCount()); templRoot.destroy(); saveResults(dest); } catch (Exception e) { throw new Error(e); } finally { new File(tmpname).delete(); } } else { String tmpFileName = dest + RuntimeUtils.genSuffix(); try { this.saveResults(tmpFileName); if (scale) { Merger.main(new String[]{"-output", dest, "-scale", "-compress", tmpFileName, src}); } else { Merger.main(new String[]{"-output", dest, tmpFileName, src}); } } finally { new File(tmpFileName).delete(); } } } }
6,016
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
TemplateFileSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/TemplateFileSaver.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import com.sun.tdk.jcov.util.MapHelper; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class TemplateFileSaver implements JCovSaver { /** * Default value for output file */ private static final String def_filename_xml = "result.xml"; /** * Default value for template file */ private static final String def_template = "template.xml"; private String filename = def_filename_xml; private String template = def_template; public TemplateFileSaver() { } public TemplateFileSaver(String filename, String template) { this.filename = filename; this.template = template; } public void saveResults() { template = PropertyFinder.findValue("template", template); filename = PropertyFinder.findValue("file", filename); try { MapHelper.mapCounts(filename, template, Collect.counts()); } catch (Exception e) { System.err.println( "Exception occurred while saving result into " + filename + " file.\n" + "Template file: " + template + "\n" + "Exception details: " + e.getMessage()); if (PropertyFinder.findValue("verbose", null) != null) { System.err.println("\nStack trace: "); e.printStackTrace(System.err); } } } }
2,640
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Collect.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/Collect.java
/* * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import java.util.Objects; /** * <p> Stores all runtime coverage information. Coverage information is stored * in array of longs (counts[MAX_SLOTS]). </p> <p> Here should be no imports! * Collect should be usable in the earliest VM lifecycle - eg in String class * loading. </p> <p> slots count can be optimized at instrumentation time * by generation Collect class exactly for instrumented data. For agent it's * possible to use increasing array (see newSlot()). </p> * * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class Collect { // coverage data public static final int MAX_SLOTS = 2000000; public static int SLOTS = MAX_SLOTS; private static final int MAX_SAVERS = 10; private static int nextSlot = 0; private static long[] counts; private static long[] counts_; // -- coverage data // savers private static JCovSaver[] savers = new JCovSaver[MAX_SAVERS]; private static int nextSaver = 0; private static Class<SaverDecorator> extension = null; protected static boolean isVMReady = false; // -- savers // saving state public static boolean enabled = false; static boolean saveEnabled = true; static boolean saveAtShutdownEnabled = true; static boolean isInitialized = false; static boolean isInternal = false; // -- saving state /** * <p> Reserves a new slot for coverage item. </p> * * @return next slot number */ public static int newSlot() { if (nextSlot >= counts.length) { long[] newCounts = new long[nextSlot * 2]; System.arraycopy(counts, 0, newCounts, 0, counts.length); counts_ = counts = newCounts; // throw new Error("Method slot count exceeded"); } return nextSlot++; } /** * <p> Get current number of slots </p> * * @return current number of slots */ public static int slotCount() { return nextSlot; } /** * <p> Increase coverage statistics on certain slot. </p> <p> Slot is an * array element which is dedicated to a certain code member (eg a block of * code). This array element stores number of times this member was 'hit' or * called. </p> * * @param slot */ public static void hit(int slot) { counts[slot]++; } /** * <p> Set number of slots </p> * * @param i new number of slots */ public static void setSlot(int i) { nextSlot = i; } /** * <p> Check whether the member was hit at least once </p> * * @param slot * @return */ public static boolean wasHit(int slot) { return counts_[slot] != 0; } /** * <p> Get all coverage data in the array. </p> <p> The real numbers are * returned always in this method. The coverage data is copied in a * temporary array while it's being saved so that new coverage data coming * from different threads would not corrupt saving coverage data. This * method will return data being saved in case Collect.saveResults() was * called. </p> * * @return coverage data */ public static long[] counts() { return counts_; } /** * <p> Get coverage data on a certain member </p> * * @param slot member ID * @return coverage data */ public static long countFor(int slot) { return counts_[slot]; } /** * <p> Set coverage data for a certain member </p> * * @param slot member ID * @param count new coverage data */ public static void setCountFor(int slot, long count) { counts[slot] = count; } /** * <p> Create the storage for coverage data. Allocates * <code>SLOTS</code> array of longs. </p> * * @see #SLOTS */ public static void enableCounts() { counts_ = counts = new long[SLOTS]; } /** * <p> Agent should not instrument classes if Collect is disable. </p> */ public static void disable() { enabled = false; } /** * <p> Agent should not instrument classes if Collect is disable. </p> */ public static void enable() { enabled = true; } /** * <p> Adds a saver to be called when saveResults is invoked </p> * * @param saver */ public static synchronized void addSaver(JCovSaver saver) { savers[nextSaver++] = saver; } /** * <p> Sets a saver to be called when saveResults is invoked. All previously * added savers will be removed. </p> * * @param saver */ public static synchronized void setSaver(JCovSaver saver) { for (int i = 0; i < nextSaver; ++i) { savers[i] = null; } nextSaver = 0; addSaver(saver); } /** * <p> Save all collected data with all savers installed in Collect. If * "jcov.saver" property is set savers names would be read from this * property. </p> <p> Coverage data array will be hidden while saveResults * is working to be sure that other threads will not corrupt data that is * being saved. </p> */ public static synchronized void saveResults() { if (!saveEnabled) { return; } // Disable hits. Can't use "enabled = false" as it will result in Agent malfunction counts = new long[counts.length]; // reset counts[] that are collecting hits - real hits will be available in counts_ String s = PropertyFinder.findValue("saver", null); if (s != null) { String[] saver = new String[s.length()]; int i = 0; while (s.length() > 0) { int k = s.indexOf(";"); if (k == 0) { s = s.substring(1); } else if (k > 0) { String newS = s.substring(0, k); if (newS.length() > 0) { saver[i++] = newS; } s = s.substring(k); } else { saver[i++] = s; break; } } for (int j = 0; j < i; j++) { try { Objects.requireNonNull(instantiateSaver(saver[j])).saveResults(); } catch (Throwable t) { t.printStackTrace(); } } } else { for (int i = 0; i < nextSaver; i++) { try { if (savers[i] != null) savers[i].saveResults(); } catch (Throwable t) { t.printStackTrace(); } } } counts_ = counts; // repoint counts_[] that are answering DataRoot about hits to newly created counts[] // Enable hits. Can't use "enabled = false" as it will result in Agent malfunction } /** * <p> Loads satellite class if it's not loaded. </p> */ private static void loadSaverExtension() { if (extension != null) { return; } String m = PropertyFinder.findValue("extension", null); if (m != null) { if (m.equals("javatest") || m.equals("jt") || m.equals("jtreg")) { m = "com.sun.tdk.jcov.NetworkSatelliteDecorator"; } try { extension = (Class<SaverDecorator>) Class.forName(m); } catch (Throwable t) { t.printStackTrace(); } } } /** * <p> Create Saver instance by name. The saver will be wrapped by Satellite * instance if any. </p> * * @return Created Saver */ private static JCovSaver instantiateSaver() { JCovSaver saver = null; // This line is replaced in ANT build script (see files filesaver.replace.properties, networksaver.replace.properties and so on) //@BUILD_MODIFIED_SAVER_STRING@// return saver; } private static JCovSaver instantiateSaver(String name) { try { return decorateSaver((JCovSaver) Class.forName(name).getDeclaredConstructor().newInstance()); } catch (Throwable t) { t.printStackTrace(); } return null; } public static JCovSaver decorateSaver(JCovSaver saver) { if (extension != null) { try { SaverDecorator s = extension.getDeclaredConstructor().newInstance(); s.init(saver); return s; } catch (Throwable t) { t.printStackTrace(); } } return saver; } /** * <p> Initialize JCov RT. This method is called in static initialization of * Collect class and in static initialization of every instrumented class * (&lt;clitin&gt; method) </p> */ public static void init() { if (!isInitialized && !isInternal) { isInternal = true; if (isVMReady || isVMReady()) { loadSaverExtension(); addSaver(instantiateSaver()); PropertyFinder.addAutoShutdownSave(); isInitialized = true; } isInternal = false; } } static { Collect.enableCounts(); Collect.init(); } /** * <p> Checks whether VM is ready to initialize JCov RT (saver). Most savers * use shutdown hook to save data in time. Shutdown hook needs Thread to be * created but it can't be created in very early VM livetime. </p> <p> Due * to restrictions JCovME version should have it's own isVMReady() * implementation. </p> * * @return true if VM is ready to install shutdown hook and to read * properties */ public static boolean isVMReady() { isVMReady = System.out != null && Runtime.getRuntime() != null; return isVMReady; // return jdk.internal.misc.VM.isBooted(); } }
11,279
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovSocketSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/JCovSocketSaver.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; /** * * @author Sergey Borodin */ public abstract class JCovSocketSaver implements JCovSaver { public static final int SOCKET_SAVER_VERSION = 0; protected static String defaultHost = "localhost"; protected static int defaultPort = 3334; protected static final String HOST = "host"; protected static final String PORT = "port"; protected String host; protected int port = -1; static void setDefaultHost(String host) { defaultHost = host; } static void setDefaultPort(int port) { defaultPort = port; } static String detectHost() { return PropertyFinder.findValue(HOST, defaultHost); } static int detectPort() { String p = null; try { p = PropertyFinder.findValue(PORT, "" + defaultPort); return Integer.parseInt(p); } catch (NumberFormatException e) { System.err.println("JCovRT: Port parse error (not a number) " + p); } catch (Throwable ignore) { } return defaultPort; } public JCovSocketSaver() { } public JCovSocketSaver(String host, int port) { this.host = host; this.port = port; } public abstract void saveResults(); }
2,481
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
NetworkSatelliteDecorator.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/NetworkSatelliteDecorator.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import java.io.*; import java.net.Socket; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * @author Andrey Titov */ public class NetworkSatelliteDecorator implements SaverDecorator { private JCovSaver wrapped; private int port = 3337; private static String host = "localhost"; private static Lock lock = new ReentrantLock(); private Thread socketClientThread = null; private volatile String name = null; public void init(JCovSaver wrap) { this.wrapped = wrap; listenObserver(); } private void listenObserver(){ socketClientThread = new Thread(new Runnable() { @Override public void run() { BufferedReader in; PrintWriter out; try { Socket socket = new Socket(host, port); in = new BufferedReader(new InputStreamReader( socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); while (true) { String line = null; try { line = in.readLine(); } catch (Exception e) { lock.lock(); try { Collect.saveResults(); //wrapped.saveResults(); } finally { lock.unlock(); } } if (line != null) { if (line.startsWith("NAME")) { name = line.substring(4, line.length()); System.setProperty("jcov.testname", name); out.println("named " + name); out.flush(); } else if (line.startsWith("SAVE")) { name = line.substring(4, line.length()); System.setProperty("jcov.testname", name); lock.lock(); try { Collect.saveResults(); //wrapped.saveResults(); } finally { lock.unlock(); } out.println("saved " + name); out.flush(); name = null; } } } } catch (Exception e) { System.err.println("JCovRT SocketClient: " + e); } } }); socketClientThread.setDaemon(true); socketClientThread.start(); } public void saveResults() { while (name == null){ try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } if (name != null) { System.setProperty("jcov.testname", name); lock.lock(); try { wrapped.saveResults(); } finally { lock.unlock(); } name = null; } } }
4,817
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
PropertyFinder.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/PropertyFinder.java
/* * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SE implementation of PropertyFinder * * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public final class PropertyFinder { /** * Reads input string substituting macros. No additional shortcuts * used. * * @param str String to parse and substitute * @return Parsed string */ public static String processMacroString(String str) { return processMacroString(str, null, null); } /** * Reads input string substituting macros. Additional shortcuts can be * used to enhance or overwrite default macros. * * @param str String to parse and substitute * @param shortcuts * @param datas * @return */ public static String processMacroString(String str, char shortcuts[], String datas[]) { if (str == null) { return str; } StringBuilder buf = new StringBuilder(); int start = 0, pos = 0; while (true) { pos = str.indexOf('%', start); if (pos < 0) { buf.append(str.substring(start)); break; } buf.append(str.substring(start, pos)); int end = str.indexOf('%', pos + 1); if (end < 0) { buf.append(str.substring(pos)); break; } String patt = str.substring(pos, end); if (end - pos < 2) { // % buf.append('%'); } else { char ch = patt.charAt(1); if (end - pos == 2) { // prebuilt patterns boolean found = false; if (shortcuts != null) { for (int i = 0; i < shortcuts.length; ++i) { if (shortcuts[i] == ch) { found = true; buf.append(datas[i]); } } } if (!found) { switch (ch) { case 'd': // M-D-Y Calendar c = Calendar.getInstance(); buf.append(c.get(Calendar.HOUR_OF_DAY)).append(':'). append(c.get(Calendar.MINUTE)).append(':'). append(c.get(Calendar.SECOND)).append('_'). append(c.get(Calendar.MONTH) + 1).append('-'). append(c.get(Calendar.DAY_OF_MONTH)).append('-'). append(c.get(Calendar.YEAR)); break; case 't': // h:m:s c = Calendar.getInstance(); buf.append(c.get(Calendar.HOUR_OF_DAY)).append(':'). append(c.get(Calendar.MINUTE)).append(':'). append(c.get(Calendar.SECOND)); break; case 'D': // VM workdir buf.append(System.getProperty("user.dir")); break; case 'R': // random int buf.append(Math.round(Math.random() * 100000)); break; case 'T': // time buf.append(System.currentTimeMillis()); break; case 'U': // username buf.append(System.getProperty("user.name")); break; case 'V': // JAVA version buf.append(System.getProperty("java.version")); break; default: --end; // including last % to next search buf.append(patt); break; } } } else if (ch == 'F') { // static field int ind = patt.lastIndexOf('.'); String className = patt.substring(2, ind ); try { Class c = Class.forName(className); Field f = c.getDeclaredField(patt.substring(ind + 1)); boolean changed = false; if (! f.isAccessible()) { f.setAccessible(true); changed = true; } try { if (f != null) { buf.append(f.get(null).toString()); } else { --end; // including last % to next search buf.append(patt); } } finally { if (changed) { f.setAccessible(false); } } } catch (Exception e) { --end; // including last % to next search buf.append(patt); } } else if (ch == 'M') { // static method int ind = patt.lastIndexOf('.'); String className = patt.substring(2, ind); try { Class c = Class.forName(className); Method m = c.getDeclaredMethod(patt.substring(ind + 1), (Class[]) null); boolean changed = false; if (!m.isAccessible()) { m.setAccessible(true); changed = true; } try { if (m != null && m.getReturnType() != Void.class) { buf.append(m.invoke(null, (Object[]) null).toString()); } else { --end; // including last % to next search buf.append(patt); } } finally { if (changed) { m.setAccessible(false); } } } catch (Exception e) { --end; // including last % to next search buf.append(patt); } } else if (ch == 'E' || ch == 'P') { // environment variable or Java property String prop = System.getenv(patt.substring(2)); if (prop != null) { buf.append(prop); } else { --end; // including last % to next search buf.append(patt); } } else { // Java property String prop = System.getProperty(patt.substring(1)); if (prop != null) { buf.append(prop); } else { --end; // including last % to next search buf.append(patt); } } } start = end + 1; } return buf.toString(); } private static Properties p; private static boolean propsRead = false; private static String propsFile; public static final String PROPERTY_FILE_PREFIX = "jcov."; public static final String JVM_PROPERTY_PREFIX = PROPERTY_FILE_PREFIX; public static final String ENV_PROPERTY_PREFIX = "JCOV_"; /** * Returns value specified by user. If sys prop defined the value is * taken from system property, if not the looks for env variable setting and * the default value is taken in the last turn. * * @param name - variable name. JCOV_{NAME} is used for sys env, jcov.{name} * is used for jvm env * @param defaultValue - default value * @return */ public static String getStaticValue(String name, String defaultValue) { try { String res = System.getProperty(PROPERTY_FILE_PREFIX + name); if (res != null) { return res; } res = System.getenv(ENV_PROPERTY_PREFIX + name.replace('.', '_').toUpperCase()); if (res != null) { return res; } } catch (Exception ignored) { } return defaultValue; } /** * Returns value specified by user. If sys prop is defined the value is * taken from system property, if not the looks for env variable setting, if * not it looks in property files and the default value is taken in the last * turn. * * @param name - variable name. JCOV_{NAME} is used for sys env, jcov.{name} * is used for jvm env * @param defaultValue - default value * @return */ public static String findValue(String name, String defaultValue) { String res = getStaticValue(name, null); if (res == null) { Properties p = findProperties(); if (p != null) { res = p.getProperty(PROPERTY_FILE_PREFIX + name, defaultValue); } else { res = defaultValue; } } return processMacroString(res, null, null); } /** * Searches for jcov property file. First candidate to read is file in * JCOV_PROPFILE system env variable. Second candidate is file in * jcov.propfile jvm env. Third candidate to read is * {user.home}/.jcov/jcov.properties file. Every filename is * firstly checked as a file and is read only if such file exists and can be * read. If it's not a file, can't be read, doesn't exist or is not a * property file then classpath resource is checked. * * @return Properties read from all possible sources or null if not found. */ private static Properties findProperties() { if (!propsRead) { propsRead = true; String propfile = getStaticValue("propfile", null); // jcov.propfile or JCOV_PROPFILE if (propfile != null) { p = loadPropertiesFile(propfile, null); if (p != null) { propsFile = propfile; return p; } } try { p = loadPropertiesFile(System.getProperty("user.home") + File.separator + ".jcov" + File.separator + "jcov.properties", null); if (p != null) { propsFile = System.getProperty("user.home") + File.separator + ".jcov" + File.separator + "jcov.properties"; } } catch (Exception ignore) { } } return p; } private static Properties loadPropertiesFile(String path, Properties properties) { try(InputStream in = new FileInputStream(path)) { Properties p = ( properties == null) ? new Properties() : properties; p.load(in); resolveProps(p); properties = p; } catch (Exception ignore) { // warning message } return properties; } /** * Reads jcov property file from specified path * If it can't be read then classpath resource is checked. * * @param path Path to look for a property file. * @return Read properties or null if file was not found neither in file * system neither in classpath */ public static Properties readProperties(String path, Properties properties) { if (properties == null) { properties = new Properties(); } return loadPropertiesFile(path, properties); } /** * Resolves all links of ${key} form on other keys in property values. * * @param props Properties to resolve. */ private static void resolveProps(Properties props) { Pattern p = Pattern.compile(".*(\\$\\{(.*)\\})"); for (Object o : props.keySet()) { String name = (String) o; String val = props.getProperty(name); Matcher m = p.matcher(val); while (m.find()) { String link = m.group(2); String lVal = props.getProperty(link); val = val.replace(m.group(1), lVal); m = p.matcher(val); } props.put(o, val); } } /** * Read a single property from property file * * @param fileName file to look value in * @param name name of value to read * @return value of "name" in fileName property file or null if such * property file doesn't exist */ public static String readPropFrom(String fileName, String name) { Properties props = loadPropertiesFile(fileName, null); return props != null ? props.getProperty(PROPERTY_FILE_PREFIX + name) : null; } /** * Describes source of a property by name. Returns a string containing * description of the property source. E.g.: <ul> <li> "JavaVM property * 'jcov.propfile' </li> <li> "system environment property 'JCOV_TEMPLATE' * </li> <li> "property file from '/temp/jcov/jcov.properties' </li> <li> * "defaults" </li> </ul> * * @param name Property name to check source * @return String describing property source. */ public static String findSource(String name) { if (name == null || name.isEmpty()) { return ""; } if (System.getProperty(JVM_PROPERTY_PREFIX + name) != null) { return "JavaVM property '" + JVM_PROPERTY_PREFIX + name + "'"; } if (System.getenv(ENV_PROPERTY_PREFIX + name.toUpperCase()) != null) { return "system environment property '" + ENV_PROPERTY_PREFIX + name.toUpperCase() + "'"; } if (!propsRead) { findProperties(); } if (propsFile != null && p.containsKey(PROPERTY_FILE_PREFIX + name)) { return "property file from '" + propsFile + "'"; } return "defaults"; } /** * Set path for properties file to read values. Can be used many times. * * @param path Path to read */ public static void setPropertiesFile(String path) { propsFile = path; p = loadPropertiesFile(path, null); propsRead = true; } public static void cleanProperties() { p = null; propsFile = null; propsRead = false; } /** * Installs shutdown hook. */ public static void addAutoShutdownSave() { if (Collect.saveAtShutdownEnabled && "true".equals(findValue("autosave", "true"))) { Thread hook = new Thread() { @Override public void run() { Collect.disable(); Collect.saveResults(); Collect.enable(); Collect.saveAtShutdownEnabled = false; Collect.saveEnabled = false; String s = PropertyFinder.findValue("data-saver", null); if(s != null) { try { Class clz = Class.forName(s); Object saver = clz.getConstructor().newInstance(); Method mthd = clz.getMethod("saveResults", new Class[] {}); mthd.invoke(saver); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new RuntimeException(e); } } } }; try { Runtime.getRuntime().addShutdownHook(hook); } catch (Exception ignore) { System.err.println("Can't set shutdown hook."); ignore.printStackTrace(); } } } }
18,155
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovSaver.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/runtime/JCovSaver.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.runtime; /** * * @author Leonid Mesnik */ public interface JCovSaver { public void saveResults(); }
1,341
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
package-info.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/package-info.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * <p> Utility classes for creating custom tools. </p> */ package com.sun.tdk.jcov.tools;
1,301
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DeflaterScaleCompressor.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/DeflaterScaleCompressor.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import com.sun.tdk.jcov.util.Utils; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; /** * Implements a scale compressor which compresses/decompresses test scales using * standard zip-compression algorithms. Since zip-compressed data may contain * unprintable characters and jcov data file is a plain ASCII file, this * compressor (when doing compression) converts each 4-bytes of the compressed * data to a hex-digit character. * * @see ScaleCompressor * @see com.sun.tdk.jcov.filedata.Scale * @author Konstantin Bobrovsky */ public class DeflaterScaleCompressor implements ScaleCompressor { public final static String sccsVersion = "%I% $LastChangedDate: 2013-09-30 17:48:28 +0400 (Mon, 30 Sep 2013) $"; protected static byte[] buf = new byte[2048]; protected static final Deflater def = new Deflater(Deflater.BEST_COMPRESSION, true); protected static final ByteArrayOutputStream bos = new ByteArrayOutputStream(512); protected static final DeflaterOutputStream dos = new DeflaterOutputStream(bos, def); protected static final Inflater inf = new Inflater(true); protected static final ByteArrayInputStream bis = new ByteArrayInputStream(buf); protected static final InflaterInputStream ios = new InflaterInputStream(bis, inf); /** * @see ScaleCompressor#decompress(char[], int, byte[], int) */ public void decompress(char[] src, int len, byte[] dst, int bits_total) throws Exception { for (int i = 0; i < len; i++) { Utils.writeHalfByteAt(Utils.hexChar2Int(src[i]), i, buf); } int buf_len = (bits_total + 7) / 8; try { ios.read(dst, 0, buf_len); inf.reset(); bis.reset(); } catch (Exception e) { e.printStackTrace(); throw new Exception("invalid compression"); } } /** * @see ScaleCompressor#compress(byte[], StringBuffer, int) */ public int compress(byte[] src, StringBuffer dst, int bits_total) { try { dos.write(src, 0, (bits_total + 7) / 8); dos.finish(); dos.flush(); bos.flush(); } catch (IOException e) { return -1; } byte[] res = bos.toByteArray(); def.reset(); bos.reset(); if (res.length * 2 > dst.length()) { dst.setLength(res.length * 2); } for (int i = 0; i < res.length * 2; i++) { dst.setCharAt(i, Utils.int2HexChar(Utils.getHalfByteAt(i, res))); } return res.length * 2; } }
4,016
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DelegateIterator.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/DelegateIterator.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import java.util.Iterator; import java.util.NoSuchElementException; /** * * @author Sergey Borodin */ public abstract class DelegateIterator<E> implements Iterator<E> { public DelegateIterator() { mode = 0; delegate = nextIterator(); } /** * 0 - "In progress" state 1 - terminate state */ private int mode; /** * current delegating iterator null means there is nothing more to iterate */ private Iterator<E> delegate; public boolean hasNext() { if (mode == 1) { return false; } else { if (delegate == null) { mode = 1; return false; } else { if (!delegate.hasNext()) { delegate = nextIterator(); return hasNext(); } else { return true; } } } } public E next() { if (mode == 1) { throw new NoSuchElementException(); } else if (delegate == null) { mode = 1; throw new NoSuchElementException(); } else { if (!delegate.hasNext()) { delegate = nextIterator(); return next(); } else { return delegate.next(); } } } protected abstract Iterator<E> nextIterator(); public void remove() { } }
2,684
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SimpleScaleCompressor.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/SimpleScaleCompressor.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import com.sun.tdk.jcov.util.Utils; /** * Implements a scale compressor, which quite efficient in compressing test * scales containing long sequences of the same character. The basic algorithm * is the following : Sequence of N characters &lt;ch&gt; (hex digits actually) * is transformed into the sequence &lt;Nrep&gt;&lt;ch&gt;, where Nrep * represents value N written in a big-radix numeric system. Digits of this * system do not include possible &lt;ch&gt;'s (i.e. hex digits) providing an * unambiguous way of backward transformation. * * @see ScaleCompressor * @see com.sun.tdk.jcov.filedata.Scale * @author Konstantin Bobrovsky */ public class SimpleScaleCompressor implements ScaleCompressor { public final static String sccsVersion = "%I% $LastChangedDate: 2009-06-08 18:52:39 +0400 (Mon, 08 Jun 2009) $"; char[] buf = new char[32]; /** * @see ScaleCompressor#decompress(char[], int, byte[], int) */ public void decompress(char[] src, int len, byte[] dst, int scale_size) throws Exception { int dst_ind = 0; int dst_len = Utils.halfBytesRequiredFor(scale_size); int src_ind = 0; do { char ch; int buf_cnt = 0; byte hex_val = -1; try { while (src_ind < len) { ch = src[src_ind++]; hex_val = Utils.hexChar2Int(ch); if (hex_val >= 0) { break; } buf[buf_cnt++] = ch; } if (hex_val < 0) { throw new Exception("malformed scale"); } int i, expand_cnt = (buf_cnt == 0) ? 1 : 0; for (i = 0, buf_cnt--; buf_cnt >= 0; buf_cnt--, i++) { expand_cnt += Utils.convert2Int(buf[buf_cnt]) * Utils.pow(Utils.radix, i); } if (dst_ind + expand_cnt > dst_len) { throw new ArithmeticException(); } for (i = 0; i < expand_cnt; i++) { Utils.writeHalfByteAt(hex_val, dst_ind++, dst); } } catch (ArithmeticException e) { throw new Exception("invalid scale compression"); } catch (IndexOutOfBoundsException e) { throw new Exception("invalid scale size"); } } while (src_ind < len); } /** * @see ScaleCompressor#compress(byte[], StringBuffer, int) */ public int compress(byte[] src, StringBuffer dst, int scale_size) { byte old_quad = Utils.getHalfByteAt(0, src); byte cur_quad; int digit_cnt = 1; int dst_ind = 0; if (scale_size <= 4) { dst.setCharAt(0, Utils.int2HexChar(old_quad)); return 1; } int size = Utils.halfBytesRequiredFor(scale_size); for (int i = 1; i < size; i++) { cur_quad = Utils.getHalfByteAt(i, src); if (cur_quad != old_quad || i == size - 1) { if (cur_quad == old_quad) { digit_cnt++; } if (digit_cnt > 2) { // worth compression dst_ind = Utils.convert2BigRadix(digit_cnt, dst, dst_ind); } else if (digit_cnt == 2) { dst.setCharAt(dst_ind++, Utils.int2HexChar(old_quad)); } dst.setCharAt(dst_ind++, Utils.int2HexChar(old_quad)); if (i == size - 1 && cur_quad != old_quad) { dst.setCharAt(dst_ind++, Utils.int2HexChar(cur_quad)); } digit_cnt = 1; } else { digit_cnt++; } old_quad = cur_quad; } return dst_ind; } }
5,087
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
EnvServiceProvider.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/EnvServiceProvider.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException; /** * * @author Andrey Titov */ public interface EnvServiceProvider extends ServiceProvider { /** * <p> If a service should accept some specific CLI options - their * parameters should be added to EnvHandler as OptionDesc objects. </p> <p> * EnvHandler should not be overwritten - it's already existing handler. * Just add some new options with * <code>addOption(OptionDescr)</code> or * <code>addOptions(OptionDescr[])</code> methods </p> * * @param handler * @see EnvHandler * @see OptionDescr */ public void extendEnvHandler(final EnvHandler handler); /** * <p> After CL string is parsed - JCov will call this method so that * Service can take some parameters from the environment. </p> <p> Use * <code>getValue(OptionDescr)</code>, * <code>getValues(OptionDescr)</code> and * <code>isSet(OptionDescr)</code> to get values of defined options. </p> * * @param handler * @return exit code. 0 means that everything was ok. Non-null return status * doesn't mean stopping the process but thrown Exception will stop the * process. */ public int handleEnv(EnvHandler handler) throws EnvHandlingException; }
2,535
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
OneElemIterator.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/OneElemIterator.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import java.util.Iterator; import java.util.NoSuchElementException; /** * * @author Sergey Borodin */ public class OneElemIterator<E> implements Iterator<E> { private E e; private boolean hasNext; public OneElemIterator(E e) { this.e = e; hasNext = true; } public boolean hasNext() { return hasNext; } public E next() { if (hasNext) { hasNext = false; return e; } else { throw new NoSuchElementException(); } } public void remove() { } }
1,811
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ServiceProvider.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/ServiceProvider.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; /** * * @author Andrey Titov */ public interface ServiceProvider { }
1,311
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
OptionDescr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/OptionDescr.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import java.util.Iterator; /** * This class offers a formal way of describing an option, e.g., whether it has * a value, whether it may be specified more than once, set of possible values * (if any), it's default value if any, it's usage information. * * @author Konstantin Bobrovsky */ public class OptionDescr { public final static int VAL_NONE = 0; public final static int VAL_SINGLE = 1; public final static int VAL_MULTI = 2; /** * <p> Option with VAL_ALL kind will take all values after it. </p> <p> E.g. * "-val_all_option val1 -val2 val3 -val4 -val5" will take all values * "val1", "-val2", "val3", "-val4", "-val5". </p> */ public final static int VAL_ALL = 3; public final static String[][] ON_OFF = new String[][]{ {"on", "on"}, {"off", "off"}}; public final static String ON = "on"; public final static String OFF = "off"; /** * option name */ public String name; /** * option title (should more descriptive than the name) */ public String title; /** * whether the option has a value */ public boolean hasValue = false; /** * set of pairs : &lt;possible value&gt;, &lt;its description&gt; */ public String[][] allowedValues; /** * whether the option may be specified more than once */ public boolean isMultiple = false; /** * usage information */ public String usage; /** * misc flags */ public int flags; /** * default value */ public String defVal; /** * aliases */ public String[] aliases; public ServiceProvider registeringSPI; public int val_kind; /** * Default constructor */ public OptionDescr() { } /** * Creates new OptionDescr. Defaults :<br> - no value<br> - no possible * values<br> - no default value<br> * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String title, String usage) { this(name, title, VAL_NONE, null, usage, null); } /** * Creates new OptionDescr. Defaults :<br> - no value<br> - no possible * values<br> - default value<br> * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String title, String usage, String defValue) { this(name, title, VAL_NONE, null, usage, defValue); } /** * Creates new OptionDescr. Defaults :<br> - no value<br> - no possible * values<br> - no default value<br> * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String[] aliases, String title, String usage) { this(name, aliases, title, VAL_NONE, null, usage, null); } /** * Creates new OptionDescr. Defaults :<br> - can be specified only once * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String title, String[][] allowed_values, String usage, String def_val) { this(name, title, VAL_SINGLE, allowed_values, usage, def_val); } /** * Creates new OptionDescr. Defaults :<br> - have an alias - can be * specified only once * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String[] aliases, String title, String[][] allowed_values, String usage, String def_val) { this(name, aliases, title, VAL_SINGLE, allowed_values, usage, def_val); } /** * Creates new OptionDescr. Defaults :<br> - possible value is arbitrary<br> * - no default value * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String title, int val_kind, String usage) { this(name, title, val_kind, null, usage, null); } /** * Creates new OptionDescr. Defaults :<br> - possible value is arbitrary<br> * - no default value * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String title, int val_kind, String usage, String defValue) { this(name, title, val_kind, null, usage, defValue); } /** * Creates new OptionDescr. Defaults :<br> - aliases are defined - possible * value is arbitrary<br> - no default value * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String[] aliases, String title, int val_kind, String usage) { this(name, aliases, title, val_kind, null, usage, null); } /** * Creates new OptionDescr. Defaults :<br> - aliases are defined - possible * value is arbitrary<br> - no default value * * @see #OptionDescr(String, String, int, String[][], String, String) */ public OptionDescr(String name, String[] aliases, String title, int val_kind, String usage, String defValue) { this(name, aliases, title, val_kind, null, usage, defValue); } /** * Creates new OptionDescr * * @param name option name * @param title option title (should more descriptive than the name) * @param val_kind one of<br> <pre> * <code>VAL_NONE</code> no value <code>VAL_SINGLE</code> has a value and * may be specified only once <code>VAL_MULTI</code> has a value and may be * specified multiple times * </pre> * @param allowed_values set of pairs : &lt;possible value&gt;, &lt;its * description&gt; * @param usage usage information * @param def_val default value */ public OptionDescr(String name, String title, int val_kind, String[][] allowed_values, String usage, String def_val) { this(name, null, title, val_kind, allowed_values, usage, def_val); } /** * Creates new OptionDescr * * @param name option name * @param aliases option aliases * @param title option title (should be more descriptive than the name) * @param val_kind one of<br> <pre> * <code>VAL_NONE</code> no value <code>VAL_SINGLE</code> has a value and * may be specified only once <code>VAL_MULTI</code> has a value and may be * specified multiple times * </pre> * @param allowed_values set of pairs : &lt;possible value&gt;, &lt;its * description&gt; * @param usage usage information * @param def_val default value */ public OptionDescr(String name, String[] aliases, String title, int val_kind, String[][] allowed_values, String usage, String def_val) { this.name = name; this.aliases = aliases; this.title = title; this.usage = usage; this.allowedValues = allowed_values; this.defVal = def_val; this.val_kind = val_kind; if (val_kind != VAL_NONE) { hasValue = true; } if (val_kind == VAL_MULTI || val_kind == VAL_ALL) { isMultiple = true; } } /** * Creates new OptionDescr, filling all fields from &lt;src&gt; * * @param src OptionDescr instance to copy fields from */ public OptionDescr(OptionDescr src) { name = src.name; title = src.title; hasValue = src.hasValue; allowedValues = src.allowedValues; isMultiple = src.isMultiple; usage = src.usage; flags = src.flags; defVal = src.defVal; } /** * @return true if &lt;this&gt; equals o, false otherwise */ public boolean equals(Object o) { if (!(o instanceof OptionDescr)) { return false; } OptionDescr od = (OptionDescr) o; return name.equals(od.name) && (title == null || od.title == null || title.equals(od.title)); } public int hashCode() { int titleHash = title == null ? 0 : title.hashCode(); return super.hashCode() + titleHash; } public boolean isName(String name) { if (name.equalsIgnoreCase(this.name)) { return true; } if (aliases == null) { return false; } for (int i = 0; i < aliases.length; i++) { if (name.equalsIgnoreCase(aliases[i])) { return true; } } return false; } /** * This method returns standard representation of usage. Syntax is: <prefix> * name (alias, alias, ...)<delimeter>'possible values', default is * (default). description. * */ private final static String TAB = " "; private final static String NL = "\n"; public String getUsage(String prefix, String delimeter, String startTab, boolean verbose) { String usageString = ""; if (title != null && title != "") { usageString = startTab + title + NL; } usageString += startTab + TAB + prefix + name; if (aliases != null && aliases.length > 0) { usageString += "("; for (int i = 0; i < aliases.length - 1; i++) { usageString += aliases[i] + ", "; } usageString += aliases[aliases.length - 1]; usageString += ")"; } if (this.hasValue) { usageString += delimeter; if (allowedValues != null && allowedValues.length > 0) { usageString += "["; for (int i = 0; i < allowedValues.length - 1; i++) { usageString += allowedValues[i][0] + "|"; } usageString += allowedValues[allowedValues.length - 1][0]; usageString += "] (By default is: " + defVal + ")"; if (verbose) { for (int i = 0; i < allowedValues.length; i++) { usageString += NL + startTab + TAB + TAB + allowedValues[i][0] + " : " + allowedValues[i][1]; } } } else { usageString += "'string value'"; if (this.defVal != null) { usageString += " (By default is: " + defVal + ")"; } if (this.isMultiple) { usageString += " (Option could be specified several times.)"; } } } if (verbose) { if (usage != null && !"".equals(usage)) { usageString += NL + startTab + TAB + usage.replace(NL, NL + startTab + TAB); } if (registeringSPI != null) { usageString += NL + startTab + TAB + TAB + "registered by " + registeringSPI.getClass(); } usageString += NL; } return usageString; } /** * Check whether value is allowed for this option * * @param value value to check * @return true if any value allowed (allowedValues is set to null) or if * value is in allowedValues; false if value is not in allowedValues */ public boolean isAllowedValue(String value) { if (allowedValues == null) { return true; } for (String[] s : allowedValues) { if (s[0].equals(value)) { return true; } } return false; } public ServiceProvider getRegisteringSPI() { return registeringSPI; } public void setRegisteringSPI(ServiceProvider spi) { this.registeringSPI = spi; } }
13,055
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
LoggingFormatter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/LoggingFormatter.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import com.sun.tdk.jcov.runtime.PropertyFinder; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * * @author Andrey Titov */ public class LoggingFormatter extends Formatter { public static boolean printStackTrace = Boolean.parseBoolean(PropertyFinder.findValue("stacktrace", "false")); @Override public String format(LogRecord record) { if (record.getThrown() != null) { StringBuilder ret = new StringBuilder(String.format("%-8s: %s", record.getLevel().getLocalizedName(), record.getMessage() != null ? formatMessage(record) + "\nException details: " : "")); if (printStackTrace) { StringWriter sw = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(sw)); ret.append(sw.toString()).append("\n"); } else { if (record.getThrown() instanceof NullPointerException) { StackTraceElement[] stackTrace = record.getThrown().getStackTrace(); if (stackTrace.length > 0) { ret.append("NPE in ").append(stackTrace[0]).append("\n"); } else { ret.append("NPE in unknown place"); StringWriter sw = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(sw)); ret.append(sw.toString()).append("\n"); } } else { ret.append(record.getThrown().getMessage()).append("\n"); } } return ret.toString(); } else { return String.format("%-8s: %s\n", record.getLevel().getLocalizedName(), formatMessage(record)); } } }
3,088
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovTool.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/JCovTool.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public abstract class JCovTool { public static class EnvHandlingException extends Exception { public EnvHandlingException(String message) { super(message); } public EnvHandlingException(String message, Throwable cause) { super(message, cause); } public EnvHandlingException() { } } public static final int SUCCESS_EXIT_CODE = 0; public static final int ERROR_CMDLINE_EXIT_CODE = 1; public static final int ERROR_EXEC_EXIT_CODE = 2; private static HashMap<String, Class> spis; protected boolean readPlugins = false; protected JCovTool() { } protected abstract EnvHandler defineHandler(); protected abstract int handleEnv(EnvHandler envHandler) throws EnvHandlingException; protected abstract String getDescr(); protected boolean isMainClassProvided() { return true; } protected abstract String usageString(); /** * Placeholder for command notes if needed * * @return Command note */ protected String noteString() { return null; } protected abstract String exampleString(); protected final void registerSPI(String envname, Class classname) { if (spis == null) { spis = new HashMap<String, Class>(); } spis.put(envname, classname); } private PrintStream out = System.out; public void setOut(PrintStream out) { this.out = out; } public PrintStream getOut() { return out; } private static final String[] allTools = { "com.sun.tdk.jcov.Exec", "com.sun.tdk.jcov.Agent", "com.sun.tdk.jcov.Instr", "com.sun.tdk.jcov.JREInstr", "com.sun.tdk.jcov.ProductInstr", "com.sun.tdk.jcov.Instr2", "com.sun.tdk.jcov.TmplGen", "com.sun.tdk.jcov.Grabber", "com.sun.tdk.jcov.GrabberManager", "com.sun.tdk.jcov.Merger", "com.sun.tdk.jcov.RepMerge", "com.sun.tdk.jcov.Filter", "com.sun.tdk.jcov.DiffCoverage", "com.sun.tdk.jcov.RepGen", "com.sun.tdk.jcov.JCov", "com.sun.tdk.jcov.IssueCoverage" }; public static final List<String> allToolsList = Collections.unmodifiableList(Arrays.asList(allTools)); /** * Prints help about all registered tools in <b>allTools</b> to standard * output * * @see #allTools */ public static void printHelp() { PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()), true); writer.println("Java Code Coverage Tool ver." + JcovVersion.getJcovVersion()); writer.println("Usage: 'java -jar jcov.jar <Name>' or 'java -cp jcov.jar com.sun.tdk.jcov.<Name>'"); writer.println("JCov includes the following components:"); writer.println(); for (String str : allTools) { Class c = null; JCovTool h = null; Object o = null; try { c = Class.forName(str); o = c.getDeclaredConstructor().newInstance(); h = (JCovTool) o; } catch (NoClassDefFoundError cndfe){ if ("com.sun.tdk.jcov.IssueCoverage".equals(str)){ System.out.println("IssueCoverage command request jdk9 or javax.tools in classpath"); continue; } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } // h.printDescr(writer); // if (h.isMainClassProvided()) { String name = c.getName(); // writer.println("\t" + str.substring(name.lastIndexOf(".") + 1) + "\t\t" + h.getDescr()); writer.println(String.format(" %-20s%s", str.substring(name.lastIndexOf(".") + 1), h.getDescr())); // } else { // h.printDescr(writer); // } } writer.println(); writer.println("Use \"java -jar jcov.jar <Name> -help\" for command-line help on each component, or \"java -jar jcov.jar <Name> -help-verbose\" for wider description"); } /** * Prints help by tool`s classname * * @param toolClassObject tool to load * @param args checks whether -help-verbose was mentioned */ public static void printHelp(JCovTool toolClassObject, String[] args) { try { JCovTool d = toolClassObject; for (int i = 0; i < args.length; i++) { if (args[i].endsWith(EnvHandler.HELP_VERBOSE.name)) { d.defineHandler().usage(true); return; } } d.defineHandler().usage(false); } catch (Exception e) { System.out.println("INTERNAL ERROR! " + e.getMessage()); e.printStackTrace(); System.exit(1); } } }
6,479
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SPIDescr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/SPIDescr.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * <p> SPIDescr is an object-descriptor for handling Service Providers in * EnvHandler </p> * * @author Andrey Titov */ public class SPIDescr { private String name; private String description; private boolean isMultiple; private String usage; private Map<String, ServiceProvider> presets; private boolean handled = false; private Class<? extends ServiceProvider> spiClass; private ServiceProvider defaultSPI; /** * Creates instance of SPIDescr class representing SPI * * @param name Name to use as alias in option * @param spiClass Underlying ServiceProvider class */ public SPIDescr(String name, Class<? extends ServiceProvider> spiClass) { this.name = name; this.spiClass = spiClass; } /** * Creates instance of SPIDescr class representing SPI * * @param name Name to use as alias in option * @param spiClass Underlying ServiceProvider class * @param description Description for this ServiceProvider to print in the * help messages */ public SPIDescr(String name, Class<? extends ServiceProvider> spiClass, String description) { this.name = name; this.description = description; this.spiClass = spiClass; } /** * Creates instance of SPIDescr class representing SPI * * @param name Name to use as alias in option * @param spiClass Underlying ServiceProvider class * @param description Description for this ServiceProvider to print in the * help messages * @param isMultiple Whether this SPI can be registered several times (NYI) * @param usage Usage string to print in the help messages */ public SPIDescr(String name, Class<? extends ServiceProvider> spiClass, String description, boolean isMultiple, String usage) { this.name = name; this.description = description; this.isMultiple = isMultiple; this.usage = usage; this.spiClass = spiClass; } /** * <p> Registers a shortcut for the SPI. For example you can register * shortcut "none" for empty Service and it will be available through the * options: "-my.spi none". In this case EnvHandler will not try to load a * class "none" but will find preset for it. </p> <p> Note that if * EnvServiceProvider will be used - EnvHandler will call defineHandler. You * don't have to call it manually. </p> * * @param preset Preset name. E.g. "none", "all", ... * @param defaultSPI ServiceProvider instance to use for the preset * @throws IllegalStateException when EnvHandler already did the * initialization */ public void addPreset(String preset, ServiceProvider defaultSPI) { if (handled) { throw new IllegalStateException("Can't modify SPI after handling the SPI"); } if (defaultSPI == null) { throw new IllegalArgumentException("Alias for a Service Provider can't be null. Use setDefault instead. "); } if (!spiClass.isInstance(defaultSPI)) { throw new IllegalArgumentException("Illegal default Service Provider class. Found " + defaultSPI.getClass() + ", required " + spiClass); } if (presets == null) { presets = new HashMap<String, ServiceProvider>(); } presets.put(preset, defaultSPI); } void setHandled(boolean handled) { this.handled = handled; } /** * Checks whether it's the name of this SPI * * @param name Name to check * @return true or false */ public boolean isName(String name) { if (name != null) { return name.equals(this.name); } return this.name == null; } /** * * @return Underlying ServiceProvider class */ public Class<? extends ServiceProvider> getSPIClass() { return spiClass; } /** * <p> Get SPI name which is used to set the SPI implementation through * environment </p> * * @return SPI name */ public String getName() { return name; } /** * <p> Get all registered SPI presets. See * {@link SPIDescr#addPreset(java.lang.String, com.sun.tdk.jcov.tools.ServiceProvider)} * for more details. </p> * * @return SPI presets or null if no presets were added */ public Collection<ServiceProvider> getPresets() { if (presets == null) { return null; } return presets.values(); } /** * <p> Get SPI preset ServiceProvider. See * {@link SPIDescr#addPreset(java.lang.String, com.sun.tdk.jcov.tools.ServiceProvider)} * for more details. </p> * * @param className * @return ServiceProvider instance registered for this preset */ public ServiceProvider getPreset(String className) { if (presets == null) { return null; } return presets.get(className); } /** * <p> Get all presets for the SPI. See * {@link SPIDescr#addPreset(java.lang.String, com.sun.tdk.jcov.tools.ServiceProvider)} * for more details. </p> * * @return Presets for the SPI. */ public Map<String, ServiceProvider> getPresetsMap() { return presets; } /** * <p> Set the default ServiceProvider for this SPI. It will be used if no * SPI will be specified by the user. </p> * * @param defaultSPI Default ServiceProvider */ public void setDefaultSPI(ServiceProvider defaultSPI) { this.defaultSPI = defaultSPI; } /** * <p> Get the default ServiceProvider. Can be null. </p> * * @return Default ServiceProvider */ public ServiceProvider getDefaultSPI() { return defaultSPI; } }
7,142
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JCovCMDTool.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/JCovCMDTool.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import com.sun.tdk.jcov.runtime.PropertyFinder; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.FilenameFilter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.logging.FileHandler; /** * * @author Andrey Titov */ public abstract class JCovCMDTool extends JCovTool { /** * CLI entry point * * @param args tool arguments (without tool name) * @return exit code */ public final int run(String[] args) { // This method manages CLI handling for all the tools except Agent tool. // If any change is performed here - check Agent CLI handling logic. EnvHandler handler = defineHandler(); if (readPlugins) { String pluginsDir = handler.getValue(EnvHandler.PLUGINDIR); File file = new File(pluginsDir); if (file.isDirectory() && file.canRead()) { File[] list = file.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); URL urls[] = new URL[list.length]; for (int i = 0; i < list.length; ++i) { try { urls[i] = list[i].toURI().toURL(); } catch (MalformedURLException ignored) { } } URLClassLoader urlCL = new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); handler.setClassLoader(urlCL); } } try { handler.parseCLIArgs(args); if (handler.isSet(EnvHandler.HELP)) { handler.usage(); return SUCCESS_EXIT_CODE; } if (handler.isSet(EnvHandler.HELP_VERBOSE)) { handler.usage(true); return SUCCESS_EXIT_CODE; } } catch (EnvHandler.CLParsingException ex) { // printing help on error only with -h or -hv options (and their aliases) if (handler.isSet(EnvHandler.HELP)) { handler.usage(); handler.getOut().println("\n Command line error: " + ex.getMessage() + "\n"); return ERROR_CMDLINE_EXIT_CODE; } if (handler.isSet(EnvHandler.HELP_VERBOSE)) { handler.usage(true); handler.getOut().println("\n Command line error: " + ex.getMessage() + "\n"); return ERROR_CMDLINE_EXIT_CODE; } handler.getOut().println(" Command line error: " + ex.getMessage() + "\n"); String name = this.getClass().getName(); handler.getOut().println("Use \"java -jar jcov.jar " + name.substring(name.lastIndexOf(".") + 1) + " -h\" for command-line help or \"java -jar jcov.jar " + name.substring(name.lastIndexOf(".") + 1) + " -hv\" for wider description"); return ERROR_CMDLINE_EXIT_CODE; } if (handler.isSet(EnvHandler.LOGFILE)) { try { FileHandler fh = new FileHandler(handler.getValue(EnvHandler.LOGFILE)); Utils.setLoggerHandler(fh); } catch (Exception ex) { handler.getOut().println("\n Error initializing logger: " + ex.getMessage() + "\n"); } } if (handler.isSet(EnvHandler.LOGLEVEL)) { Utils.setLoggingLevel(handler.getValue(EnvHandler.LOGLEVEL)); } // handle environment on SPIs try { handler.initializeSPIs(); } catch (Exception ex) { handler.getOut().println("Service Provider initialization error: " + ex.getMessage() + "\n"); if (handler.isSet(EnvHandler.PRINT_ENV)) { handler.printEnv(); } else { handler.getOut().println("Use -print-env option to find where this Service Provider is set\n"); } return ERROR_CMDLINE_EXIT_CODE; } // give environment to the tool int res = SUCCESS_EXIT_CODE; try { res = handleEnv(handler); } catch (EnvHandlingException ex) { handler.getOut().println("Command line error: " + ex.getMessage() + "\n"); String name = this.getClass().getName(); handler.getOut().println("Use \"java -jar jcov.jar " + name.substring(name.lastIndexOf(".") + 1) + " -h\" for command-line help or \"java -jar jcov.jar " + name.substring(name.lastIndexOf(".") + 1) + " -hv\" for wider description"); if (handler.isSet(EnvHandler.PRINT_ENV)) { handler.printEnv(); } return ERROR_CMDLINE_EXIT_CODE; } if (handler.isSet(EnvHandler.PRINT_ENV)) { handler.printEnv(); return SUCCESS_EXIT_CODE; } if (res != SUCCESS_EXIT_CODE) { handler.usage(); return res; } // run tool execution try { return run(); } catch (Exception e) { if( ! e.getMessage().isEmpty() ) { System.err.println(e.getMessage()); } if ( e.getMessage().isEmpty() || PropertyFinder.findValue("stacktrace", "").equals("true")) { e.printStackTrace(System.err); } return ERROR_EXEC_EXIT_CODE; } } protected abstract int run() throws Exception; }
6,878
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JcovVersion.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/JcovVersion.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; /** * * @author Andrey Titov */ public class JcovVersion { public static String jcovVersion = "DEV"; public static String jcovBuildNumber = "DEV"; public static String jcovMilestone = "DEV"; public static String getJcovVersion() { return "DEV"; } }
1,522
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
EnvHandler.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/EnvHandler.java
/* * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; import com.sun.tdk.jcov.runtime.PropertyFinder; import com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; /** * <p> This class provides easy way to parse command line options, retrieve/set * options values. Each option is assumed to have the following syntax : * -&lt;option_name&gt; [&lt;option_value&gt;] and can be specified more than * once. If an option is specified multiple times, than all its values can be * retrieved by the getValues() method. </p> * * @author Konstantin Bobrovsky */ public class EnvHandler { public static final String OPTION_SPECIFIER = "-"; public static final String OPT_VAL_DELIM = "="; public static final String PROP_FILE_SPECIFIER = "@"; public static final String PROP_OPT_DELIM = ";"; public static final String AGENT_OPT_DELIM = ","; /** * Non-options arguments */ private String[] tail; /** * repository for (option, value) pairs */ protected Map<String, List<String>> options = new HashMap<String, List<String>>(); /** * descriptions of options which will be accepted by the parse method */ protected List<OptionDescr> validOptions; /** * Owner of this handler (used for printing usage) */ protected JCovTool tool; /** * Properties read from CLI (@ support) */ Properties CLProperties = new Properties(); private List<SPIDescr> spiDescrs = new LinkedList<SPIDescr>(); private Map<SPIDescr, ArrayList<ServiceProvider>> readProviders = new HashMap<SPIDescr, ArrayList<ServiceProvider>>(); private ClassLoader classLoader = ClassLoader.getSystemClassLoader(); private EnvServiceProvider extendingSPI; /** * checks if given string can be an option */ public static boolean isOption(String s) { return s.startsWith(OPTION_SPECIFIER); } @Deprecated /** * EnvHandler should be constructed with JCovTool instance */ public EnvHandler() { validOptions = new LinkedList<OptionDescr>(); for (OptionDescr d : SHARED_OPTIONS) { validOptions.add(d); } } public EnvHandler(OptionDescr[] valid_options, JCovTool tool) { // validOptions = new ArrayList<OptionDescr>(Arrays.asList(valid_options)); // no need to add elements so just using Arrays wrapper validOptions = new LinkedList(Arrays.asList(valid_options)); for (OptionDescr d : SHARED_OPTIONS) { validOptions.add(d); } this.tool = tool; } public EnvHandler(List<OptionDescr> validOptions, JCovTool tool) { this.validOptions = validOptions; for (OptionDescr d : SHARED_OPTIONS) { validOptions.add(d); } this.tool = tool; } private OptionDescr getOptionByName(String name) { for (int i = 0; i < validOptions.size(); i++) { if (validOptions.get(i).isName(name)) { return validOptions.get(i); } } return null; } /** * <p> Finds SPIDescr by name assigned to the SPI. SPI name is a string * which can be used by a user to assign custom ServiceProvider through CLI, * variables, properties and so on. </p> * * @param name SPIDescr name * @return SPI descriptor */ public SPIDescr getSPIDescrByName(String name) { for (SPIDescr spi : spiDescrs) { if (spi.isName(name)) { return spi; } } return null; } /** * <p> Finds SPIDescr by underlying ServiceProvider class </p> * * @param spiClass ServiceProviced class to find * @return SPIDescr assigned for the ServiceProvider. <code>null</code> if * the ServiceProvider is not registered. */ public SPIDescr getSPIByClass(Class<? extends ServiceProvider> spiClass) { for (SPIDescr spi : spiDescrs) { if (spiClass == spi.getSPIClass()) { return spi; } } return null; } private void addSPI(SPIDescr spi, ServiceProvider customProviderInstance) { if (customProviderInstance instanceof EnvServiceProvider) { extendingSPI = (EnvServiceProvider) customProviderInstance; extendingSPI.extendEnvHandler(this); extendingSPI = null; } ArrayList<ServiceProvider> list = readProviders.get(spi); if (list == null) { list = new ArrayList<ServiceProvider>(1); list.add(customProviderInstance); readProviders.put(spi, list); } else { list.add(customProviderInstance); } } /** * <p> Load and pre-init (call defineHandler()) a ServiceProvider. </p> <p> * Note that this ServiceProvider will be registered in the EnvHandler * automatically as <b>spiClass</b>. Pass null to <b>spiClass</b> to disable * registering. </p> */ private ServiceProvider instantiateServiceProvider(SPIDescr spi, String className) throws Exception { ServiceProvider alias = spi.getPreset(className); if (alias != null) { addSPI(spi, alias); return alias; } ServiceProvider customProviderInstance = (ServiceProvider) classLoader.loadClass(className).getDeclaredConstructor().newInstance(); addSPI(spi, customProviderInstance); return customProviderInstance; } /** * Parse command line arguments and fill environment * * @param options_array command line (or parsed agent line) params * @throws Exception */ public void parseCLIArgs(String options_array[]) throws CLParsingException { ArrayList<String> opts = new ArrayList<String>(Arrays.asList(options_array)); LinkedList<String> tailList = new LinkedList<String>(); CLProperties = new Properties(); processSPIs(opts); // we want to get all real options in any case to be able to check -h CLParsingException toThrow = null; try { ListIterator<String> it = opts.listIterator(); // Looking for -propfile option specified while (it.hasNext()) { String opt = it.next(); if (isOption(opt)) { opt = opt.substring(1); if (PROPERTYFILE.isName(opt)) { if (!it.hasNext()) { if (toThrow == null) { toThrow = new CLParsingException("Option '" + opt + "' is invalid: value expected."); } } String prop = it.next(); if ("".equals(prop)) { break; } PropertyFinder.setPropertiesFile(prop); break; } } } it = opts.listIterator(); while (it.hasNext()) { String option = it.next(); if (option.startsWith(PROP_FILE_SPECIFIER)) { String filename = option.substring(1); CLProperties = PropertyFinder.readProperties(filename, CLProperties); } else { if (!isOption(option)) { tailList.add(option); // not an option and not an option value - error or tail } else { option = option.substring(1); // removing OPTION_SPECIFIER OptionDescr optDescr = getOptionByName(option); // no need to check allowedOptions - getOptionByName will return null in case such option is invalid (HELP and HELP_VERBOSE are allowed for all) if (optDescr == null) { if (toThrow == null) { toThrow = new CLParsingException("Option '" + option + "' is invalid."); } } else { if (!optDescr.isMultiple && options.containsKey(optDescr.name)) { if (toThrow == null) { toThrow = new CLParsingException("Option is specified twice : " + option); } } if (optDescr.hasValue) { try { processOption(it, optDescr, option); } catch (NoSuchElementException e) { // it.next() if (toThrow == null) { toThrow = new CLParsingException("Option '" + option + "' is invalid: value expected."); } } } else { setOption(optDescr); } } } } } } finally { if (toThrow != null) { throw toThrow; } } if (!tailList.isEmpty()) { tail = tailList.toArray(new String[tailList.size()]); } else { tail = null; } } private void processOption(ListIterator<String> it, OptionDescr optDescr, String option) throws CLParsingException { String value; if (optDescr.val_kind == OptionDescr.VAL_ALL) { if (!it.hasNext()) { throw new NoSuchElementException(); } while (it.hasNext()) { value = it.next(); addValuedOption(value, option, optDescr); } } else { value = it.next(); if (value.startsWith(PROP_FILE_SPECIFIER)) { value = PropertyFinder.readPropFrom(value.substring(1), option); } addValuedOption(value, option, optDescr); } } private void processSPIs(ArrayList<String> opts) throws CLParsingException { if (!spiDescrs.isEmpty()) { // Loading registered SPIs ListIterator<String> it = opts.listIterator(); while (it.hasNext()) { String opt = it.next(); if (isOption(opt)) { opt = opt.substring(1); // cutting "-" SPIDescr descr = getSPIDescrByName(opt); if (descr != null) { if (!it.hasNext()) { throw new CLParsingException("Service provider '" + opt + "' is invalid: value expected"); } it.remove(); String className = it.next(); it.remove(); try { instantiateServiceProvider(descr, className); } catch (ClassNotFoundException e) { throw new CLParsingException("Service Provider class '" + className + "' not found"); } catch (ClassCastException e) { throw new CLParsingException("Invalid class for Service Provider '" + opt + "': '" + className + "' - not a Service provider"); } catch (InstantiationException e) { throw new CLParsingException("Can't instantiate Service Provider class '" + className + "'"); } catch (Exception e) { throw new CLParsingException("Error loading Service Provider '" + className + "': exception " + e.getClass() + " occured '" + e.getMessage() + "'", e); } } } } // Initializing loaded SPIs for (SPIDescr descr : spiDescrs) { if (!readProviders.containsKey(descr)) { String className = PropertyFinder.findValue(descr.getName(), null); if (className != null) { try { instantiateServiceProvider(descr, className); } catch (ClassNotFoundException e) { throw new CLParsingException("Service Provider class '" + className + "' not found"); } catch (ClassCastException e) { throw new CLParsingException("Invalid class for Service Provider '" + descr.getName() + "': '" + className + "' - not a Service provider"); } catch (InstantiationException e) { throw new CLParsingException("Can't instantiate Service Provider class '" + className + "'"); } catch (Exception e) { throw new CLParsingException("Error loading Service Provider '" + className + "': exception " + e.getClass() + " occured '" + e.getMessage() + "'", e); } } else { if (descr.getDefaultSPI() != null) { addSPI(descr, descr.getDefaultSPI()); } } } } } } /** * Check whether option name is registered in this envhandler. Uses * getOptionByName * * @param name option name * @return true if name is in validOptions of envhandler or if it's system * option (HELP, HELP_VERBOSE) * @see #getOptionByName(java.lang.String) */ public boolean isValidOption(String name) { return getOptionByName(name) == null; } private void setOption(OptionDescr optDescr) { options.put(optDescr.name, null); } private void addValuedOption(String value, String option, OptionDescr optDescr) throws CLParsingException { if (value == null) { throw new CLParsingException("Option '" + option + "' is invalid: value expected."); } if (!optDescr.isAllowedValue(value)) { // if allowedValues are null - returns true throw new CLParsingException("Invalid value for option '" + option + "' : '" + value + "'"); } if (!optDescr.isMultiple) { ArrayList<String> list = new ArrayList<String>(1); list.add(value); options.put(optDescr.name, list); } else { List<String> list = options.get(optDescr.name); if (list == null) { list = new LinkedList<String>(); options.put(optDescr.name, list); } list.add(value); } } /** * Parses agent parameters string (option=value,option,option=value) to * string array * * @param args arguments to parse (option=value,option,option=value) * @return string array (option; value; option; option; value) */ public static String[] parseAgentString(String args) { if (args == null || args.trim().length() == 0) { return new String[0]; } String[] opts = args.split(AGENT_OPT_DELIM); LinkedList<String> res = new LinkedList<String>(); for (String s : opts) { int ind = s.indexOf(OPT_VAL_DELIM); if (ind == -1) { if (s.contains(PROP_FILE_SPECIFIER)) { res.add(s); } else { res.add(OPTION_SPECIFIER + s); } } else { res.add(OPTION_SPECIFIER + s.substring(0, ind)); res.add(s.substring(ind + 1)); } } return res.toArray(new String[res.size()]); } /** * sets the option with the specified name. The effect is the same as of the * parse("-&lt;option_name&gt;") invocation. */ public void set(String option_name) { set(option_name, (String) null); } /** * assigns the specified value to the option. Any previously assigned values * are destroyed. */ public void set(String option_name, String option_value) { List<String> opt_values = options.get(option_name); if (opt_values == null) { opt_values = new LinkedList<String>(); options.put(option_name, opt_values); } if (option_value == null) { return; } opt_values.add(option_value); } /** * assigns the specified array of values to the option. Any previously * assigned values are destroyed. */ public void set(String option_name, String[] option_values) { if (option_values == null) { options.put(option_name, null); } else { List<String> opt_values = new ArrayList<String>(Arrays.asList(option_values)); options.put(option_name, opt_values); } } /** * assigns the specified vector of values to the option. Any previously * assigned values are destroyed. */ public void set(String option_name, List<String> option_values) { options.put(option_name, option_values); } public String getCleanValue(OptionDescr option) { if (!validOptions.contains(option)) { return null; } if (!option.hasValue && isSet(option)) { return "on"; } String[] values = getCleanValues(option); if (values == null) { return option.defVal; } return values[0]; } public String getValue(OptionDescr option) { if (!validOptions.contains(option)) { return option.defVal; } if (!option.hasValue && isSet(option)) { return "on"; } String[] values = getValues(option); if (values == null) { return PropertyFinder.processMacroString(option.defVal, null, null); } return values[0]; } /** * returns all values of given option. For example, for "-opt=val0 * -opt=val1" options getValues("opt") will return {"val0", "val1"}. */ private String[] getValues(String option_name) { List<String> opt_values = options.get(option_name); if (opt_values == null) { // no such option in the CL environment if (CLProperties.containsKey("jcov." + option_name)) { return ((String) CLProperties.get("jcov." + option_name)).split(PROP_OPT_DELIM); } String res = PropertyFinder.findValue(option_name, null); if (res != null) { return res.split(PROP_OPT_DELIM); } return null; } if (opt_values.isEmpty()) { return null; } return opt_values.toArray(new String[opt_values.size()]); } public String[] getCleanValues(OptionDescr option) { if (!validOptions.contains(option)) { return null; } if (!option.hasValue && isSet(option)) { return new String[]{"on"}; } String[] values = getValues(option.name); if (values == null || values.length == 0) { return option.defVal == null ? null : new String[]{option.defVal}; } return values; } /** * returns all values of given option. For example, for "-opt=val0 * -opt=val1" options getValues("opt") will return {"val0", "val1"}. */ public String[] getValues(OptionDescr option) { String[] values = getCleanValues(option); if (values != null) { for (int i = 0; i < values.length; ++i) { values[i] = PropertyFinder.processMacroString(values[i], null, null); } } return values; } /** * Returns tail, the least of parameters with put options at the end of * args. */ public String[] getTail() { return tail; } /** * checks if given options has been successfully parsed by the parse(String) * method */ public boolean isSet(OptionDescr option) { if (!validOptions.contains(option)) { return false; } return options.containsKey(option.name) || CLProperties.containsKey("jcov." + option.name) || (PropertyFinder.findValue(option.name, null) != null); } /** * @return String representation of currently set options, as they would * appear on the command line */ public String unParse() { StringBuilder builder = new StringBuilder(); Iterator<String> it = options.keySet().iterator(); while (it.hasNext()) { String opt_name = it.next(); String[] opt_values = getValues(opt_name); if (opt_values != null) { for (int j = 0; j < opt_values.length; j++) { builder.append(OPTION_SPECIFIER).append(opt_name).append(OPT_VAL_DELIM).append(opt_values[j]); if (j < opt_values.length - 1) { builder.append(" "); } } } else { builder.append(OPTION_SPECIFIER).append(opt_name); } if (it.hasNext()) { builder.append(" "); } } return builder.toString(); } public void printEnv() { for (OptionDescr descr : validOptions) { String source = null; if (options.containsKey(descr.name)) { source = "cmd"; } else { source = PropertyFinder.findSource(descr.name); } if (descr.equals(PRINT_ENV) && "defaults".equals(source)) { continue; } if (descr.isMultiple) { System.out.println("Property '" + descr.name + "' has values '" + Arrays.toString(getValues(descr)) + "' from " + source); } else { if (descr.hasValue) { System.out.println("Property '" + descr.name + "' has value '" + getValue(descr) + "' from " + source); } else { if (isSet(descr)) { System.out.println("Property '" + descr.name + "' is set from " + source); } } } } } public Map<String, List<String>> getFullEnvironment() { Map<String, List<String>> map = new HashMap<String, List<String>>(options); for (OptionDescr opt : validOptions) { if (map.containsKey(opt.name)) { continue; } if (!opt.hasValue) { map.put(opt.name, null); continue; } String[] values = getValues(opt); map.put(opt.name, Arrays.asList(values)); } return map; } /** * @return the number of options set */ public int size() { return options.size(); } public void usage(boolean verbose) { if (tool == null) { return; } if (!verbose) { out.println("Try \"-help-verbose\" for more detailed help"); } out.println("Usage:"); out.println("> " + tool.usageString()); if( tool.noteString() != null ) { out.println(tool.noteString()); } if (validOptions != null) { out.println(" Options:"); for (OptionDescr od : validOptions) { if (SHARED_OPTIONS.contains(od)) { continue; } out.println(od.getUsage("-", " ", " ", verbose)); } for (OptionDescr od : SHARED_OPTIONS) { out.println(od.getUsage("-", " ", " ", verbose)); } } if (!spiDescrs.isEmpty()) { out.println("Service providers: "); for (SPIDescr spi : spiDescrs) { out.print(" -"); out.print(spi.getName()); out.print(" : "); Class clazz = spi.getSPIClass(); out.println(clazz.getSimpleName()); } } out.print("Example: "); out.println(tool.exampleString()); } public void usage() { usage(isSet(HELP_VERBOSE)); } private PrintStream out = System.out; public void setOut(PrintStream out) { this.out = out; } public PrintStream getOut() { return out; } /** * <p> Registers new SPI to be processed by JCov </p> <p> Registering SPI * should be done before EnvHandler will process environment - in * Tool.defineEnv() method or before Tool.handleEnv() method. </p> * * @param spiDescr SPI to register * @see EnvHandler#getSPIs(com.sun.tdk.jcov.tools.SPIDescr) */ public void registerSPI(SPIDescr spiDescr) { if (spiDescrs.contains(spiDescr)) { return; } spiDescrs.add(spiDescr); Collection<ServiceProvider> defs = spiDescr.getPresets(); if (defs != null) { for (ServiceProvider def : defs) { if (def instanceof EnvServiceProvider) { extendingSPI = (EnvServiceProvider) def; extendingSPI.extendEnvHandler(this); extendingSPI = null; } } } } /** * <p> Removes option from JCov environment so that it wouldn't be * accessible through getValue() method </p> * * @param descr Option to remove * @return true if this option was removed */ public boolean removeOption(OptionDescr descr) { return validOptions.remove(descr); } /** * Adds OptionsDescr to this environment so that it will be parsed by * EnvHandler * * @param descr OptionDescr to add * @return true when OptionDescr was successfully added */ public boolean addOption(OptionDescr descr) { // check that such option doesn't exitst int pos = 1, foundPos = -1; for (OptionDescr d : validOptions) { if (d.name.equals(descr.name)) { return false; } if (foundPos < 0) { if (d.title != null && !d.title.isEmpty() && d.title.equals(descr.title)) { descr.title = ""; foundPos = pos; } } ++pos; } if (extendingSPI != null) { descr.setRegisteringSPI(extendingSPI); } if (foundPos > 0) { validOptions.add(foundPos, descr); } else { validOptions.add(descr); } return true; } /** * Adds several options to JCov environment * * @param optionDescr Options to add */ public void addOptions(OptionDescr[] optionDescr) { for (OptionDescr opt : optionDescr) { addOption(opt); } } /** * <p> Get all instantiated ServiceProviders for registered ServiceProvider * (SPIClass) </p> * * @param <SPIClass> Registered ServiceProvider class * @param spiClass Registered ServiceProvider class * @return List of all instantiated Providers for the class */ public <SPIClass extends ServiceProvider> ArrayList<SPIClass> getSPIs(Class<SPIClass> spiClass) { return (ArrayList<SPIClass>) getSPIs(getSPIByClass(spiClass)); } /** * <p> Get all instantiated ServiceProviders for registered ServiceProvider * </p> * * @param descr Registered SPI * @return List of all instantiated Providers for the SPI */ public ArrayList<ServiceProvider> getSPIs(SPIDescr descr) { if (descr == null) { return new ArrayList<ServiceProvider>(0); } ArrayList<ServiceProvider> get = readProviders.get(descr); if (get == null) { if (descr.getDefaultSPI() != null) { get = new ArrayList<ServiceProvider>(1); get.add(descr.getDefaultSPI()); return get; } return new ArrayList<ServiceProvider>(0); } return (ArrayList<ServiceProvider>) get; } /** * <p> Initializes all instantiated ServiceProviders by calling handleEnv() * for each of them. </p> <p> This method will not stop if any of the * ServiceProviders will return not-null exit code but will stop in case of * any exception </p> * * @return Initialization exit code (0) * @throws com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException */ public int initializeSPIs() throws EnvHandlingException { for (ArrayList<ServiceProvider> list : readProviders.values()) { for (ServiceProvider sp : list) { if (sp instanceof EnvServiceProvider) { int retCode = ((EnvServiceProvider) sp).handleEnv(this); } } } for (SPIDescr spi : spiDescrs) { if (spi.getDefaultSPI() != null && (spi.getDefaultSPI() instanceof EnvServiceProvider)) { ((EnvServiceProvider) spi.getDefaultSPI()).handleEnv(this); } Collection<ServiceProvider> aliaseSPIs = spi.getPresets(); if (aliaseSPIs != null && !aliaseSPIs.isEmpty()) { for (ServiceProvider sp : aliaseSPIs) { if (sp instanceof EnvServiceProvider) { ((EnvServiceProvider) sp).handleEnv(this); } } } } return 0; } void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } public static class CLParsingException extends Exception { public CLParsingException(Throwable cause) { super(cause); } public CLParsingException(String message, Throwable cause) { super(message, cause); } public CLParsingException(String message) { super(message); } public CLParsingException() { } } /** * Help option "-help", "-h", "-?" */ public static final OptionDescr HELP = new OptionDescr("help", new String[]{"h", "?"}, "Basic options", null); /** * Help option for more verbose help "-help-verbose", "-hv" */ public static final OptionDescr HELP_VERBOSE = new OptionDescr("help-verbose", new String[]{"hv"}, null, null); /** * JCov property file location "-propfile" */ public static final OptionDescr PROPERTYFILE = new OptionDescr("propfile", "", OptionDescr.VAL_SINGLE, (String) null, (String) null); /** * Printing all environment and sources for each option value "-print-env", * "-env" */ public static final OptionDescr PRINT_ENV = new OptionDescr("print-env", new String[]{"env"}, (String) null, (String) null); /** * JCov plugin directory location "-plugindir" */ public static final OptionDescr PLUGINDIR = new OptionDescr("plugindir", "", OptionDescr.VAL_SINGLE, "Directory to read plugins (SPIs)", "plugins"); /** * Redirecting logging to a file */ public static final OptionDescr LOGFILE = new OptionDescr("log.file", "", OptionDescr.VAL_SINGLE, "Set file for output logging"); /** * Setting verbosity */ public static final OptionDescr LOGLEVEL = new OptionDescr("log.level", new String[]{"log"}, "", OptionDescr.VAL_SINGLE, "Set level of logging", ""); static final List<OptionDescr> SHARED_OPTIONS = Arrays.asList(new OptionDescr[]{HELP, HELP_VERBOSE, PRINT_ENV, PROPERTYFILE, PLUGINDIR, LOGFILE, LOGLEVEL}); }
33,395
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ScaleCompressor.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/ScaleCompressor.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; /** * Interface for a test scale compressor. * * @author Konstantin Bobrovsky */ public interface ScaleCompressor { /** * Takes &lt;src&gt; as a symbol representation of the test scale and * transforms (decompresses) it into canonical representation (as a sequence * of bits) writing result to &lt;dst&gt; * * @param src symbol representation of the test scale * @param len number of symbols in &lt;src&gt; (deduced from * &lt;scale_size&gt;) * @param dst storage for canonical representation * @param scale_size test scale size (deduced from &lt;len&gt;) * @exception Exception if a decompression error occurs * @see com.sun.tdk.jcov.filedata.Scale */ void decompress(char[] src, int len, byte[] dst, int scale_size) throws Exception; /** * Takes &lt;src&gt; as a canonical representation of the test scale and * transforms (compresses) it into a symbol representation writing the * result to &lt;dst&gt;. * * @param src canonical representation of the test scale * @param dst storage for symbol (compressed) representation * @param scale_size test scale size * @see com.sun.tdk.jcov.filedata.Scale */ int compress(byte[] src, StringBuffer dst, int scale_size); }
2,532
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JcovStats.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/tools/JcovStats.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.tools; /** * This class is a centralized storage for 9 coverage statistics numbers. Also * offers some service methods. * * @author Konstantin Bobrovsky */ public class JcovStats { public final static String sccsVersion = "%I% $LastChangedDate: 2011-08-25 16:47:35 +0400 (Thu, 25 Aug 2011) $"; public int methods_tot; public int methods_cov; public float method_cvg; public int blocks_tot; public int blocks_cov; public float block_cvg; public int branches_tot; public int branches_cov; public float branch_cvg; public final static int IND_MET_COV = 0; public final static int IND_MET_TOT = 1; public final static int IND_MET_CVG = 2; public final static int IND_BLO_COV = 3; public final static int IND_BLO_TOT = 4; public final static int IND_BLO_CVG = 5; public final static int IND_BRN_COV = 6; public final static int IND_BRN_TOT = 7; public final static int IND_BRN_CVG = 8; /** * Mergers &lt;this&gt; stats with another so that &lt;this&gt; contains sum * of both */ public void merge(JcovStats src) { blocks_tot += src.blocks_tot; blocks_cov += src.blocks_cov; branches_tot += src.branches_tot; branches_cov += src.branches_cov; methods_tot += src.methods_tot; methods_cov += src.methods_cov; } /** * Calculates coverage percentage fields */ public void calculate() { block_cvg = blocks_tot != 0 ? (float) blocks_cov / (float) blocks_tot : 1.0f; branch_cvg = branches_tot != 0 ? (float) branches_cov / (float) branches_tot : 1.0f; method_cvg = methods_tot != 0 ? (float) methods_cov / (float) methods_tot : 1.0f; } /** * @return number in the field with the specified index wrapping it in an * Object */ public Object getNumber(int field_ind) { switch (field_ind) { case IND_MET_COV: return Integer.valueOf(methods_cov); case IND_MET_TOT: return Integer.valueOf(methods_tot); case IND_MET_CVG: if (methods_tot > 0) { return Float.valueOf((float) ((int) (method_cvg * 100000.0)) / 1000); } return "N/A"; case IND_BLO_COV: return Integer.valueOf(blocks_cov); case IND_BLO_TOT: return Integer.valueOf(blocks_tot); case IND_BLO_CVG: if (blocks_tot > 0) { return Float.valueOf((float) ((int) (block_cvg * 100000.0)) / 1000); } return "N/A"; case IND_BRN_COV: return Integer.valueOf(branches_cov); case IND_BRN_TOT: return Integer.valueOf(branches_tot); case IND_BRN_CVG: if (branches_tot > 0) { return Float.valueOf((float) ((int) (branch_cvg * 100000.0)) / 1000); } return "N/A"; default: return null; } } }
4,333
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
package-info.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/package-info.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * <p> This package contains classes for simplifying reports generation. </p> * <p> {@link com.sun.tdk.jcov.report.ProductCoverage} class and underlying * classes allow to get sums over coverage information for entire product or for * some part of it. For example it's possible to get number of covered classes * in all product, or number of covered classes in some package, or number of * covered methods in a package. See * {@link com.sun.tdk.jcov.report.AbstractCoverage#getData(com.sun.tdk.jcov.report.DataType)} * method for more details. </p> <p> ProductCoverage class is the top class in * coverage hierarchy. It provides access to the following classes: </p> <ul> * <li>PackageCoverage</li> <li>ClassCoverage</li> <li>MethodCoverage</li> * <li>FieldCoverage</li> <li>ItemCoverage</li> <li>LineCoverage</li> </ul> <p> * ProductCoverage contains a list of PackageCoverage classes, PackageCoverage * contains ClassCoverages, which contains MethodCoverages and FieldCoverages. * Each MethodCoverage contains a number of ItemCoverage classes which can be * BlockCoverage or BranchCoverage representing blocks and branches * respectively. </p> <p> LineCoverage contains information about which lines of * the code are covered and which are not. </p> <p> The following example shows * how to iterate through coverage data and how to get coverage information. * </p> * <pre> * <code> * import com.sun.tdk.jcov.report.CoverageData; * import com.sun.tdk.jcov.report.ClassCoverage; * import com.sun.tdk.jcov.report.DataType; * import com.sun.tdk.jcov.report.MethodCoverage; * import com.sun.tdk.jcov.report.PackageCoverage; * import com.sun.tdk.jcov.report.ProductCoverage; * import com.sun.tdk.jcov.util.Utils; * import java.util.List; * * public class Main { * public static void main(String[] args) { * String fileName = args[0]; * String testlistFileName = args.length > 1 ? args[1] : null; * * try { * ProductCoverage coverage = new ProductCoverage(fileName); * String[] testlist = testlistFileName != null ? Utils.readLines(testlistFileName) : null; * for (PackageCoverage pc: coverage.getPackages()) { * for (ClassCoverage cc: pc.getClasses()) { * System.out.println("# class: " + cc.getFullClassName() + " method coverage: " + cc.getCoverageString(DataType.METHOD)); * for (MethodCoverage mc: cc.getMethods()) { * CoverageData blc = mc.getData(DataType.BLOCK); * CoverageData brc = mc.getData(DataType.BRANCH); * CoverageData lcc = mc.getData(DataType.LINE); * System.out.println(" meth: " + mc.getName() + mc.getSignature()); * System.out.println(" blocks: " + blc + "; branches: " + brc + "; lines: " + lcc.getCovered() + "/" + lcc.getTotal()); * if (testlistFileName != null) { * List&lt;String&gt; coveringTests = mc.getCoveringTests(testlist); * System.out.println(" covered by tests: " + coveringTests.toString()); * } * } * } * } * } catch (Throwable ex) { * System.err.println("Exception " + ex); * } * } * } * </code> * </pre> <p> * <code>com.sun.tdk.jcov.report</code> package also contains a number of * classes that can be used to create custom reports. </p> <p> * {@link com.sun.tdk.jcov.report.ReportGenerator} class can be passed to the * RepGen tool through {@link com.sun.tdk.jcov.report.ReportGeneratorSPI} * Service Provider. Implementing these interfaces it's possible to generate * custom report right from JCov RepGen tool. See * {@link com.sun.tdk.jcov.report.DefaultReportGeneratorSPI} for an extended * example. </p> */ package com.sun.tdk.jcov.report;
5,197
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
MethodCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/MethodCoverage.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.data.Scale; import com.sun.tdk.jcov.instrument.DataMethod.LineEntry; import java.util.Map; import java.util.HashMap; import com.sun.tdk.jcov.instrument.DataBlockTarget; import com.sun.tdk.jcov.instrument.DataBlockTargetCond; import com.sun.tdk.jcov.instrument.XmlNames; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.util.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static com.sun.tdk.jcov.report.DataType.*; /** * <p> This class provides access to method coverage information. Sums of * underlying coverage information can be obtained by * <code>getData(DataType)</code> method using DataType.METHOD, DataType.BLOCK, * DataType.BRANCH, DataType.LINE. </p> <p> To access specific method/field * information use * <code>getMethodCoverageList()</code> and * <code>getFieldCoverageList()</code> methods </p> * * @author Leonid Mesnik */ public class MethodCoverage extends MemberCoverage implements Iterable<ItemCoverage> { private LineCoverage lineCoverage = new LineCoverage(); private List<ItemCoverage> items = new ArrayList<ItemCoverage>(); private boolean inAnonymClass = false; private boolean lambdaMethod = false; private boolean anonymon = false; private DataType[] supportedColumns = {METHOD, BLOCK, BRANCH, LINE}; private boolean isInAnc = false; protected String ancInfo; /** * <p> Creates new MethodCoverage instance without counting blocks </p> * * @param method DataMethod to read data from */ public MethodCoverage(DataMethod method, AncFilter[] ancFilters, String ancReason) { this(method, false, ancFilters, ancReason); } public MethodCoverage(DataMethod method, boolean countBlocks) { this(method, countBlocks, null, null); } /** * <p> Creates new MethodCoverage instance </p> * * @param method * @param countBlocks not used */ public MethodCoverage(DataMethod method, boolean countBlocks, AncFilter[] ancFilters, String ancReason) { access = method.getAccess(); modifiersString = Arrays.deepToString(method.getAccessFlags()); name = method.getName(); signature = (method.getVmSignature() != null) ? method.getVmSignature() : ""; startLine = (method.getLineTable() != null && method.getLineTable().size() > 0) ? method.getLineTable().get(0).line : 0; count = method.getCount(); scale = method.getScale(); modifiers = method.getModifiers(); isInAnc = ancReason != null; ancInfo = ancReason; detectItems(method, items, isInAnc, ancFilters); List<LineEntry> lineTable = method.getLineTable(); if (lineTable != null) { lineCoverage.processLineTable(lineTable); for (ItemCoverage item : items) { for (LineEntry le : lineTable) { if (le.bci >= item.startLine && le.bci <= item.endLine) { if (item.count > 0) { lineCoverage.hitLine(le.line); } else { if (isInAnc || item.isInAnc()) { lineCoverage.markLineAnc(le.line); } } if (item.getSourceLine() < 0) { // not set yet item.setSrcLine(le.line); } } } if (item.getSourceLine() < 0 && lineTable.size() > 0){ item.setSrcLine(lineTable.get(lineTable.size() - 1).line); } } } } private static String isBlockInAnc(DataMethod m, DataBlock b , AncFilter[] filters, List<String> ancBlockReasons){ if (filters == null){ return null; } for (AncFilter filter : filters){ if (filter.accept(m , b)){ String ancReason = filter.getAncReason(); if (ancBlockReasons.size() == 0) { ancBlockReasons.add("All blocks are filtered:"); } if (!ancBlockReasons.contains(ancReason)) { ancBlockReasons.add(ancReason); } return ancReason; } } return null; } public void setAnonymOn(boolean anonym) { this.anonymon = anonym; } public void setInAnonymClass(boolean inAnonymClass) { this.inAnonymClass = inAnonymClass; } public boolean isInAnonymClass() { return inAnonymClass; } public void setLambdaMethod(boolean lambdaMethod) { this.lambdaMethod = lambdaMethod; } public boolean isLambdaMethod() { return lambdaMethod; } /** * Finds coverage items in terms of legacy jcov (blocks and branches) */ void detectItems(DataMethod m, List<ItemCoverage> list, boolean isInAnc, AncFilter[] ancFilters) { Map<DataBlock, ItemCoverage> added = new HashMap<DataBlock, ItemCoverage>(); List<String> ancBlockReasons = new ArrayList<String>(); for (DataBlock db : m.getBlocks()) { if (db instanceof DataBlockTarget /* db.isNested()*/) { continue; } int type = type(db); ItemCoverage item = null; if (type == CT_BLOCK) { item = ItemCoverage.createBlockCoverageItem(db.startBCI(), db.endBCI(), db.getCount(), db.getScale()); } else { item = ItemCoverage.createBranchCoverageItem(db.startBCI(), db.endBCI(), db.getCount(), db.getScale()); } String ancReason = isBlockInAnc(m, db, ancFilters, ancBlockReasons); if (isInAnc || ancReason != null){ item.setAncInfo(ancInfo != null ? ancInfo : ancReason); } boolean isNew = true; for (DataBlock d : added.keySet()) { if (d.startBCI() == db.startBCI() && type(d) == type(db) && added.get(d).isBlock()) { added.get(d).count += db.getCount(); if (added.get(d).scale != null && db.getScale() != null) { for (int i = 0; i < added.get(d).scale.size(); i++) { if (db.getScale().isBitSet(i)) { added.get(d).scale.setBit(i, true); } } } isNew = false; break; } } if (isNew) { added.put(db, item); if (type != CT_METHOD) { list.add(item); } } } for (DataBlockTarget db : m.getBranchTargets()) { int type = type(db); ItemCoverage item = null; if (type == CT_BLOCK) { item = ItemCoverage.createBlockCoverageItem(db.startBCI(), db.endBCI(), db.getCount(), db.getScale()); } else { item = ItemCoverage.createBranchCoverageItem(db.startBCI(), db.endBCI(), db.getCount(), db.getScale()); } String ancReason = isBlockInAnc(m, db, ancFilters, ancBlockReasons); if (isInAnc || ancReason != null){ item.setAncInfo(ancInfo != null ? ancInfo : ancReason); } boolean isNew = true; for (DataBlock d : added.keySet()) { if (d.startBCI() == db.startBCI() && type(d) == type(db) && added.get(d).isBlock()) { added.get(d).count += db.getCount(); if (added.get(d).scale != null && db.getScale() != null) { for (int i = 0; i < added.get(d).scale.size(); i++) { if (db.getScale().isBitSet(i)) { added.get(d).scale.setBit(i, true); } } } isNew = false; break; } } if (isNew) { added.put(db, item); list.add(item); } } for (DataBlock db : added.keySet()) { ItemCoverage i = added.get(db); if (!i.isBlock()) { ItemCoverage i2 = ItemCoverage.createBlockCoverageItem(i.startLine, i.endLine, i.count, db.getScale()); String ancReason = isBlockInAnc(m, db, ancFilters, ancBlockReasons); if (isInAnc || ancReason != null){ i2.setAncInfo(ancInfo != null ? ancInfo : ancReason); } boolean isNew = true; for (DataBlock d : added.keySet()) { if (d.startBCI() == db.startBCI() && added.get(d).isBlock()) { added.get(d).count += db.getCount(); if (added.get(d).scale != null && db.getScale() != null){ Scale s = Scale.createZeroScale(added.get(d).scale.size()); for (int j = 0; j < added.get(d).scale.size(); j++) { if (added.get(d).scale.isBitSet(j) || db.getScale().isBitSet(j)) { s.setBit(j, true); } } added.get(d).scale = s; } isNew = false; break; } } if (isNew) { added.put(db, i2); list.add(i2); } } } if (!isInAnc && ancBlockReasons.size() - 1 == list.size()) { StringBuilder methodAncReason = new StringBuilder(); for (String ancBlock : ancBlockReasons) { methodAncReason.append(" ").append(ancBlock); } setAncInfo(methodAncReason.toString()); } } public void setAncInfo(String ancInfo){ isInAnc = (ancInfo != null && !ancInfo.isEmpty()); this.ancInfo = ancInfo; } public boolean isMethodInAnc(){ return isInAnc; } public String getAncInfo(){ return ancInfo; } /** * Detects type of the DataBlock * * @param db * @return code * @see #CT_METHOD * @see #CT_BRANCH_TRUE * @see #CT_BRANCH_FALSE * @see #CT_CASE * @see #CT_SWITCH_WO_DEF * @see #CT_BLOCK */ public static int type(DataBlock db) { String type = db.kind(); if (type.equals(XmlNames.METHENTER)) { return CT_METHOD; } if (type.equals(XmlNames.COND)) { DataBlockTargetCond cond = (DataBlockTargetCond) db; return cond.side() ? CT_BRANCH_TRUE : CT_BRANCH_FALSE; } if (type.equals(XmlNames.CASE)) { return CT_CASE; } if (type.equals(XmlNames.DEFAULT)) { return CT_SWITCH_WO_DEF; } return CT_BLOCK; } /** * Returns list of blocks+branches * * @return all items that are included into this method */ public List<ItemCoverage> getItems() { return items; } public Iterator<ItemCoverage> iterator() { return items.iterator(); } /** * @return line coverage */ public LineCoverage getLineCoverage() { return lineCoverage; } /** * Coverage kind (used in HTML reports as header for label) * * @return DataType.MEHTOD */ public DataType getDataType() { return DataType.METHOD; } /** * <p> Allows to get sums over the coverage statistics of this method. E.g. * getData(DataType.BRANCH) will return coverage data containing the total * number of branches in this method and number of covered branches in this * method. getData(DataType.BLOCK) will return block coverage of this * method. </p> <p> Allows to sum though METHOD, BLOCK, BRANCH and LINE * types </p> * * @param column Type to sum * @return CoverageData representing 2 fields - total number of members and * number of covered members * @see DataType * @see CoverageData * @see MemberCoverage#getHitCount() */ public CoverageData getData(DataType column) { return getData(column, -1); } @Override public CoverageData getData(DataType column, int testNumber) { switch (column) { case METHOD: if (inAnonymClass && !anonymon) { return new CoverageData(0, 0, 0); } if (name.startsWith("lambda$")){ return new CoverageData(0, 0, 0); } if (testNumber > -1) { int c = (count > 0 && isCoveredByTest(testNumber)) ? 1 : 0; if (isInAnc) { return new CoverageData(c, 1 - c, 1); } return new CoverageData(c, 0, 1); } int c = count > 0 ? 1 : 0; if (isInAnc) { return new CoverageData(c, 1 - c, 1); } return new CoverageData(c, 0, 1); case BLOCK: case BRANCH: if (inAnonymClass && !anonymon && modifiers.isSynthetic()) { return new CoverageData(0, 0, 0); } CoverageData result = new CoverageData(0, 0, 0); for (ItemCoverage item : items) { if (testNumber < 0 || item.isCoveredByTest(testNumber)) { result.add(item.getData(column)); } else { CoverageData icov = item.getData(column); if (isInAnc){ result.add(new CoverageData(0, 1, icov.getTotal())); } else { result.add(new CoverageData(0, icov.getAnc(), icov.getTotal())); } } } return result; case LINE: return lineCoverage; default: return new CoverageData(); } } protected DataType[] getDataTypes() { return supportedColumns; } /** * Returns method name and signature in JLS format * * @return Method signature in readable form (JLS) */ public String getReadableSignature() { return Utils.convertVMtoJLS(name, signature); } /** * @param lineNumber line number * @return true if passed line is covered, false otherwise. */ public boolean isLineCovered(int lineNumber) { return lineCoverage.isLineCovered(lineNumber); } // Types of Jcov items public static final int CT_FIRST_KIND = 1; public static final int CT_METHOD = 1; public static final int CT_FIKT_METHOD = 2; public static final int CT_BLOCK = 3; public static final int CT_FIKT_RET = 4; public static final int CT_CASE = 5; public static final int CT_SWITCH_WO_DEF = 6; public static final int CT_BRANCH_TRUE = 7; public static final int CT_BRANCH_FALSE = 8; public static final int CT_LINE = 9; public static final int CT_LAST_KIND = 9; }
16,947
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ReportGeneratorSPI.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ReportGeneratorSPI.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.tools.ServiceProvider; /** * Service provider for creating custom reports * * @author Andrey Titov */ public interface ReportGeneratorSPI extends ServiceProvider { /** * @param formatName Name of the format specified by user (eg "-format * html") * @return custom report by name (eg "java -jar jcov.jar repgen -type myrep" * where "myrep" is name for a custom report) */ public ReportGenerator getReportGenerator(String formatName); }
1,738
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ClassCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ClassCoverage.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.data.Scale; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataField; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.Modifiers; import com.sun.tdk.jcov.report.javap.JavapClass; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * <p> This class provides access to class coverage information. Sums of * underlying coverage information can be obtained by * <code>getData(DataType)</code> method using DataType.CLASS, DataType.METHOD, * DataType.FIELD, DataType.BLOCK, DataType.BRANCH, DataType.LINE. </p> <p> To * access specific method/field information use * <code>getMethodCoverageList()</code> and * <code>getFieldCoverageList()</code> methods </p> * * @see ProductCoverage * @see DataType * @see CoverageData * * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class ClassCoverage extends AbstractCoverage { private String source; private boolean javapSource = false; private JavapClass javapClass; private List<MethodCoverage> methods = new ArrayList<MethodCoverage>(); private List<FieldCoverage> fields = new ArrayList<FieldCoverage>(); private LineCoverage lineCoverage = new LineCoverage(); private DataType[] supportedColumns = {DataType.CLASS, DataType.METHOD, DataType.FIELD, DataType.BLOCK, DataType.BRANCH, DataType.LINE}; private final int access; private final String fullname; private final String name; private final String packagename; private final String modulename; private final Modifiers modifiers; private boolean isInAnc = false; protected String ancInfo; /** * <p> Creates new ClassCoverage instance. </p> * * @param clz DataClass to read data from * @param srcRootPaths Paths for sources * @param filter Allows to filter read data */ public ClassCoverage(DataClass clz, String srcRootPaths[], MemberFilter filter) { this(clz, srcRootPaths, null, filter); } public ClassCoverage(DataClass clz, String srcRootPaths[], List<JavapClass> javapClasses, MemberFilter filter) { this(clz, srcRootPaths, null, filter, null, false); } public ClassCoverage(DataClass clz, String srcRootPaths[], List<JavapClass> javapClasses, MemberFilter filter, AncFilter[] ancFilters, boolean anonym) { access = clz.getAccess(); fullname = clz.getFullname(); name = clz.getName(); packagename = clz.getPackageName(); modulename = clz.getModuleName(); modifiers = clz.getModifiers(); if (ancFilters != null){ for (AncFilter ancFilter : ancFilters){ if (ancFilter.accept(clz)){ isInAnc = true; setAncInfo(ancFilter.getAncReason()); break; } } } for (DataMethod method : clz.getMethods()) { if (filter != null && !filter.accept(clz, method)) { continue; } MethodCoverage methodCoverage = null; if (ancFilters != null){ for (AncFilter ancFilter : ancFilters){ if (isInAnc || ancFilter.accept(clz, method)){ methodCoverage = new MethodCoverage(method, ancFilters, ancFilter.getAncReason()); methodCoverage.setAncInfo(ancFilter.getAncReason()); break; } } } if (methodCoverage == null) { methodCoverage = new MethodCoverage(method, ancFilters, null); } methodCoverage.setAnonymOn(anonym); if (method.getName() != null && method.getName().matches("\\$\\d.*")) { methodCoverage.setInAnonymClass(true); } if (method.getModifiers().isSynthetic() && method.getName().startsWith("lambda$")){ methodCoverage.setLambdaMethod(true); } methods.add(methodCoverage); lineCoverage.processLineCoverage(methodCoverage.getLineCoverage()); } for (DataField field : clz.getFields()) { if (filter != null && !filter.accept(clz, field)) { continue; } FieldCoverage fieldCoverage = new FieldCoverage(field); fields.add(fieldCoverage); } if (javapClasses == null) { this.source = findBestSource(clz, srcRootPaths); } else { javapSource = true; for (JavapClass jpClass : javapClasses) { if (jpClass != null && jpClass.getClassName() != null && (jpClass.getClassName()).equals(name)) { javapClass = jpClass; break; } } } Collections.sort(methods); Collections.sort(fields); } /** * @return true if the class doesn't contain neither methods or fields */ public boolean isEmpty() { return methods.isEmpty() && fields.isEmpty(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if class access modifiers are <b>public</b> or * <b>protected</b> * @see ClassCoverage#getAccess() */ public boolean isPublicAPI() { return modifiers.isPublic() || modifiers.isProtected(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if class is <b>public</b> or <b>protected</b> * @see ClassCoverage#getAccess() */ public boolean isPublic() { return modifiers.isPublic(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if class is <b>public</b> * @see ClassCoverage#getAccess() */ public boolean isPrivate() { return modifiers.isPrivate(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if class is <b>protected</b> * @see ClassCoverage#getAccess() */ public boolean isProtected() { return modifiers.isProtected(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if class is <b>abstract</b> * @see ClassCoverage#getAccess() */ public boolean isAbstract() { return modifiers.isAbstract(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if class is <b>final</b> * @see ClassCoverage#getAccess() */ public boolean isFinal() { return modifiers.isFinal(); } /** * <p> Use this method to check for specific modifiers. </p> * * @return Access bit-mask. */ public int getAccess() { return access; } /** * @param test Number of a test in the testlist * @return true when any method in this class is marked as hit by the * <b>test</b> bit in scales * @see Scale */ public boolean isCoveredByTest(int test) { for (MethodCoverage method : methods) { Scale s = method.getScale(); if (s != null && s.isBitSet(test)) { return true; } } return false; } /** * @return classname in VM notation */ public String getName() { return name; } /** * @return getData(DataType.CLASS_COVERED) > 0; */ public boolean isCovered() { for (MethodCoverage method : methods) { if (method.count > 0) { return true; } } return false; } /** * @return methods in this class */ public List<MethodCoverage> getMethods() { return methods; } /** * @return fields in this class */ public List<FieldCoverage> getFields() { return fields; } /** * @return package name in VM notation */ public String getPackageName() { return packagename; } public String getModuleName() { return modulename; } /** * @return canonical classname */ public String getFullClassName() { return fullname.replace('/', '.'); } /** * @return classname in VM notation ('/' as package separators) */ public String getFullClassNameFilename() { return fullname; } /** * Get class sourcefile * * @return class sourcefile */ public String getSource() { return source; } public boolean isJavapSource() { return javapSource; } public JavapClass getJavapClass() { return javapClass; } /** * Coverage kind (used in HTML reports as header for label) * * @return DataType.CLASS */ public DataType getDataType() { return DataType.CLASS; } protected DataType[] getDataTypes() { return supportedColumns; } /** * Returns true if passed line is covered, false otherwise. * * @param lineNum line number * @return true if passed line is covered, false otherwise. */ public boolean isLineCovered(int lineNum) { return lineCoverage.isLineCovered(lineNum); } public boolean isLineInAnc(int lineNum){ return lineCoverage.isLineAnc(lineNum); } public void setAncInfo(String ancInfo){ isInAnc = (ancInfo != null && !ancInfo.isEmpty()); this.ancInfo = ancInfo; } public String getAncInfo(){ return ancInfo; } /** * Returns true if the line with the given number contains java code * * @param lineNum line number * @return true if the line with the given number contains java code */ public boolean isCode(long lineNum) { return lineCoverage.isCode(lineNum); } /** * <p> Allows to get sums over the coverage of this class. E.g. * getData(DataType.METHOD) will return coverage data containing the total * number of methods in this class and number of covered methods in this * class. </p> <p> Allows to sum though CLASS, METHOD, FIELD, BLOCK, BRANCH * and LINE types </p> * * @param column Type to sum * @return CoverageData representing 2 fields - total number of members and * number of covered members * @see DataType * @see CoverageData */ public CoverageData getData(DataType column, int testNumber) { switch (column) { case CLASS: boolean allMethodsInANC = true; for (MethodCoverage method : methods) { if (method.count > 0 && (testNumber < 0 || method.isCoveredByTest(testNumber))) { if (isInAnc) { return new CoverageData(1, 1, 1); } return new CoverageData(1, 0, 1); } if (method.count <= 0 && !method.isMethodInAnc()){ allMethodsInANC = false; } } if (isInAnc || (allMethodsInANC && methods.size() > 0)) { return new CoverageData(0, 1, 1); } return new CoverageData(0, 0, 1); case METHOD: case BLOCK: case BRANCH: CoverageData covered = new CoverageData(0, 0, 0); for (MethodCoverage method : methods) { if (testNumber < 0 || method.isCoveredByTest(testNumber)) { covered.add(method.getData(column, testNumber)); } else { CoverageData mcov = method.getData(column, testNumber); covered.add(new CoverageData(0, mcov.getAnc() ,mcov.getTotal())); } } return covered; case FIELD: covered = new CoverageData(0, 0, 0); for (FieldCoverage field : fields) { covered.add(field.getData(column)); } return covered; case LINE: return new CoverageData(lineCoverage.getCovered(), lineCoverage.getAnc(), lineCoverage.getTotal()); default: return new CoverageData(); } } public CoverageData getData(DataType column) { return getData(column, -1); } /** * Finds a source that is the most acceptable for this DataClass * * @param clz * @param source_paths * @return */ private static String findBestSource(DataClass clz, String[] source_paths) { if (source_paths == null) { return clz.getSource(); } final char sep = File.separatorChar; String source_name = clz.getSource(); boolean dummy = false; if (source_name == null) { String clzName = clz.getName(); int indexOf = clzName.indexOf('$'); if (indexOf > 0) { clzName = clzName.substring(0, indexOf); } else { clzName = clzName + ".java"; } source_name = clzName; dummy = true; } if (source_name.startsWith(pref) && source_name.endsWith(suff)) { source_name = source_name.substring(0, source_name.length() - suff.length()); source_name = source_name.substring(pref.length()); dummy = true; } source_name = source_name.replace('/', sep); source_name = source_name.replace('\\', sep); source_name = Utils.basename(source_name); if (dummy) { int i = source_name.indexOf("$"); if (i > 0) { source_name = source_name.substring(0, i) + ".java"; } } String pckg = clz.getPackageName(); source_name = pckg.replace('/', File.separatorChar) + sep + source_name; for (int i = 0; i < source_paths.length; i++) { File f = new File(source_paths[i] + source_name); if (f.exists()) { return f.getAbsolutePath(); } else{ if (clz.getModuleName() != null) { if (source_paths[i].contains("#module")) { f = new File(source_paths[i].replaceAll("\\#module", clz.getModuleName()) + source_name); if (f.exists()) { return f.getAbsolutePath(); } } f = new File(source_paths[i].concat(clz.getModuleName()).concat(String.valueOf(sep)).concat(source_name)); if (f.exists()) { return f.getAbsolutePath(); } } } } return clz.getSource(); // not found } static final String pref = "<UNKNOWN_SOURCE/"; static final String suff = ">"; }
16,992
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ParameterizedAncFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ParameterizedAncFilter.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; /** * This interface represents an ability to pass a string parameter. Syntax of using default parameterized filters: * <pre>java ... RepGen -ancdf &lt;filter&gt;:&lt;parameter&gt;</pre> */ public interface ParameterizedAncFilter extends AncFilter { /** * Sets filter parameter specified in the command line. * @param parameter * @throws Exception */ void setParameter(String parameter) throws Exception; }
1,679
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
PackageCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/PackageCoverage.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.report.javap.JavapClass; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * <p> This class provides access to package coverage information. Sums of * underlying coverage information can be obtained by * <code>getData(DataType)</code> method using DataType.CLASS, DataType.METHOD, * DataType.FIELD, DataType.BLOCK, DataType.BRANCH, DataType.LINE. </p> * * @author Leonid Mesnik * @see ProductCoverage * @see ClassCoverage * @see DataType * @see CoverageData */ public class PackageCoverage extends AbstractCoverage implements Iterable<ClassCoverage> { private String name; private List<ClassCoverage> classCoverageList; private DataType[] supportedColumns = {DataType.CLASS, DataType.METHOD, DataType.BLOCK, DataType.BRANCH, DataType.LINE}; /** * <p> Creates new PackageCoverage instance. </p> * * @param fileImage DataRoot to read data from * @param name Name of the package * @param srcRoots Paths for sources * @param filter Allows to filter read data */ public PackageCoverage(DataRoot fileImage, String name, String srcRoots[], ProductCoverage.CoverageFilter filter, AncFilter[] ancfilters) { this(fileImage, name, srcRoots, null, filter, ancfilters); } public PackageCoverage(DataRoot fileImage, String name, String srcRoots[], List<JavapClass> javapClasses, ProductCoverage.CoverageFilter filter, AncFilter[] ancfilters) { this(fileImage, name, srcRoots, null, filter, ancfilters, false); } public PackageCoverage(DataRoot fileImage, String name, String srcRoots[], List<JavapClass> javapClasses, ProductCoverage.CoverageFilter filter, AncFilter[] ancfilters, boolean anonym) { this.name = name; classCoverageList = _getClassCoverageList(fileImage, srcRoots, javapClasses, filter, ancfilters, anonym); if (classCoverageList != null) { java.util.Collections.sort(classCoverageList); } } /** * @return all classes in this package */ public List<ClassCoverage> getClasses() { return classCoverageList; } private List<ClassCoverage> _getClassCoverageList(DataRoot fileImage, String srcRoots[], List<JavapClass> javapClasses, ProductCoverage.CoverageFilter filter, AncFilter[] ancfilters, boolean anonym) { List<ClassCoverage> result = new ArrayList<ClassCoverage>(); DataPackage pkg = fileImage.findPackage(name, ""); for (DataClass cls : pkg.getClasses()) { ClassCoverage cc = new ClassCoverage(cls, srcRoots, javapClasses, filter, ancfilters, anonym); if (filter == null || filter.accept(cc)) { result.add(cc); } } return result; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PackageCoverage other = (PackageCoverage) obj; if (this.name == null || !this.name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } /** * <p> Allows to get sums over the coverage of this package. E.g. * getData(DataType.METHOD) will return coverage data containing the total * number of methods in this package and number of covered methods in this * package. </p> <p> Allows to sum though CLASS, METHOD, FIELD, BLOCK, * BRANCH and LINE types </p> * * @param column Type to sum * @return CoverageData representing 2 fields - total number of members and * number of covered members * @see DataType * @see CoverageData */ public CoverageData getData(DataType column) { return getData(column, -1); } public CoverageData getData(DataType column, int testNumber) { switch (column) { case CLASS: case METHOD: case FIELD: case BLOCK: case BRANCH: case LINE: CoverageData covered = new CoverageData(); for (ClassCoverage classCoverage : getClasses()) { if (testNumber < 0 || classCoverage.isCoveredByTest(testNumber)) { covered.add(classCoverage.getData(column, testNumber)); } else { covered.add(new CoverageData(0, 0, classCoverage.getData(column, testNumber).getTotal())); } } return covered; default: return new CoverageData(); } } /** * <p> Coverage kind (used in HTML reports as header for label) </p> * * @return DataType.PACKAGE */ public DataType getDataType() { return DataType.PACKAGE; } protected DataType[] getDataTypes() { return supportedColumns; } /** * @return name of the package */ @Override public String getName() { return name.replace('/', '.'); } /** * @return true when any class is covered (getData(DataType.CLASS_COVERED) > * 0) */ public boolean isCovered() { return getData(DataType.CLASS).getCovered() > 0; } /** * @return true if this any class of this package is covered (at least 1 hit * was made) by specified test (by position in the testlist) */ @Override public boolean isCoveredByTest(int testnum) { for (ClassCoverage c : classCoverageList) { if (c.isCoveredByTest(testnum)) { return true; } } return false; } public Iterator<ClassCoverage> iterator() { return classCoverageList.iterator(); } /** * @return false if package doesn't contain any classes */ public boolean isEmpty() { return classCoverageList.isEmpty(); } }
7,490
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SubpackageCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/SubpackageCoverage.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import static com.sun.tdk.jcov.report.DataType.*; /** * Class that allows to accumulate coverage of package with it subpackages. * * @author Dmitry Fazunenko * @see ProductCoverage * @see DataType * @see CoverageData */ public class SubpackageCoverage extends AbstractCoverage { private int class_cov = 0; private int class_anc = 0; private int class_tot = 0; private int meth_cov = 0; private int meth_anc = 0; private int meth_tot = 0; private int field_cov = 0; private int field_anc = 0; private int field_tot = 0; private int block_cov = 0; private int block_anc = 0; private int block_tot = 0; private int branch_cov = 0; private int branch_anc = 0; private int branch_tot = 0; private int line_cov = 0; private int line_anc = 0; private int line_tot = 0; public SubpackageCoverage() { } /** * Appends given coverage data to the already collected ones. * * @param cov */ public void add(AbstractCoverage cov) { CoverageData d = cov.getData(CLASS); class_cov += d.getCovered(); class_anc += d.getAnc(); class_tot += d.getTotal(); d = cov.getData(METHOD); meth_cov += d.getCovered(); meth_anc += d.getAnc(); meth_tot += d.getTotal(); d = cov.getData(FIELD); field_cov += d.getCovered(); field_anc += d.getAnc(); field_tot += d.getTotal(); d = cov.getData(BLOCK); block_cov += d.getCovered(); block_anc += d.getAnc(); block_tot += d.getTotal(); d = cov.getData(BRANCH); branch_cov += d.getCovered(); branch_anc += d.getAnc(); branch_tot += d.getTotal(); d = cov.getData(LINE); line_cov += d.getCovered(); line_anc += d.getAnc(); line_tot += d.getTotal(); } private DataType[] supportedColumns = {CLASS, METHOD, FIELD, BLOCK, BRANCH, LINE}; @Override public DataType getDataType() { return DataType.PRODUCT; } public CoverageData getData(DataType column) { return getData(column, -1); } @Override public CoverageData getData(DataType column, int testNumber) { switch (column) { case CLASS: return new CoverageData(class_cov, class_anc, class_tot); case METHOD: return new CoverageData(meth_cov, meth_anc, meth_tot); case FIELD: return new CoverageData(field_cov, field_anc, field_tot); case BLOCK: return new CoverageData(block_cov, block_anc, block_tot); case BRANCH: return new CoverageData(branch_cov, branch_anc, branch_tot); case LINE: return new CoverageData(line_cov, line_anc, line_tot); default: return new CoverageData(); } } @Override protected DataType[] getDataTypes() { return supportedColumns; } public String getName() { return ""; } public boolean isCovered() { return getData(DataType.CLASS).getCovered() > 0; } @Override /** * throws UnsupportedOperationException */ public boolean isCoveredByTest(int testnum) { throw new UnsupportedOperationException("Not supported here yet."); } }
4,627
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AncFilterFactory.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/AncFilterFactory.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import java.util.Collection; /** * Implementations of this interface are responsible for mapping short names provided with {@code ancdf} options to * AncFilter instances. Instances of this interface are discovered through {@code ServiceLoader} API. */ public interface AncFilterFactory { /** * Creates an instance of {@code AncFilter} identified by a short name. * @param shortName * @return {@code AncFilter} or null, if {@code shortName} does not correspond to any filter supported by this factory. */ AncFilter instantiate(String shortName); /** * Instantiases all supported {@code AncFilter}s, which could be instanciated without additional information, * such as parameters of {@code ParameterizedAncFilter} * @return */ Collection<AncFilter> instantiateAll(); }
2,070
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DefaultReportGeneratorSPI.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/DefaultReportGeneratorSPI.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.ant.AntableSPI; import com.sun.tdk.jcov.report.text.TextReportGenerator; import com.sun.tdk.jcov.report.html.CoverageReport; import com.sun.tdk.jcov.tools.EnvHandler; import com.sun.tdk.jcov.tools.EnvServiceProvider; import com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException; import com.sun.tdk.jcov.tools.OptionDescr; /** * * @author Andrey Titov */ public class DefaultReportGeneratorSPI implements ReportGeneratorSPI, AntableSPI, EnvServiceProvider { protected CoverageReport html = null; protected TextReportGenerator txt = null; protected boolean showMethods = true; protected boolean showBlocks = true; protected boolean showBranches = true; protected boolean showLines = true; protected boolean showOverviewColorBars = false; protected boolean generateShortFormat; protected boolean showFields; public ReportGenerator getReportGenerator(String name) { if ("txt".equalsIgnoreCase(name) || "text".equalsIgnoreCase(name)) { if (txt == null) { txt = new TextReportGenerator(); } txt.setGenerateShortFormat(generateShortFormat); txt.setShowMethods(showMethods); txt.setShowBlocks(showBlocks); txt.setShowBranches(showBranches); txt.setShowFields(showFields); txt.setShowLines(showLines); return txt; } else if ("html".equalsIgnoreCase(name)) { if (html == null) { html = new CoverageReport(); } html.setShowMethods(showMethods); html.setShowBlocks(showBlocks); html.setShowBranches(showBranches); html.setShowLines(showLines); html.setShowOverviewColorBars(showOverviewColorBars); return html; } return null; } public void extendEnvHandler(final EnvHandler handler) { handler.addOptions(new OptionDescr[]{ DSC_NO_BLOCK, DSC_NO_BRANCH, DSC_NO_LINE, DSC_NO_METHOD, DSC_NO_FIELD, DSC_SHORT, DSC_OVERVIEW_COLORBARS}); } public int handleEnv(EnvHandler opts) throws EnvHandlingException { showMethods = !opts.isSet(DSC_NO_METHOD); showFields = !opts.isSet(DSC_NO_FIELD); showBlocks = !opts.isSet(DSC_NO_BLOCK); showBranches = !opts.isSet(DSC_NO_BRANCH); showLines = !opts.isSet(DSC_NO_LINE); generateShortFormat = opts.isSet(DSC_SHORT); showOverviewColorBars = opts.isSet(DSC_OVERVIEW_COLORBARS); return 0; } /** * <p> Allows to use this SPI through ANT wrappers </p> <p> * DefaultReportGeneratorSPI allows following attributes: <ul> * <li>hideMethods</li> <li>hideFields</li> <li>hideLines</li> * <li>hideBlocks</li> <li>hideBranches</li> <li>short</li> </ul> </p> * * @param attrName ANT attribute name. * @param attrValue Value of attribute to set. * @return False if this attribute name is not supported. If SPI returns * FALSE here - JCov will try to resolve setter method (setXXX where XXX is * attrName). If neither setter method exists neither handleAttribute() * accepts the attrName - BuildException would thrown. */ public boolean handleAttribute(String attrName, String attrValue) { if ("hideMethods".equalsIgnoreCase(attrName)) { showMethods = !Boolean.parseBoolean(attrValue); return true; } else if ("hideBlocks".equalsIgnoreCase(attrName)) { showBlocks = !Boolean.parseBoolean(attrValue); return true; } else if ("hideBranches".equalsIgnoreCase(attrName)) { showBranches = !Boolean.parseBoolean(attrValue); return true; } else if ("hideLines".equalsIgnoreCase(attrName)) { showLines = !Boolean.parseBoolean(attrValue); return true; } else if ("short".equalsIgnoreCase(attrName)) { generateShortFormat = Boolean.parseBoolean(attrValue); return true; } else if ("hideFields".equalsIgnoreCase(attrName)) { showFields = !Boolean.parseBoolean(attrValue); return true; } return false; } protected final static OptionDescr DSC_SHORT = new OptionDescr("short", "Additional filtering", "Generate short summary text report."); protected final static OptionDescr DSC_NO_METHOD = new OptionDescr("nomethod", "Additional filtering", "Hide method coverage from report"); protected final static OptionDescr DSC_NO_FIELD = new OptionDescr("nofields", "Additional filtering", "Hide field coverage from report"); protected final static OptionDescr DSC_NO_BRANCH = new OptionDescr("nobranch", "Additional filtering", "Hide branch coverage from report"); protected final static OptionDescr DSC_NO_BLOCK = new OptionDescr("noblock", "Additional filtering", "Hide block coverage from report"); protected final static OptionDescr DSC_NO_LINE = new OptionDescr("noline", "Additional filtering", "Hide line coverage from report"); protected final static OptionDescr DSC_OVERVIEW_COLORBARS = new OptionDescr("addoverviewbars", "Additional reporting", "Adds colorful bars to the overview frames."); }
6,696
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
LineCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/LineCoverage.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.instrument.DataMethod.LineEntry; import java.util.HashMap; import java.util.List; /** * <p> Class providing information about line coverage - it contains numbers of * covered and uncovered lines. </p> * * @author Dmitry Fazunenko */ public class LineCoverage extends CoverageData { final HashMap<Long, Boolean> lines_hits = new HashMap<Long, Boolean>(); final HashMap<Long, Boolean> lines_ancs = new HashMap<Long, Boolean>(); public LineCoverage() { } /** * Return true if passed line is covered, false otherwise. * * @param lineNum line number * @return true if passed line is covered, false otherwise. */ public boolean isLineCovered(long lineNum) { Boolean isHit = lines_hits.get(lineNum); return isHit != null && isHit.booleanValue(); } public boolean isLineAnc(long lineNum) { Boolean isAnc = lines_ancs.get(lineNum); return isAnc != null && isAnc.booleanValue(); } /** * Return true if the line with the given number contains java code * * @param lineNum line number * @return true if the line with the given number contains java code */ public boolean isCode(long lineNum) { return lines_hits.get(lineNum) != null; } /** * Merges given lineTable with the own one * * @param lineTable */ void processLineTable(final List<LineEntry> lineTable) { if (lineTable == null) { return; } for (LineEntry le : lineTable) { ++total; lines_hits.put((long) le.line, false); lines_ancs.put((long) le.line, false); } } /** * Marks the given line as covered. Does nothing if the line is not in the * coverage * * @param line - line number */ public void hitLine(long line) { Boolean wasHit = lines_hits.get(line); if (wasHit != null) { boolean was = lines_hits.put(line, true); if (!was) { ++covered; } } } public void markLineAnc(long line) { Boolean isAnc = lines_ancs.get(line); if (isAnc != null) { boolean was = lines_ancs.put(line, true); if (!was){ ++anc; } } } private void markLineAnc(long line, boolean isAnc) { Boolean wasAnc = lines_ancs.get(line); if (wasAnc != null) { if (!wasAnc && isAnc) { ++anc; } else if (wasAnc && !isAnc) { --anc; } lines_ancs.put(line, isAnc || wasAnc); } else{ if (isAnc && !isLineCovered(line)) { ++anc; } lines_ancs.put(line, isAnc); } } private void hitLine(long line, boolean isHit) { Boolean wasHit = lines_hits.get(line); if (wasHit != null) { if (!wasHit && isHit) { ++covered; } else if (wasHit && !isHit) { --covered; } lines_hits.put(line, isHit || wasHit); } else { if (isHit) { ++covered; } // no else as this line was not hit ++total; lines_hits.put(line, isHit); } } /** * Merges the given LineCoverage data with the own ones. * * @param lineCov - coverage data to merge */ void processLineCoverage(LineCoverage lineCov) { for (long line : lineCov.lines_hits.keySet()) { hitLine(line, lineCov.lines_hits.get(line)); } for (long line : lineCov.lines_ancs.keySet()) { markLineAnc(line, lineCov.lines_ancs.get(line)); } } /** * @return line having the smallest number */ public long firstLine() { long firstLine = -1; for (long lineNum : lines_hits.keySet()) { if (firstLine < 0 || lineNum < firstLine) { firstLine = lineNum; } } return firstLine < 0 ? 1 : firstLine; } /** * @return line having the largest number */ public long lastLine() { long lastLine = -1; for (long lineNum : lines_hits.keySet()) { if (lastLine < 0 || lineNum > lastLine) { lastLine = lineNum; } } return lastLine < 0 ? 1 : lastLine; } }
5,727
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ItemCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ItemCoverage.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.data.Scale; import com.sun.tdk.jcov.instrument.DataBlock; /** * ItemCoverage has 2 inheritors: BlockCoverage and BranchCoverage. Use * isBlock() method to differ them if needed * * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public abstract class ItemCoverage extends AbstractCoverage { /** * Creates new block coverage data * * @param b * @return new block coverage data */ public static ItemCoverage createBlockCoverageItem(DataBlock b) { return createBlockCoverageItem(b.startBCI(), b.endBCI(), b.getCount(), b.getScale()); } /** * Creates new block coverage data * * @param startBCI * @param endBCI * @param cnt * @return new block coverage data */ public static ItemCoverage createBlockCoverageItem(int startBCI, int endBCI, long cnt) { return new BlockCoverage(startBCI, endBCI, cnt, null); } /** * Creates new block coverage data * * @param startBCI * @param endBCI * @param cnt * @return new block coverage data */ public static ItemCoverage createBlockCoverageItem(int startBCI, int endBCI, long cnt, Scale scale) { return new BlockCoverage(startBCI, endBCI, cnt, scale); } /** * Creates new branch coverage data * * @param b * @return new block coverage data */ public static ItemCoverage createBranchCoverageItem(DataBlock b) { return createBranchCoverageItem(b.startBCI(), b.endBCI(), b.getCount(), b.getScale()); } /** * Creates new branch coverage data * * @param startBCI * @param endBCI * @param cnt * @return new block coverage data */ public static ItemCoverage createBranchCoverageItem(int startBCI, int endBCI, long cnt) { return new BranchCoverage(startBCI, endBCI, cnt, null); } /** * Creates new branch coverage data * * @param startBCI * @param endBCI * @param cnt * @return new block coverage data */ public static ItemCoverage createBranchCoverageItem(int startBCI, int endBCI, long cnt, Scale scale) { return new BranchCoverage(startBCI, endBCI, cnt, scale); } protected final int startLine; protected final int endLine; protected long count; private int srcLine = -1; protected Scale scale; protected boolean isInAnc = false; protected String ancInfo; protected ItemCoverage(int startLine, int endLine, long count, Scale scale) { this.startLine = startLine; this.endLine = endLine; this.count = count; this.scale = scale; } public boolean isInAnc() { return isInAnc; } public void setAncInfo(String ancInfo){ isInAnc = true; this.ancInfo = ancInfo; } public String getAncInfo(){ return ancInfo; } protected void setSrcLine(int srcLine) { this.srcLine = srcLine; } /** * @return line position in source file */ public int getSourceLine() { return srcLine; } /** * @return hit count */ public long getCount() { return count; } /** * @return last line position in source file */ public int getEndLine() { return endLine; } /** * @return first line position in source file */ public int getStartLine() { return startLine; } /** * @return true if this object is instance of BlockCoverage */ public abstract boolean isBlock(); /** * @return true when any hit was collected */ public boolean isCovered() { return count > 0; } @Override public boolean isCoveredByTest(int testnum) { return scale != null && scale.isBitSet(testnum); } @Override public String toString() { String b = isBlock() ? "BLOCK " : "BRANCH "; return b + startLine + ":" + endLine + " " + count; } /** * @return { DataType.BLOCK, DataType.BRANCH } * @see DataType */ public static DataType[] getAllPossibleTypes() { return new DataType[]{DataType.BLOCK, DataType.BRANCH}; } /** * Data covering blocks */ private static class BlockCoverage extends ItemCoverage { private BlockCoverage(DataBlock dataBlock) { this(dataBlock.startBCI(), dataBlock.endBCI(), dataBlock.getCount(), dataBlock.getScale()); } private BlockCoverage(int startBCI, int endBCI, long cnt, Scale scale) { super(startBCI, endBCI, cnt, scale); } /** * Coverage kind (used in HTML reports as header for label) * * @return DataType.BLOCK */ public DataType getDataType() { return DataType.BLOCK; } /** * @return {DataType.BLOCK} */ protected DataType[] getDataTypes() { return new DataType[]{DataType.BLOCK}; } public CoverageData getData(DataType column) { return getData(column, -1); } public CoverageData getData(DataType column, int testNumber) { switch (column) { case BLOCK: int value = count == 0 ? 0 : 1; if (isInAnc){ return new CoverageData(value, 1 - value, 1); } return new CoverageData(value, 0, 1); default: return new CoverageData(); } } @Override public String getName() { return "block"; } @Override public boolean isBlock() { return true; } } /** * Data covering branches */ private static class BranchCoverage extends ItemCoverage { private BranchCoverage(int startBCI, int endBCI, long cnt, Scale scale) { super(startBCI, endBCI, cnt, scale); } /** * Coverage kind (used in HTML reports as header for label) * * @return DataType.BRANCH */ public DataType getDataType() { return DataType.BRANCH; } /** * @return {DataType.BRANCH} */ protected DataType[] getDataTypes() { return new DataType[]{DataType.BRANCH}; } public CoverageData getData(DataType column) { return getData(column, -1); } public CoverageData getData(DataType column, int testNumber) { switch (column) { case BRANCH: int value = count == 0 ? 0 : 1; if (isInAnc){ return new CoverageData(value, 1 - value, 1); } return new CoverageData(value, 0, 1); default: return new CoverageData(); } } @Override public String getName() { return "branch"; } @Override public boolean isBlock() { return false; } } }
8,446
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AbstractCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/AbstractCoverage.java
/* * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.util.NaturalComparator; import java.util.ArrayList; import java.util.List; /** * Base class for Product, Package, Class, Method, Field, Block, Branch and Line * Coverage * * @author Leonid Mesnik * @author Dmitry Fazunenko */ public abstract class AbstractCoverage implements Comparable { /** * @return DataType representing type of this coverage data (eg * DataType.CLASS for classes coverage information) */ public abstract DataType getDataType(); /** * <p> Sums coverage over selected {@link DataType}. Every coverage member * has it own list of supported DataTypes to sum. E.g. ClassCoverage can sum * coverage only for classes (itself), methods, fields, blocks, branches and * lines. </p> <p> getData(DataType) sums the underlying coverage and * returns a {@link CoverageData} object which encapsulates 2 numbers - * number of <b>all</b> underlying elements and number of <b>covered</b> * elements. E.g. ClassCoverage.getData(DataType.METHOD) will return number * of all methods in this class and number of covered methods in this class. * </p> * * @param type type coverage to sum * @return Summed coverage in CoverageData object */ public abstract CoverageData getData(DataType type); public abstract CoverageData getData(DataType type, int testNumber); /** * @return member name (eg packagename of classname) */ public abstract String getName(); /** * @return true if this member is covered (at least 1 hit was made) */ public abstract boolean isCovered(); /** * @return true if this member is covered (at least 1 hit was made) by * specific test (by position in the testlist) */ public abstract boolean isCoveredByTest(int testnum); protected abstract DataType[] getDataTypes(); /** * @param kind * @return true if this coverage member has underlying <b>kind</b> member * (eg Class has Fields and Methods) */ public final boolean isSupported(DataType kind) { for (DataType name : getDataTypes()) { if (name.equals(kind)) { return true; } } return false; } /** * <p> Formats coverage using default formatter. By default it's * PercentFormatter that formats coverage in form of "percent% * (covered/total)" or " -" if total is null </p> * * @param type Data type * @return Formatted coverage data * @see AbstractCoverage#getData(com.sun.tdk.jcov.report.DataType) * @see CoverageData#getFormattedCoverage() */ public final String getCoverageString(DataType type) { return getCoverageString(type, false); } public final String getCoverageString(DataType type, boolean withAnc) { CoverageData data = getData(type); return data.getFormattedCoverage(withAnc); } /** * <p> Formats coverage using specified formatter. </p> * * @param type Data type * @param f Formatter to format string * @return Formatted coverage data * @see AbstractCoverage#getData(com.sun.tdk.jcov.report.DataType) * @see * CoverageData#getFormattedCoverage(com.sun.tdk.jcov.report.AbstractCoverage.CoverageFormatter) */ public final String getCoverageString(DataType type, CoverageFormatter f) { CoverageData data = getData(type); return data.getFormattedCoverage(f); } public final String getCoverageString(DataType type, CoverageANCFormatter f, boolean withAnc) { CoverageData data = getData(type); return data.getFormattedCoverage(f, withAnc); } public int compareTo(Object obj) { return NaturalComparator.INSTANCE.compare(this.getName(), ((AbstractCoverage) obj).getName()); } /** * @param testlist Testlist in order of tests were run * @return List of testnames covering this member */ public List<String> getCoveringTests(String testlist[]) { ArrayList<String> list = new ArrayList<>(testlist.length / 10); for (int i = 0; i < testlist.length; ++i) { if (isCoveredByTest(i)) { list.add(testlist[i]); } } return list; } /** * CoverageFormatter serves to format CoverageData objects into strings */ public interface CoverageFormatter { /** * * @param data CoverageData object to format * @return formatted coverage data */ String format(CoverageData data); } public interface CoverageANCFormatter { /** * @param data CoverageData object to format * @param withAnc Show acceptable not covered data * @return formatted coverage data */ String format(CoverageData data, boolean withAnc); } /** * Default CoverageFormatter that formats coverage in form of "percent% * (covered/total)" or " -" if total is null */ public static class PercentFormatter implements CoverageFormatter, CoverageANCFormatter { public String format(CoverageData data){ if (data.total == 0) { return " -"; } else { return String.format("%4d%% (%d/%d)", Math.floorDiv(data.covered * 100, data.total), data.covered, data.total); } } public String format(CoverageData data, boolean withAnc){ if (data.total == 0) { return " -"; } else { if (!withAnc) { return String.format("%4d%% (%d/%d)", Math.floorDiv(data.covered * 100, data.total), data.covered, data.total); } return String.format("%4d%% (%d/%d/%d)", Math.floorDiv((data.covered + data.anc) * 100, data.total), data.covered, data.anc, data.total); } } } }
7,274
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ReportGenerator.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ReportGenerator.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.report.javap.JavapClass; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.IOException; import java.util.List; /** * Interface for creating custom reports * * @see ReportGeneratorSPI * @author Andrey Titov */ public interface ReportGenerator { /** * <p> JCov RepGen will call this method before reading XML datafile. </p> * * @param outputPath Value of "-output" option. "report" by default. * @throws IOException */ public void init(String outputPath) throws IOException; /** * <p> This method should create report </p> * * @param coverage Coverage data * @param options Some useful data (testlist and paths to the sources) * @throws IOException * @see ProductCoverage */ public void generateReport(ProductCoverage coverage, Options options) throws IOException; /** * <p> Class encapsulating some useful data </p> <p> It will be filled by * the RepGen and passed to each ReportGenerator </p> */ public static class Options { /** * Non-parsed path to sources (eg "classes/:tests/" or "classes;tests" * for Win) */ private String srcRootPath; /** * Parsed paths to sources */ private String[] srcRootPaths; /** * TestList object. */ private SmartTestService testListService; /** * Classes are results of the javap command */ private List<JavapClass> classes; /** * show coverage for each test in result.xml (use when result.xml has * been gotten after merge operation with scales) */ private boolean withTestsInfo; /** * true if RepGen has been run for several result.xml files (will give * different view of the result report) */ private boolean mergeRepGenMode; private InstrumentationOptions.InstrumentationMode mode; private boolean anonym = false; private String mainReportTitle = null; private String overviewListTitle = null; private String entitiesTitle = null; /** * Creates empty Options */ public Options() { srcRootPath = null; srcRootPaths = null; testListService = null; } /** * Creates Options instance * * @param srcRootPath Path to the sources (divided by * File.pathSeparator) * @param testListService STS object */ public Options(String srcRootPath, SmartTestService testListService, List<JavapClass> classes, boolean withTestInfo, boolean mergeRepGenMode) { this(srcRootPath, testListService, classes, withTestInfo, mergeRepGenMode, null, null, null); } /** * Creates Options instance * * @param srcRootPath Path to the sources (divided by * File.pathSeparator) * @param testListService STS object */ public Options(String srcRootPath, SmartTestService testListService, List<JavapClass> classes, boolean withTestInfo, boolean mergeRepGenMode, String mainTitle, String overviewTitle, String entitiesTitle) { this.withTestsInfo = withTestInfo; this.mergeRepGenMode = mergeRepGenMode; this.classes = classes; this.srcRootPath = srcRootPath; this.testListService = testListService; if (srcRootPath != null) { this.srcRootPaths = Utils.getSourcePaths(srcRootPath); } else { this.srcRootPaths = null; } this.mainReportTitle = mainTitle; this.overviewListTitle = overviewTitle; this.entitiesTitle = entitiesTitle; } public List<JavapClass> getJavapClasses() { return classes; } /** * Non-parsed path to sources (eg "classes/:tests/" or "classes;tests" * for Win) * * @return Non-parsed path to sources (eg "classes/:tests/" or * "classes;tests" for Win) */ public String getSrcRootPath() { return srcRootPath; } /** * Parsed paths to sources * * @return Parsed paths to sources */ public String[] getSrcRootPaths() { return srcRootPaths; } /** * Sets parsed paths to sources * * @param srcRootPaths Parsed paths to sources */ public void setSrcRootPaths(String[] srcRootPaths) { this.srcRootPaths = srcRootPaths; srcRootPath = ""; if (srcRootPaths.length > 0) { for (int i = 0; i < srcRootPaths.length - 1; ++i) { srcRootPath += srcRootPaths[i] + File.pathSeparatorChar; } srcRootPath += srcRootPaths[srcRootPaths.length - 1]; } } /** * TestList object * * @return TestList object */ public SmartTestService getTestListService() { return testListService; } public void setSrcRootPath(String srcRootPath) { this.srcRootPath = srcRootPath; if (srcRootPath != null) { this.srcRootPaths = Utils.getSourcePaths(srcRootPath); } } public void setTestListService(SmartTestService testListService) { this.testListService = testListService; } public boolean isWithTestsInfo() { return withTestsInfo; } public boolean isMergeRepGenMode() { return mergeRepGenMode; } public void setInstrMode(InstrumentationOptions.InstrumentationMode mode) { this.mode = mode; } public InstrumentationOptions.InstrumentationMode getInstrMode() { return this.mode; } public void setAnonymOn(boolean anonym) { this.anonym = anonym; } public boolean isAnonymOn() { return anonym; } public String getMainReportTitle() { return mainReportTitle; } public String getOverviewListTitle() { return overviewListTitle; } public String getEntitiesTitle() { return entitiesTitle; } } }
7,845
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DataType.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/DataType.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; /** * <p> Enumeration of coverage data types. </p> * * @author Baechul Kim * @since 1.0 */ public enum DataType { PRODUCT("Product"), /** * Value of java class package coverage kind. */ PACKAGE("Package"), /** * Value of java class coverage kind . */ CLASS("Class"), /** * Value of java method coverage kind. */ METHOD("Method"), /** * Value of java field coverage kind. */ FIELD("Field"), /** * Value of java block coverage kind. */ BLOCK("Block"), /** * Value of java branch coverage kind. */ BRANCH("Branch"), /** * Value of native(c/c++) source file coverage kin . */ SOURCE("Source"), /** * Value of native(c/c++) line coverage kind. */ LINE("Line"), ITEM("Item"), ITEM_START_LINE("Start Line"), ITEM_END_LINE("End Line"), ITEM_COVERAGE_FORMAT("Coverage Format"), ITEM_NATIVE_KIND("Native Kind"), ITEM_HIT_COUNT("Hit Count"); private String title; private DataType(String title) { this.title = title; } /** * Return a short description of this enum value, which can be used as a * name or title in the representation. * * @return a short description of this enum value, which can be used as a * name or title in the representation. */ public String getTitle() { return title; } void setTitle(String title) { this.title = title; } @Override public String toString() { return getTitle(); } }
2,824
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
CoverageData.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/CoverageData.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; /** * <p> This class represents coverage data. It contains number of covered * members (getCovered()) and total member number (getTotal()). </p> <p> * getFormattedCoverage() allows to get coverage in form ready for output </p> * * @author Andrey Titov * @see AbstractCoverage#getData(com.sun.tdk.jcov.report.DataType) */ public class CoverageData { protected int covered; protected int total; protected int anc; /** * default formatter to use in getFormattedCoverage * * @see #getFormattedCoverage() * @see AbstractCoverage.CoverageFormatter * @see AbstractCoverage.PercentFormatter */ public static final AbstractCoverage.CoverageANCFormatter defaultFormatter = new AbstractCoverage.PercentFormatter(); /** * Creates zero-filled coverage data object */ public CoverageData() { this.covered = this.anc = this.total = 0; } /** * Creates coverage data object * * @param covered member hit count * @param total total member count * @param anc acceptable non coverage */ public CoverageData(int covered, int anc, int total) { this.covered = covered; this.total = total; this.anc = anc; } /** * @return acceptable non coverage count */ public int getAnc() { return anc; } /** * @param anc acceptable non coverage count */ public void setAnc(int anc) { this.anc = anc; } /** * @return member hit count */ public int getCovered() { return covered; } /** * @param covered member hit count */ public void setCovered(int covered) { this.covered = covered; } /** * @return total member count */ public int getTotal() { return total; } /** * @param total total member count */ public void setTotal(int total) { this.total = total; } /** * sums two coverage data objects * * @param data data object to add * @return this object */ public CoverageData add(CoverageData data) { covered += data.covered; total += data.total; anc += data.anc; return this; } /** * <p> Formats coverage using default formatter. By default it's * PercentFormatter that formats coverage in form of "percent% * (covered/total)" or " -" if total is null </p> * * @return formatted coverage string * @see AbstractCoverage.CoverageFormatter * @see AbstractCoverage.PercentFormatter */ public String getFormattedCoverage() { return getFormattedCoverage(false); } public String getFormattedCoverage(boolean withANC) { return defaultFormatter.format(this, withANC); } /** * Formats coverage using specified formatter * * @param f formatter to use * @return formatted coverage string * @see AbstractCoverage.CoverageFormatter * @see AbstractCoverage.PercentFormatter */ public String getFormattedCoverage(AbstractCoverage.CoverageFormatter f) { return f.format(this); } public String getFormattedCoverage(AbstractCoverage.CoverageANCFormatter f, boolean withANC) { return f.format(this, withANC); } /** * @return coverage string in form of "covered/total" */ @Override public String toString() { if (total == 0) { return "-"; } if (anc == 0){ return String.format("%d/%d", covered, total); } return String.format("%d/%d/%d", covered, anc, total); } }
4,903
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SmartTestService.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/SmartTestService.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * @author Leonid Mesnik */ public class SmartTestService implements Iterable<Test> { private List<Test> allTests; /** * <p> Creates empty STS </p> */ public SmartTestService() { allTests = new ArrayList<Test>(); } /** * <p> Creates a STS from the testlist </p> * * @param tests testlist as array of testnames */ public SmartTestService(String[] tests) { allTests = new ArrayList<Test>(tests.length); for (String test : tests) { allTests.add(new SmartTest(test)); } } /** * <p> Creates a STS from the input stream. Testnames should be divided by a * newline. </p> * * @param reader Input stream to read */ public SmartTestService(BufferedReader reader) { try { allTests = new ArrayList<Test>(); String name = null; while ((name = reader.readLine()) != null) { allTests.add(new SmartTest(name)); // System.out.println("Add " + name); } //System.out.println("Read " + allTests.size()); } catch (IOException ioe) { throw new Error(ioe); } } /** * <p> Get all tests covering a certain class </p> * * @param clz Class to check * @return List of tests which are covering the class */ public List<Test> getHitTestByClasses(ClassCoverage clz) { List<Test> result = new ArrayList<Test>(); if (allTests.isEmpty()) { result.addAll(allTests); } else { for (int i = 0; i < allTests.size(); i++) { if (clz.isCoveredByTest(i)) { result.add(allTests.get(i)); } } } return result; } public List<Test> getAllTests(){ return allTests; } /** * <p> Get number of tests in the STS </p> * * @return Count of tests */ public int getTestCount() { return allTests.size(); } public Iterator<Test> iterator() { return allTests.iterator(); } private static class SmartTest implements Test { private String name; private String testername; SmartTest(String name) { this.name = name; } SmartTest(String name, String testername) { this.name = name; this.testername = testername; } public String getTestName() { return name; } public String getTestOwner() { return testername; } } }
4,005
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ProductCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ProductCoverage.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.filter.MemberFilter; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataField; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataPackage; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.report.javap.JavapClass; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * <p> The product coverage container serves for accessing coverage information * retrieved from the XML files or any other sources. </p> <p> Following * coverage objects are structured hierarchically and can be browsed from the * <code>ProductCoverage</code>. </p> <p> <ol> * <li><code>{@link ProductCoverage}</code><br> A top level product * coverage</li> <li><code>{@link PackageCoverage}</code><br> A package * coverage</li> <li><code>{@link ClassCoverage}</code><br> A class * coverage</li> <li><code>{@link MethodCoverage}</code><br> A method * coverage</li> <li><code>{@link ItemCoverage}</code><br> Represents a block or * branch coverage (depends on the coverage format).</li> * <li><code>{@link FieldCoverage}</code><br> A field coverage</li> * <li><code>{@link LineCoverage}</code><br> Represents line coverage.</li> * </ol> </p> <p> <b>Accessing coverage data</b> </p> <p> The coverage data can * be accessed by * <code>getData(DataType)</code> method. This method sums coverage information * over all the children so * <code>getData(DataType.CLASS)</code> will return number of covered classes * and the number of all classes in the product. More information can be found * at {@link AbstractCoverage} interface. </p> <p> To get package information * use * <code>getPackages()</code> method. </p> * * @author Baechul Kim * @author Andrey Titov * @see PackageCoverage * @see ClassCoverage * @see MethodCoverage * @see ItemCoverage * @see LineCoverage * @see CoverageData * @see DataType * @see DataRoot * @since 1.0 */ public class ProductCoverage extends AbstractCoverage implements Iterable<PackageCoverage> { private ArrayList<PackageCoverage> packages; private DataType[] supportedColumns = {DataType.CLASS, DataType.METHOD, DataType.FIELD, DataType.BLOCK, DataType.BRANCH, DataType.LINE}; private ArrayList<ClassCoverage> classes; private String productName; private AncFilter[] ancfilters = null; /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. DataRoot is read from * <b>filename</b>. </p> <p> This constructor reads file with scales and * doesn't filter data. </p> * * @param filename A file to read data from. * @throws FileFormatException when any problem with file reading occurs. * @see CoverageFilter * @see ProductCoverage#ProductCoverage(java.lang.String, boolean, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(String filename) throws FileFormatException { this(readFileImage(filename, true), null, null, null, true); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. DataRoot is read from * <b>filename</b>. </p> <p> This constructor reads file with scales and * doesn't filter data. </p> * * @param filename A file to read data from. * @param srcPaths Paths to sources * @throws FileFormatException when any problem with file reading occurs. * @see CoverageFilter * @see ProductCoverage#ProductCoverage(java.lang.String, boolean, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(String filename, String srcPaths[]) throws FileFormatException { this(readFileImage(filename, true), srcPaths, null, null, true); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. DataRoot is read from * <b>filename</b>. </p> <p> This constructor doesn't filter data. </p> * * @param filename A file to read data from. * @param readScales JCov will read scales only when readScales is set to * true. If the file doesn't contain scales - they would be created. * @param srcPaths Paths to sources * @throws FileFormatException when any problem with file reading occurs. * @see CoverageFilter * @see ProductCoverage#ProductCoverage(java.lang.String, boolean, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(String filename, boolean readScales, String srcPaths[]) throws FileFormatException { this(readFileImage(filename, readScales), srcPaths, null, null, true); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. DataRoot is read from * <b>filename</b>. </p> <p> This constructor doesn't filter data. </p> * * @param filename A file to read data from. * @param readScales JCov will read scales only when readScales is set to * true. If the file doesn't contain scales - they would be created. * @throws FileFormatException when any problem with file reading occurs. * @see CoverageFilter * @see ProductCoverage#ProductCoverage(java.lang.String, boolean, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(String filename, boolean readScales) throws FileFormatException { this(readFileImage(filename, readScales), null, null, null, true); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. DataRoot is read from * <b>filename</b>. </p> * * @param filename A file to read data from. * @param readScales JCov will read scales only when readScales is set to * true. If the file doesn't contain scales - they would be created. * @param srcPaths Paths to sources * @param filter Allows to filter data * @throws FileFormatException when any problem with file reading occurs. * @see CoverageFilter */ public ProductCoverage(String filename, boolean readScales, String srcPaths[], CoverageFilter filter) throws FileFormatException { this(Reader.readXML(filename, readScales, filter), srcPaths, null, filter, true); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. DataRoot is read from * <b>filename</b>. </p> <p> A default filter is used to control reading of * non-public and abstract members. </p> * * @param filename A file to read data from. * @param readScales JCov will read scales only when readScales is set to * true. If the file doesn't contain scales - they would be created. * @param srcPaths Paths to sources * @param isPublicAPI Read only public API (public or protected members). * Use CoverageFilter to control filtering more precisely. * @param noAbstract Do not read abstract members * @throws FileFormatException when any problem with file reading occurs. * @see CoverageFilter * @see ProductCoverage#ProductCoverage(java.lang.String, boolean, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(String filename, boolean readScales, String srcPaths[], boolean isPublicAPI, boolean noAbstract) throws FileFormatException { this(readFileImage(filename, readScales), srcPaths, null, new DefaultFilter(isPublicAPI, noAbstract), true); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. <p> <p> A default filter is * used to control reading of non-public and abstract members. </p> * * @param fileImage DataRoot representing coverage information. DataRoot can * be read with DataRoot.read() method * @throws FileFormatException * @see CoverageFilter * @see DataRoot * @see DataRoot#read(java.lang.String) * @see * ProductCoverage#ProductCoverage(com.sun.tdk.jcov.instrument.DataRoot, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(DataRoot fileImage) { this(fileImage, null, null, null, false); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. <p> <p> A default filter is * used to control reading of non-public and abstract members. </p> * * @param fileImage DataRoot representing coverage information. DataRoot can * be read with DataRoot.read() method * @param srcPaths Paths to sources * @throws FileFormatException * @see CoverageFilter * @see DataRoot * @see DataRoot#read(java.lang.String) * @see * ProductCoverage#ProductCoverage(com.sun.tdk.jcov.instrument.DataRoot, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(DataRoot fileImage, String srcPaths[]) { this(fileImage, srcPaths, null, null, false); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. <p> <p> A default filter is * used to control reading of non-public and abstract members. </p> * * @param fileImage DataRoot representing coverage information. DataRoot can * be read with DataRoot.read() method * @param srcRootPaths Paths to sources * @param isPublicAPI Read only public API (public or protected members). * Use CoverageFilter to control filtering more precisely. * @param noAbstract Do not read abstract members * @throws FileFormatException * @see CoverageFilter * @see DataRoot * @see DataRoot#read(java.lang.String) * @see * ProductCoverage#ProductCoverage(com.sun.tdk.jcov.instrument.DataRoot, * java.lang.String[], * com.sun.tdk.jcov.report.ProductCoverage.CoverageFilter) */ public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, boolean isPublicAPI, boolean noAbstract) { this(fileImage, srcRootPaths, javapClasses, new DefaultFilter(noAbstract, isPublicAPI), false, false); } public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, boolean isPublicAPI, boolean noAbstract, AncFilter[] ancfilters) { this(fileImage, srcRootPaths, javapClasses, new DefaultFilter(noAbstract, isPublicAPI), false, false, ancfilters); } public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, boolean isPublicAPI, boolean noAbstract, boolean anonym) { this(fileImage, srcRootPaths, javapClasses, new DefaultFilter(noAbstract, isPublicAPI), false, anonym, null); } public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, boolean isPublicAPI, boolean noAbstract, boolean anonym, AncFilter[] ancfilters) { this(fileImage, srcRootPaths, javapClasses, new DefaultFilter(noAbstract, isPublicAPI), false, anonym, ancfilters); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. </p> <p> Note that empty * packages/classes will not be stored. </p> * * @param fileImage DataRoot representing coverage information. DataRoot can * be read with DataRoot.read() method * @param srcRootPaths Paths to sources * @param filter Allows to filter data * @throws FileFormatException * @see CoverageFilter * @see DataRoot * @see DataRoot#read(java.lang.String) */ public ProductCoverage(DataRoot fileImage, String srcRootPaths[], CoverageFilter filter) { this(fileImage, srcRootPaths, null, filter, false); } public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, CoverageFilter filter, boolean releaseAfter) { this(fileImage, srcRootPaths, null, filter, false, false); } public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, CoverageFilter filter, boolean releaseAfter, boolean anonym){ this(fileImage, srcRootPaths, null, filter, false, false, null); } /** * <p> Creates a new instance of ProductCoverage which is the top level * coverage object in the coverage objects tree. </p> <p> Note that empty * packages/classes will not be stored. </p> * * @param fileImage DataRoot representing coverage information. DataRoot can * be read with DataRoot.read() method * @param srcRootPaths Paths to sources * @param filter Allows to filter data * @param releaseAfter Allows to automatically destroy DataRoot right after * ProductCoverage initialization * @throws FileFormatException * @see CoverageFilter * @see DataRoot * @see DataRoot#read(java.lang.String) */ public ProductCoverage(DataRoot fileImage, String srcRootPaths[], List<JavapClass> javapClasses, CoverageFilter filter, boolean releaseAfter, boolean anonym, AncFilter[] ancfilters) { packages = new ArrayList<PackageCoverage>(); classes = new ArrayList<ClassCoverage>(); if (filter == null) { filter = new DefaultFilter(false, false); } this.ancfilters = ancfilters; List<DataPackage> packs = fileImage.getPackages(); ArrayList<String> packageNames = new ArrayList<String>(packs.size()); for (DataPackage p : packs) { packageNames.add(p.getName()); } java.util.Collections.sort(packageNames); for (String pkg : packageNames) { PackageCoverage pc = new PackageCoverage(fileImage, pkg, srcRootPaths, javapClasses, filter, ancfilters, anonym); List<ClassCoverage> pkgClasses = pc.getClasses(); classes.addAll(pkgClasses); if (filter.accept(pc)) { packages.add(pc); } } if (releaseAfter) { fileImage.destroy(); } } /** * Determine if the ANC filters were set * @return */ public boolean isAncFiltersSet(){ return ancfilters != null; } private static DataRoot readFileImage(String filename, boolean useScales) throws FileFormatException { return Reader.readXML(filename, useScales, null); } /** * <p> Coverage kind (used in HTML reports as header for label). DataType is * used to get sums over the coverage through getData() method </p> * * @return DataType.PRODUCT * @see DataType * @see ProductCoverage#getData(com.sun.tdk.jcov.report.DataType) */ public DataType getDataType() { return DataType.PRODUCT; } /** * @return packages in this product */ public List<PackageCoverage> getPackages() { return packages; } /** * @return iterator for packages in this product */ public Iterator<PackageCoverage> iterator() { return packages.iterator(); } /** * <p> Allows to get sums over the coverage of this product. E.g. * getData(DataType.CLASS) will return coverage data containing the total * number of classes in the product and number of covered classes in the * product. </p> <p> Allows to sum though PACKAGE, CLASS, METHOD, FIELD, * BLOCK, BRANCH and LINE types </p> * * @param column Type to sum * @return CoverageData representing 2 fields - total number of members and * number of covered members * @see DataType * @see CoverageData */ public CoverageData getData(DataType column) { return getData(column, -1); } public CoverageData getData(DataType column, int testNumber) { CoverageData covered = new CoverageData(0, 0, 0); switch (column) { case PACKAGE: for (PackageCoverage pCoverage : packages) { covered.add(pCoverage.getData(column, testNumber)); } return covered; case CLASS: case METHOD: case FIELD: case BLOCK: case BRANCH: case LINE: for (ClassCoverage classCoverage : classes) { if (testNumber < 0 || classCoverage.isCoveredByTest(testNumber)) { covered.add(classCoverage.getData(column, testNumber)); } else { covered.add(new CoverageData(0, 0, classCoverage.getData(column).getTotal())); } } return covered; default: return new CoverageData(); } } protected DataType[] getDataTypes() { return supportedColumns; } /** * <p> Set the product name </p> * * @param name */ public void setName(String name) { productName = name; } /** * @return product name */ @Override public String getName() { return productName == null ? "" : productName; } /** * @return true when any class is covered (getData(DataType.CLASS_COVERED) > * 0) */ public boolean isCovered() { for (ClassCoverage c : classes) { if (c.isCovered()) { return true; } } return false; } @Override /** * @return true if any class in this product is covered (at least 1 hit was * made) by specified test (by position in the testlist) */ public boolean isCoveredByTest(int testnum) { for (ClassCoverage c : classes) { if (c.isCoveredByTest(testnum)) { return true; } } return false; } /** * Default filter that allows to filter abstract and non-public members. * Also filters out empty classes and packages. */ public static class DefaultFilter extends CoverageFilter { private boolean noAbstract; private boolean isPublicAPI; public DefaultFilter(boolean noAbstract, boolean isPublicAPI) { this.noAbstract = noAbstract; this.isPublicAPI = isPublicAPI; } public boolean accept(DataClass clz) { return true; } public boolean accept(DataClass clz, DataMethod m) { return !(noAbstract && m.isAbstract() || isPublicAPI && !m.isPublicAPI()); } public boolean accept(DataClass clz, DataField f) { return !(isPublicAPI && !f.isPublicAPI()); } @Override public boolean accept(ClassCoverage cc) { return !(!cc.isPublicAPI() && isPublicAPI || cc.isEmpty() && noAbstract); } @Override public boolean accept(PackageCoverage cc) { return !cc.isEmpty(); } } /** * Filter for ProductCoverage. Allows to filter ClassCoverage and * PackageCoverage after their full construction */ public static abstract class CoverageFilter implements MemberFilter { public abstract boolean accept(ClassCoverage cc); public abstract boolean accept(PackageCoverage cc); } }
21,169
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AncFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/AncFilter.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; /** * @author Alexey Fedorchenko */ public interface AncFilter { public boolean accept(DataClass clz); public boolean accept(DataClass clz, DataMethod m); public boolean accept(DataMethod m, DataBlock b); public String getAncReason(); }
1,642
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
MemberCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/MemberCoverage.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.data.Scale; import com.sun.tdk.jcov.instrument.Modifiers; import com.sun.tdk.jcov.util.Utils; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Base class for Method and Field Coverage. * * @author Dmitry Fazunenko */ public abstract class MemberCoverage extends AbstractCoverage { protected long count; protected int startLine; protected String name; protected String signature; protected String modifiersString; protected int access; protected Scale scale; protected Modifiers modifiers; /** * @return hit count. */ public Long getHitCount() { return count; } /** * @return name of this member (field or method) */ public String getName() { return name; } /** * @return true when at least 1 hit was collected */ public boolean isCovered() { return getHitCount() > 0; } /** * @return signature of this member (field or method) */ public String getSignature() { return signature; } /** * Returns member name and signature in JLS format * * @return Member signature in readable form (JLS) */ public String getReadableSignature() { return Utils.convertVMtoJLS(name, signature); } /** * @return String-encoded modifiers */ public String getModifiersString() { return modifiersString; } /** * @return start line in source file */ public int getStartLine() { return startLine; } @Override public boolean isCoveredByTest(int testnum) { return scale != null && scale.isBitSet(testnum); } /** * <p> In contract from getCoveringTests(String[]) this method uses * information about how many tests were run from scale information itself. * </p> * * @return Numbers of tests which covered this method. Will return * Collections.EMPTY_LIST when scales were not read */ public List<Integer> getCoveringTests() { if (scale == null) { return Collections.EMPTY_LIST; } ArrayList<Integer> list = new ArrayList<Integer>(scale.size() / 10); for (int i = 0; i < scale.size(); ++i) { if (scale.isBitSet(i)) { list.add(i); } } return list; } /** * <b> Use scales to find out which code was covered by some specific test. * Scale contains a bit-mask, first bit refers to the first test in the * testlist, second bit to the second test and so on. For example "1101" * scale means that the method was hit by 1, 2 and 4 tests in the testlist. * </b> * * @return Scale information of this method. Can be null if data was read * without scales. * @see Scale */ public Scale getScale() { return scale; } /** * @return Number of tests that were run against this member. This number * should be similar for the entire product. */ public int getScaleSize() { return scale.size(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if member access modifiers are <b>public</b> or * <b>protected</b> * @see ClassCoverage#getAccess() */ public boolean isPublicAPI() { return modifiers.isPublic() || modifiers.isProtected(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if member is <b>public</b> or <b>protected</b> * @see ClassCoverage#getAccess() */ public boolean isPublic() { return modifiers.isPublic(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if member is <b>public</b> * @see ClassCoverage#getAccess() */ public boolean isPrivate() { return modifiers.isPrivate(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if member is <b>protected</b> * @see ClassCoverage#getAccess() */ public boolean isProtected() { return modifiers.isProtected(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if member is <b>abstract</b> * @see ClassCoverage#getAccess() */ public boolean isAbstract() { return modifiers.isAbstract(); } /** * <p> Use getAccess() method to check for more specific modifiers. * getAccess() method returns a bit-mask * constants. </p> * * @return true if member is <b>final</b> * @see ClassCoverage#getAccess() */ public boolean isFinal() { return modifiers.isFinal(); } /** * <p> Use this method to check for specific modifiers. </p> * * @return Access bit-mask. */ public int getAccess() { return access; } }
6,630
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Test.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/Test.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public interface Test { public String getTestOwner(); public String getTestName(); }
1,402
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FieldCoverage.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/FieldCoverage.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report; import com.sun.tdk.jcov.instrument.DataField; import java.util.Arrays; import static com.sun.tdk.jcov.report.DataType.*; /** * <p> This class provides access to field coverage information. * <code>getData(DataType.FIELD)</code> will return 1/1 if this field is * covered. </p> <p> To access specific method/field information use * <code>getMethodCoverageList()</code> and * <code>getFieldCoverageList()</code> methods </p> * * @author Dmitry Fazunenko */ public class FieldCoverage extends MemberCoverage { private DataType[] supportedColumns = {FIELD}; /** * Creates new instance of FieldCoverage * * @param fld */ public FieldCoverage(DataField fld) { access = fld.getAccess(); modifiersString = Arrays.deepToString(fld.getAccessFlags()); name = fld.getName(); signature = fld.getSignature(); startLine = 0; count = fld.getCount(); scale = fld.getScale(); modifiers = fld.getModifiers(); } /** * Coverage kind (used in HTML reports as header for label) * * @return DataType.FIELD */ @Override public DataType getDataType() { return DataType.FIELD; } @Override /** * <p> Only FIELD type is allowed. </p> * * @param column Type to sum * @return CoverageData representing 2 fields - total number of members and * number of covered members * @see DataType * @see CoverageData * @see MemberCoverage#getHitCount() */ public CoverageData getData(DataType column) { return getData(column, -1); } public CoverageData getData(DataType column, int testNumber) { switch (column) { case FIELD: return new CoverageData(count > 0 ? 1 : 0, 0, 1); default: return new CoverageData(); } } @Override protected DataType[] getDataTypes() { return supportedColumns; } }
3,225
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
CoverageReport.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/html/CoverageReport.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.html; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.instrument.XmlNames; import com.sun.tdk.jcov.report.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.tdk.jcov.report.html.resources.CopyResources; import com.sun.tdk.jcov.report.javap.JavapClass; import com.sun.tdk.jcov.report.javap.JavapCodeLine; import com.sun.tdk.jcov.report.javap.JavapLine; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class CoverageReport implements ReportGenerator { private ProductCoverage coverage; private SmartTestService testService; private boolean isGenSrc4Zero = false; private boolean isGenHitTests = false; private boolean isAddTestsInfo = false; private boolean isMergeRepGenMode = false; private boolean isAnonymOn = false; private String title = "Coverage report"; private String mainReportTitle; private String overviewListTitle; private String entitiesTitle; private String dir; private boolean showLines; private boolean showFields; private boolean showBranches; private boolean showBlocks; private boolean showMethods; private boolean showOverviewColorBars; private static final Logger logger; private InstrumentationOptions.InstrumentationMode mode; static { logger = Logger.getLogger(CoverageReport.class.getName()); logger.setLevel(Level.WARNING); } @Override public void init(String dir) throws IOException { this.dir = dir; File d = new File(dir); if (d.exists() && !d.isDirectory()) { throw new IOException("Not a directory: " + dir); } if (!d.exists() && !d.mkdirs()) { throw new IOException("Failed to create directory: " + dir); } } @Override public void generateReport(ProductCoverage coverage, Options options) throws IOException { this.coverage = coverage; if (options.getTestListService() != null) { this.setTestService(options.getTestListService()); this.setGenHitTests(true); this.setAddTestsInfo(options.isWithTestsInfo()); this.setMergeRepGenMode(options.isMergeRepGenMode()); } this.setInstrMode(options.getInstrMode()); this.isAnonymOn = options.isAnonymOn(); mainReportTitle = options.getMainReportTitle() == null ? "Coverage report" : options.getMainReportTitle(); overviewListTitle = options.getOverviewListTitle() == null ? "Coverage report" : options.getOverviewListTitle(); entitiesTitle = options.getEntitiesTitle() == null ? "Coverage report" : options.getEntitiesTitle(); setGenSrc4Zero(true); generate(); } public void generate() throws IOException { File directory = new File(dir); directory.mkdirs(); CopyResources.copy(directory); generateSourceFiles(directory); generateFrameset(directory); HashMap<String, ArrayList<ModuleCoverageData>> modules = getModulesCoverage(); if (modules == null || (modules.size() == 1 && XmlNames.NO_MODULE.equals(modules.keySet().iterator().next()))){ modules = null; } generateOverview(directory, modules); if (modules != null) { generateModulesList(directory, modules); } generatePackageList(directory, modules); generateClassList(directory); } private void generateModulesList(File directory, HashMap<String, ArrayList<ModuleCoverageData>> modules) throws IOException{ List<PackageCoverage> list = coverage.getPackages(); for (String moduleName: modules.keySet()) { HashMap<String, ArrayList<ModuleCoverageData>> module = new HashMap<String, ArrayList<ModuleCoverageData>>(); module.put(moduleName, modules.get(moduleName)); generateModuleOverview(directory, list, module); } } private HashMap<String, ArrayList<ModuleCoverageData>> getModulesCoverage(){ HashMap<String, ArrayList<ModuleCoverageData>> modules = null; List<PackageCoverage> list = coverage.getPackages(); if (list == null || list.size() == 0 || list.get(0) == null || list.get(0).getClasses() == null || list.get(0).getClasses().get(0).getModuleName() == null){ return modules; } modules = new HashMap<String, ArrayList<ModuleCoverageData>>(); for (PackageCoverage pkg : list) { String moduleName = pkg.getClasses().get(0).getModuleName(); if (modules.get(moduleName) == null) { ArrayList<ModuleCoverageData> coverageDataList = new ArrayList<ModuleCoverageData>(); if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int test = 0; test < testService.getTestCount(); test++) { coverageDataList.add(new ModuleCoverageData(pkg, test)); } } coverageDataList.add(new ModuleCoverageData(pkg)); modules.put(moduleName, coverageDataList); } else { ArrayList<ModuleCoverageData> modulesCD = modules.get(moduleName); if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int test = 0; test < testService.getTestCount(); test++) { modulesCD.get(test).addPackage(pkg, test); } } modulesCD.get(modulesCD.size()-1).addPackage(pkg); } } return modules; } public void setVerbose(boolean verbose) { logger.setLevel(verbose ? Level.CONFIG : Level.WARNING); } public void setTestService(SmartTestService testService) { this.testService = testService; } public void setGenSrc4Zero(boolean isGenSrc4Zero) { this.isGenSrc4Zero = isGenSrc4Zero; } public void setGenHitTests(boolean isGenHitTests) { this.isGenHitTests = isGenHitTests; } public void setAddTestsInfo(boolean isWithTestsInfo) { this.isAddTestsInfo = isWithTestsInfo; } public void setMergeRepGenMode(boolean isMergeRepGenMode) { this.isMergeRepGenMode = isMergeRepGenMode; } public void setInstrMode(InstrumentationOptions.InstrumentationMode mode) { this.mode = mode; } public void setTitle(String title) { this.title = title; } private void generateFrameset(File dir) throws IOException { File fsFile = new File(dir, "index.html"); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream( fsFile), Charset.defaultCharset()))); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>" + title + " " /* + coverage.getData(ColumnName.PRODUCT)*/ + "</title>"); pw.println("<link rel =\"stylesheet\" type=\"text/css\" href=\"style.css\" title=\"Style\">"); generateScriptsHeader(pw); pw.println("</head>"); String leftPaneStyle = "left20Container"; String rightPaneStyle = "right80Container"; if (showOverviewColorBars){ leftPaneStyle = "left30Container"; rightPaneStyle = "right70Container"; } pw.println("<body>"); pw.println("<div class=\"container\">"); pw.println(" <div class=\""+leftPaneStyle+"\">"); pw.println(" <div class=\"leftTop\">"); pw.println(" <iframe seamless src=\"overview-frame.html\" name=\"packageListFrame\" title=\"All Packages\"></iframe>"); pw.println(" </div>"); pw.println(" <div class=\"leftBottom\">"); pw.println(" <iframe src=\"allclasses-frame.html\" name=\"packageFrame\" title=\"All classes and interfaces (except non-static nested types)\"></iframe>"); pw.println(" </div>"); pw.println(" </div>"); pw.println(" <div class=\""+rightPaneStyle+"\">"); pw.println(" <iframe src=\"overview-summary.html\" name=\"classFrame\" title=\"Package, class and interface descriptions\"></iframe>"); pw.println(" </div>"); pw.println("</div>"); pw.println("</body>"); pw.println("</html>"); pw.close(); } private void generatePackageList(File dir, HashMap<String, ArrayList<ModuleCoverageData>> modules) throws IOException { File fsFile = new File(dir, "overview-frame.html"); logger.log(Level.INFO, "generatePackageList:{0}", fsFile.getAbsolutePath()); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream( fsFile), Charset.defaultCharset()))); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>coverage report</title>"); pw .println("<link rel =\"stylesheet\" type=\"text/css\" href=\"style.css\" title=\"Style\">"); pw.println("</head>"); pw.println("<body>"); pw.println("<span class=\"title\">" + overviewListTitle + "</span><br>"); // pw.println("<span class=\"title2\">" + coverage.getData(ColumnName.PRODUCT) // + "</span>"); pw.println("<br>"); pw.println("<table>"); pw.println("<tr>"); pw.println("<td nowrap=\"nowrap\">"); pw.println("<a href=\"overview-summary.html\" target=\"classFrame\">Overview</a><br>"); pw.println("<a href=\"allclasses-frame.html\" target=\"packageFrame\">All classes</a>"); pw.println("</td>"); pw.println("</tr>"); pw.println("</table>"); if (modules != null) { pw.println("<table>"); pw.println("<tr>"); pw.println("<td nowrap=\"nowrap\"><span class=\"title2\">All modules</span></td>"); pw.println("</tr>"); pw.println("<tr>"); pw.println("<td nowrap=\"nowrap\">"); List<String> modulesList = new ArrayList<String>(modules.keySet()); Collections.sort(modulesList); for (String module : modulesList){ pw.println("<a href=\"" + module + "/module-summary.html"+ "\" target=\"classFrame\"" + " onClick=\"parent.frames[1].location.href='" + "allclasses-frame.html" + "';\">" + module+ "</a><br>"); } pw.println("</tr>"); pw.println("</table>"); } pw.println("<table>"); pw.println("<tr>"); pw.println("<td nowrap=\"nowrap\"><span class=\"title2\">All packages</span></td>"); pw.println("</tr>"); pw.println("<tr>"); pw.println("<td nowrap=\"nowrap\">"); List<PackageCoverage> list = coverage.getPackages(); for (PackageCoverage pkg : list) { String pkgPath = pkg.getName().replace('.', '/'); String url = pkgPath + "/package-frame.html"; logger.log(Level.FINE, "generatePackageList:url:{0}", url); String pkgCovData = ""; if (showOverviewColorBars) { pkgCovData = generatePercentResult(pkg.getCoverageString(DataType.METHOD, coverage.isAncFiltersSet()), true); } pw.println("<a href=\"" + url + "\" target=\"packageFrame\"" + " onClick=\"parent.frames[2].location.href='" + pkgPath + "/package-summary.html" + "';\">" + pkgCovData + pkg.getName()+ "</a><br>"); } pw.println("</td>"); pw.println("</tr>"); pw.println("</table>"); pw.println("</body>"); pw.println("</html>"); pw.close(); for (PackageCoverage pkg : list) { generateClassList(dir, pkg); generateOverview(dir, pkg, null); } } private void generateClassList(File dir) throws IOException { generateClassList(dir, null); } private void generateClassList(File dir, PackageCoverage pkg) throws IOException { String filename; String rootRef; Collection<ClassCoverage> classes; String urlDirectory = ""; if (pkg == null) { rootRef = ""; filename = "allclasses-frame.html"; java.util.List<PackageCoverage> list = coverage.getPackages(); classes = new ArrayList<ClassCoverage>(); for (PackageCoverage pcov : list) { classes.addAll(pcov.getClasses()); } Collections.sort((List) classes); } else { rootRef = getRelativePath(pkg.getName()); filename = pkg.getName().replace('.', '/') + "/package-frame.html"; classes = pkg.getClasses(); urlDirectory = "."; } logger.log(Level.INFO, "generateClassList:filename:{0}", filename); File fsFile = new File(dir, filename); if (!fsFile.getParentFile().exists()) { logger.log(Level.INFO, "mkdirs:{0}", fsFile.getParentFile()); fsFile.getParentFile().mkdirs(); } PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream( fsFile), Charset.defaultCharset())); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>coverage report</title>"); pw.println("<link rel =\"stylesheet\" type=\"text/css\" href=\"" + rootRef + "style.css\" title=\"Style\">"); pw.println("</head>"); pw.println("<body>"); if (pkg != null) { pw.println("<p>"); pw.println("<a href=\"package-summary.html\" target=\"classFrame\">" + pkg.getName() + "</a> " + "<span class=\"text_italic\">&nbsp;" + pkg.getCoverageString(DataType.METHOD, coverage.isAncFiltersSet()) + "</span><br>"); pw.println("</p>"); } pw.println("<span class=\"title\">All classes</span>"); pw.println("<table>"); pw.println("<tr>"); pw.println("<td nowrap=\"nowrap\">"); int i = 0; for (ClassCoverage theClass : classes) { logger.log(Level.INFO, "{0} generateClassList:theClass:{1}", new Object[]{++i, theClass.getName()}); String prc = showFields ? theClass.getData(DataType.METHOD).add(theClass.getData(DataType.FIELD)).toString() : theClass.getCoverageString(DataType.METHOD, coverage.isAncFiltersSet()); if (pkg == null) { if (theClass.getFullClassName().lastIndexOf('.') > 0) { urlDirectory = theClass.getFullClassName().substring(0, theClass.getFullClassName().lastIndexOf('.')).replace('.', '/'); } else { urlDirectory = "."; } } String classCovBar = ""; if (showOverviewColorBars) { classCovBar = generatePercentResult(theClass.getCoverageString(DataType.METHOD, coverage.isAncFiltersSet()), true); } String classFilename = theClass.getName() + ".html"; pw.println("<a href=\"" + urlDirectory + "/" + classFilename + "\" target=\"classFrame\">" +classCovBar + theClass.getName() + "</a><span class=\"text_italic\">&nbsp;" + prc + "</span><br>"); } pw.println("</td>"); pw.println("</tr>"); pw.println("</table>"); pw.println("</body>"); pw.println("</html>"); pw.close(); } private void generateOverview(File dir, HashMap<String, ArrayList<ModuleCoverageData>> modules) throws IOException { generateOverview(dir, null, modules); } private void generateModuleOverview(File dir, List<PackageCoverage> allPkgList, HashMap<String, ArrayList<ModuleCoverageData>> module) throws IOException { String filename = "overview-summary.html"; String rootRef = "../"; String moduleName = module.keySet().iterator().next(); if (moduleName != null) { filename = moduleName + "/module-summary.html"; rootRef = "../"; } else { rootRef = ""; } File fsFile = new File(dir, filename); if (!fsFile.getParentFile().exists()) { logger.log(Level.INFO, "mkdirs:{0}", fsFile.getParentFile()); fsFile.getParentFile().mkdirs(); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream( fsFile), Charset.defaultCharset()))); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>coverage report</title>"); pw.println("<link rel =\"stylesheet\" type=\"text/css\" href=\"" + rootRef + "style.css\" title=\"Style\">"); pw.println("<script type=\"text/javascript\" src=\"" + rootRef + "sorttable.js\"></script>"); pw.println("</head>"); pw.println("<body>"); pw.println("<p>"); pw.println("<span class=\"title\"> <b>" + entitiesTitle + " " + /*coverage.getData(ColumnName.PRODUCT) + */ "</b> </span>"); pw.println("</p>"); if (module != null) { generateModulesInfo(pw, module, true/*,""*/); } //pw.println("</tr>"); pw.println("</table>"); pw.println("<p>"); List<PackageCoverage> modulesPkgList = new ArrayList<PackageCoverage>(); for (PackageCoverage pc : allPkgList){ if (pc.getClasses().get(0).getModuleName().equals(moduleName)){ modulesPkgList.add(pc); } } List<PackageCoverage> pkgList = modulesPkgList; List<ClassCoverage> classes = new ArrayList<ClassCoverage>(); for (PackageCoverage thePackage : pkgList) { classes.addAll(thePackage.getClasses()); } //PackageCoverage thePackage = pc; SubpackageCoverage subCov = new SubpackageCoverage(); // if (thePackage != null) { //pkgList = getSubPackages(thePackage); // if (pkgList.size() > 0) { //subCov.add(thePackage); pw.println("<span class=\"title2\">Packages</span><br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"subpackages\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">Name</th>"); pw.println("<th class=\"report_number\">#classes</th>"); pw.println("<th class=\"report\">%class</th>"); printColumnHeaders(pw, ""); //pw.println("<th class=\"report\">%total</th>"); pw.println("</tr>"); for (PackageCoverage pkg : pkgList) { subCov.add(pkg); pw.println("<tr class=\"report\">"); String subPkgDir = "../"+pkg.getName()/*.substring( thePackage.getName().length() + 1)*/.replace('.', '/'); pw .println("<td class=\"reportText\"><a href=\"" + subPkgDir + "/package-summary.html\">" + pkg.getName() + "</a></td>"); pw.println("<td class=\"reportValue\">" + pkg.getData(DataType.CLASS).getTotal() + "</td>"); pw.println("<td class=\"reportValue\">" + decorate(pkg.getCoverageString(DataType.CLASS, coverage.isAncFiltersSet())) + "</td>"); printColumnCoverages(pw, pkg, true, ""); /*pw.println("<td class=\"reportValue\">" + generatePercentResult(pkg.getTotalCoverageString()) + "</td>");*/ pw.println("</tr>"); } pw.println("</table>"); pw.println("<p>"); // } logger.log(Level.INFO, "generateOverview:classes.size:{0}", classes.size()); if (classes.size() > 0) { pw.println("<span class=\"title2\">Classes</span><br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"classes\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">Name</th>"); printColumnHeaders(pw, ""); // pw.println("<th class=\"report\">%total</th>"); pw.println("</tr>"); int i = 0; for (ClassCoverage cc : classes) { logger.log(Level.INFO, "{0} generateOverview():cl:{1}", new Object[]{++i, cc.getName()}); String classFilename = cc.getName(); pw.println("<tr class=\"report\">"); pw.println("<td class=\"reportText\"><a href=\"" +"../"+cc.getPackageName().replace('.', '/')+"/"+ classFilename + ".html\">" + classFilename + "</a></td>"); printColumnCoverages(pw, cc, true, ""); // pw.println("<td class=\"reportValue\">" // + generatePercentResult(cc.getTotalCoverageString()) + "</td>"); pw.println("</tr>"); } pw.println("</table>"); } //} pw.println(generateFooter()); pw.println("</body>"); pw.println("</html>"); pw.close(); } private void generateOverview(File dir, PackageCoverage thePackage, HashMap<String, ArrayList<ModuleCoverageData>> modules) throws IOException { String filename = "overview-summary.html"; String rootRef; if (thePackage != null) { filename = thePackage.getName().replace('.', '/') + "/package-summary.html"; rootRef = getRelativePath(thePackage.getName()); } else { rootRef = ""; } logger.log(Level.INFO, "generateOverview:filename:{0}", filename); File fsFile = new File(dir, filename); if (!fsFile.getParentFile().exists()) { logger.log(Level.INFO, "mkdirs:{0}", fsFile.getParentFile()); fsFile.getParentFile().mkdirs(); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream( fsFile), Charset.defaultCharset()))); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>coverage report</title>"); pw.println("<link rel =\"stylesheet\" type=\"text/css\" href=\"" + rootRef + "style.css\" title=\"Style\">"); pw.println("<script type=\"text/javascript\" src=\"" + rootRef + "sorttable.js\"></script>"); pw.println("</head>"); pw.println("<body>"); String otitle = thePackage == null ? mainReportTitle : entitiesTitle; pw.println("<span class=\"title\">" + otitle + " " + /*coverage.getData(ColumnName.PRODUCT) + */ "</span>"); pw.println("<br>"); pw.println("<br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">&nbsp;</th>"); pw.println("<th class=\"report_number\">#classes</th>"); printColumnHeaders(pw, ""); // pw.println("<th class=\"report\">%total</th>"); pw.println("</tr>"); pw.println("<tr class=\"report\">"); if (thePackage != null) { pw.println("<td class=\"reportText\"> <b>" + thePackage.getName() + "</b></td>"); pw.println("<td class=\"reportValue_number\">" + thePackage.getData(DataType.CLASS).getTotal() + "</td>"); printColumnCoverages(pw, thePackage, false, ""); // pw.println("<td class=\"reportValue\">" // + generatePercentResult(thePackage.getTotalCoverageString()) // + "</td>"); } else { pw.println("<td class=\"reportText\"> <b>" + "Overall statistics" + "</b> </td>"); pw.println("<td class=\"reportValue_number\">" + coverage.getData(DataType.CLASS).getTotal() + "</td>"); printColumnCoverages(pw, coverage, false, ""); // pw.println("<td class=\"reportValue\">" // + generatePercentResult(coverage.getTotalCoverageString()) + "</td>"); } pw.println("</tr>"); pw.println("</table>"); pw.println("<p>"); List<PackageCoverage> pkgList = null; SubpackageCoverage subCov = new SubpackageCoverage(); if (thePackage != null) { //generateModulesInfo(pw, modules, false, thePackage.getName()); pkgList = getSubPackages(thePackage); if (pkgList.size() > 0) { subCov.add(thePackage); pw.println("<span class=\"title2\">Subpackages</span><br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"subpackages\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">Name</th>"); pw.println("<th class=\"report_number\">#classes</th>"); pw.println("<th class=\"report\">%class</th>"); printColumnHeaders(pw, ""); //pw.println("<th class=\"report\">%total</th>"); pw.println("</tr>"); for (PackageCoverage pkg : pkgList) { subCov.add(pkg); pw.println("<tr class=\"report\">"); String subPkgDir = pkg.getName().substring( thePackage.getName().length() + 1).replace('.', '/'); pw .println("<td class=\"reportText\"><a href=\"" + subPkgDir + "/package-summary.html\">" + pkg.getName() + "</a></td>"); pw.println("<td class=\"reportValue_number\">" + pkg.getData(DataType.CLASS).getTotal() + "</td>"); pw.println("<td class=\"reportValue\">" + decorate(pkg.getCoverageString(DataType.CLASS, coverage.isAncFiltersSet())) + "</td>"); printColumnCoverages(pw, pkg, true, ""); /*pw.println("<td class=\"reportValue\">" + generatePercentResult(pkg.getTotalCoverageString()) + "</td>");*/ pw.println("</tr>"); } pw.println("</table>"); pw.println("<p>"); } List<ClassCoverage> classes = thePackage.getClasses(); logger.log(Level.INFO, "generateOverview:classes.size:{0}", classes.size()); if (classes.size() > 0) { pw.println("<span class=\"title2\">Classes</span><br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"classes\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">Name</th>"); printColumnHeaders(pw, ""); // pw.println("<th class=\"report\">%total</th>"); pw.println("</tr>"); int i = 0; for (ClassCoverage cc : classes) { logger.log(Level.INFO, "{0} generateOverview():cl:{1}", new Object[]{++i, cc.getName()}); String classFilename = cc.getName(); pw.println("<tr class=\"report\">"); pw.println("<td class=\"reportText\"><a href=\"" + classFilename + ".html\">" + classFilename + "</a></td>"); printColumnCoverages(pw, cc, true, ""); // pw.println("<td class=\"reportValue\">" // + generatePercentResult(cc.getTotalCoverageString()) + "</td>"); pw.println("</tr>"); } pw.println("</table>"); } } else { pkgList = coverage.getPackages(); if (pkgList.size() > 0) { if (modules != null) { generateModulesInfo(pw, modules, false); } pw.println("<span class=\"title2\">Packages</span><br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"packages\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">Name</th>"); pw.println("<th class=\"report_number\">#classes</th>"); printColumnHeaders(pw, ""); // pw.println("<th class=\"report\">%total</th>"); pw.println("</tr>"); for (PackageCoverage pkg : pkgList) { pw.println("<tr class=\"report\">"); pw .println("<td class=\"reportText\"><a href=\"" + pkg.getName().replace('.', '/') + "/package-summary.html\">" + pkg.getName() + "</a></td>"); pw.println("<td class=\"reportValue_number\">" + pkg.getData(DataType.CLASS).getTotal() + "</td>"); printColumnCoverages(pw, pkg, true, ""); // pw.println("<td class=\"reportValue\">" // + generatePercentResult(pkg.getTotalCoverageString()) + "</td>"); pw.println("</tr>"); } pw.println("</table>"); } } if (thePackage != null && pkgList != null && pkgList.size() > 0) { // sub packages summary pw.println("<p>"); pw.println("<span class=\"title2\">Total (including subpackages)</span><br>"); pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"total_w_subpackages\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">-</th>"); pw.println("<th class=\"report_number\">#classes</th>"); //pw.println("<th class=\"report\">%total</th>"); printColumnHeaders(pw, ""); pw.println("</tr>"); pw.println("<tr class=\"report\">"); pw.println("<td class=\"reportValue\"></td>"); pw.println("<td class=\"reportValue_number\">" + subCov.getData(DataType.CLASS).getTotal() + "</td>"); //pw.println("<td class=\"reportValue\">" // + decorate(subCov.getClassCoverageString()) + "</td>"); printColumnCoverages(pw, subCov, true, ""); pw.println("</table>"); pw.println("<br>"); } pw.println(generateFooter()); pw.println("</body>"); pw.println("</html>"); pw.close(); } private void generateModulesInfo(PrintWriter pw, HashMap<String, ArrayList<ModuleCoverageData>> modules, boolean decorate){ if (modules.keySet().size() > 1) { pw.println("<span class=\"title2\">Modules</span><br>"); } else{ pw.println("<span class=\"title2\">Module</span><br>"); } pw.println("<table class=\"report\" cellpadding=\"0\" cellspacing=\"0\" id=\"modules\">"); pw.println("<tr class=\"report\">"); pw.println("<th class=\"report\">Name</th>"); pw.println("<th class=\"report_number\">#classes</th>"); printColumnHeaders(pw, ""); pw.println("</tr>"); List<String> modulesList = new ArrayList<String>(modules.keySet()); Collections.sort(modulesList); for (String module : modulesList) { pw.println("<tr class=\"report\">"); if (!decorate) { pw.println("<td class=\"reportText\"><a href=\"" + module + "/module-summary.html\">" + module + "</a></td>"); } else{ pw.println("<td class=\"reportText\"> <b>" + module + " </b> </a></td>"); } int moduleDataColumnsSize = modules.get(module).size(); ModuleCoverageData totalModuleCD = modules.get(module).get(moduleDataColumnsSize-1); pw.println("<td class=\"reportValue_number\">" + totalModuleCD.getData()[columns.classes.number].getTotal() + "</td>"); for (int i = 1; i< totalModuleCD.getData().length; i++) { if (show(columns.valueOf(i))) { if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int test = 0; test < testService.getTestCount(); test++) { if (show(columns.valueOf(i)) && i != columns.line.number) { CoverageData cd = modules.get(module).get(test).getData()[i]; pw.println("<td class=\"reportValue\">" + decorate(cd.getFormattedCoverage(coverage.isAncFiltersSet())) + "</td>"); } } } CoverageData cd = totalModuleCD.getData()[i]; if (!decorate) { pw.println("<td class=\"reportValue\">" + decorate(cd.getFormattedCoverage(coverage.isAncFiltersSet())) + "</td>"); } else { pw.println("<td class=\"reportValue\">" + generatePercentResult(cd.getFormattedCoverage(coverage.isAncFiltersSet())) + "</td>"); } } } pw.println("</tr>"); } pw.println("</table>"); pw.println("<p>"); } private class ModuleCoverageData { private CoverageData[] collectedData; public ModuleCoverageData() { collectedData = new CoverageData[6]; } public ModuleCoverageData(PackageCoverage pkg) { collectedData = new CoverageData[]{ pkg.getData(DataType.FIELD), pkg.getData(DataType.METHOD), pkg.getData(DataType.BLOCK), pkg.getData(DataType.BRANCH), pkg.getData(DataType.LINE), pkg.getData(DataType.CLASS)}; } public ModuleCoverageData(PackageCoverage pkg, int testNumber) { collectedData = new CoverageData[]{ pkg.getData(DataType.FIELD, testNumber), pkg.getData(DataType.METHOD, testNumber), pkg.getData(DataType.BLOCK, testNumber), pkg.getData(DataType.BRANCH, testNumber), pkg.getData(DataType.LINE, testNumber), pkg.getData(DataType.CLASS, testNumber)}; } public void addPackage(PackageCoverage pkg, int testNumber) { collectedData[columns.field.number].add(pkg.getData(DataType.FIELD, testNumber)); collectedData[columns.method.number].add(pkg.getData(DataType.METHOD, testNumber)); collectedData[columns.block.number].add(pkg.getData(DataType.BLOCK, testNumber)); collectedData[columns.branch.number].add(pkg.getData(DataType.BRANCH, testNumber)); collectedData[columns.line.number].add(pkg.getData(DataType.LINE, testNumber)); collectedData[columns.classes.number].add(pkg.getData(DataType.CLASS, testNumber)); } public void addPackage(PackageCoverage pkg) { collectedData[columns.field.number].add(pkg.getData(DataType.FIELD)); collectedData[columns.method.number].add(pkg.getData(DataType.METHOD)); collectedData[columns.block.number].add(pkg.getData(DataType.BLOCK)); collectedData[columns.branch.number].add(pkg.getData(DataType.BRANCH)); collectedData[columns.line.number].add(pkg.getData(DataType.LINE)); collectedData[columns.classes.number].add(pkg.getData(DataType.CLASS)); } public CoverageData[] getData(){ return collectedData; } } public enum columns { method(1), field(0), block(2), branch(3), line(4), classes(5); private int number; private static Map<Integer, columns> map = new HashMap<Integer, columns>(); static { for (columns column : columns.values()) { map.put(column.number, column); } } public static columns valueOf(int number) { return map.get(number); } private columns(final int number) { this.number = number; } } /** * Returns true if a column needs to be shown * * @param col * @return false, if the column should not appear in the report */ boolean show(columns col) { switch (col) { case method: return showMethods; case field: return showFields; case block: return showBlocks; case branch: return showBranches; case line: return showLines; } return false; // should never occur } /** * Returns true if a column needs to be shown * * @param col * @return false, if the column should not appear in the report */ String getColumnData(columns col, AbstractCoverage cc) { switch (col) { case method: return cc.getCoverageString(DataType.METHOD, coverage.isAncFiltersSet()); case field: return cc.getCoverageString(DataType.FIELD, coverage.isAncFiltersSet()); case block: return cc.getCoverageString(DataType.BLOCK, coverage.isAncFiltersSet()); case branch: return cc.getCoverageString(DataType.BRANCH, coverage.isAncFiltersSet()); case line: return cc.getCoverageString(DataType.LINE, coverage.isAncFiltersSet()); } return ""; } String getFormattedColumnData(columns col, AbstractCoverage cc, int testNumber) { switch (col) { case method: return cc.getData(DataType.METHOD, testNumber).getFormattedCoverage(coverage.isAncFiltersSet()); case field: return cc.getData(DataType.FIELD, testNumber).getFormattedCoverage(coverage.isAncFiltersSet()); case block: return cc.getData(DataType.BLOCK, testNumber).getFormattedCoverage(coverage.isAncFiltersSet()); case branch: return cc.getData(DataType.BRANCH, testNumber).getFormattedCoverage(coverage.isAncFiltersSet()); case line: return ""; } return ""; } void printColumnHeaders(PrintWriter pw, String pad) { for (columns col : columns.values()) { if (show(col)) { if (col != columns.line && testService != null && (isAddTestsInfo || isMergeRepGenMode)) { int testNumber = 0; Iterator<Test> iterator = testService.iterator(); while (iterator.hasNext()) { Test test = iterator.next(); testNumber++; pw.println("<th class=\"report\" title=\"" + test.getTestName() + "\">" + "#" + testNumber + "</th>"); } } pw.println(pad + "<th class=\"report\">%" + col + "</th>"); } } } /** * * @param pw print writer * @param cov - class or package coverage * @param decorate - if true, <i>decorate()</i> method will be used, * <i>generatePercentResult()</i> - otherwise */ void printColumnCoverages(PrintWriter pw, AbstractCoverage cov, boolean decorate, String pad) { for (columns col : columns.values()) { if (show(col)) { String testsData = ""; if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int test = 0; test < testService.getTestCount(); test++) { String columnData = getFormattedColumnData(col, cov, test); if (mode != null && mode.equals(InstrumentationOptions.InstrumentationMode.METHOD) && col != columns.method && !columnData.isEmpty()) { columnData = "-"; } if (!columnData.isEmpty()) { if (!columnData.trim().equals("-")) { testsData += "<td class=\"reportValue\">" + columnData + "</td>"; } else { testsData += "<td class=\"reportValue\"><span style=\"text-align: center;\">" + columnData + "</span></td>"; } } } } String data = getColumnData(col, cov); if (mode != null && mode.equals(InstrumentationOptions.InstrumentationMode.METHOD) && col != columns.method) { data = "-"; } String dataToShow = decorate ? decorate(data) : generatePercentResult(data); pw.println(pad + testsData + "<td class=\"reportValue\">" + dataToShow + "</td>"); } } } // temporarily workaround for CR 6523425 private List<PackageCoverage> getSubPackages(PackageCoverage thePackage) { ArrayList<PackageCoverage> list = new ArrayList<PackageCoverage>(); String name = thePackage.getName(); for (PackageCoverage pn : coverage) { String pname = pn.getName(); int idx = pname.indexOf(name); if (idx != -1 && !name.equals(pname) && pname.replaceAll(name, "").startsWith(".")) { list.add(pn); } } return list; } private void generateSourceFiles(File dir) throws IOException { logger.info("generating source files..."); List<PackageCoverage> pkglist = coverage.getPackages(); int i = 0; for (PackageCoverage pkgcov : pkglist) { logger.log(Level.FINE, "package:{0}", pkgcov.getName()); List<ClassCoverage> clslist = pkgcov.getClasses(); for (ClassCoverage clscov : clslist) { ++i; if (clscov == null) { logger.log(Level.SEVERE, "{0}clscov is NULL!", i); continue; } logger.log(Level.INFO, "{0} {1}", new Object[]{i, clscov.getName()}); generateSourceFile(dir, clscov); } } } private void generateSourceFile(File directory, ClassCoverage theClass) throws IOException { String srcOutputFilename = theClass.getFullClassName().replace('.', '/') + ".html"; File srcOutputFile = new File(directory, srcOutputFilename); logger.log(Level.FINE, "srcOutputFile:{0}", srcOutputFile.getAbsolutePath()); File dirOutputFile = srcOutputFile.getParentFile(); if (dirOutputFile != null && !dirOutputFile.exists()) { logger.log(Level.INFO, "mkdirs:{0}", dirOutputFile); dirOutputFile.mkdirs(); } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream( srcOutputFile), Charset.defaultCharset()))); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>tests coverage</title>"); String rootRef = getRelativePath(theClass.getPackageName()); pw.println("<link rel =\"stylesheet\" type=\"text/css\" href=\"" + rootRef + "style.css\" title=\"Style\">"); pw.println("<script type=\"text/javascript\" src=\"" + rootRef + "sorttable.js\"></script>"); generateScriptsHeader(pw); pw.println("</head>"); pw.println("<body>"); if (!theClass.getPackageName().isEmpty()) { generateNavHeader(pw, theClass.getName() + ".html", "" + theClass.getPackageName().replaceAll("[a-zA-Z0-9]+", "..") + "/index.html?" + srcOutputFilename); } else{ generateNavHeader(pw, theClass.getName() + ".html", "" + theClass.getName()+"/../index.html?" + srcOutputFilename); } //pw.println("<span class=\"title\">" + title + " " // + coverage.getData(ColumnName.PRODUCT) + "</span>"); if (isGenHitTests) { pw.println("<p>"); pw.println("<a href=\"#hittests\">Hit Tests</a>"); } pw.println("<br>"); pw.println(" <table cellspacing=\"0\" cellpadding=\"0\"class=\"report\">"); pw.println(" <tr class=\"report\">"); pw.println(" <th class=\"report\">&nbsp;</th>"); printColumnHeaders(pw, " "); // pw.println(" <th class=\"report\">%total</th>"); pw.println(" </tr>"); pw.println(" <tr class=\"report\">"); pw.println(" <td class=\"reportText\"><span class=\"text\"> <b>" + theClass.getFullClassName() + "</b></span></td>"); printColumnCoverages(pw, theClass, false, " "); // pw.println(" <td class=\"reportValue\">" // + generatePercentResult(theClass.getTotalCoverageString()) + "</td>"); pw.println(" </tr>"); pw.println(" </table>"); pw.println(" <br>"); String src = theClass.getSource(); boolean isGenerate; File srcfile = null; // can be null if (src == null || theClass.isJavapSource()) { isGenerate = false; } else { srcfile = new File(src); isGenerate = srcfile.exists(); } int mcount = theClass.getData(DataType.METHOD).getCovered(); if (mcount == 0 && !isGenSrc4Zero) { isGenerate = false; } HashMap<Integer, MemberCoverage> methodsForLine = new HashMap<Integer, MemberCoverage>(); HashMap<Integer, List<ItemCoverage>> itemsForLine = new HashMap<Integer, List<ItemCoverage>>(); List<MethodCoverage> methodList = theClass.getMethods(); //Collections.sort((List) methodList); for (MethodCoverage mcov : methodList) { methodsForLine.put(Integer.valueOf(mcov.getStartLine()), mcov); for (ItemCoverage icov : mcov.getItems()) { int srcLine = icov.getSourceLine(); if (srcLine > 0) { List<ItemCoverage> listIcov = itemsForLine.get(srcLine); if (listIcov == null) { listIcov = new LinkedList<ItemCoverage>(); itemsForLine.put(srcLine, listIcov); } listIcov.add(icov); } } } generateMemberTable(pw, theClass, "method", methodList, isGenerate, theClass.isJavapSource()); List<FieldCoverage> fieldList = theClass.getFields(); //Collections.sort((List) fieldList); if (showFields) { for (FieldCoverage fcov : fieldList) { int startLine = fcov.getStartLine(); methodsForLine.put(new Integer(startLine), fcov); logger.log(Level.FINE, "{0}-{1}", new Object[]{fcov.getName(), startLine}); } generateMemberTable(pw, theClass, "field", fieldList, isGenerate, theClass.isJavapSource()); } if (isGenerate) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(srcfile), Charset.defaultCharset())); String lineStr; int numLine = 1; pw.println(" <table cellspacing=\"0\" cellpadding=\"0\" class=\"src\">"); while ((lineStr = br.readLine()) != null) { generateSourceLine(pw, lineStr, numLine, theClass, methodsForLine, itemsForLine, null); numLine++; } br.close(); pw.println(" </table>"); } if (theClass.isJavapSource()) { pw.println(" <table cellspacing=\"0\" cellpadding=\"0\" class=\"src\">"); JavapClass javapClass = theClass.getJavapClass(); if (javapClass != null) { String lineStr; int numLine = 1; methodsForLine = new HashMap<Integer, MemberCoverage>(); for (MethodCoverage mcov : methodList) { List<JavapLine> lines = javapClass.getMethod(mcov.getName() + mcov.getSignature()); if (lines != null) { methodsForLine.put(lines.get(0).getLineNumber(), mcov); } } for (JavapLine line : javapClass.getLines()) { lineStr = line.getTextLine(); generateSourceLine(pw, lineStr, numLine, theClass, methodsForLine, itemsForLine, line); numLine++; } } pw.println(" </table>"); } pw.println("<p>"); if (isGenHitTests) { pw.println(generateHitTests(theClass)); } pw.println(generateFooter()); pw.println("</body>"); pw.println("</html>"); pw.close(); } private void generateSourceLine(PrintWriter pw, String lineStr, int numLine, ClassCoverage theClass, HashMap<Integer, MemberCoverage> methodsForLine, HashMap<Integer, List<ItemCoverage>> itemsForLine, JavapLine javapLine) { pw.println(" <tr>"); if (javapLine == null) { MemberCoverage mcov = methodsForLine.get(numLine); List<ItemCoverage> items = itemsForLine.get(numLine); String lineCov = null; String ancInfo = ""; if (!theClass.isCode(numLine)) { lineCov = "numLine"; } else { String unCover = theClass.isLineInAnc(numLine) ? "numLineAnc" : "numLineUnCover"; lineCov = theClass.isLineCovered(numLine) ? "numLineCover" : unCover; if (theClass.isLineInAnc(numLine) && !theClass.isLineCovered(numLine)) { if (theClass.getAncInfo() != null){ ancInfo = "title = \"" + theClass.getAncInfo() + "\" "; } else if (mcov instanceof MethodCoverage && ((MethodCoverage) mcov).getAncInfo() != null){ ancInfo = "title = \"" + ((MethodCoverage) mcov).getAncInfo() + "\" "; } else { if (items == null) { int upLine = numLine; List<ItemCoverage> upItems; while ((upItems = itemsForLine.get(upLine)) == null) { upLine--; } for (ItemCoverage i : upItems) { if (i.isInAnc()) { ancInfo = "title = \"" + i.getAncInfo() + "\" "; break; } } } } } } String link = ""; if (mcov != null) { link = "<a name=\"src_" + numLine + "\"></a>"; } if (items != null) { int allcovered = 0; int allanc = 0; Map<DataType, Integer> covered = new HashMap(); Map<DataType, Integer> total = new HashMap(); for (DataType kind : ItemCoverage.getAllPossibleTypes()) { covered.put(kind, 0); total.put(kind, 0); } for (ItemCoverage icov : items) { DataType kind = icov.getDataType(); total.put(kind, total.get(kind) + 1); if (icov.getCount() != 0) { covered.put(kind, covered.get(kind) + 1); allcovered++; } if (icov.isInAnc()){ allanc++; } } String shortInfo = ""; for (DataType kind : ItemCoverage.getAllPossibleTypes()) { if (total.get(kind) != 0) { shortInfo += kind.getTitle() + ":&nbsp;" + covered.get(kind) + "/" + total.get(kind) + "&nbsp;"; } } boolean isGreen = items.size() == allcovered; String nbHitsCov = isGreen ? "nbHitsCovered" : items.size() == allanc ? "nbHitsAnc" : "nbHitsUncovered"; ancInfo = ""; if (!theClass.isLineCovered(numLine)){ if (items.size() == allanc) { lineCov = "numLineAnc"; if (theClass.getAncInfo() != null){ ancInfo = "title = \"" + theClass.getAncInfo() + "\" "; } else if (mcov instanceof MethodCoverage && ((MethodCoverage) mcov).getAncInfo() != null){ ancInfo = "title = \"" + ((MethodCoverage) mcov).getAncInfo() + "\" "; } else{ ancInfo = "title = \"" + items.get(0).getAncInfo() + "\" "; } } } else{ ancInfo = ""; for (ItemCoverage i : items) { if (!i.isCovered()) { if (theClass.getAncInfo() != null){ ancInfo = "title = \"" + theClass.getAncInfo() + "\" "; break; } else if (mcov instanceof MethodCoverage && ((MethodCoverage) mcov).getAncInfo() != null){ ancInfo = "title = \"" + ((MethodCoverage) mcov).getAncInfo() + "\" "; break; } else if (i.isInAnc() && i.getAncInfo() != null){ ancInfo = "title = \"" + i.getAncInfo() + "\" "; break; } } } } pw.println(" <td "+ancInfo+"class=\"" + lineCov + "\">&nbsp;" + numLine + link + "</td>"); if (isMergeRepGenMode) { StringBuilder totalInfo = new StringBuilder(); if (total.get(DataType.BLOCK) == null || total.get(DataType.BLOCK) == 0) { totalInfo.append("-:"); } else { totalInfo.append(total.get(DataType.BLOCK)).append(":"); } if (total.get(DataType.BRANCH) == null || total.get(DataType.BRANCH) == 0) { totalInfo.append("-"); } else { totalInfo.append(total.get(DataType.BRANCH)); } pw.println(" <td class=\"nbHits\" title=\"#blocks:#branches\" >&nbsp;" + totalInfo + " </td>"); } else { pw.println(" <td class=\"" + nbHitsCov + "\">&nbsp;" + shortInfo + "</td>"); } if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { int testNumber = 0; Iterator<Test> iterator = testService.iterator(); while (iterator.hasNext()) { Test test = iterator.next(); String testCovered = theClass.isLineInAnc(numLine) ? "numLineAnc" : "numLineUnCover"; int block = 0; int branch = 0; boolean blocks = false; boolean branches = false; for (ItemCoverage item : itemsForLine.get(numLine)) { if (item.isInAnc()){ testCovered = "numLineAnc"; } if (!blocks && item.isBlock()) { blocks = true; } if (!branches && !item.isBlock()) { branches = true; } if (item.isCoveredByTest(testNumber)) { testCovered = "numLineCover"; if (item.isBlock()) { block++; } else { branch++; } } } testNumber++; StringBuilder testInfo = new StringBuilder(); if (!blocks) { testInfo.append("-:"); } else { testInfo.append(block).append(":"); } if (!branches) { testInfo.append("-"); } else { testInfo.append(branch); } pw.println(" <td " + "title=\"" + test.getTestName() + " (Block:Branch)\" class=\"" + testCovered + "\">&nbsp;" + testInfo + "</td>"); } } pw.println(" <td class=\"src\"><pre class=\"src\">&nbsp;" + JavaToHtml.syntaxHighlight(lineStr) + "</pre></td>"); // just string without any items } else { pw.println(" <td "+ancInfo+"class=\"" + lineCov + "\">&nbsp;" + numLine + link + "</td>"); pw.println(" <td class=\"nbHits\">&nbsp;</td>"); if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int k = 0; k < testService.getTestCount(); k++) { if (theClass.isCode(numLine)) { String testCovered = theClass.isLineInAnc(numLine) ? "numLineAnc" : "numLineUnCover"; ancInfo = ""; if (theClass.isLineCovered(numLine)) { for (int i = numLine; i >= 0; i--) { if (itemsForLine.get(i) != null) { for (ItemCoverage item : itemsForLine.get(i)) { if (item.isCoveredByTest(k)) { testCovered = "numLineCover"; } else{ if (item.isInAnc()){ testCovered = "numLineAnc"; ancInfo = "title = \""+item.getAncInfo()+"\" "; } } } break; } } } pw.println(" <td " + ancInfo + "class=\"" + testCovered + "\">&nbsp;</td>"); } else { pw.println(" <td class=\"nbHits\">&nbsp;</td>"); } } } pw.println(" <td class=\"src\"><pre class=\"src\">&nbsp;" + JavaToHtml.syntaxHighlight(lineStr) + "</pre></td>"); } } else { //two lines are from the method string to first javap output (1 - method name and sig, 2 - "Code:") MemberCoverage mcov = methodsForLine.get(javapLine.getLineNumber() + 2); String link = ""; if (mcov != null) { if (mcov.getName().equals("<clinit>")) { link = "<a name=\"src_" + mcov.getStartLine() + "cl" + "\"></a>"; } else { link = "<a name=\"src_" + mcov.getStartLine() + "\"></a>"; } } if (javapLine instanceof JavapCodeLine) { boolean isGreen = ((JavapCodeLine) javapLine).isVisited(); String unCover = theClass.isLineInAnc(numLine) ? "nbHitsAnc" : "nbHitsUncovered"; String nbHitsCov = isGreen ? "nbHitsCovered" : unCover; String htmlStr = javapLine.getTextLine(). replaceAll("\\<", "&#60;"). replaceAll("\\>", "&#62;"). replaceAll("\\s++$", ""); pw.println(" <td>" + numLine + link + "</td>"); pw.println(" <td class=\"" + nbHitsCov + "\">&nbsp;" + " " + "</td>"); pw.println(" <td class=\"src\"><pre class=\"src\">&nbsp;" + htmlStr + "</pre></td>"); } else { pw.println(" <td>" + numLine + link + "</td>"); pw.println(" <td class=\"nbHits\">&nbsp;</td>"); pw.println(" <td class=\"src\"><pre class=\"src\">&nbsp;" + JavaToHtml.syntaxHighlight(lineStr) + "</pre></td>"); } } pw.println(" </tr>"); } private void generateMemberTable(PrintWriter pw, ClassCoverage theClass, String fieldOrMethod, List<? extends MemberCoverage> list, boolean isGenerate, boolean javapReport) { pw.println(" <br>"); pw.println(" <table cellspacing=\"0\" cellpadding=\"0\"class=\"report\" id=\"mcoverage\">"); pw.println(" <tr class=\"report\">"); pw.println(" <th class=\"report\">hit count</th>"); if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int i = 0; i < testService.getTestCount(); i++) { pw.println(" <th class=\"report\"> #" + (i + 1) + "</th>"); } } pw.println(" <th class=\"report\">" + fieldOrMethod + " name</th>"); pw.println(" <th class=\"report\">" + fieldOrMethod + " modifiers</th>"); pw.println(" <th class=\"report\">" + fieldOrMethod + " signature</th>"); pw.println(" </tr>"); for (MemberCoverage mcov : list) { if (!isAnonymOn && mcov instanceof MethodCoverage) { if (((MethodCoverage) mcov).isInAnonymClass()) { continue; } } if (mcov instanceof MethodCoverage && ((MethodCoverage) mcov).isLambdaMethod()){ continue; } pw.println(" <tr class=\"report\">"); long c = mcov.getHitCount(); if (c > 0) { pw.println(" <td class=\"reportValue_covered\"><span class=\"text\">" + c + "</span></td>"); } else { if (mcov.getData(mcov.getDataType()).getAnc() > 0){ String tooltip = ""; if (mcov instanceof MethodCoverage){ String info = theClass.getAncInfo(); if (info == null){ info = ((MethodCoverage)mcov).getAncInfo() != null ? ((MethodCoverage)mcov).getAncInfo() : ((MethodCoverage)mcov).getItems().get(0).getAncInfo(); } tooltip = "title=\"" + info + "\" "; } pw.println(" <td class=\"reportValue_anc\""+tooltip+"><span class=\"text\">" + c + "</span></td>"); } else { pw.println(" <td class=\"reportValue_uncovered\"><span class=\"text\">" + c + "</span></td>"); } } if (testService != null && (isAddTestsInfo || isMergeRepGenMode)) { for (int i = 0; i < testService.getTestCount(); i++) { if (mcov.getCoveringTests().contains(i)) { pw.println(" <td class=\"numLineCover\"><span style=\"text-align: center;\">" + "+" + "</span></td>"); } else { if (mcov.getData(mcov.getDataType()).getAnc() > 0){ String tooltip = ""; if (mcov instanceof MethodCoverage){ String info = theClass.getAncInfo(); if (info == null){ info = ((MethodCoverage)mcov).getAncInfo() != null ? ((MethodCoverage)mcov).getAncInfo() : ((MethodCoverage)mcov).getItems().get(0).getAncInfo(); } tooltip = "title=\"" + info + "\" "; } pw.println(" <td class=\"numLineAnc\" "+tooltip+"><span style=\"text-align: center;\">" + "-" + "</span></td>"); } else { pw.println(" <td class=\"numLineUnCover\"><span style=\"text-align: center;\">" + "-" + "</span></td>"); } } } } String mname = mcov.getName().replaceAll("<", "&lt;").replaceAll( ">", "&gt;"); if (isGenerate || javapReport) { //fda pw.println(" <td class=\"reportText\"><span class=\"text\"><a href=\"#" //fda + mcov.getSignature() + "\">" + mname + "</a></span></td>"); if (javapReport && mcov.getName().equals("<clinit>")) { pw.println(" <td class=\"reportText\"><span class=\"text\"><a href=\"#src_" + mcov.getStartLine() + "cl" + "\">" + mname + "</a></span></td>"); } else { pw.println(" <td class=\"reportText\"><span class=\"text\"><a href=\"#src_" + mcov.getStartLine() + "\">" + mname + "</a></span></td>"); } } else { pw.println(" <td class=\"reportText\"><span class=\"text\">" + mname + "</span></td>"); } String mmodifiers = mcov.getModifiersString(); pw.println(" <td class=\"reportText\"><span class=\"text\">" + mmodifiers + "</span></td>"); pw.println(" <td class=\"reportText\"><span class=\"text\">" + mcov.getReadableSignature().replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</span></td>"); pw.println(" </tr>"); } pw.println(" </table>"); pw.println(" <br>"); } private static String constructShortDescr(List<ItemCoverage> items) { String str = ""; return str; } // to compare two reports it's much more convenient to not include // date of generation private static final String REPORT_DATE = System.getProperty("test.mode") == null ? DateFormat.getInstance().format(new Date()) : "date"; private void generateScriptsHeader(PrintWriter pw) { pw.println("<script type=\"text/javascript\">"); pw.println(" targetPage = \"\" + window.location.search;"); pw.println(" if (targetPage != \"\" && targetPage != \"undefined\")"); pw.println(" targetPage = targetPage.substring(1);"); pw.println(" if (targetPage.indexOf(\":\") != -1 || (targetPage != \"\" && !validURL(targetPage)))"); pw.println(" targetPage = \"undefined\";"); pw.println(" function validURL(url) {"); pw.println(" var pos = url.indexOf(\".html\");"); pw.println(" if (pos == -1 || pos != url.length - 5)"); pw.println(" return false;"); pw.println(" var allowNumber = false;"); pw.println(" var allowSep = false;"); pw.println(" var seenDot = false;"); pw.println(" for (var i = 0; i < url.length - 5; i++) {"); pw.println(" var ch = url.charAt(i);"); pw.println(" if ('a' <= ch && ch <= 'z' ||"); pw.println(" 'A' <= ch && ch <= 'Z' ||"); pw.println(" ch == '$' ||"); pw.println(" ch == '_') {"); pw.println(" allowNumber = true;"); pw.println(" allowSep = true;"); pw.println(" } else if ('0' <= ch && ch <= '9' ||"); pw.println(" ch == '-') {"); pw.println(" if (!allowNumber)"); pw.println(" return false;"); pw.println(" } else if (ch == '/' || ch == '.') {"); pw.println(" if (!allowSep)"); pw.println(" return false;"); pw.println(" allowNumber = false;"); pw.println(" allowSep = false;"); pw.println(" if (ch == '.')"); pw.println(" seenDot = true;"); pw.println(" if (ch == '/' && seenDot)"); pw.println(" return false;"); pw.println(" } else {"); pw.println(" return false;"); pw.println(" }"); pw.println(" }"); pw.println(" return true;"); pw.println(" }"); pw.println(" function loadFrames() {"); pw.println(" if (targetPage != \"\" && targetPage != \"undefined\")"); pw.println(" top.classFrame.location = top.targetPage;"); pw.println(" }"); pw.println("</script>"); } private void generateNavHeader(PrintWriter pw, String noframesPath, String index_classPath) { pw.println("<table>"); pw.println("<tr>"); pw.println("<td>"); pw.println("<a href=\"" + index_classPath + "\" target=\"_top\">Frames</a>"); pw.println("<a href=\"" + noframesPath + "\" target=\"_top\">No Frames</a>"); pw.println("</td>"); pw.println("</tr>"); pw.println("</table>"); } private String generateFooter() { StringBuilder sb = new StringBuilder(); sb.append("<br>"); sb.append("<table cellpadding=\"0\" cellspacing=\"0\" class=\"report\">"); sb.append(" <tr class=\"report\">"); sb.append(" <td class=\"reportText\"><span class=\"text\">"); sb.append(" Report generated ").append(REPORT_DATE); sb.append(" </span></td>"); sb.append(" </tr>"); sb.append("</table>"); return sb.toString(); } private String generateHitTests(ClassCoverage n) { StringBuilder sb = new StringBuilder(); if (n != null) { try { sb .append("<a name=\"hittests\"><span class=\"title\">Hit tests</span></a>"); sb .append("<table cellpadding=\"0\" cellspacing=\"0\" class=\"report\">"); sb.append(" <tr class=\"report\">"); sb.append(" <th class=\"report\">#</th>"); // sb.append(" <th class=\"report\">owner</th>"); sb.append(" <th class=\"report\">Test name</th>"); sb.append(" </tr>"); List<Test> hitlist = testService != null ? testService.getHitTestByClasses(n) : new ArrayList<Test>(); if (isAddTestsInfo || isMergeRepGenMode){ hitlist = testService.getAllTests(); } int i = 1; for (Test httest : hitlist) { String owner = httest.getTestOwner(); String tname = httest.getTestName(); sb.append(" <tr class=\"report\">"); sb.append(" <td class=\"reportValue\">").append(i++).append("</td>"); // sb.append(" <td class=\"reportText\">" + owner + "</td>"); StringBuilder append = sb.append(" <td class=\"reportText\">").append(tname).append("</td>"); sb.append(" </tr>"); } sb.append("</table>"); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); } private String generatePercentResult(String percentValue) { return generatePercentResult(percentValue, false); } private String generatePercentResult(String percentValue, boolean onlyColorBar) { String value = percentValue; String cov_total = ""; double anc = 0; int idx = value.indexOf("%"); if (idx != -1) { value = value.substring(0, idx); cov_total = percentValue.substring(idx + 1); String[] ancs = percentValue.split("/"); if (ancs.length == 3){ try { anc = Double.parseDouble(ancs[1])/Double.parseDouble(ancs[2].substring(0,ancs[2].indexOf(")")))*100; } catch (Exception e) { e.printStackTrace(); } } } double rest = 0; boolean badNumber = false; double dvalue = 0; try { dvalue = new Double(value.replace(',', '.')).doubleValue(); rest = 100d - (dvalue); } catch (NumberFormatException e) { badNumber = true; } StringBuilder sb = new StringBuilder(); if (onlyColorBar) { sb.append("<table cellpadding=\"0\" cellspacing=\"0\">"); } else{ sb.append("<table cellpadding=\"0\" cellspacing=\"0\" style=\"margin: 0 auto;\">"); sb.append("<tr>"); sb.append("<td><span class=\"text\"><b>").append(value.trim()).append("</b>%").append(cov_total.trim()).append("</span></td>"); } if (!badNumber) { if (onlyColorBar) { sb.append("<td>"); sb.append("<table class=\"percentGraph\" cellpadding=\"0\" cellspacing=\"0\" style=\"padding-right: 5px\">"); } else{ sb.append("<tr>"); sb.append("<td>"); sb.append("<table class=\"percentGraph\" cellpadding=\"0\" cellspacing=\"0\">"); } sb.append("<tr>"); if (anc > 0) { sb.append("<td class=\"percentCovered\" width=\"").append((int)(dvalue - anc)).append("\"></td>"); sb.append("<td class=\"percentAnc\" width=\"").append((int)anc).append("\"></td>"); if (dvalue < 100) { sb.append("<td class=\"percentUnCovered\" width=\"").append((int)rest).append("\"></td>"); } } else{ sb.append("<td class=\"percentCovered\" width=\"").append(value).append("\"></td>"); sb.append("<td class=\"percentUnCovered\" width=\"").append((int)rest).append("\"></td>"); } sb.append("</tr>"); sb.append("</table>"); sb.append("</td>"); } if (!onlyColorBar) { sb.append("</tr>"); } sb.append("</table>"); return sb.toString(); } private String getRelativePath(String path) { if (path != null && !path.equals("")) { // java.awt.event - ../../../ return path.replace('.', '/').replaceAll("\\w+", "..") + "/"; } else { return ""; } } private String decorate(String coverageString) { int idx = coverageString.indexOf("%"); if (idx != -1) { StringBuilder sb = new StringBuilder(); sb.append("<table class=\"report\">"); sb.append("<tr>"); sb.append("<td class=\"coverage_left\">"); sb.append("<span class=\"text_bold\">"); sb.append(coverageString.substring(0, idx+1).trim()); sb.append("</span>"); sb.append("</td>"); sb.append("<td class=\"coverage_right\"> "); sb.append("<span class=\"text\">"); sb.append(coverageString.substring(idx+1).trim()); sb.append("</span>"); sb.append("</td>"); sb.append("</tr>"); sb.append("</table>"); return sb.toString(); } return coverageString; } public void setShowMethods(boolean showMethods) { this.showMethods = showMethods; } public void setShowBlocks(boolean showBlocks) { this.showBlocks = showBlocks; } public void setShowBranches(boolean showBranches) { this.showBranches = showBranches; } public void setShowFields(boolean showFields) { this.showFields = showFields; } public void setShowLines(boolean showLines) { this.showLines = showLines; } public void setShowOverviewColorBars(boolean showOverviewColorBars){ this.showOverviewColorBars = showOverviewColorBars; } }
81,183
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JavaToHtml.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/html/JavaToHtml.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.html; /** * CodeViewer.java * * Bill Lynch & Matt Tucker CoolServlets.com, October 1999 * * Please visit CoolServlets.com for high quality, open source Java servlets. * * Copyright (C) 1999 CoolServlets.com * * Any errors or suggested improvements to this class can be reported as * instructed on Coolservlets.com. We hope you enjoy this program... your * comments will encourage further development! * * This software is distributed under the terms of The BSD License. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 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. Neither name of CoolServlets.com nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY COOLSERVLETS.COM 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 COOLSERVLETS.COM 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. */ import java.util.HashMap; /** * * @since 1.0 */ public class JavaToHtml { private static HashMap reservedWords = new HashMap(); private static boolean inMultiLineComment = false; private static String commentStart = "<span Class=\"comment\">"; private static String commentEnd = "</span>"; private static String stringStart = "<span Class=\"string\">"; private static String stringEnd = "</span>"; private static String reservedWordStart = "<span Class=\"keyword\">"; private static String reservedWordEnd = "</span>"; static { loadHash(); } /** * Passes off each line to the first filter. * * @param line The line of Java code to be highlighted. * @return Highlighted line. */ public static String syntaxHighlight(String line) { return htmlFilter(line); } /* * Filter html tags into more benign text. */ private static String htmlFilter(String line) { if (line == null || line.equals("")) { return ""; } // replace ampersands with HTML escape sequence for ampersand; line = replace(line, "&", "&#38;"); // replace the \\ with HTML escape sequences. fixes a problem when // backslashes proceed quotes. line = replace(line, "\\\\", "&#92;&#92;"); // replace \" sequences with HTML escape sequences; line = replace(line, "" + (char) 92 + (char) 34, "&#92;&#34"); // replace less-than signs which might be confused // by HTML as tag angle-brackets; line = replace(line, "<", "&#60;"); // replace greater-than signs which might be confused // by HTML as tag angle-brackets; line = replace(line, ">", "&#62;"); return multiLineCommentFilter(line); } /* * Filter out multiLine comments. State is kept with a private boolean * variable. */ private static String multiLineCommentFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); int index; //First, check for the end of a multi-line comment. if (inMultiLineComment && (index = line.indexOf("*/")) > -1 && !isInsideString(line, index)) { inMultiLineComment = false; buf.append(commentStart); buf.append(line.substring(0, index)); buf.append("*/").append(commentEnd); if (line.length() > index + 2) { buf.append(inlineCommentFilter(line.substring(index + 2))); } return buf.toString(); } //If there was no end detected and we're currently in a multi-line //comment, we don't want to do anymore work, so return line. else if (inMultiLineComment) { buf.append(commentStart); buf.append(line); buf.append(commentEnd); return buf.toString(); } //We're not currently in a comment, so check to see if the start //of a multi-line comment is in this line. else if ((index = line.indexOf("/*")) > -1 && !isInsideString(line, index)) { inMultiLineComment = true; //Return result of other filters + everything after the start //of the multiline comment. We need to pass the through the //to the multiLineComment filter again in case the comment ends //on the same line. buf.append(inlineCommentFilter(line.substring(0, index))); buf.append(commentStart).append("/*"); buf.append(multiLineCommentFilter(line.substring(index + 2))); buf.append(commentEnd); return buf.toString(); } //Otherwise, no useful multi-line comment information was found so //pass the line down to the next filter for processing. else { return inlineCommentFilter(line); } } /* * Filter inline comments from a line and formats them properly. */ private static String inlineCommentFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); int index; if ((index = line.indexOf("//")) > -1 && !isInsideString(line, index)) { buf.append(stringFilter(line.substring(0, index))); buf.append(commentStart); buf.append(line.substring(index)); buf.append(commentEnd); } else { buf.append(stringFilter(line)); } return buf.toString(); } /* * Filters strings from a line of text and formats them properly. */ private static String stringFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); if (line.indexOf("\"") <= -1) { return keywordFilter(line); } int start = 0; int startStringIndex = -1; int endStringIndex = -1; int tempIndex; //Keep moving through String characters until we want to stop... while ((tempIndex = line.indexOf("\"")) > -1) { //We found the beginning of a string if (startStringIndex == -1) { startStringIndex = 0; buf.append(stringFilter(line.substring(start, tempIndex))); buf.append(stringStart).append("\""); line = line.substring(tempIndex + 1); } //Must be at the end else { startStringIndex = -1; endStringIndex = tempIndex; buf.append(line.substring(0, endStringIndex + 1)); buf.append(stringEnd); line = line.substring(endStringIndex + 1); } } buf.append(keywordFilter(line)); return buf.toString(); } /* * Filters keywords from a line of text and formats them properly. */ private static String keywordFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); HashMap usedReservedWords = new HashMap(); // >= Java2 only (not thread-safe) //Hashtable usedReservedWords = new Hashtable(); // < Java2 (thread-safe) int i = 0, startAt = 0; char ch; StringBuffer temp = new StringBuffer(); while (i < line.length()) { temp.setLength(0); ch = line.charAt(i); startAt = i; // 65-90, uppercase letters // 97-122, lowercase letters while (i < line.length() && ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_')) { temp.append(ch); i++; if (i < line.length()) { ch = line.charAt(i); } } // System.out.println("found " + temp.toString()); String tempString = temp.toString(); if (reservedWords.containsKey(tempString) && !usedReservedWords.containsKey(tempString)) { // usedReservedWords.put(tempString, tempString); line = replace(line, tempString, (reservedWordStart + tempString + reservedWordEnd), startAt, true); // line = replace(line, "[^_a-zA-Z0-9]" + tempString + "[^_a-zA-Z0-9]", (reservedWordStart + tempString + reservedWordEnd), startAt); i += (reservedWordStart.length() + reservedWordEnd.length()); } else { i++; } } buf.append(line); return buf.toString(); } /* * All important replace method. Replaces all occurrences of oldString in * line with newString. */ private static String replace(String line, String oldString, String newString) { return replace(line, oldString, newString, 0, false); } /* * All important replace method. Replaces all occurrences of oldString in * line with newString. */ private static String replace(String line, String oldString, String newString, int startAt, boolean once) { int i = startAt; while ((i = line.indexOf(oldString, i)) >= 0) { line = (new StringBuffer().append(line.substring(0, i)) .append(newString) .append(line.substring(i + oldString.length()))).toString(); i += newString.length(); if (once) { break; // workarounding "if (ident_if_ier)" problem } } return line; } /* * Checks to see if some position in a line is between String start and * ending characters. Not yet used in code or fully working :) */ private static boolean isInsideString(String line, int position) { if (line.indexOf("\"") < 0) { return false; } int index; String left = line.substring(0, position); String right = line.substring(position); int leftCount = 0; int rightCount = 0; while ((index = left.indexOf("\"")) > -1) { leftCount++; left = left.substring(index + 1); } while ((index = right.indexOf("\"")) > -1) { rightCount++; right = right.substring(index + 1); } if (rightCount % 2 != 0 && leftCount % 2 != 0) { return true; } else { return false; } } /* * Load Hashtable (or HashMap) with Java reserved words. */ private static void loadHash() { reservedWords.put("abstract", "abstract"); reservedWords.put("assert", "assert"); reservedWords.put("boolean", "boolean"); reservedWords.put("break", "break"); reservedWords.put("byte", "byte"); reservedWords.put("case", "case"); reservedWords.put("catch", "catch"); reservedWords.put("char", "char"); reservedWords.put("class", "class"); reservedWords.put("const", "const"); reservedWords.put("continue", "continue"); reservedWords.put("default", "default"); reservedWords.put("do", "do"); reservedWords.put("double", "double"); reservedWords.put("else", "else"); reservedWords.put("enum", "enum"); reservedWords.put("extends", "extends"); reservedWords.put("false", "false"); reservedWords.put("final", "final"); reservedWords.put("finally", "finally"); reservedWords.put("float", "float"); reservedWords.put("for", "for"); reservedWords.put("goto", "goto"); reservedWords.put("if", "if"); reservedWords.put("implements", "implements"); reservedWords.put("import", "import"); reservedWords.put("instanceof", "instanceof"); reservedWords.put("int", "int"); reservedWords.put("interface", "interface"); reservedWords.put("long", "long"); reservedWords.put("native", "native"); reservedWords.put("new", "new"); reservedWords.put("null", "null"); reservedWords.put("package", "package"); reservedWords.put("private", "private"); reservedWords.put("protected", "protected"); reservedWords.put("public", "public"); reservedWords.put("return", "return"); reservedWords.put("short", "short"); reservedWords.put("static", "static"); reservedWords.put("strictfp", "strictfp"); reservedWords.put("super", "super"); reservedWords.put("switch", "switch"); reservedWords.put("synchronized", "synchronized"); reservedWords.put("this", "this"); reservedWords.put("throw", "throw"); reservedWords.put("throws", "throws"); reservedWords.put("transient", "transient"); reservedWords.put("true", "true"); reservedWords.put("try", "try"); reservedWords.put("void", "void"); reservedWords.put("volatile", "volatile"); reservedWords.put("while", "while"); } }
15,422
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
CopyResources.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/html/resources/CopyResources.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.html.resources; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * @author Dmitry Fazunenko * @author Alexey Fedorchenko */ public class CopyResources { public static void copy(File destDir) throws IOException { if (!destDir.exists()) { destDir.mkdirs(); } copyResourceFromJar("style.css", destDir); copyResourceFromJar("sorttable.js", destDir); } private static void copyResourceFromJar(String resourceName, File destDir) throws IOException { int n; byte[] buf = new byte[1024]; InputStream in = null; FileOutputStream out = null; destDir.mkdirs(); try { in = CopyResources.class.getResourceAsStream(resourceName); if (in == null) { throw new IllegalArgumentException("Resource " + resourceName + " does not exist in this package."); } out = new FileOutputStream(new File(destDir, resourceName)); while ((n = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, n); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } }
2,784
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
TextReportGenerator.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/text/TextReportGenerator.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.text; import com.sun.tdk.jcov.report.ClassCoverage; import com.sun.tdk.jcov.report.DataType; import com.sun.tdk.jcov.report.FieldCoverage; import com.sun.tdk.jcov.report.MethodCoverage; import com.sun.tdk.jcov.report.PackageCoverage; import com.sun.tdk.jcov.report.ProductCoverage; import com.sun.tdk.jcov.report.ReportGenerator; import java.io.PrintWriter; import java.io.FileWriter; import java.io.IOException; import com.sun.tdk.jcov.tools.JcovStats; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; /** * Used to generate text-form reports based on the contents of a JcovFileImage * object. Html-form report generators are also available. * * @see com.sun.tdk.jcov.filedata.JcovFileImage * @see HtmlReportGenerator * @author Konstantin Bobrovsky */ public class TextReportGenerator implements ReportGenerator { public final static String sccsVersion = "%I% $LastChangedDate: 2013-10-14 18:13:10 +0400 (Mon, 14 Oct 2013) $"; /** * format specifier, as used in command-line option */ public final static String FMT_TEXT = "text"; /** * default report file name */ public static final String DEFAULT_REPORT_NAME = "report.txt"; /** * where to write the report */ protected PrintWriter out; /** * Error/message log */ private static String[] spaces = new String[]{"", " ", " ", " ", " ", " ", " "}; private static String[] dashes = new String[]{"", " ", ". ", ".. ", "... ", ".... ", "..... "}; private static final Logger logger; private boolean generateShortFormat; private boolean showMethods; private boolean showBlocks; private boolean showBranches; private boolean showLines; private boolean showFields; static { Utils.initLogger(); logger = Logger.getLogger(TextReportGenerator.class.getName()); logger.setLevel(Level.WARNING); } @Override public void init(String outputFile) throws IOException { outputFile = detectOutputTextFileName(outputFile); if (outputFile == null) { out = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())); } else { out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile), Charset.defaultCharset())); } } Options options; @Override public void generateReport(ProductCoverage coverage, Options options) { this.options = options; out.println("Coverage Report: "); String sumFormat = "ALL: classes:%1$s;"; String pkgFormat = "PKG%1s: %2s classes:%3$s;"; String clsFormat = "CLS%1s: %2$s "; String mthFormat = "MTH%1s: %2$s hits: %3$s"; String fldFormat = "FLD%1s: %2$s hits: %3$s"; if (showMethods) { sumFormat += " methods:%2$s;"; pkgFormat += " methods:%4$s;"; clsFormat += " methods:%3$s;"; } if (showBlocks) { sumFormat += " blocks:%3$s;"; pkgFormat += " blocks:%5$s;"; clsFormat += " blocks:%4$s;"; mthFormat += " blocks:%4$s;"; } if (showBranches) { sumFormat += " branches:%4$s;"; pkgFormat += " branches:%6$s;"; clsFormat += " branches:%5$s;"; mthFormat += " branches:%5$s;"; } if (showLines) { sumFormat += " lines:%5$s;"; pkgFormat += " lines:%7$s;"; clsFormat += " lines:%6$s;"; mthFormat += " lines:%6$s;"; } out.println(String.format(sumFormat, coverage.getCoverageString(DataType.CLASS, coverage.isAncFiltersSet()), coverage.getData(DataType.METHOD).add(coverage.getData(DataType.FIELD)).toString(), coverage.getCoverageString(DataType.BLOCK, coverage.isAncFiltersSet()), coverage.getCoverageString(DataType.BRANCH, coverage.isAncFiltersSet()), coverage.getCoverageString(DataType.LINE, coverage.isAncFiltersSet()))); for (PackageCoverage pkgCov : coverage) { out.println(String.format(pkgFormat, pkgCov.isCovered() ? "+" : "-", pkgCov.getName(), pkgCov.getCoverageString(DataType.CLASS, coverage.isAncFiltersSet()), pkgCov.getData(DataType.METHOD).add(pkgCov.getData(DataType.FIELD)).toString(), pkgCov.getCoverageString(DataType.BLOCK, coverage.isAncFiltersSet()), pkgCov.getCoverageString(DataType.BRANCH, coverage.isAncFiltersSet()), pkgCov.getCoverageString(DataType.LINE, coverage.isAncFiltersSet()))); for (ClassCoverage clsCov : pkgCov.getClasses()) { out.println(String.format(clsFormat, clsCov.isCovered() ? "+" : "-", clsCov.getName(), clsCov.getData(DataType.METHOD).add(clsCov.getData(DataType.FIELD)).toString(), clsCov.getCoverageString(DataType.BLOCK, coverage.isAncFiltersSet()), clsCov.getCoverageString(DataType.BRANCH, coverage.isAncFiltersSet()), clsCov.getCoverageString(DataType.LINE, coverage.isAncFiltersSet()))); if (!generateShortFormat && showMethods) { for (MethodCoverage mthCov : clsCov.getMethods()) { out.println(String.format(mthFormat, mthCov.isCovered() ? "+" : "-", mthCov.getName() + mthCov.getSignature(), mthCov.getHitCount(), mthCov.getCoverageString(DataType.BLOCK, coverage.isAncFiltersSet()), mthCov.getCoverageString(DataType.BRANCH, coverage.isAncFiltersSet()), mthCov.getCoverageString(DataType.LINE, coverage.isAncFiltersSet()))); } } if (!generateShortFormat && showFields) { for (FieldCoverage fldCov : clsCov.getFields()) { out.println(String.format(fldFormat, fldCov.isCovered() ? "+" : "-", fldCov.getName(), fldCov.getHitCount())); } } out.println(); } } out.flush(); out.close(); } /** * prints given three numbers */ private static void printTrio(PrintWriter out, long num1, long num2, float prcnt, int align) { boolean use_dashes = false; if (align < 0) { align = -align; use_dashes = true; } String s1 = Long.toString(num1); String s2 = Long.toString(num2); String s3 = num1 == 0 ? "N/A" : (prcnt < 0.01 ? "0.0" : Float.toString(prcnt * 100.0f)); String[] fill = use_dashes ? dashes : spaces; out.print(fill[align - s1.length()]); out.print(s1 + " "); out.print(fill[align - s2.length()]); out.print(s2 + " "); if (num1 > 0) { int dot_ind = s3.indexOf((int) '.'); out.print(fill[3 - dot_ind]); out.print(s3.substring(0, dot_ind + 2) + "% "); } else { out.print(fill[6 - s3.length()]); out.print(s3 + " "); } } public static void printStats(PrintWriter out, JcovStats stats) { printStats(out, stats, false); } /** * prints given coverage statistics */ public static void printStats(PrintWriter out, JcovStats stats, boolean use_dashes) { int align = use_dashes ? -7 : 7; out.print(" "); printTrio(out, stats.methods_tot, stats.methods_cov, stats.method_cvg, align); printTrio(out, stats.blocks_tot, stats.blocks_cov, stats.block_cvg, align); printTrio(out, stats.branches_tot, stats.branches_cov, stats.branch_cvg, align); } /** * prints class/method modifiers */ private void printModifiers(String[] modifiers) { if (modifiers == null || modifiers.length == 0) { return; } out.print("["); for (int i = 0; i < modifiers.length; i++) { out.print(modifiers[i]); if (i < modifiers.length - 1) { out.print(" "); } } out.print("]"); } /** * Detects filename of the text report. Creates all necessary directies. * * @param value - value specified via "-output" option * @return */ private static String detectOutputTextFileName(String value) { if (value == null) { return null; } File f = new File(value); if (f.exists()) { if (f.isDirectory()) { return value + File.separator + DEFAULT_REPORT_NAME; } else { return value; } } File dir = f; String result = value; if (value.endsWith(File.separator) || value.endsWith("/")) { result = dir.getPath() + File.separator + DEFAULT_REPORT_NAME; } else { dir = f.getParentFile(); } if (dir != null) { dir.mkdirs(); } return result; } public void setGenerateShortFormat(boolean generateShortFormat) { this.generateShortFormat = generateShortFormat; } public void setShowMethods(boolean showMethods) { this.showMethods = showMethods; } public void setShowBlocks(boolean showBlocks) { this.showBlocks = showBlocks; } public void setShowBranches(boolean showBranches) { this.showBranches = showBranches; } public void setShowFields(boolean showFields) { this.showFields = showFields; } public void setShowLines(boolean showLines) { this.showLines = showLines; } }
11,466
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ToStringANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/ToStringANCFilter.java
/* * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class ToStringANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { if (m.getName() != null && m.getName().equals("toString") && m.getVmSignature().startsWith("()")){ return true; } return false; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "toString() method filter"; } }
2,097
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
EmptyANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/EmptyANCFilter.java
/* * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class EmptyANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { if (m.getBlocks().size() == 1 && m.getBlocks().get(0).startBCI() == 0 && m.getBlocks().get(0).startBCI() == m.getBlocks().get(0).endBCI()){ return true; } return false; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "Empty method filter"; } }
2,125
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DeprecatedANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/DeprecatedANCFilter.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class DeprecatedANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { if (m.getModifiers().isDeprecated()){ return true; } return false; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "Deprecated method filter"; } }
2,001
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
GetterANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/GetterANCFilter.java
/* * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class GetterANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { if (m.getName().startsWith("get") && m.getBlocks().size() == 1 && m.getBlocks().get(0).startBCI() == 0 && m.getBlocks().get(0).endBCI() == 4 && m.getVmSignature().startsWith("()")) { return true; } return false; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "Getter method filter"; } }
2,202
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DefaultAncFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/DefaultAncFilter.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public interface DefaultAncFilter extends AncFilter { public String getFilterName(); }
1,426
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SyntheticANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/SyntheticANCFilter.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class SyntheticANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { if (m.getModifiers().isSynthetic()){ return true; } return false; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "Synthetic method filter"; } }
1,998
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
SetterANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/SetterANCFilter.java
/* * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class SetterANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { if (m.getName().startsWith("set") && m.getBlocks().size() == 1 && m.getBlocks().get(0).startBCI() == 0 && m.getBlocks().get(0).endBCI() == 5 && m.getVmSignature().length() - m.getVmSignature().replaceAll(";","").length() <= 1){ return true; } return false; } @Override public boolean accept(DataMethod m, DataBlock b) { return false; } @Override public String getAncReason() { return "Setter method filter"; } }
2,247
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ListANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/ListANCFilter.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.report.AncFilter; import com.sun.tdk.jcov.report.ParameterizedAncFilter; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * * This class provides an ability to use externally generated lists of methods to be used * as an ANC filter. There are certain assumptions on the file format: * <ul> * <li>Lines containing comments must start with "#" symbol.</li> * <li>First line in the file should be a comment and must contain the "ANC reason"</li> * <li>Every non-comment line should be empty or be in a form of * &lt;class-name#&lt&gt;&lt;method-name-andsignature&gt;. Example: java/lang/String#indexOf(I)I</li> * </ul> */ public class ListANCFilter implements ParameterizedAncFilter { private static final String COMMENT_PREFIX = "#"; private static final String CLASS_METHOD_SEPARATOR = "#"; private Map<String, Set<String>> excludes; private String ancReason; /** * {@inheritDoc} */ @Override public boolean accept(DataClass dc) { assertInitialized(); return false; } private void assertInitialized() { if(excludes == null) { throw new IllegalStateException("No ANC list was provided"); } } /** * {@inheritDoc} */ @Override public boolean accept(DataClass dc, DataMethod dm) { assertInitialized(); String className = dc.getFullname(); String methodName = dm.getName(); int dot = methodName.indexOf("."); if(dot > -1) { className = className + methodName.substring(0, dot); methodName = methodName.substring(dot + 1); } Set<String> methods = excludes.get(className); return methods != null && methods.contains(methodName + dm.getVmSignature()); } /** * {@inheritDoc} */ @Override public boolean accept(DataMethod dm, DataBlock db) { assertInitialized(); return false; } /** * {@inheritDoc} */ @Override public String getAncReason() { assertInitialized(); return ancReason; } /** * {@inheritDoc} */ @Override public void setParameter(String parameter) throws IOException { if(parameter == null) throw new IllegalArgumentException("File must not be null for list filter."); excludes = new HashMap<>(); try(BufferedReader in = new BufferedReader(new FileReader(parameter))) { String line = in.readLine(); if(line != null && line.startsWith(COMMENT_PREFIX)) { ancReason = line.substring(COMMENT_PREFIX.length()); } else { throw new IllegalStateException("No ANC reason was provided."); } while((line = in.readLine()) != null) { if(line.startsWith(COMMENT_PREFIX)) { continue; } int separator = line.indexOf(CLASS_METHOD_SEPARATOR); if (separator > -1) { String clss = line.substring(0, separator); Set<String> mthds = excludes.get(clss); if (mthds == null) { mthds = new HashSet<>(); excludes.put(clss, mthds); } mthds.add(line.substring(separator + 1)); } else { if (line.length() > 0) { throw new IllegalStateException("Unidentifiable method " + line); } } } } } }
5,164
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
BuiltInAncFilters.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/BuiltInAncFilters.java
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.report.AncFilter; import com.sun.tdk.jcov.report.AncFilterFactory; import com.sun.tdk.jcov.report.ParameterizedAncFilter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import static java.util.stream.Collectors.toList; public class BuiltInAncFilters implements AncFilterFactory { private static final Map<String, Class<? extends AncFilter>> filterClasses; static { filterClasses = new HashMap(); filterClasses.put("catch", CatchANCFilter.class); filterClasses.put("deprecated", DeprecatedANCFilter.class); filterClasses.put("empty", EmptyANCFilter.class); filterClasses.put("getter", GetterANCFilter.class); filterClasses.put("list", ListANCFilter.class); filterClasses.put("setter", SetterANCFilter.class); filterClasses.put("synthetic", SyntheticANCFilter.class); filterClasses.put("throw", ThrowANCFilter.class); filterClasses.put("toString", ToStringANCFilter.class); } @Override public AncFilter instantiate(String shortName) { try { return filterClasses.get(shortName).newInstance(); } catch (InstantiationException|IllegalAccessException e) { throw new RuntimeException("Unable to instantiate filter " + shortName, e); } } @Override public Collection<AncFilter> instantiateAll() { List<AncFilter> filters = new ArrayList<>(); for(Class<? extends AncFilter> cls : filterClasses.values()) { if(!ParameterizedAncFilter.class.isAssignableFrom(cls)) { try { filters.add(cls.newInstance()); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Unable to instantiate filter " + cls.getName(), e); } } } return filters; } }
3,257
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ThrowANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/ThrowANCFilter.java
/* * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.*; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class ThrowANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { return false; } @Override public boolean accept(DataMethod m, DataBlock b) { if (m instanceof DataMethodWithBlocks){ for (BasicBlock bb : ((DataMethodWithBlocks) m).getBasicBlocks()){ if (bb.startBCI() == b.startBCI() && bb.endBCI() == b.endBCI() && bb.exit != null && bb.exit instanceof DataExitSimple && ((DataExitSimple) bb.exit).opcodeName().equals("athrow")){ return true; } } } return false; } @Override public String getAncReason() { return "Throw block filter"; } }
2,255
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
CatchANCFilter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/ancfilters/CatchANCFilter.java
/* * Copyright (c) 2014, 2018 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.ancfilters; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.XmlNames; import com.sun.tdk.jcov.report.AncFilter; /** * @author Alexey Fedorchenko */ public class CatchANCFilter implements AncFilter { @Override public boolean accept(DataClass clz) { return false; } @Override public boolean accept(DataClass clz, DataMethod m) { return false; } @Override public boolean accept(DataMethod m, DataBlock b) { if (b.kind() != null && b.kind().equals(XmlNames.CATCH)){ return true; } return false; } @Override public String getAncReason() { return "Catch block filter"; } }
2,053
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JavapCodeLine.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/javap/JavapCodeLine.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.javap; /** * Codeline of the javap output for classfile. This line could be covered or * not. * * @author Alexey Fedorchenko */ public class JavapCodeLine extends JavapLine { private int codeNumber; private boolean visited; public int getCodeNumber() { return codeNumber; } public void setCodeNumber(int number) { codeNumber = number; } public void setVisited(boolean value) { visited = value; } public boolean isVisited() { return visited; } }
1,767
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JavapClass.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/javap/JavapClass.java
/* * Copyright (c) 2014,2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.javap; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * JavapClass object representing javap output for the specified class * * @author Alexey Fedorchenko */ public class JavapClass { private String packageName; private String className; // class as list of JavapLines private final ArrayList<JavapLine> lines = new ArrayList<>(); // method in the class is list of lines numbers in the javap output private final HashMap<String, ArrayList<Integer>> methods = new HashMap<>(); /** * return method in the class like list of JavapLines * * @param nameAndVMSig name and VMsig string is needed to find method in the * class * @return method in the class like list of JavapLines */ public List<JavapLine> getMethod(String nameAndVMSig) { List<Integer> numbers = methods.get(nameAndVMSig); if (numbers == null || numbers.isEmpty()) { return null; } return lines.subList(numbers.get(0), numbers.get(numbers.size() - 1) + 1); } public String getClassName() { return className; } public String getPackageName() { return packageName; } /** * return javap result for class like list of JavapLines */ public List<JavapLine> getLines() { return lines; } /** * parse specified class file and fill JavapClass object data * * @param filePath - path to the class file */ void parseJavapFile(String filePath, String jarPath) { try { BufferedReader inStream; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, Charset.defaultCharset())); JavapClassReader.read(filePath, jarPath, pw); inStream = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), Charset.defaultCharset())); String textLine; String lastMethodString = ""; int lineNumber = 0; while ((textLine = inStream.readLine()) != null) { if (textLine.startsWith("Warning:")) { //do not parse javap warnings continue; } // try to find class in javap output if (textLine.contains("class") && textLine.contains("{")) { parsePackageAndClassNames(textLine); } // try to find method in javap output if (textLine.contains("(") && (textLine.contains(");") || textLine.contains(") throws"))) { // check if it is constructor or not if (!textLine.contains("." + className + "(")) { lastMethodString = parseMethodString(textLine); } else { lastMethodString = parseClassString(textLine); } methods.put(lastMethodString, new ArrayList<>()); } else { if (textLine.trim().equals("static {};")) { lastMethodString = parseStaticBlockString(); methods.put(lastMethodString, new ArrayList<>()); } } // try to find code lines which could be covered if (textLine.contains(":") && !textLine.contains("Code") && !textLine.contains("case") && !textLine.contains("default") && !textLine.contains("Exception table")) { addCodeLine(lineNumber, textLine, lastMethodString); } else { addLine(lineNumber, textLine); } lineNumber++; } inStream.close(); } catch (Exception e) { System.err.println("Error in parsing javap file:"); e.printStackTrace(); } } final private static String[] JavaClassTokens = new String[] {"implements", "extends", "{"}; private void parsePackageAndClassNames(String textLine) { for( String s : JavaClassTokens) { if (textLine.contains(s)) { textLine = textLine.substring(0, textLine.indexOf(s)); } } textLine = textLine.substring(textLine.indexOf("class")+5).trim(); int ind = textLine.indexOf('<'); if(ind != -1){ textLine = textLine.substring(0, ind); } ind = textLine.lastIndexOf('.'); if( ind > 0 ) { packageName = textLine.substring(0,ind); className = textLine.substring(ind+1); } else { className = textLine; packageName = ""; } } private String parseStaticBlockString() { return "<clinit>()V"; } private String parseClassString(String textLine) { textLine = removeGenericsInfo(textLine); String vmSig = encodeVmSignature(substringBetween(textLine, "\\(", "\\)", false), null); return "<init>" + vmSig; } private String parseMethodString(String textLine) { textLine = removeGenericsInfo(textLine); String methodName = substringBetween(textLine, "\\ ", "\\(", true); String returnType = substringBetween(textLine, "\\ ", " " + methodName, true); String vmSig = encodeVmSignature(substringBetween(textLine, "\\(", "\\)", false), returnType); return methodName + vmSig; } private static String encodeVmType(String oneMethodParam) { String className = oneMethodParam.replaceAll("[\\,\\[\\]]", ""); String s = className; if (className.lastIndexOf(".") > -1) { s = className.substring(className.lastIndexOf(".")); } String dim = oneMethodParam.replaceAll("[^\\[\\]]", ""); String newType; switch (s) { case "boolean": case "Boolean": newType = "Z"; break; case "void": case "Void": newType = "V"; break; case "int": case "Integer": newType = "I"; break; case "long": case "Long": newType = "J"; break; case "char": case "Character": newType = "C"; break; case "byte": case "Byte": newType = "B"; break; case "double": case "Double": newType = "D"; break; case "short": case "Short": newType = "S"; break; case "float": case "Number": newType = "F"; break; default: newType = "L"; break; } StringBuilder prefix = new StringBuilder(); for (int i = 0; i < dim.length() / 2; i++) { prefix.append("["); } if (className.lastIndexOf(".") > -1) { return prefix + newType + className.replaceAll("\\.", "/") + ";"; } else { return prefix + newType; } } private static String removeGenericsInfo(String textLine) { if (textLine != null) { textLine = textLine.replaceAll("<.*?>", ""); } return textLine; } private static String encodeVmSignature(String params, String returnValue) { if (params == null && returnValue == null) { return "()V"; } StringBuilder vmSig = new StringBuilder(); if (params != null) { if (params.contains(" ")) { for (String p : params.split(" ")) { vmSig.append(encodeVmType(p)); } } else { vmSig.append(encodeVmType(params)); } } if (returnValue == null || returnValue.equals("void")) { return "(" + vmSig + ")V"; } return "(" + vmSig + ")" + encodeVmType(returnValue); } private void addCodeLine(int lineNumber, String textLine, String methodNameAndVMsig) { JavapCodeLine codeLine = new JavapCodeLine(); try { codeLine.setCodeNumber(Integer.parseInt(textLine.substring(0, textLine.indexOf(":")).trim())); } catch (NumberFormatException nfe) { System.err.println(nfe + " in code line: " + textLine); } codeLine.setLineNumber(lineNumber); codeLine.setTextLine(textLine); if (methods.get(methodNameAndVMsig) != null) { methods.get(methodNameAndVMsig).add(lineNumber); } lines.add(codeLine); } private void addLine(int lineNumber, String textLine) { JavapLine codeLine = new JavapLine(); codeLine.setLineNumber(lineNumber); codeLine.setTextLine(textLine); lines.add(codeLine); } private static String substringBetween(String str, String open, String close, boolean firstValue) { // does not allow any characters from the "close" string in the end String regexStringLast = "([^" + open + "]+)(?=" + close + "[^" + close + "]*$)"; // just try to find string between open and close String regexString = "([^" + open + "]+)(?=" + close + ")"; if (!firstValue) { regexString = regexStringLast; } Pattern p = Pattern.compile(regexString); str = str.trim(); int i = str.indexOf("//"); if (i > -1) { str = str.substring(0, i); } Matcher m = p.matcher(str); if (m.find()) { return m.group(1).trim(); } return null; } }
11,482
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JavapRepGen.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/javap/JavapRepGen.java
/* * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.javap; import com.sun.tdk.jcov.RepGen; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.instrument.DataBlock; import com.sun.tdk.jcov.instrument.DataBlockTarget; import com.sun.tdk.jcov.instrument.DataBranch; import com.sun.tdk.jcov.instrument.DataClass; import com.sun.tdk.jcov.instrument.DataMethod; import com.sun.tdk.jcov.instrument.DataRoot; import com.sun.tdk.jcov.io.ClassSignatureFilter; import com.sun.tdk.jcov.io.Reader; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.IOException; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.String.format; /** * Report generation for classfiles (javap output will be used as source). * * @author Alexey Fedorchenko */ public class JavapRepGen { private final RepGen repGen; private static String strMsg = ""; public JavapRepGen(RepGen repGen){ this.repGen = repGen; } /** * find the list of classfiles in the specified root * * @param root - directory to find classfiles * @param result - result list of classfiles */ private void finder(File root, List<File> result) { File[] files = root.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { if (file.getName().endsWith(".class")) { result.add(file); } } else if (file.isDirectory()) { finder(file, result); } } } } /** * main method to create report with javap output for classes * * @param templatePath - path to the result.xml (xml file for creating report) * @param classesPath - path to the product classes * @param outPath - path where report should be saved */ public void run(String templatePath, String classesPath, String outPath) { DataRoot file_image; ClassSignatureFilter acceptor = new ClassSignatureFilter(null, null, null); try { file_image = Reader.readXML(templatePath, false, acceptor); } catch (FileFormatException ex) { Logger.getLogger(JavapRepGen.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); return; } if (classesPath == null) { JavapRepGen.printErrorMsg("no input classes specified"); return; } ArrayList<File> classFiles = new ArrayList<>(); ArrayList<String> classFilesInJar = new ArrayList<>(); File rootFile = new File(classesPath); HashMap<String, JavapClass> classes = new HashMap<>(); if (rootFile.isDirectory()) { finder(rootFile, classFiles); } else if (rootFile.isFile()) { String extension = ""; int i = rootFile.getName().lastIndexOf('.'); if (i > 0) { extension = rootFile.getName().substring(i + 1); } if ("class".equals(extension)) { classFiles.add(rootFile); } else { try { JarFile jarFile = new JarFile(rootFile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class")) { classFilesInJar.add(entry.getName().replaceAll("/", ".") .replace("\\", ".").substring(0, entry.getName().lastIndexOf(".class"))); } } } catch (IOException ioe) { // if there is no class files user will have the message } } } if (classFiles.isEmpty() && classFilesInJar.isEmpty()) { JavapRepGen.printErrorMsg("no .class files found at the specified path: " + classesPath); return; } filterClasses(classFiles, classesPath); filterClassesInJar(classFilesInJar); for (File classFile : classFiles) { JavapClass javapClass = new JavapClass(); javapClass.parseJavapFile(classFile.getAbsolutePath(), null); classes.put(javapClass.getClassName(), javapClass); } for (String classFileInJar : classFilesInJar) { JavapClass javapClass = new JavapClass(); javapClass.parseJavapFile(classFileInJar, rootFile.getAbsolutePath()); classes.put(javapClass.getClassName(), javapClass); } //reading block and branch coverage and mark lines in javap classes. for (DataClass dataClass : file_image.getClasses()) { for (DataMethod dataMethod : dataClass.getMethods()) { ArrayList<Integer> visitedBlocksNumbers = new ArrayList<>(); for (DataBlock dataBlock : dataMethod.getBlocks()) { if (dataBlock.getCount() > 0) { for (int index = dataBlock.startBCI(); index <= dataBlock.endBCI(); index++) { visitedBlocksNumbers.add(index); } } } for (DataBranch dataBranch : dataMethod.getBranches()) { for (DataBlockTarget dataBranchTarget : dataBranch.getBranchTargets()) { if (dataBranchTarget.getCount() > 0) { for (int index = dataBranchTarget.startBCI(); index <= dataBranchTarget.endBCI(); index++) { visitedBlocksNumbers.add(index); } } } } List<JavapLine> methodLines; JavapClass javapClass = classes.get(dataClass.getName()); if (javapClass != null) { methodLines = javapClass.getMethod(dataMethod.getName() + dataMethod.getVmSignature()); if (methodLines != null) { for (JavapLine javapLine : methodLines) { if ((javapLine instanceof JavapCodeLine) && visitedBlocksNumbers.contains(((JavapCodeLine) javapLine).getCodeNumber())) { ((JavapCodeLine) javapLine).setVisited(true); } } } } else { JavapRepGen.printErrorMsg(format("Can't get javap output for %s.class (%s) at the specified path: %s", dataClass.getName(), templatePath, classesPath)); } } } try { Result res = new Result(templatePath); repGen.generateReport(repGen.getDefaultReportGenerator(), outPath, res, null, new ArrayList(classes.values())); } catch (Exception e) { JavapRepGen.printErrorMsg("error in report generation: " + e); } } private static void printErrorMsg(String msg) { if ( strMsg.hashCode() != msg.hashCode() ) { strMsg = msg; System.err.println(msg); } } private void filterClasses(ArrayList<File> files, String classesPath) { ArrayList<File> newFiles = new ArrayList<>(); if (files.size() > 1) { classesPath = new File(classesPath+"/").getAbsolutePath().replaceAll("\\\\","/"); for (File classFile : files) { String className = classFile.getAbsolutePath().replaceAll("\\\\","/"); if (className.startsWith(classesPath + "/")){ className = className.substring(classesPath.length()+1); } if (className.endsWith(".class")) { className = className.substring(0, className.lastIndexOf(".class")); } if (Utils.accept(Utils.concatFilters(repGen.getInclude(), repGen.getExclude()), null, "/" + className, null)) { newFiles.add(classFile); } } files.clear(); files.addAll(newFiles); } } private void filterClassesInJar(ArrayList<String> filesInJar) { ArrayList<String> newFilesInJar = new ArrayList<>(); for (String classFile : filesInJar) { if (Utils.accept(Utils.concatFilters(repGen.getInclude(), repGen.getExclude()), null, "/" + classFile.replaceAll("\\.", "/"), null)) { newFilesInJar.add(classFile); } } filesInJar.clear(); filesInJar.addAll(newFilesInJar); } }
10,129
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JavapClassReader.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/javap/JavapClassReader.java
/* * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.javap; import com.sun.tools.javap.Main; import java.io.File; import java.io.PrintWriter; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; /** * This class is used to run javap on class files * * @author Alexey Fedorchenko */ public class JavapClassReader { private static URLClassLoader classLoader = null; private static Method method; private static Object instance; private static File toolsJar; public static void read(String filePath, String jarPath, PrintWriter pw) { // Note: if the RepGen is being started by JDK 9 and above then // the option "--add-exports jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED" should be added to the JVM command-line. try { if (jarPath == null) { Main.run(new String[]{"-c", "-p", filePath}, pw); } else { Main.run(new String[]{"-c", "-p", "-classpath", jarPath, filePath}, pw); } } catch (NoClassDefFoundError error) { if (classLoader == null) { File javaHome = new File(System.getProperty("java.home")); if (javaHome.getName().equals("jre")) { javaHome = javaHome.getParentFile(); toolsJar = new File(new File(javaHome, "lib"), "tools.jar"); if (toolsJar.exists()) { try { classLoader = new URLClassLoader(new URL[]{toolsJar.toURI().toURL()}, ClassLoader.getSystemClassLoader()); Class classToLoad = Class.forName("com.sun.tools.javap.Main", true, classLoader); method = classToLoad.getDeclaredMethod("run", String[].class, PrintWriter.class); instance = classToLoad.getDeclaredConstructor().newInstance(); String[] params; if (jarPath == null) { params = new String[]{"-c", "-p", filePath}; } else { params = new String[]{"-c", "-p", "-classpath", jarPath, filePath}; } try { Object result = method.invoke(instance, params, pw); } catch (Exception ex) { printToolsJarError(); } } catch (Exception e) { printToolsJarError(); } } else { printToolsJarError(); } } else { System.err.println("cannot execute javap, perhaps jdk8/lib/tools.jar is missing from the classpath"); System.err.println("example: java -cp jcov.jar:tools.jar com.sun.tdk.jcov.RepGen -javap path_to_classes -o path_to_javap_output path_to_result.xml"); return; } } else { String[] params; if (jarPath == null) { params = new String[]{"-c", "-p", filePath}; } else { params = new String[]{"-c", "-p", "-classpath", jarPath, filePath}; } try { method.invoke(instance, params, pw); } catch (Exception ex) { printToolsJarError(); } } } } private static void printToolsJarError() { System.err.println("cannot execute javap, perhaps jdk8/lib/tools.jar is missing from the classpath and from java.home"); System.err.println("example: java -cp jcov.jar:tools.jar com.sun.tdk.jcov.RepGen -javap path_to_classes -o path_to_javap_output path_to_result.xml"); return; } }
5,144
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
JavapLine.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/report/javap/JavapLine.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.report.javap; /** * Line of the javap output for classfile * * @author Alexey Fedorchenko */ public class JavapLine { private int lineNumber; private String line; public int getLineNumber() { return lineNumber; } public String getTextLine() { return line; } public void setLineNumber(int number) { lineNumber = number; } public void setTextLine(String textLine) { line = textLine; } }
1,699
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Instrument.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/Instrument.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; import com.sun.tdk.jcov.Instr; import com.sun.tdk.jcov.instrument.InstrumentationOptions; import com.sun.tdk.jcov.runtime.PropertyFinder; import com.sun.tdk.jcov.tools.OptionDescr; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.resources.FileResource; /** * * @author Andrey Titov */ public class Instrument extends Task { private File destdir; private File productDir; private List<BinPath> implantTo = new LinkedList<BinPath>(); private List<FileSet> files = new LinkedList<FileSet>(); private PatternSet filter; private LinkedList<SavePoint> saveBegin = new LinkedList<SavePoint>(); private LinkedList<SavePoint> saveEnd = new LinkedList<SavePoint>(); private boolean verbose; private File template; private File outtemplate; private boolean showabstract = false; private boolean shownative = false; private boolean showfields = false; public File propfile = null; // private String type; // not used (MERGE now) // private String flushClasses; // not wrapped public Instrument() { } @Override public void execute() throws BuildException { File oldBase = null; if (propfile != null) { PropertyFinder.setPropertiesFile(propfile.getPath()); } if (destdir != null) { if (destdir.exists() && !destdir.isDirectory()) { throw new BuildException("Output path is a file"); } if (this.productDir != null) { if (!this.productDir.exists()) { throw new BuildException("Project directory + " + this.productDir + " doesn't exist"); } if (!this.productDir.isDirectory()) { throw new BuildException("Project path " + this.productDir + " is not a directory"); } if (!destdir.exists()) { throw new BuildException("Output directory " + destdir + " doesn't exist"); } copyProduct(); log("Product mode: working in " + destdir + "...", 3); oldBase = convertPaths(); } } else if (this.productDir != null) { throw new BuildException("Destdir needed in project mode"); } String[] paths = getUniquePaths(); if (implantTo.isEmpty() && paths.length < 1) { log("Warning: no binaries found to instrument", 2); } log("Creating instrumentator", 4); Instr instr = new Instr(); log("Reseting instrumentator to defaults", 3); instr.resetDefaults(); log("Configuring insturumentator", 4); applyFilter(filter, instr); if (template != null) { instr.setTemplate(template.getPath()); } else { instr.setTemplate("template.xml"); } instr.setVerbose(verbose); String[] saveBeg = null; int size = saveBegin.size(); int i = 0; if (size > 0) { saveBeg = new String[size]; i = 0; for (SavePoint sp : saveBegin) { saveBeg[i] = sp.name; } } String[] saveE = null; size = saveEnd.size(); if (size > 0) { saveE = new String[size]; i = 0; for (SavePoint sp : saveEnd) { saveE[i] = sp.name; } } String defValue = showabstract ? OptionDescr.ON : OptionDescr.OFF; showabstract = OptionDescr.ON.equals(PropertyFinder.findValue(InstrumentationOptions.DSC_ABSTRACT.name, defValue)); defValue = showfields ? OptionDescr.ON : OptionDescr.OFF; showfields = OptionDescr.ON.equals(PropertyFinder.findValue(InstrumentationOptions.DSC_FIELD.name, defValue)); defValue = shownative ? OptionDescr.ON : OptionDescr.OFF; shownative = OptionDescr.ON.equals(PropertyFinder.findValue(InstrumentationOptions.DSC_NATIVE.name, defValue)); instr.config(showabstract, showfields, shownative, saveBeg, saveE); log("Insturumentator configured", 4); try { instr.startWorking(); log("Instrumentation started", 4); log(String.format("Parameters: filter incl %s excl %s; template %s; outtemplate %s; save_beg %s save_end %s; abstract %s fields %s native %s", Arrays.toString(incl), Arrays.toString(excl), template, outtemplate, Arrays.toString(saveBeg), Arrays.toString(saveE), showabstract, showfields, shownative), 3); for (BinPath path : implantTo) { File output = (productDir == null ? destdir : null); if (path.implantRT == null) { log("Implanting runtime file was not found for binary " + path.path + ". Please use <files> if you want to instrument single file without implanting runtime binaries.", 2); throw new BuildException("Cannot implant runtime data"); } log(path.getInstrumentingLog(output), 2); instr.instrumentFile(path.path.getPath(), output, path.implantRT.getPath()); } log("<implantTo> instrumentation complete", 4); if (paths != null && paths.length > 0) { File output = (productDir == null ? destdir : null); log("Instrumenting paths " + Arrays.toString(paths), 3); for (FileSet fs : files) { File root = fs.getDir(); Iterator it = fs.iterator(); while (it.hasNext()) { FileResource file = (FileResource) it.next(); if (!implantToContains(file.getFile())) { instr.instrumentFile(root.getPath() + File.separator + file.getName(), new File(output, file.getName()), null); } } } // for (String s : paths) { // instr.instrumentFile(s, output, null); // } } log("<files> instrumentation complete", 4); if (productDir != null) { log("Resetting basedir", 3); getProject().setBaseDir(oldBase); } if (outtemplate != null) { log("Writing result template to " + outtemplate, 2); instr.finishWork(outtemplate.getPath()); } else { log("Writing result template to template.xml", 2); instr.finishWork(); } log("Instrumentation finished", 3); } catch (BuildException e) { throw e; } catch (Exception e) { log("Instrumentation task failed: ", e, 1); e.printStackTrace(); // e.printStackTrace(); throw new BuildException("Instrumentation task failed: " + e.getMessage(), e); } if (propfile != null) { PropertyFinder.cleanProperties(); } } private void copyProduct() { Copy copy = new Copy(); copy.setProject(getProject()); copy.setTaskName("instrument"); FileSet fileSet = new FileSet(); fileSet.setDir(productDir); copy.addFileset(fileSet); copy.setTodir(destdir); copy.perform(); } /** * Converts all paths that should be converted to destdir (enables product * mode) * * @return old BaseDir file object */ private File convertPaths() { File oldBase = getProject().getBaseDir(); getProject().setBaseDir(productDir); String proj = destdir.getPath(); if (files != null) { for (FileSet fs : files) { fs.setDir(new File(proj + fs.getDir().getPath().substring(oldBase.getPath().length()))); } } return oldBase; } // public void setType(String type) { // com.sun.tdk.jcov.instrument.Options.setInstrumentationType(type); // } public void setVerbose(Boolean verbose) throws Exception { this.verbose = verbose; } public void setTemplate(File template) { if (!template.exists()) { throw new BuildException("Template " + template + " doesn't exist"); } if (!template.isFile()) { throw new BuildException("Template " + template + " is not a file"); } this.template = template; } public void setOutTemplate(File outtemplate) { if (outtemplate.exists()) { if (outtemplate.isDirectory()) { this.outtemplate = new File(outtemplate, "template.xml"); log("Warning, path for template " + outtemplate + " is directory, writing to " + this.outtemplate, 3); return; } throw new BuildException("Template " + outtemplate + " exist"); } else { this.outtemplate = outtemplate; } } public void setDestdir(File destdir) { this.destdir = destdir; } public void setProductDir(File project) { this.productDir = project; } public PatternSet createFilter() throws Exception { if (filter != null) { throw new Exception("filter should be only one"); } filter = new PatternSet(); return filter; } public SavePoint createSaveBegin() throws Exception { SavePoint sp = new SavePoint(); saveBegin.add(sp); return sp; } public SavePoint createSaveEnd() throws Exception { SavePoint sp = new SavePoint(); saveEnd.add(sp); return sp; } public static class SavePoint { private String name; public void setName(String name) { this.name = name; } } public BinPath createImplantTo() { BinPath path = new BinPath(); implantTo.add(path); return path; } public class BinPath { protected File path; protected File implantRT; public void setPath(File path) throws Exception { if (destdir != null && productDir != null) { String proj = destdir.getPath(); path = new File(proj + path.getPath().substring(getProject().getBaseDir().getPath().length())); } else { if (!path.exists()) { throw new BuildException("Binary root " + path + " doesn't exist"); } } this.path = path; } public void setImplantRT(File implantRT) { if (!implantRT.exists()) { throw new BuildException("Runtime file " + implantRT + " doesn't exist"); } if (!implantRT.isFile() || !implantRT.getName().endsWith("jar")) { throw new BuildException("Runtime file " + implantRT + " is not a jar file"); } this.implantRT = implantRT; } public String getInstrumentingLog(File output) { if (output != null) { return String.format("Instrumenting classfiles dir %s to %s with implanted %s", path.getPath(), output, implantRT); } else { return String.format("Instrumenting classfiles dir %s with implanted %s", path.getPath(), implantRT); } } } public FileSet createFiles() { FileSet fs = new FileSet(); files.add(fs); return fs; } /** * Filters out from "files" fileset all entries that were intruduced in * "inplantTo" * * @return filtered paths array */ private String[] getUniquePaths() { if (files == null || files.isEmpty()) { return null; } HashSet<String> pathsSet = new HashSet<String>(); for (FileSet fs : files) { fs.getDir(); Iterator it = fs.iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof FileResource) { FileResource fr = (FileResource) o; File file = fr.getFile(); if (!implantToContains(file)) { pathsSet.add(file.getPath()); } } } } return pathsSet.toArray(new String[pathsSet.size()]); } private boolean implantToContains(File file) { for (BinPath bp : implantTo) { if (bp.path.equals(file)) { return true; } } return false; } String[] incl; String[] excl; private void applyFilter(PatternSet filter, Instr instr) { incl = instr.getInclude(); excl = instr.getExclude(); if (filter != null) { incl = filter.getIncludePatterns(getProject()); excl = filter.getExcludePatterns(getProject()); instr.setFilter(incl, excl); } } public void setNative(boolean shownative) { this.shownative = shownative; } public void setFields(boolean showfields) { this.showfields = showfields; } public void setAbstract(boolean showabstract) { this.showabstract = showabstract; } public void setPropfile(File path) { this.propfile = path; } }
14,956
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Grabber.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/Grabber.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; import com.sun.tdk.jcov.constants.MiscConstants; import java.io.File; import java.io.IOException; import java.net.BindException; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * * @author Andrey Titov * @author Alexey Fedorchenko */ public class Grabber extends Task { private int port = MiscConstants.JcovPortNumber; private File template; private File output; private int count = 0; private boolean saveonrecieve = false; private boolean startCommandListener = true; private int commandport = MiscConstants.JcovGrabberCommandPort; private File logFile; private File propFile; private String outTestList; private boolean mergeByTestNames = false; @Override public void execute() throws BuildException { if (template == null || !template.exists() || !template.isFile()) { throw new BuildException("Incorrect template: " + template); } if (output == null) { output = new File(getProject().getBaseDir(), "result.xml"); } com.sun.tdk.jcov.Grabber grabber = new com.sun.tdk.jcov.Grabber(); if (logFile != null) { try { Logger logger = LogManager.getLogManager().getLogger(""); Handler[] handlers = logger.getHandlers(); for (int i = 0; i < handlers.length; i++) { logger.removeHandler(handlers[i]); } FileHandler fh = new FileHandler(logFile.getPath()); logger.addHandler(fh); logger.setLevel(Level.FINE); LogManager.getLogManager().addLogger(logger); } catch (Exception ex) { throw new BuildException(ex); } } else { LogManager.getLogManager().getLogger("").setLevel(Level.OFF); } try { grabber.setPort(port); grabber.setOutputFilename(output.getPath()); grabber.setTemplate(template.getPath()); grabber.setMaxCount(count); grabber.setSaveOnReceive(saveonrecieve); grabber.setCommandPort(commandport); grabber.setOutTestList(outTestList); grabber.setMergeByTestNames(mergeByTestNames); if (startCommandListener) { grabber.start(true); } else { grabber.start(false); } // setting run command after starting the server to use real ports grabber.setRunCommand(String.format("ANT: grabber port: %d, command port: %d, template: %s, output: %s, save on: %s, max connections: %s", grabber.getServerPort(), grabber.getCommandListenerPort(), template, output, (saveonrecieve ? "recieve" : "exit"), (count > 0 ? Integer.toString(count) : "unlimited"))); } catch (BindException ex) { throw new BuildException("Can't bind to specified port", ex); } catch (IOException ex) { throw new BuildException("Can't create server", ex); } if (propFile != null) { try { grabber.writePropfile(propFile.getPath()); } catch (IOException ex) { log(ex, 2); } } log("Server started at port " + port + " listening commands on " + commandport); } public void setPort(int port) { this.port = port; } public void setCommandport(int commandport) { this.commandport = commandport; } public void setSaveonrecieve(boolean saveonrecieve) { this.saveonrecieve = saveonrecieve; } public void setCount(int count) { this.count = count; } public void setOutput(File output) { this.output = output; } public void setTemplate(File template) { this.template = template; } public void setLogFile(File logFile) { this.logFile = logFile; } public void setPropertiesFile(File propFile) { this.propFile = propFile; } public void setOutTestList(String outTestList) { this.outTestList = outTestList; } public void setMergeByTestNames(boolean mergeByTestNames) { this.mergeByTestNames = mergeByTestNames; } public void setStartCommandListener(boolean startCommandListener) { this.startCommandListener = startCommandListener; } }
5,856
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AntableSPI.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/AntableSPI.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; /** * * @author Andrey Titov */ public interface AntableSPI { /** * Allows to use this SPI through ANT wrappers * * @param attrName ANT attribute name. * @param attrValue Value of attribute to set. * @return False if this attribute name is not supported. If SPI returns * FALSE here - JCov will try to resolve setter method (setXXX where XXX is * attrName). If neither setter method exists neither handleAttribute() * accepts the attrName - BuildException would thrown. */ public boolean handleAttribute(String attrName, String attrValue); }
1,837
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
GrabberManager.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/GrabberManager.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; import com.sun.tdk.jcov.constants.MiscConstants; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.condition.Condition; /** * * @author Andrey Titov * @author Alexey Fedorchenko */ public class GrabberManager extends Task implements Condition { private int port = MiscConstants.JcovGrabberCommandPort; private String host = "localhost"; private String command; private File output; private File propertiesFile; @Override public void execute() throws BuildException { com.sun.tdk.jcov.GrabberManager ctrl = new com.sun.tdk.jcov.GrabberManager(); if (propertiesFile != null) { try { ctrl.initPortFromFile(propertiesFile.getPath()); } catch (FileNotFoundException ex) { throw new BuildException("Properties file not found", ex); } catch (IOException ex) { throw new BuildException(ex); } } else { ctrl.setPort(port); } ctrl.setHost(host); if (command != null) { try { if ("save".equalsIgnoreCase(command)) { ctrl.sendSaveCommand(); } else if ("kill".equalsIgnoreCase(command)) { ctrl.sendKillCommand(); } else if ("forcekill".equalsIgnoreCase(command)) { ctrl.sendForceKillCommand(); } else if ("status".equalsIgnoreCase(command)) { String status = ctrl.sendStatusCommand(); if (output != null) { String[] split = status.split(";"); Utils.writeLines(output.getPath(), split); } } else { throw new BuildException("Command " + command + " is not supported. Only 'save', 'kill' and 'forcekill' are supported."); } } catch (IOException ex) { if ("Connection refused".equals(ex.getMessage())) { throw new BuildException("Connection refused on " + host + ":" + port); } else { throw new BuildException(ex); } } } } public void setCommand(String command) { this.command = command; } public boolean eval() throws BuildException { com.sun.tdk.jcov.GrabberManager ctrl = new com.sun.tdk.jcov.GrabberManager(port, host); boolean working = false; try { String gotstatus = ctrl.sendStatusCommand(); String[] split = gotstatus.split(";"); working = Boolean.parseBoolean(split[0]); } catch (IOException ex) { if ("Connection refused".equals(ex.getMessage())) { log("Connection refused on " + host + ":" + port); return false; } else { throw new BuildException(ex); } } return working; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setOutput(File output) { this.output = output; } public void setPropertiesFile(File propertiesFile) { this.propertiesFile = propertiesFile; } }
4,731
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Merge.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/Merge.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; import com.sun.tdk.jcov.Merger; import static com.sun.tdk.jcov.Merger.BreakOnError; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.resources.FileResource; /** * * @author Andrey Titov */ public class Merge extends Task { private LinkedList<FileSet> sources; private LinkedList<JCovFile> results; private PatternSet filter; private File output; private File testList; private int looseLevel; private boolean compressScales; private String breakOnError; private File template; private File skippedList; private File fileList; private boolean generateScales; public File fmlist; public LinkedList<FM> fm = new LinkedList<FM>(); public Merge() { results = new LinkedList<JCovFile>(); sources = new LinkedList<FileSet>(); } @Override public void execute() throws BuildException { Merger merger = new Merger(); merger.resetDefaults(); String fms[] = merger.getFm(); if (fmlist != null) { try { String[] readLines = Utils.readLines(fmlist.getPath()); for (String s : readLines) { fm.add(new FM(s)); } } catch (IOException ex) { throw new BuildException("Unable to read fmlist", ex); } } int fmsize = fm.size(); if (fmsize > 0) { fms = new String[fmsize]; int i = 0; for (FM f : fm) { fms[i++] = f.value; } merger.setClassModifiers(fms); } if (filter != null) { String incl[] = merger.getInclude(); String excl[] = merger.getExclude(); if (filter.getExcludePatterns(getProject()) != null) { excl = filter.getExcludePatterns(getProject()); } if (filter.getIncludePatterns(getProject()) != null) { incl = filter.getIncludePatterns(getProject()); } merger.setFilters(incl, excl, fms); } BreakOnError boe = Merger.BreakOnError.fromString(breakOnError); if (boe == null) { boe = BreakOnError.getDefault(); } merger.setBreakOnError(boe); merger.setLoose_lvl(looseLevel); merger.setRead_scales(testList != null || generateScales); merger.setCompress(compressScales); Result files[] = null; LinkedList<Result> paths = new LinkedList<Result>(); for (JCovFile file : results) { paths.add(file.getResult()); } for (FileSet fs : sources) { Iterator it = fs.iterator(); while (it.hasNext()) { Object next = it.next(); if (next instanceof FileResource) { FileResource file = (FileResource) next; paths.add(new Result(file.getFile().getAbsolutePath())); } else { // can be? } } } if (fileList != null) { if (!fileList.exists() || !fileList.isFile()) { log("WARNING: filelist " + fileList + " doesn't exist"); } else { try { String[] filesInList = Utils.readLines(fileList.getPath()); for (String f : filesInList) { paths.add(Merger.parseResultFromString(f)); } } catch (IOException ex) { throw new BuildException("Error while parsing filelist", ex); } } } if (paths.size() < 2) { if (paths.size() == 0) { throw new BuildException("No jcov files found to merge - need at least 2 jcov files."); } if (paths.size() == 1) { throw new BuildException("Need at least 2 jcov files to merge. Found 1: " + paths.getFirst().getResultPath()); } } files = paths.toArray(new Result[paths.size()]); paths = null; Merger.Merge merge; if (template != null) { merge = new Merger.Merge(files, template.getPath()); } else { merge = new Merger.Merge(files, null); } try { merger.mergeAndWrite(merge, testList == null ? null : testList.getPath(), output == null ? null : output.getPath(), skippedList == null ? null : skippedList.getPath()); } catch (IOException ex) { Logger.getLogger(Merge.class.getName()).log(Level.SEVERE, null, ex); } if (merge.getErrors() > 0) { log("Merger produced " + merge.getErrors() + " errors while working", 2); } if (merge.getSkippedCount() > 0) { List<String> skippedFiles = merge.getSkippedFiles(); log(skippedFiles.size() + (skippedFiles.size() > 1 ? " file was skipped due to errors" : " files were skipped due to errors"), 2); log("Skipped file" + (skippedFiles.size() > 1 ? "s: " + Arrays.toString(skippedFiles.toArray(new String[skippedFiles.size()])) : ": " + skippedFiles.get(0)), 3); if (skippedList != null) { log("Skipped files list was written to " + skippedList, 3); } } if (merge.getResult() == null && boe != BreakOnError.TEST) { throw new BuildException("Merging failed"); } } public void setBreakOnError(String breakOnError) { this.breakOnError = breakOnError; } public void setCompressScales(boolean compressScales) { this.compressScales = compressScales; } public void setOutput(File destdir) { this.output = destdir; } public void setLooseLevel(int looseLevel) { this.looseLevel = looseLevel; } public void setSkippedList(File skippedList) { this.skippedList = skippedList; } public void setTemplate(File template) { this.template = template; } public void setTestList(File testList) { this.testList = testList; } public void setFileList(File fileList) { this.fileList = fileList; } public FileSet createFiles() { FileSet fs = new FileSet(); sources.add(fs); return fs; } public PatternSet createFilter() throws Exception { if (filter != null) { throw new BuildException("Filter should be only one"); } filter = new PatternSet(); return filter; } public JCovFile createJcovFile() { JCovFile res = new JCovFile(); results.add(res); return res; } public static class JCovFile { private String respath; private String[] testList; private int first = -1; private int last = -1; public void setPath(String path) { this.respath = path; } public void setTestListPath(String path) throws IOException { if (testList != null) { throw new BuildException("Test list is already set by testName attribute"); } if (first >= 0 || last >= 0) { testList = Merger.initTestList(path, first, last); } else { testList = Merger.initTestList(path); } } public String[] getTestList() { if (testList == null) { String res = new File(respath).getName(); testList = new String[]{res}; } return testList; } public void setTestName(String name) { if (testList != null) { throw new BuildException("Test list is already set by testListPath attribute"); } testList = new String[]{name}; } private Result getResult() { return new Result(respath, testList); } public void setFirst(int first) { this.first = first; } public void setLast(int last) { this.last = last; } } public void setGenerateScales(boolean generateScales) { this.generateScales = generateScales; } public void setFmlist(File fmlist) throws IOException { String[] lines = Utils.readLines(fmlist.getPath()); for (String s : lines) { fm.add(new FM(s)); } this.fmlist = fmlist; } public FM createFM() { FM f = new FM(); fm.add(f); return f; } public static class FM { private String value; public FM() { } public FM(String value) { this.value = value; } public void setValue(String value) { this.value = value; } } }
10,556
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AllTasks.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/AllTasks.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * * @author Andrey Titov */ public class AllTasks extends Task { @Override public void execute() throws BuildException { getProject().addTaskDefinition("grabber", Grabber.class); getProject().addTaskDefinition("grabber-manager", GrabberManager.class); getProject().addTaskDefinition("instrument", Instrument.class); getProject().addTaskDefinition("merge", Merge.class); getProject().addTaskDefinition("report", Report.class); } }
1,807
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Report.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/ant/Report.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.ant; import com.sun.tdk.jcov.RepGen; import com.sun.tdk.jcov.data.Result; import com.sun.tdk.jcov.processing.ProcessingException; import com.sun.tdk.jcov.report.DefaultReportGeneratorSPI; import com.sun.tdk.jcov.report.ReportGeneratorSPI; import com.sun.tdk.jcov.report.javap.JavapRepGen; import com.sun.tdk.jcov.runtime.PropertyFinder; import com.sun.tdk.jcov.util.Utils; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DynamicAttribute; import org.apache.tools.ant.IntrospectionHelper; import org.apache.tools.ant.RuntimeConfigurable; import org.apache.tools.ant.Task; import org.apache.tools.ant.UnsupportedAttributeException; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.types.PatternSet; /** * * @author Andrey Titov * @author Alexey Fedorchenko */ public class Report extends Task implements DynamicAttribute { private PatternSet filter; public File srcRootPath; public boolean noAbstract = false; // not used public boolean isPublicAPI = false; public boolean noline = false; public boolean noblock = false; public boolean nobranch = false; public boolean nomethod = false; public boolean nofields = false; public String customFilter; public String customReportSPI; public ReportGeneratorSPI customReportSPIInstance; public String format = "html"; public File destdir = new File("report"); public File propfile = null; public File filename; public File testlist; public String getJavap() { return javap; } public void setJavap(String javap) { this.javap = javap; } public String javap; public boolean rewrite; public File fmlist; public LinkedList<FM> fm = new LinkedList<FM>(); private boolean customAttributes; @Override public void setDynamicAttribute(String attrName, String attrVal) throws BuildException { boolean ok = false; if (customReportSPIInstance != null && customReportSPIInstance instanceof AntableSPI) { ok = ((AntableSPI) customReportSPIInstance).handleAttribute(attrName, attrVal); } if (!ok) { try { IntrospectionHelper.getHelper(customReportSPIInstance.getClass()).setAttribute(getProject(), customReportSPIInstance, attrName, attrVal); } catch (Exception ex) { throw new UnsupportedAttributeException("report has no such attribute '" + attrName + "' neither in Report ServiceProvider '" + customReportSPIInstance.getClass() + "'", attrName); } } else { customAttributes = true; } } @Override public void maybeConfigure() throws BuildException { RuntimeConfigurable rt = getRuntimeConfigurableWrapper(); boolean found = false; for (Object o : rt.getAttributeMap().entrySet()) { Entry e = (Entry) o; if ("ReportSPI".equalsIgnoreCase(e.getKey().toString())) { try { customReportSPI = e.getValue().toString(); customReportSPIInstance = (ReportGeneratorSPI) Class.forName(customReportSPI).newInstance(); found = true; break; } catch (ClassNotFoundException ex) { throw new BuildException("Can't create report generator " + customReportSPI, ex); } catch (InstantiationException ex) { throw new BuildException("Can't create report generator " + customReportSPI, ex); } catch (IllegalAccessException ex) { throw new BuildException("Can't create report generator " + customReportSPI, ex); } catch (ClassCastException ex) { throw new BuildException("Can't create report generator " + customReportSPI + " - not a ReportGeneratorSPI", ex); } } } if (!found) { customReportSPIInstance = new DefaultReportGeneratorSPI(); } super.maybeConfigure(); } @Override public void execute() throws BuildException { RepGen repGen = new RepGen(); if (propfile != null) { PropertyFinder.setPropertiesFile(propfile.getPath()); } if (customReportSPIInstance.getClass() == DefaultReportGeneratorSPI.class && !customAttributes) { nomethod = Boolean.valueOf(PropertyFinder.findValue("nomethod", String.valueOf(nomethod))); noblock = Boolean.valueOf(PropertyFinder.findValue("noblock", String.valueOf(noblock))); nobranch = Boolean.valueOf(PropertyFinder.findValue("nobranch", String.valueOf(nobranch))); noline = Boolean.valueOf(PropertyFinder.findValue("noline", String.valueOf(noline))); nofields = Boolean.valueOf(PropertyFinder.findValue("nofields", String.valueOf(nofields))); ((DefaultReportGeneratorSPI) customReportSPIInstance).handleAttribute("hideMethods", String.valueOf(nomethod)); ((DefaultReportGeneratorSPI) customReportSPIInstance).handleAttribute("hideBlocks", String.valueOf(noblock)); ((DefaultReportGeneratorSPI) customReportSPIInstance).handleAttribute("hideBranches", String.valueOf(nobranch)); ((DefaultReportGeneratorSPI) customReportSPIInstance).handleAttribute("hideLines", String.valueOf(noline)); ((DefaultReportGeneratorSPI) customReportSPIInstance).handleAttribute("hideFields", String.valueOf(nofields)); } initRepGen(repGen); try { if (rewrite && destdir != null) { if (destdir.exists()) { Delete d = new Delete(); d.setProject(getProject()); d.setDir(destdir); d.setTaskName("rewrite"); d.perform(); } } if (filename != null) { if (javap != null) { repGen.setDataProcessorsSPIs(null); new JavapRepGen(repGen).run(filename.getPath(), javap, destdir.getPath()); if (propfile != null) { PropertyFinder.cleanProperties(); } return; } repGen.generateReport(format, destdir.getPath(), new Result(filename.getPath(), testlist != null ? testlist.getPath() : null), srcRootPath != null ? srcRootPath.getPath() : repGen.getSrcRootPath()); } else { throw new BuildException("Input jcov file needed to generate report"); } } catch (ProcessingException ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { ex.printStackTrace(); Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex); } if (propfile != null) { PropertyFinder.cleanProperties(); } } public void initRepGen(RepGen repGen) { try { repGen.resetDefaults(); } catch (Exception ex) { Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex); } if (customFilter != null && !customFilter.equals(repGen.getFilter())) { repGen.setFilter(customFilter); } String fms[] = repGen.getFms(); if (fm.size() > 0) { fms = new String[fm.size()]; int i = 0; for (FM f : fm) { fms[i++] = f.value; } repGen.setFms(fms); } if (filter != null) { String[] includes = repGen.getInclude(); String[] excludes = repGen.getExclude(); String[] incl = filter.getIncludePatterns(getProject()); if (incl != null) { includes = incl; } String[] excl = filter.getExcludePatterns(getProject()); if (excl != null) { excludes = excl; } repGen.setFilters(includes, excludes, fms); } if (repGen.isIsPublicAPI() != isPublicAPI) { repGen.setIsPublicAPI(isPublicAPI); } if (repGen.isNoAbstract() != noAbstract) { repGen.setNoAbstract(noAbstract); } repGen.setReportGeneratorSPIs(new ReportGeneratorSPI[]{customReportSPIInstance}); } public void setOutput(File path) { this.destdir = path; } public void setPropfile(File path) { this.propfile = path; } public void setNoline(boolean noline) { this.noline = noline; } public void setNoblock(boolean noblock) { this.noblock = noblock; } public void setNobranch(boolean nobranch) { this.nobranch = nobranch; } public void setNomethod(boolean nomethod) { this.nomethod = nomethod; } public void setNofields(boolean nofields) { this.nofields = nofields; } public void setJcovFile(File filename) { this.filename = filename; } public void setFormat(String format) { this.format = format; } public void setSource(File source) { this.srcRootPath = source; } public void setHideAbstract(Boolean value) { this.noAbstract = value; } public void setPublicApi(Boolean isPublicApi) { this.isPublicAPI = isPublicApi; } public void setFilter(String filter) { this.customFilter = filter; } public void setTestList(File testlist) { this.testlist = testlist; } public void setReportSPI(String spi) { this.customReportSPI = spi; } public void setRewrite(boolean rewrite) { this.rewrite = rewrite; } public PatternSet createFilter() { if (filter != null) { throw new BuildException("Filter should be only one"); } PatternSet ps = new PatternSet(); filter = ps; return ps; } public void setTest(boolean test) { if (test) { System.setProperty("test.mode", "true"); } } public void setFmlist(File fmlist) throws IOException { String[] lines = Utils.readLines(fmlist.getPath()); for (String s : lines) { fm.add(new FM(s)); } this.fmlist = fmlist; } public FM createFM() { FM f = new FM(); fm.add(f); return f; } public static class FM { private String value; public FM() { } public FM(String value) { this.value = value; } public void setValue(String value) { this.value = value; } } }
12,165
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
Attribute.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/Attribute.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; /** * Class representing name-value pair. * * @author Dmitry Fazunenko */ public class Attribute { /** * Attribute name */ public final String name; /** * Attribute value */ public final String value; /** * Creates an instance of Attribute * * @param name - name of attribute * @param value - value of attribute */ public Attribute(String name, String value) { this.name = name; this.value = value; } /** * @return string as name=value */ @Override public String toString() { return name + "=" + value; } public static Attribute parse(String token) { if (token == null) { return null; } int index = token.indexOf('='); if (index < 1) { return null; } return new Attribute(token.substring(0, index), token.substring(index + 1)); } }
2,198
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
FileFormatException.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/FileFormatException.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; /** * Exception signaling the problem with reading API sig file. * * @author Dmitry Fazunenko */ public class FileFormatException extends Exception { /** * Error happened at the particular line * * @param message - what's happened * @param lineNum - line # * @param fileName - file being parsed */ public FileFormatException(String message, int lineNum, String fileName) { this("Error parsing: " + fileName + " line# " + lineNum + ":" + message); } public FileFormatException(String message) { super(message); } }
1,840
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
AbstractDescr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/AbstractDescr.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; import java.util.ArrayList; import java.util.List; /** * Base class for class and class member description. * * @author Dmitry Fazunenko */ public abstract class AbstractDescr { /** * Name of the abstract element */ public final String name; /** * Custom attributes */ public final List<Attribute> attributes; public AbstractDescr(String name) { this.name = name; this.attributes = new ArrayList<Attribute>(); } /** * Invokes addAttribute(new Attribute(name, value)); */ public void addAttribute(String name, String value) { addAttribute(new Attribute(name, value)); } /** * Adds attribute to the list of element attributes. Does nothing if attr is * null, or element already contains such attribute. * * @param attr */ public void addAttribute(Attribute attr) { if (attr != null && !attributes.contains(attr)) { attributes.add(attr); } } /** * Removes attribute from the list of element attributes. Does nothing if * attr is null. * * @param attr */ public void removeAttribute(Attribute attr) { if (attr != null) { attributes.remove(attr); } } /** * Finds the first attribute with specified name. * * @param attrName - name of the attribute * @return value of the first found attribute or null, if not found */ public String getAttribute(String attrName) { List<String> list = getAllAttributes(attrName); if (list != null && list.size() > 0) { return list.get(0); } else { return null; } } /** * Returns values of all found attributes with the specified name. * * @param attrName - name of the attribute * @return a list of values or an empty list, if no attributes found. */ public List<String> getAllAttributes(String attrName) { ArrayList<String> list = new ArrayList<String>(); for (Attribute attr : attributes) { if (attr.name.equals(attrName)) { list.add(attr.value); } } return list; } }
3,469
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
API.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/API.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; /** * Class representing entire API set * * @author Dmitry Fazunenko */ public class API { private final HashMap<String, ClassDescr> classes = new HashMap<String, ClassDescr>(); private API() { this(new ArrayList<ClassDescr>()); } public API(List<ClassDescr> classList) { if (classList != null) { for (ClassDescr cls : classList) { addClass(cls); } } } public static API parseSigFile(String sigFileName, APIReader reader) throws IOException, FileFormatException { return parseSigFile(new File(sigFileName), reader); } public static API parseSigFile(File sigFile, APIReader reader) throws IOException, FileFormatException { API api = new API(); for (ClassDescr cls : reader.read(sigFile)) { api.addClass(cls); } return api; } public ClassDescr getClass(String name) { return classes.get(name); } public void addClass(ClassDescr cls) { if (cls != null) { classes.put(cls.name, cls); } } public SortedSet<String> getAllClassNames() { TreeSet<String> treeSet = new TreeSet<String>(); treeSet.addAll(classes.keySet()); return treeSet; } }
2,737
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
MemberDescr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/MemberDescr.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; /** * Class representing either class method or class field. * * @author Dmitry Fazunenko */ public class MemberDescr extends AbstractDescr implements Comparable { /** * Parent class */ private ClassDescr parent; /** * Signature of a member in VM representation format */ public final String signature; /** * Flag indicating whether the member is method or field. */ public final boolean isMethod; /** * Create an instance of MemberDescr * * @param name * @param signature * @param access */ public MemberDescr(String name, String signature) { super(name); this.signature = signature; this.isMethod = signature.indexOf('(') >= 0; } public void setParent(ClassDescr parent) { this.parent = parent; } public ClassDescr getParent() { return parent; } private String toCompareString() { return isMethod + name + signature; } public int compareTo(Object o) { MemberDescr mem = (MemberDescr) o; return toCompareString().compareTo(mem.toCompareString()); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof MemberDescr)) { return false; } return toCompareString().equals(((MemberDescr) obj).toCompareString()); } @Override public int hashCode() { return toCompareString().hashCode(); } }
2,723
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
ClassDescr.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/ClassDescr.java
/* * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; import java.util.ArrayList; import java.util.List; /** * Class representing an API class. * * @author Dmitry Fazunenko */ public class ClassDescr extends AbstractDescr { /** * List of class methods and fields */ public final List<MemberDescr> members = new ArrayList<>(); /** * Creates an instance of ClassDescr * * @param name - full qualified class name */ public ClassDescr(String name) { super(name); } /** * Adds a new member to the class. Does nothing if mem is null or the class * already contains this member. * * @param mem */ public void addMember(MemberDescr mem) { if (mem != null && !members.contains(mem)) { mem.setParent(this); members.add(mem); } } /** * Removes a member from the class * * @param mem */ public void removeMember(MemberDescr mem) { if (mem != null) { members.remove(mem); } } /** * Finds a class method by its name and signature. * * @param name method's name * @param signature method's signature * @return found member or null. */ public MemberDescr findMethod(String name, String signature) { for (MemberDescr mem : members) { if (mem.isMethod && mem.name.equals(name) && mem.signature.equals(signature)) { return mem; } } return null; } /** * Finds a class method by its name. * * @param name field name * @return found member or null. */ public MemberDescr findField(String name) { for (MemberDescr mem : members) { if (!mem.isMethod && mem.name.equals(name)) { return mem; } } return null; } }
3,091
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
APIReader.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/APIReader.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; import java.io.File; import java.io.IOException; import java.util.List; /** * Interface for parsing sig files * * @author Dmitry Fazunenko */ public interface APIReader { /** * Reads passed file. * * @param sigFile - file to parse * @return list of classes read * @throws IOException - in case of i/o problem * @throws FileFormatException - in case incorrect file format */ public List<ClassDescr> read(File sigFile) throws IOException, FileFormatException; }
1,759
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
APIWriter.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/api/APIWriter.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.api; /** * Interface for creating sig files * * @author Dmitry Fazunenko */ public interface APIWriter { /** * Writes the entire API * * @param api */ public void writeAPI(API api); /** * Writes the ClassDescr * * @param cls */ public void writeClassDescr(ClassDescr cls); /** * Writes comment * * @param comment */ public void writeComment(String comment); public void close(); }
1,710
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
package-info.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/package-info.java
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * <p> Package containing product structure information as well as it's coverage * data. </p> */ package com.sun.tdk.jcov.instrument;
1,347
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
LocationConcrete.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/LocationConcrete.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * LocationConcrete * * @author Robert Field */ public abstract class LocationConcrete extends LocationAbstract { private int startBCI; private int endBCI; /** * Creates a new instance of LocationAbstract */ protected LocationConcrete(int rootId, int startBCI, int endBCI) { super(rootId); this.startBCI = startBCI; this.endBCI = endBCI; } LocationConcrete(int rootId, int bci) { this(rootId, bci, bci); } LocationConcrete(int rootId) { this(rootId, -1, -1); } public void setStartBCI(int startBCI) { this.startBCI = startBCI; } public void setEndBCI(int endBCI) { this.endBCI = endBCI; } public int startBCI() { return startBCI; } public int endBCI() { return endBCI; } public boolean isSameLocation(LocationConcrete other) { return startBCI == other.startBCI && endBCI == other.endBCI && kind().equals(other.kind()); } void writeObject(DataOutput out) throws IOException { out.writeShort(startBCI); out.writeShort(endBCI); } LocationConcrete(int rootId, DataInput in) throws IOException { super(rootId); startBCI = in.readShort(); endBCI = in.readShort(); } }
2,633
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z
DataAbstract.java
/FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataAbstract.java
/* * Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tdk.jcov.instrument; import com.sun.tdk.jcov.data.FileFormatException; import com.sun.tdk.jcov.instrument.asm.ASMModifiers; import com.sun.tdk.jcov.instrument.reader.Reader; import com.sun.tdk.jcov.instrument.reader.ReaderFactory; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * DataAbstract * * * @author Robert Field */ public abstract class DataAbstract { final private static Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>()); static volatile int invokeCount = 0; public static int getInvokeID(String owner, String name, String descr) { String sig = owner + "." + name + descr; synchronized (map) { Integer id = map.get(sig); if (id != null) { return id; } //return 0; id = invokeCount++; map.put(sig, id); return id; } } //never used public static void addID(String className, String name, String descr, int id) { String sig = className + "." + name + descr; map.put(sig, id); } protected int rootId; DataAbstract(int rootId) { this.rootId = rootId; } /** * @return DataRoot ID this Data object belongs to */ public int rootId() { return rootId; } /** * XML Generation. Not supposed to use outside. */ public abstract String kind(); void xmlTagOpen(XmlContext ctx, String tag) { ctx.indent(); ctx.print("<"); ctx.print(tag); xmlAttrs(ctx); ctx.println(">"); } void xmlTagClose(XmlContext ctx, String tag) { ctx.indent(); ctx.print("</"); ctx.print(tag); ctx.println(">"); } void xmlTagSingle(XmlContext ctx, String tag) { ctx.indent(); ctx.print("<"); ctx.print(tag); xmlAttrs(ctx); ctx.println("/>"); } void xmlAttrs(XmlContext ctx) { } void xmlBody(XmlContext ctx) { } public static class LocationCoords { public int start; public int end; } public void xmlGen(XmlContext ctx) { xmlTagOpen(ctx, kind()); ctx.incIndent(); xmlBody(ctx); ctx.decIndent(); xmlTagClose(ctx, kind()); } void xmlGenBodiless(XmlContext ctx) { xmlTagSingle(ctx, kind()); } void xmlAccessFlags(XmlContext ctx, Modifiers access) { ctx.print(" " + XmlNames.FLAGS + "='"); String[] flags = accessFlags(access); for (String fl : flags) { ctx.print(" " + fl); } ctx.print("'"); } /** * XML reading. Not supposed to use outside. */ public void readDataFrom() throws FileFormatException { ReaderFactory rf = DataRoot.getInstance(rootId).getReaderFactory(); Reader r = rf.getReaderFor(this); r.readData(this); } String[] accessFlags(Modifiers access) { List<String> flags = new ArrayList<String>(); if (access.isPublic()) { flags.add(XmlNames.A_PUBLIC); } if (access.isPrivate()) { flags.add(XmlNames.A_PRIVATE); } if (access.isProtected()) { flags.add(XmlNames.A_PROTECTED); } if (access.isStatic()) { flags.add(XmlNames.A_STATIC); } if (access.isFinal()) { flags.add(XmlNames.A_FINAL); } if (access.isSynchronized()) { flags.add(XmlNames.A_SYNCHRONIZED); } if (access.isVolatile()) { flags.add(XmlNames.A_VOLATILE); } if (access.isBridge()) { flags.add(XmlNames.A_BRIDGE); } if (access.isVarargs()) { flags.add(XmlNames.A_VARARGS); } if (access.isTransient()) { flags.add(XmlNames.A_TRANSIENT); } if (access.isNative()) { flags.add(XmlNames.A_NATIVE); } if (access.isInterface()) { flags.add(XmlNames.A_INTERFACE); } if (access.isAbstract()) { flags.add(XmlNames.A_ABSTRACT); } if (access.isStrict()) { flags.add(XmlNames.A_STRICT); } if (access.isAnnotation()) { flags.add(XmlNames.A_ANNOTATION); } if (access.isEnum()) { flags.add(XmlNames.A_ENUM); } if (access.isSynthetic()) { flags.add(XmlNames.A_SYNTHETIC); } return flags.isEmpty() ? new String[0] : flags.toArray(new String[flags.size()]); } public Modifiers access(String[] accessFlags) { return ASMModifiers.parse(accessFlags); } public String access(Modifiers access) { String res = ""; for (String s : accessFlags(access)) { res += " " + s; } res = res.length() > 0 ? res.substring(1) : res; return res; } protected DataRoot getDataRoot() { return DataRoot.getInstance(rootId); } static void writeString(DataOutput out, String s) throws IOException { if (s != null) { out.writeBoolean(true); out.writeUTF(s); } else { out.writeBoolean(false); } } static String readString(DataInput in) throws IOException { if (in.readBoolean()) { return in.readUTF(); } else { return null; } } static void writeStrings(DataOutput out, String[] strs) throws IOException { if (strs != null) { out.writeShort(strs.length); for (int i = 0; i < strs.length; ++i) { out.writeUTF(strs[i]); } } else { out.writeShort(Short.MAX_VALUE); } } static String[] readStrings(DataInput in) throws IOException { int len = in.readShort(); if (len != Short.MAX_VALUE) { String res[] = new String[len]; for (int i = 0; i < len; ++i) { res[i] = in.readUTF(); } return res; } else { return null; } } }
7,587
Java
.java
openjdk/jcov
16
12
0
2019-05-15T06:46:03Z
2024-04-16T17:20:11Z