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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MapHelper.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/util/MapHelper.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.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
/**
* For now, there is no way to map counts on legacy data file, because ther is
* no info about item IDs.
*
* @author Sergey Borodin
*/
public class MapHelper {
public static void mapCounts(String outputFile, String templateFile,
long[] counts) throws Exception {
String template = new File(outputFile).exists()
? outputFile : templateFile;
map(outputFile, template, counts);
}
private static void map(String output, String templ, long[] counts) throws Exception {
if (output.equals(templ)) {
if (counts == null) {
return; // nothing to do - file already exists
}
String out_tmp = output + RuntimeUtils.genSuffix();
mapXMLFast(out_tmp, templ, counts);
// we need to close input stream and
// delete file "output" before renaming another one into it.
File f_out = new File(output);
f_out.delete();
new File(out_tmp).renameTo(f_out);
} else {
mapXMLFast(output, templ, counts);
}
}
/**
* The method assumes that templ is an XML with jcov data. This method
* provides update of this file without parsing templ into XML model. This
* methods just reads the given file line by line and modifies those lines
* which contains "id=...".
*
* <b>Note</b> this method is very sensitive to changes of XML format.
*
* @param result - output file to be created
* @param templ - file will be used as a template (it could be result.xml)
* @param counts - array of counts
*
* @throws Exception
*/
private static void mapXMLFast(String result, String templ, long[] counts) throws Exception {
checkTemplate(templ);
FileInputStream is = new FileInputStream(templ);
File outputFile = new File(result);
if (!outputFile.getAbsoluteFile().getParentFile().exists()) {
throw new Exception("Specified directory for output file doesn't exist - " + outputFile.getParentFile().getPath());
}
if (outputFile.exists() && !outputFile.canWrite()) {
throw new Exception("Can't write output file");
}
if (outputFile.exists() && !outputFile.canRead()) {
throw new Exception("Can't read output file");
}
FileOutputStream os = new FileOutputStream(outputFile, false);
BufferedReader r = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, Charset.defaultCharset()));
try {
String s = r.readLine();
while (s != null) {
int i = s.indexOf("id=");
if (i != -1 && counts != null) {
int id = 0;
long count = 0;
i += 4; //id="
int id_end = s.indexOf("\"", i);
id = Integer.parseInt(s.substring(i, id_end));
if (counts[id] == 0) {
pw.println(s); // nothing changed
} else if (s.indexOf("count", i) > 0) {
i = id_end + 9; //"_count="
String res = s.substring(0, i);
int count_end = s.indexOf("\"", i);
count = Long.parseLong(s.substring(i, count_end));
count += counts[id];
res += count;
res += s.substring(count_end);
pw.println(res);
} else {
String res = s.substring(0, id_end + 1) + " count=\"" + counts[id] + "\"" + s.substring(id_end + 1);
pw.println(res);
}
} else {
pw.println(s);
}
s = r.readLine();
}
pw.flush();
} finally {
pw.close();
r.close();
is.close();
os.close();
}
}
/**
* Performs some basic checks that given template is a jcov file. Throws
* exception in case of error found.
*
* @param templ - template file name
*/
private static void checkTemplate(String templ) throws Exception {
FileInputStream is = new FileInputStream(templ);
BufferedReader r = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
try {
String s = r.readLine();
if (!"<?xml version='1.0' encoding='UTF-8'?>".equalsIgnoreCase(s)) {
throw new RuntimeException(templ + " doesn't seem to be an XML file");
}
s = r.readLine();
while (s != null && s.trim().length() == 0) {
s = r.readLine();
}
if (s == null) {
throw new RuntimeException(templ + " an empty XML file");
}
if (!s.startsWith("<coverage")) {
throw new RuntimeException(templ + " not a jcov coverage file");
}
} finally {
r.close();
is.close();
}
}
}
| 6,741 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
AddToProduct.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/util/AddToProduct.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.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.CodeSource;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipException;
/**
* AddToProduct - is the class responsible for injecting content of a
* jcov_xxx_server.jar into a user application jar file. This class will be
* executed when the following command is given:
* <pre>
* java -jar jcov_xxx_saver.jar myProduct.jar
* </pre>
*
* @author Alexey Fedorchenko
*/
public class AddToProduct {
// inJars is set of jar files to modified
private static Set inJars;
// jarEntryNames is a set to check and inform user about entries duplication
private static Set jarEntryNames;
private static final String THIS_CLASS = AddToProduct.class.getName().replace('.', '/') + ".class";
public static void main(String[] args) {
CodeSource src = AddToProduct.class.getProtectionDomain().getCodeSource();
if (src == null) {
System.err.println("Can't find main file in specified source");
return;
}
URL location = src.getLocation();
JarFile currentJar = null;
try {
currentJar = new JarFile(location.getFile());
} catch (ZipException ze) {
System.err.println("Can't read jar file to add it in products jars");
return;
} catch (IOException ioe) {
System.err.println("Can't use this functionality not from jar file");
return;
}
if (args.length == 0) {
System.err.println("Please specify products jars to add this jar in");
return;
}
inJars = new HashSet<JarFile>();
for (int i = 0; i < args.length; i++) {
try {
inJars.add(new JarFile(args[i]));
} catch (SecurityException ze) {
System.out.println("Access to the specified product jar: " + args[i] + " is denied");
} catch (IOException ioe) {
System.out.println("Product jar " + args[i] + " doesn't exist");
}
}
if (inJars.isEmpty()) {
System.err.println("Please specify products jars to add this jar in");
return;
}
Iterator itr = inJars.iterator();
while (itr.hasNext()) {
JarFile product = (JarFile) itr.next();
File archiveFile = new File(product.getName() + "_temp");
try {
FileOutputStream stream = new FileOutputStream(archiveFile);
JarOutputStream fos = new JarOutputStream(stream, product.getManifest());
jarEntryNames = new HashSet();
writeEntriesToJar(product.entries(), fos, product);
writeEntriesToJar(currentJar.entries(), fos, currentJar);
fos.flush();
fos.close();
File origFile = new File(product.getName());
if (!origFile.delete()) {
System.out.println("Can not delete product jar: " + product.getName() + " the result is in the " + product.getName() + "_temp");
} else {
archiveFile.renameTo(origFile);
}
} catch (IOException ioe) {
System.out.println("IOException while processing product jar file: " + product.getName() + " " + ioe);
}
}
}
private static void writeEntriesToJar(Enumeration<JarEntry> en, JarOutputStream fos, JarFile outJar) throws IOException {
while (en.hasMoreElements()) {
JarEntry element = en.nextElement();
if (!element.getName().equals("META-INF/")
&& !element.getName().equals("META-INF/MANIFEST.MF")
&& !element.getName().equals(THIS_CLASS)) {
if (!jarEntryNames.add(element.getName())) {
System.err.println("Duplicate jar entry [" + element.getName() + "]");
continue;
}
fos.putNextEntry(element);
InputStream filereader = outJar.getInputStream(element);
final int buffersize = 1024;
byte buffer[] = new byte[buffersize];
int readcount = 0;
while ((readcount = filereader.read(buffer, 0, buffersize)) >= 0) {
if (readcount > 0) {
fos.write(buffer, 0, readcount);
}
}
fos.closeEntry();
filereader.close();
}
}
}
}
| 6,076 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
NaturalComparator.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/util/NaturalComparator.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.util;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
/**
* Class that implements comparison of String in natural order: a1, a2, ...,
* a10, a11
*
* @author Dmitry Fazunenko
*/
public final class NaturalComparator implements Comparator<String> {
private NaturalComparator() {
}
public static final NaturalComparator INSTANCE = new NaturalComparator();
private final HashMap<String, NaturalComparator.CompoundString> hash = new HashMap<String, NaturalComparator.CompoundString>();
/**
* {@inheritDoc} <p> Null values are allowed. In which case returns a
* positive integer, negative integer, or zero as the first argument is
* null, second argument is null or both are null.
*/
@Override
public int compare(String s1, String s2) {
if (s1 != null && s2 != null) {
return getCS(s1).compareTo(getCS(s2));
} else if (s1 != null) {
return -1;
} else if (s2 != null) {
return 1;
} else {
return 0;
}
}
private NaturalComparator.CompoundString getCS(String s) {
NaturalComparator.CompoundString cs = hash.get(s);
if (cs == null) {
cs = new NaturalComparator.CompoundString(s);
hash.put(s, cs);
}
return cs;
}
/**
* class representing strings which are mix of digits and chars
*/
static class CompoundString implements Comparable<NaturalComparator.CompoundString> {
ArrayList<String> chars;
ArrayList<Long> nums;
CompoundString(String s) {
chars = new ArrayList<String>();
nums = new ArrayList<Long>();
final int len = s.length();
int prev = 0;
int pos = 0;
while (true) {
// looking for chars
while (pos < len && !Character.isDigit(s.charAt(pos))) {
pos++;
}
if (pos == len) {
chars.add(s.substring(prev));
break;
}
// digit found!
chars.add(s.substring(prev, pos));
prev = pos;
pos++;
while (pos < len && Character.isDigit(s.charAt(pos))) {
pos++;
}
if (pos == len) {
nums.add(Long.parseLong(s.substring(prev)));
break;
}
nums.add(Long.parseLong(s.substring(prev, pos)));
prev = pos;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.size(); i++) {
sb.append(chars.get(i));
if (i < nums.size()) {
sb.append(nums.get(i));
}
}
return sb.toString();
}
@Override
public int compareTo(NaturalComparator.CompoundString s2) {
int k = 0;
while (true) {
// compare char part k
if (k < chars.size() && k < s2.chars.size()) {
int res = chars.get(k).compareTo(s2.chars.get(k));
if (res != 0) {
return res;
}
} else {
// one str is shorter than another
return chars.size() - s2.chars.size();
}
// compare numbs part k
if (k < nums.size() && k < s2.nums.size()) {
int res = nums.get(k).compareTo(s2.nums.get(k));
if (res != 0) {
return res;
}
} else {
// one str is shorter than another
return nums.size() - s2.nums.size();
}
k++;
}
}
}
}
| 5,253 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DebugUtils.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/util/DebugUtils.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.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
*
* @author Sergey Borodin
*/
public class DebugUtils {
public static final java.util.logging.Logger log;
static {
Utils.initLogger();
log = Logger.getLogger("com.sun.tdk.jcov");
}
public static void flushInstrumentedClass(String flushPath,
String className, byte[] data) {
File root = new File(flushPath);
String path = root.getAbsolutePath() + File.separator + className + ".class";
File classFile = prepareFile(path);
try {
FileOutputStream fos = new FileOutputStream(classFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
public static byte[] readClass(String className, String flushPath) {
File root = new File(flushPath);
String path = root.getAbsolutePath() + File.separator + className + ".class";
File f = new File(path);
int classLength = (int) f.length();
FileInputStream fis;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
// logger.log(Level.SEVERE, "File not found - skipped", e);
return null;
}
try {
byte classBuf[] = new byte[classLength];
fis.read(classBuf, 0, classLength); // read in class data
fis.close();
return classBuf;
} catch (IOException e) {
// logger.log(Level.SEVERE, "Error reading '" + fname + "' - skipped", e);
return null;
}
}
public static PrintWriter getPrintWriter(String className, String flushPath) {
File root = new File(flushPath);
String path = root.getAbsolutePath() + File.separator + className + ".java";
File classFile = prepareFile(path);
try {
return new PrintWriter(new OutputStreamWriter(new FileOutputStream(classFile), Charset.defaultCharset()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void attachLogger() {
try {
FileHandler fh = new FileHandler("jcov.log");
fh.setFormatter(new SimpleFormatter());
log.addHandler(fh);
log.setLevel(Level.ALL);
} catch (Exception e) {
log.warning("File " + "jcov.log" + " could not be opened");
}
}
private static File prepareFile(String path) {
File classFile = new File(path);
if (!classFile.exists()) {
try {
File parent = classFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
classFile.createNewFile();
} catch (IOException e) {
System.out.println("Can't create file: " + path);
System.out.println(e.getMessage());
}
}
return classFile;
}
}
| 4,656 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
RuntimeUtils.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/util/RuntimeUtils.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.util;
import java.util.Random;
/**
* This class implements miscellaneous utilities, necessary for Jcov runtime
*
* @author Sergey Borodin
*/
public class RuntimeUtils {
private static Random random;
public static String genSuffix() {
if (random == null) {
random = new Random();
}
StringBuilder sb = new StringBuilder(".");
sb.append(Integer.toHexString(random.nextInt()));
sb.append('-');
sb.append(Integer.toHexString(random.nextInt()).substring(4));
sb.append('-');
sb.append(Integer.toHexString(random.nextInt()).substring(4));
sb.append('-');
sb.append(Integer.toHexString(random.nextInt()).substring(4));
sb.append('-');
sb.append(Integer.toHexString(random.nextInt()));
sb.append(Integer.toHexString(random.nextInt()).substring(4));
return sb.toString();
}
/**
* @return number of bit quadruples necessary to accomodate
* <bits_total> bits
*/
public static int halfBytesRequiredFor(int bits_total) {
return (bits_total + 3) / 4;
}
}
| 2,360 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Utils.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/util/Utils.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.util;
import com.sun.tdk.jcov.runtime.PropertyFinder;
import com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException;
import com.sun.tdk.jcov.tools.LoggingFormatter;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.UnknownHostException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.logging.Formatter;
import java.util.logging.*;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import static java.lang.String.format;
/**
* This class implements miscellaneous utilities, necessary for Jcov
*/
public final class Utils {
private static Handler loggerHandler = null;
private final static int ASCII_CHARS_TOTAL = 128;
private static char[] buf = new char[32];
private static File[] fileSysRoots;
private static boolean fileSysRootsGot = false;
/**
* Represent digits in a big-radix numeric system
*/
final static char[] chars = {
'q', 'w', 'r', 't', 'y', 'u', 'i', 'o', 'p', 's',
'g', 'h', 'j', 'k', 'l', 'z', 'x', 'v', 'n', 'm',
'Q', 'W', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'S',
'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'V', 'N', 'M',
'!', '@', '#', '$', '%', '^', '&', '*', '(', ')',
'_', '+', '|', '~', '-', '=', '\\', '[', ']', '{',
'}', ';', '\'', ':', '\"', ',', '.', '/', '<', '>', '?'
};
public final static int radix = chars.length;
static int[] map = new int[ASCII_CHARS_TOTAL];
private static final Logger logger = Logger.getLogger("com.sun.tdk.jcov");
static {
for (int i = 0; i < radix; i++) {
map[chars[i]] = i;
}
}
public enum FILE_TYPE {
ZIP, JAR, WAR, CLASS;
public String getExtension() {
return "." + this.name().toLowerCase();
}
public static boolean hasExtension(String fileName, FILE_TYPE... fTypes) {
for (FILE_TYPE ftype : fTypes) {
if (fileName.endsWith(ftype.getExtension())) {
return true;
}
}
return false;
}
}
/**
* It's possible to set custom classfile extension by "clext" property (through jcov.clext system property, JCOV_CLEXT
* environment variable and so on) - for example "clazz:.klass".
*/
public static final List<String> CUSTOM_CLASS_FILE_EXTENSIONS =
Arrays.asList(PropertyFinder.findValue("clext", "").split(":").clone());
public static boolean isClassFile(String fileName) {
if (FILE_TYPE.hasExtension(fileName, FILE_TYPE.CLASS)) {
return true;
}
return CUSTOM_CLASS_FILE_EXTENSIONS.stream().anyMatch(ext -> fileName.endsWith(ext));
}
public final static int VER1_6 = 160; // 1.6
public final static int VER1_7 = 160; // 1.7
public final static int VER1_8 = 160; // 1.8
public final static int VER9 = 900; // 9
public final static int VER10 = 1000; // 10
public final static int VER17 = 1700; // 17
public final static int VER18 = 1800; // 18
public final static int VER19 = 1900; // 19
public final static int VER20 = 2000; // 20
private static int javaVersion = -1;
/**
* @return JVM version: java.version * 100
*/
public static int getJavaVersion() {
if (javaVersion == -1) {
String ver = System.getProperty("java.version");
for (int i = 1; i < 30; i++) {
if (ver.startsWith(format((i <= 8) ? "1.%d" : "%d", i))) {
return (i <= 8) ? 100 + i * 10 : i * 100;
} else if(ver.startsWith("%d", i)) {
return i* 100;
}
}
javaVersion = VER9;
}
return javaVersion;
}
/**
* Checks if given array's length is not less than given length.
*
* @param buf array to be checked
* @param length minimum required length
* @param copy_old_buf whether to copy the contents of given buf to newly
* created array, if minimum length requirement is not met
* @return buf if the buf length is ok, newly created array of length +
* length/2 size otherwise
*/
public static byte[] ensureBufLength(byte[] buf, int length, boolean copy_old_buf) {
if (buf.length >= length) {
return buf;
}
byte[] tmp_buf = new byte[length + length / 2];
if (copy_old_buf) {
System.arraycopy(buf, 0, tmp_buf, 0, buf.length);
}
return tmp_buf;
}
/**
* Constructs 'relative' path for given two paths. For example, for
* "/aaa/bbb/ccc/ddd" and "/aaa/xxx/yyy" relative path would be
* "../../../xxx/yyy". NOTE: this code is probably system dependent
*
* @param ref_path reference path
* @param tst_path path to construct relative form for
* @return constructed relative path
*/
public static String getRelativePath(String ref_path, String tst_path) {
String[] ref_arr = split(ref_path, File.separatorChar);
String[] tst_arr = split(tst_path, File.separatorChar);
int last_match_ind = -1;
String res = "";
for (int i = 0; i < ref_arr.length && i < tst_arr.length; i++) {
if (!ref_arr[i].equals(tst_arr[i])) {
break;
}
last_match_ind = i;
}
for (int i = 0; i < ref_arr.length - last_match_ind - 1; i++) {
res += ".." + File.separator;
}
for (int i = last_match_ind + 1; i < tst_arr.length; i++) {
res += tst_arr[i] + File.separator;
}
if (res.equals("")) {
res = "." + File.separator;
}
return res.substring(0, res.length() - 1);
}
private static File[] getFileSystemRoots() {
if (!fileSysRootsGot) {
fileSysRoots = File.listRoots();
fileSysRootsGot = true;
}
return fileSysRoots;
}
public static String getRelativePath(File ref_file, File tst_file) {
File[] roots = getFileSystemRoots();
String ref_path = null;
String tst_path = null;
try {
ref_path = ref_file.getCanonicalPath();
tst_path = tst_file.getCanonicalPath();
} catch (IOException e) {
ref_path = ref_file.getAbsolutePath();
tst_path = tst_file.getAbsolutePath();
}
if (roots != null) {
for (int i = 0; i < roots.length; i++) {
String root = roots[i].getAbsolutePath();
if (ref_path.startsWith(root) != tst_path.startsWith(root)) {
return null;
}
}
}
return getRelativePath(ref_path, tst_path);
}
public static String basename(String path) {
int i1 = path.lastIndexOf(File.separatorChar);
int i2 = path.lastIndexOf("/");
int i = i1 > i2 ? i1 : i2;
if (i == -1) {
return path;
}
return path.substring(i + 1);
}
public static String substitute(String s, String from, String to) {
if (s == null || from == null || s.equals("") || from.equals("")) {
return s;
}
String res = "";
int ind = s.indexOf(from);
while (ind >= 0) {
res += s.substring(0, ind);
res += to;
s = s.substring(ind + 1);
ind = s.indexOf(from);
}
res += s;
return res;
}
public static String[] split(String s, char delim) {
String str = s;
if (str == null) {
return null;
}
Vector v = new Vector();
for (int ind = str.indexOf(delim); ind >= 0; ind = str.indexOf(delim)) {
if (ind > 0) {
v.addElement(str.substring(0, ind));
}
str = str.substring(ind + 1);
}
if (str.length() > 0) {
v.addElement(str);
}
String[] res = new String[v.size()];
v.copyInto(res);
return res;
}
public static String[] getSourcePaths(String s) {
String[] source_paths = split(s, File.pathSeparatorChar);
for (int i = 0; i < source_paths.length; i++) {
String path = source_paths[i];
if (!path.equals("") && !(path.endsWith("/") && !path.endsWith(File.separator))) {
path += File.separator;
source_paths[i] = path;
}
}
return source_paths;
}
/**
* Calculates string representation of given value in a numeric system,
* where digits are all characters from the chars array field, and the radix
* is chars.length, and writes it to given String buffer starting from ind.
*
* @param val value to convert
* @param sbuf buffer where the representation of the value is written
* @param ind starting index in sbuf
* @return ind + length of the string representation
* @see #chars
*/
public static int convert2BigRadix(int val, StringBuffer sbuf, int ind) {
int i = 0;
while (val > 0) {
buf[i++] = chars[val % radix];
val = val / radix;
}
for (int j = 1; j <= i; j++) {
sbuf.setCharAt(ind + j - 1, buf[i - j]);
}
return ind + i;
}
/**
* @return value of the big-radix numeric system digit
*/
public static int convert2Int(char digit) {
return map[digit];
}
/**
* @return value of the hex digit
*/
public static byte hexChar2Int(char ch) {
boolean f1 = ch >= '0' && ch <= '9';
boolean f2 = ch >= 'A' && ch <= 'F';
boolean f3 = ch >= 'a' && ch <= 'f';
if (!(f1 || f2 || f3)) {
return -1;
}
if (f1) {
return (byte) (ch - '0');
} else if (f2) {
return (byte) (10 + ch - 'A');
} else {
return (byte) (10 + ch - 'a');
}
}
/**
* @return hexadecimal digit with given value
*/
public static char int2HexChar(int val) {
if (val >= 0 && val < 10) {
return (char) (val + '0');
}
if (val >= 10 && val < 16) {
return (char) (val + 'a' - 10);
}
return (char) -1;
}
/**
* @return <base> in power of <power>
*/
public static int pow(int base, int power) {
int i, res = 1;
for (i = 0; i < power; i++) {
res *= base;
}
return res;
}
/**
* Writes 4 lower bits of the <half_byte> to <dst> at
* <ind>. ind = 1 corresponds to the 4 high bits in dst[0].
*/
public static void writeHalfByteAt(byte half_byte, int ind, byte[] dst) {
int i = ind / 2;
byte val;
if (ind % 2 == 0) {
val = (byte) (dst[i] & 0xF0);
dst[i] = (byte) (val | half_byte);
} else {
val = (byte) (dst[i] & 0xF);
dst[i] = (byte) (val | (half_byte << 4));
}
}
/**
* @return 4-bit value from <src>{<ind>} (<src> treated as
* an array of 4-bit values)
*/
public static byte getHalfByteAt(int ind, byte[] src) {
return (byte) ((ind % 2 == 0) ? src[ind / 2] & 0xF : (src[ind / 2] >>> 4) & 0xF);
}
/**
* @return 4-bit value from <src> at <ind>
*/
public static byte getHalfByteAt(int ind, byte src) {
return (byte) ((ind % 2 == 0) ? src & 0xF : (src >>> 4) & 0xF);
}
/**
* @return number of bit quadruples necessary to accomodate
* <bits_total> bits
*/
public static int halfBytesRequiredFor(int bits_total) {
return (bits_total + 3) / 4;
}
/**
* Compares 2 String arrays
*
* @return -1 if arr1 < arr2 0 if arr1 == arr2 1 if arr1 > arr2
*/
public static int compareStringArrays(String[] arr1, String[] arr2) {
boolean b1 = arr1 == null || arr1.length == 0;
boolean b2 = arr2 == null || arr2.length == 0;
if (b1 == true && b2 == true) {
return 0;
}
if (b1 == true && b2 == false) {
return -1;
}
if (b1 == false && b2 == true) {
return 1;
}
int min_len = arr1.length > arr2.length ? arr2.length : arr1.length;
for (int i = 0; i < min_len; i++) {
int res = arr1[i].compareTo(arr2[i]);
if (res != 0) {
return res;
}
}
return arr1.length > arr2.length ? 1 : -1;
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T, U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object) newType == (Object) Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
/**
* The same as
* <code>readLines(fileName, -1, -1)</code>
*/
public static String[] readLines(String fileName) throws IOException {
return readLines(fileName, -1, -1);
}
/**
* Reads the text files ignoring leading and tailing line spaces, and empty
* lines.
*
* @param fileName file to read
* @param start number of line to start from. -1 means start from 0.
* @param end number of line to end with. -1 means read all lines till the
* end.
* @return read lines. Never returns null.
* @throws java.io.IOException - if file does not exist, or i/o errors
* happened
*/
public static String[] readLines(String fileName, int start, int end) throws IOException {
ArrayList lst = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.defaultCharset()));
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
if ((start == -1 || i >= start)
&& (end == -1 || i <= end)) {//to check range
line = line.trim();
if (line.length() > 0 /*&& !line.startsWith("#")*/) {
lst.add(line);
}
}
i++;
}
reader.close();
return (String[]) lst.toArray(new String[0]);
}
/**
* Writes the lines into the file
*
* @param fileName file to read
* @throws java.io.IOException - if i/o errors happened
*/
public static void writeLines(String fileName, String[] lines) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
fileName), Charset.defaultCharset()));
for (int i = 0; i < lines.length; i++) {
writer.write(lines[i]);
writer.newLine();
}
writer.flush();
writer.close();
}
public static void copyFile(File from, File to) throws FileNotFoundException, IOException {
FileChannel infc = null;
FileChannel outfc = null;
try {
infc = new FileInputStream(from).getChannel();
outfc = new FileOutputStream(to).getChannel();
long transfered = infc.transferTo(0, from.length(), outfc);
while (transfered < from.length()) {
transfered = infc.transferTo(transfered, from.length(), outfc);
}
} finally {
try {
if (infc != null) {
infc.close();
}
} catch (Exception ignore) {
}
try {
if (outfc != null) {
outfc.close();
}
} catch (Exception ignore) {
}
}
to.setExecutable(from.canExecute());
to.setReadable(from.canRead());
to.setWritable(from.canWrite());
}
/**
* Class of two int fields
*/
public static class Pair {
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int a;
public int b;
}
public static void addToClasspath(String[] sourcePaths) {
if (ClassLoader.getSystemClassLoader() instanceof URLClassLoader) {
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sClass = URLClassLoader.class;
try {
Method method = sClass.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
URL[] urls = new URL[sourcePaths.length];
for (int i = 0; i < sourcePaths.length; i++) {
urls[i] = new File(sourcePaths[i]).toURI().toURL();
method.invoke(systemClassLoader, new Object[]{urls[i]});
}
} catch (Throwable t) {
t.printStackTrace();
}
} else {
// Java 9+
String[] classpath = System.getProperty("java.class.path").split(File.pathSeparator);
// eliminate paths that could be missed in classpath
//1. For class files in a(n) (un)named package, the class path ends
// with the directory that contains the class files. (should be in classpath)
//2. jar,zip,war should be a part of classpath (should be in classpath)
List<String> paths = new ArrayList<>();
Arrays.stream(sourcePaths).
forEach(
path -> {
File file = Paths.get(path).toFile();
if (file.isDirectory()) {
if (!file.getName().equalsIgnoreCase("jmods")) {
paths.add(path);
}
} else if (file.isFile()) {
if (FILE_TYPE.hasExtension(path, FILE_TYPE.ZIP, FILE_TYPE.JAR, FILE_TYPE.WAR)) {
paths.add(path);
}
}
}
);
for (String path : paths) {
if (!Arrays.stream(classpath).anyMatch(cp -> cp.equals(path))) {
String cps = paths.stream().collect(Collectors.joining("#"));
String s1 = cps.replaceAll("#", ":");
String s2 = cps.replaceAll("#", " ");
System.err.format("Warning: Add input source(s) to the classpath: -cp jcov.jar:%s%n" +
"Example: java -cp jcov.jar:%s ToolName -t <template> -o <output> %s%n",
s1, s1, s2);
break;
}
}
}
}
/**
* Adds all classes and jars from specified directory to classpath
*
* @param directory - directory to find all jars and classes
*/
public static void addToClasspath(File directory) {
if (directory.exists() && directory.isDirectory()) {
ArrayList<String> classes = new ArrayList<>();
getClassesAndJars(directory, classes);
Utils.addToClasspath(classes.toArray(new String[]{}));
}
}
private static void getClassesAndJars(File dir, List<String> classes) {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
getClassesAndJars(f, classes);
} else {
if (FILE_TYPE.hasExtension(f.getAbsolutePath(), FILE_TYPE.JAR, FILE_TYPE.CLASS)) {
classes.add(f.getAbsolutePath());
}
}
}
}
public static void setLoggerHandler(Handler loggerHandler) {
loggerHandler.setFormatter(LoggerHandlerDelegator.formatter);
if (Utils.loggerHandler != null) {
loggerHandler.setLevel(Utils.loggerHandler.getLevel());
}
Utils.loggerHandler = loggerHandler;
}
public static void setLoggingLevel(Level level) {
logger.setLevel(level);
loggerHandler.setLevel(level);
}
public static void setLoggingLevel(String levelStr) {
Level level;
levelStr = levelStr.toUpperCase();
if ("VERBOSE".equals(levelStr) || "V".equals(levelStr)) {
level = Level.INFO;
} else if ("QUIET".equals(levelStr) || "Q".equals(levelStr)) {
level = Level.OFF;
} else {
level = Level.parse(levelStr);
}
setLoggingLevel(level);
}
public static class LoggerHandlerDelegator extends Handler {
private static LoggingFormatter formatter = new LoggingFormatter();
@Override
public Formatter getFormatter() {
return formatter;
}
@Override
public synchronized void setLevel(Level newLevel) throws SecurityException {
Utils.loggerHandler.setLevel(newLevel);
}
@Override
public void publish(LogRecord record) {
Utils.loggerHandler.publish(record);
}
@Override
public void flush() {
Utils.loggerHandler.flush();
}
@Override
public void close() throws SecurityException {
Utils.loggerHandler.close();
}
}
public static void initLogger() {
if (loggerHandler == null) {
setLoggerHandler(new ConsoleHandler());
}
if (System.getProperty("java.util.logging.config.file") == null) {
try (InputStream in = Utils.class.getResourceAsStream("/com/sun/tdk/jcov/logging.properties")) {
if (ClassLoader.getSystemClassLoader().equals(Utils.class.getClassLoader())) {
LogManager.getLogManager().readConfiguration(in);
} else {
LogManager.getLogManager().reset();
}
} catch (Exception ignore) {
}
}
}
public static void initLogger(String propfile) {
if (System.getProperty("java.util.logging.config.file") == null) {
System.setProperty("java.util.logging.config.file", propfile);
try (InputStream in = Utils.class.getResourceAsStream(propfile)) {
LogManager.getLogManager().readConfiguration(in);
} catch (Exception ignore) {
}
}
}
/**
* <p> Convert JVM type notation (as described in the JVM II 4.3.2, p.100)
* to JLS type notation : </p> <ul> <li/>[<s> -> <s>[] <s>
* is converted recursively <li/>L<s>; -> <s> characters '/' are
* replaced by '.' in <s> <li/>B -> byte <li/>C -> char <li/>D ->
* double <li/>F -> float <li/>I -> int <li/>J -> long <li/>S -> short
* <li/>Z -> boolean <li/>V -> void valid only in method return type </ul>
*
* @param s VM signature string to convert
* @return JLS signature string
*/
public static String convertVMType(String s) {
return getTypeName(s.replace('/', '.'));
}
/**
* @param typeName
* @return convert JVM type to JLS notation (including arrays and links)
*/
public static String getTypeName(String typeName) {
StringBuilder sb = new StringBuilder();
int dims = 0;
while (typeName.charAt(dims) == '[') {
dims++;
}
String type;
if (typeName.charAt(dims) == 'L') {
type = typeName.substring(dims + 1, typeName.length() - 1);
} else {
type = PrimitiveTypes.getPrimitiveType(typeName.charAt(dims));
}
sb.append(type);
for (int i = 0; i < dims; ++i) {
sb.append("[]");
}
return sb.toString();
}
static enum PrimitiveTypes {
BOOLEAN('Z', "boolean"),
VOID('V', "void"),
INT('I', "int"),
LONG('J', "long"),
CHAR('C', "char"),
BYTE('B', "byte"),
DOUBLE('D', "double"),
SHORT('S', "short"),
FLOAT('F', "float");
private char VMSig;
private String JLS;
private PrimitiveTypes(char VMSig, String JLS) {
this.VMSig = VMSig;
this.JLS = JLS;
}
public static String getPrimitiveType(char c) {
for (PrimitiveTypes type : PrimitiveTypes.values()) {
if (type.VMSig == c) {
return type.JLS;
}
}
return null;
}
public static Character getPrimitiveType(String str) {
for (PrimitiveTypes type : PrimitiveTypes.values()) {
if (type.JLS.equals(str)) {
return type.VMSig;
}
}
return null;
}
}
/**
* Convert JVM method signature to JLS format
*
* @param methName
* @param VMsig
* @return formatted method signature (ret name(arg1,arg2,arg3))
*/
public static String convertVMtoJLS(String methName, String VMsig) {
Matcher m = java.util.regex.Pattern.compile("\\(([^\\)]*)\\)(.*)").matcher(VMsig);
if (m.matches()) {
return format("%s %s(%s)", convertVMType(m.group(2)), methName, getArgs(m.group(1)));
} else {
return methName + " " + VMsig; // some problem occured
}
}
private static String getArgs(String descr) throws IllegalArgumentException {
if (descr.equals("")) {
return descr;
}
int pos = 0;
int lastPos = descr.length();
String type;
StringBuilder args = new StringBuilder();
int dims = 0;
while (pos < lastPos) {
char ch = descr.charAt(pos);
if (ch == 'L') {
int delimPos = descr.indexOf(';', pos);
if (delimPos == -1) {
delimPos = lastPos;
}
type = convertVMType(descr.substring(pos, delimPos + 1));
pos = delimPos + 1;
} else if (ch == '[') {
dims++;
pos++;
continue;
} else {
type = PrimitiveTypes.getPrimitiveType(ch);
pos++;
}
args.append(type);
for (int i = 0; i < dims; ++i) {
args.append("[]");
}
dims = 0;
if (pos < lastPos) {
args.append(',');
}
}
return args.toString();
}
public static Pattern[] concatFilters(String[] includes, String[] excludes) {
return concatFilters(includes, excludes, false);
}
public static Pattern[] concatModuleFilters(String[] includes, String[] excludes) {
return concatFilters(includes, excludes, true);
}
private static Pattern[] concatFilters(String[] includes, String[] excludes, boolean modulePattern) {
if (includes == null || includes.length == 1 && includes[0].equals("")) {
includes = new String[0];
}
if (excludes == null || excludes.length == 1 && excludes[0].equals("")) {
excludes = new String[0];
}
Pattern alls[];
ArrayList<Pattern> list = new ArrayList<Pattern>(includes.length + excludes.length);
for (int i = 0; i < includes.length; ++i) {
if (includes[i].contains("|")) {
String[] split = includes[i].split("\\|");
for (int j = 0; j < split.length; ++j) {
list.add(new Pattern(split[j], true, modulePattern));
}
} else {
list.add(new Pattern(includes[i], true, modulePattern));
}
}
for (int i = 0; i < excludes.length; ++i) {
if (excludes[i].contains("|")) {
String[] split = excludes[i].split("\\|");
for (int j = 0; j < split.length; ++j) {
list.add(new Pattern(split[j], false, modulePattern));
}
} else {
list.add(new Pattern(excludes[i], false, modulePattern));
}
}
alls = list.toArray(new Pattern[list.size()]);
java.util.Arrays.sort(alls);
return alls;
}
/**
* <p> ClassName specific pattern implementation. Patterns are compared
* taking into account classname separators ('/' and '$' signs) as well as
* allowing to users some simplifications ('.' as package separator instead
* of '/', ignoring leading '/'). </p> <p> Pattern can describe inclusion or
* exclusion -
* <code>included</code> field. Patterns are using wildcards ('*') but it's
* prohibited to use extended pattern syntax (eg grouping). </p>
*/
public static class Pattern implements Comparable<Pattern> {
public String element;
public java.util.regex.Pattern patt;
public boolean included;
public String getElement() {
return element;
}
public void setElement(String element) {
this.element = element;
}
public boolean isIncluded() {
return included;
}
public void setIncluded(boolean included) {
this.included = included;
}
/**
* @param element Should not be null
* @param include
*/
public Pattern(String element, boolean include, boolean modulePattern) {
try {
if ("/".equals(element)) {
this.element = element;
this.included = include;
this.patt = java.util.regex.Pattern.compile("/[a-zA-Z0-9_\\$]+");
} else {
if (modulePattern) {
this.element = element.replaceAll("([^\\\\])\\$", "$1\\\\\\$");
} else {
this.element = element.replaceAll("\\.", "/").replaceAll("([^\\\\])\\$", "$1\\\\\\$");
}
if (this.element.endsWith("/")) {
this.element = this.element.substring(0, this.element.length() - 1);
}
if (!modulePattern) {
if (this.element.length() == 0 || !this.element.startsWith("/")) {
this.element = "/" + this.element;
}
}
this.patt = java.util.regex.Pattern.compile(this.element.replace('*', '#').replaceAll("##", "[a-zA-Z0-9_\\$/]*").replaceAll("#", "[a-zA-Z0-9_\\$]*") + "(/.*|\\$.*)*");
this.included = include;
}
} catch (PatternSyntaxException e) {
int p = element.indexOf('\\');
if (p > -1) {
throw new IllegalArgumentException("Illegal character '\\' in the pattern '" + element + "' near index " + p);
}
p = element.indexOf('(');
if (p > -1) {
throw new IllegalArgumentException("Illegal character '(' in the pattern '" + element + "' near index " + p);
}
p = element.indexOf(')');
if (p > -1) {
throw new IllegalArgumentException("Illegal character ')' in the pattern '" + element + "' near index " + p);
}
p = element.indexOf('[');
if (p > -1) {
throw new IllegalArgumentException("Illegal character '[' in the pattern '" + element + "' near index " + p);
}
p = element.indexOf(']');
if (p > -1) {
throw new IllegalArgumentException("Illegal character ']' in the pattern '" + element + "' near index " + p);
}
throw new IllegalArgumentException("Illegal characters in the pattern '" + element + "'");
}
}
@Override
public String toString() {
return (included ? "+" : "-") + element;
}
public int compareTo(Pattern o) {
int i = 0, j = 0;
if (element.contains("$")) {
if (!o.element.contains("$")) {
return 1;
}
} else {
if (o.element.contains("$")) {
return -1;
}
}
char my[] = element.toCharArray();
char his[] = o.element.toCharArray();
for (; i < my.length && j < his.length; ++i, ++j) {
char me = my[i];
char him = his[i];
if (me == '/' ^ him == '/') { // if only one of the strings finished ("/com/su/tdk" VS "/com/sun/tdk" or otherwise) - checking. If both - they are OK
if (me == '/') { // "/com/su/tdk" VS "/com/sun/tdk": this is lesser
return -1;
}
// else
return 1;// "/com/sunn/tdk" VS "/com/sun/tdk": this is bigger
}
int res = me - him;
if (res != 0) {
if (me == '*') {
if (i < my.length - 1 && my[i + 1] == '*') {
return -2;
}
return -1;
}
if (him == '*') {
if (i < his.length - 1 && his[i + 1] == '*') {
return 2;
}
return 1;
}
return res;
} else {
if (me == '*' && i < my.length - 1 && my[i + 1] == '*') {
return 2;
} else if (him == '*' && i < his.length - 1 && his[i + 1] == '*') {
return -2;
}
}
}
if (i == my.length && j == his.length) { // two strings are equal
if (included == o.included) {
return 0;
} else {
if (included) {
return 1;
}
if (o.included) {
return -1;
}
return 0;
}
}
if (i == my.length) { // "/com/sun" VS "/com/sun/tdk" - this = parent
return -1000;
}
if (j == his.length) { // "/com/sun/tdk" VS "/com/sun" - this = child
return 1000;
}
return 0; // should not happen
}
}
/**
* <p> Check whether a
* <code>className</code> is accepted by patterns. </p>
*
* @param alls patterns to use
* @param allowedModifs class modificators to accept. Ignored if null.
* @param className class name to check
* @param sig class's signature
* @return true if a class name is accepted by all patters and contain at
* least one allowed modificator
*/
public static boolean accept(Pattern[] alls, String[] allowedModifs, String className, String sig) {
if (alls.length == 0) {
if (allowedModifs != null && sig != null && allowedModifs.length != 0) {
for (int j = 0; j < allowedModifs.length; j++) {
if (sig.contains(allowedModifs[j])) {
return true;
}
}
return false;
}
return true;
}
Boolean parentIncluded = null; // null means that no pattern matching the className found - neither including or excluding
boolean included = false;
// System.out.println("c: " + className);
outer:
for (int i = 0; i < alls.length; ++i) {
if (alls[i].included) {
included = true;
}
// System.out.println("match: " + alls[i].patt.toString());
if (alls[i].patt.matcher(className).matches()) {
// System.out.println("matched " + alls[i].included);
parentIncluded = alls[i].included;
}
}
if (sig == null || allowedModifs == null || allowedModifs.length == 0) {
return parentIncluded != null ? parentIncluded : !included; // if parent package was not found (parentIncluded == null) - accept depends on was ANYTHING included or not
}
for (int j = 0; j < allowedModifs.length; j++) {
if (sig.contains(allowedModifs[j])) {
return true;
}
}
return false;
}
public enum CheckOptions {
FILE_EXISTS,
FILE_NOTEXISTS,
FILE_ISFILE,
FILE_ISDIR,
FILE_NOTISDIR,
FILE_PARENTEXISTS,
FILE_CANREAD,
FILE_CANWRITE,
INT_NONNEGATIVE,
INT_POSITIVE,
INT_NOT_NULL,
FILE_NOTISFILE
}
/**
* <p> Checks that hostname is valid </p>
*
* @param hostname Hostname to check
* @param description Hostname description (eg "remote server address")
* @throws com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException
*/
public static void checkHostCanBeNull(String hostname, String description) throws EnvHandlingException {
if (hostname != null) {
try {
InetAddress.getByName(hostname);
} catch (UnknownHostException ex) {
throw new EnvHandlingException("Incorrect " + description + " (" + hostname + ") - unknown host, can't resolve");
}
}
}
/**
* <p> Checks a file for some criterias </p>
*
* @param filename File to check
* @param description File description (eg "output directory")
* @param opts criterias to check
* @return File object related with <code>filename</code>
* @throws com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException
*/
public static File checkFileNotNull(String filename, String description, CheckOptions... opts) throws EnvHandlingException {
if (filename == null) {
throw new IllegalArgumentException("Argument " + description + " should not be null");
}
final File f = new File(filename);
checkFile(f, description, opts);
return f;
}
/**
* <p> Checks a file for some criterias </p>
*
* @param filename File to check
* @param description File description (eg "output directory")
* @param opts criterias to check
* @return File object related with <code>filename</code> or null
* @throws com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException
*/
public static File checkFileCanBeNull(String filename, String description, CheckOptions... opts) throws EnvHandlingException {
if (filename == null) {
return null;
}
final File f = new File(filename);
checkFile(f, description, opts);
return f;
}
/**
* <p> Checks a file for some criteria </p>
*
* @param file File to check. Can't be null.
* @param description File description
* @param opts criteria to check
* @throws com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException
*/
public static void checkFile(File file, String description, CheckOptions... opts) throws EnvHandlingException {
for (CheckOptions opt : opts) {
switch (opt) {
case FILE_EXISTS:
if (!file.exists()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - doesn't exist");
}
break;
case FILE_NOTEXISTS:
if (file.exists()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - shouldn't exist");
}
break;
case FILE_CANREAD:
if (!file.canRead()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - can't read");
}
break;
case FILE_CANWRITE:
if (file.isFile()) {
// file exists
if (!file.canWrite()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - can't write");
}
} else {
// a new file
File parentDir = file.getAbsoluteFile().getParentFile();
if (parentDir == null || !parentDir.isDirectory() || !Files.isWritable(parentDir.toPath())) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - can't write");
}
}
break;
case FILE_ISFILE:
if (!file.isFile()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - is not a file");
}
break;
case FILE_NOTISFILE:
if (file.isFile()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - should not be a file");
}
break;
case FILE_ISDIR:
if (!file.isDirectory()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - is not a directory");
}
break;
case FILE_NOTISDIR:
if (file.isDirectory()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - should not be a directory");
}
break;
case FILE_PARENTEXISTS:
File parent = file.getAbsoluteFile().getParentFile();
if (parent != null && !parent.exists()) {
throw new EnvHandlingException("Incorrect " + description + " (" + file.getPath() + ") - parent directory doesn't exist");
}
break;
}
}
}
/**
* Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname or
* empty list if the abstract pathname does not denote a directory
*
* @param dir abstract pathname denotes a directory
*/
public static List<File> getListFiles(File dir) {
ArrayList<File> listFiles = new ArrayList<>();
File[] list = dir.listFiles();
if (list != null && list.length > 0) {
listFiles.addAll(Arrays.asList(list));
}
return listFiles;
}
/**
* <p> Converts a string to integer using Integer.parseInt() and checks some
* criterias </p>
*
* @param value String to convert
* @param description value description (eg "port number")
* @param opts criterias to check
* @return integer value
* @throws com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException
*/
public static int checkedToInt(String value, String description, CheckOptions... opts) throws EnvHandlingException {
try {
int port = Integer.parseInt(value);
for (CheckOptions opt : opts) {
switch (opt) {
case INT_POSITIVE:
if (port <= 0) {
throw new EnvHandlingException("Incorrect " + description + " (" + port + ") - should be positive");
}
break;
case INT_NONNEGATIVE:
if (port < 0) {
throw new EnvHandlingException("Incorrect " + description + " (" + port + ") - should not be negative");
}
break;
case INT_NOT_NULL:
if (port == 0) {
throw new EnvHandlingException("Incorrect " + description + " (0) - should not be null");
}
break;
}
}
return port;
} catch (NumberFormatException ex) {
throw new EnvHandlingException("Incorrect " + description + " (" + value + ") - not a number");
}
}
static public void unzipFolder(File srcFolder, String destZipFile) throws Exception {
ZipFile zip = new ZipFile(srcFolder);
Enumeration zipFileEntries = zip.entries();
while (zipFileEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
File destFile = new File(destZipFile, entry.getName());
destFile.getParentFile().mkdirs();
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
int currentByte;
byte data[] = new byte[2048];
while ((currentByte = is.read(data, 0, 2048)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
}
/**
* Adds directory to zip archive
*
* @param srcFolder directory to zip
* @param destZipFile result zip file
* @throws Exception exceptions while working with file system
*/
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + File.separator + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
in.close();
}
}
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + File.separator + fileName, zip);
} else {
addFileToZip(path + File.separator + folder.getName(), srcFolder + File.separator + fileName, zip);
}
}
}
public static void copyDirectory(File source, File destination) throws IOException {
if (!source.exists()) {
throw new IllegalArgumentException("Source directory (" + source.getPath() + ") doesn't exist.");
}
if (!source.isDirectory()) {
throw new IllegalArgumentException("Source (" + source.getPath() + ") must be a directory.");
}
destination.mkdirs();
File[] files = source.listFiles();
for (File file : files) {
if (file.isDirectory()) {
copyDirectory(file, new File(destination, file.getName()));
} else {
copyFile(file, new File(destination, file.getName()));
}
}
}
public static boolean deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
if (null != files) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
}
return (directory.delete());
}
private static String checkName(String name) {
if (name != null && !name.isEmpty()) {
return name;
}
return "";
}
private static final HashSet<String> classNameExclusion = new HashSet() {{
add("java/lang/System");
add("java/lang/String");
add("java/lang/StringLatin1");
add("java/lang/String$CaseInsensitiveComparator");
add("java/lang/Thread");
add("java/lang/ThreadGroup");
add("java/lang/RuntimePermission");
add("java/security/Permission");
add("java/security/BasicPermission");
add("java/lang/Class");
add("java/lang/Runtime");
}};
private static final HashSet<String> methodNameExclusion = new HashSet() {{
add("<clinit>");
add("<init>");
add("init");
add("length");
add("coder");
add("isLatin1");
add("charAt");
add("equals");
add("add");
add("checkAccess");
add("checkParentAccess");
add("getSecurityManager");
add("allowSecurityManager");
add("registerNatives");
add("currentTimeMillis");
add("identityHashCode");
add("nanoTime");
add("getId");
add("threadId");
add("getRuntime");
}};
public static boolean isAdvanceStaticInstrAllowed(String className, String methodName) {
if (classNameExclusion.contains(className)) {
if (methodNameExclusion.contains(methodName)) {
return false;
}
}
return true;
}
}
| 52,850 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
TextReportTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/view/TextReportTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.FileCoverage;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import openjdk.codetools.jcov.report.source.SourcePath;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import static org.testng.Assert.assertTrue;
public class TextReportTest {
static SourceHierarchy source;
static FileCoverage coverage;
static Path reportFile;
@BeforeClass
static void init() throws IOException {
Path root = SingleFiletReportTest.createFiles();
source = new SourcePath(root, root);
coverage = new FileCoverage() {
@Override
public List<CoveredLineRange> ranges(String file) {
return file.equals(SingleFiletReportTest.FILE_11) ? List.of(
new CoveredLineRange(1, 1, Coverage.COVERED),
new CoveredLineRange(3, 4, Coverage.UNCOVERED),
new CoveredLineRange(6, 8, Coverage.COVERED)
) : List.of();
}
};
reportFile = Files.createTempFile("report", "txt");
}
@Test
void everyOdd() throws Exception {
SourceFilter filter = file -> List.of(
new LineRange(2, 2),
new LineRange(4, 4),
new LineRange(6, 6),
new LineRange(8, 8)
);
var files = new FileSet(Set.of(SingleFiletReportTest.FILE_11, SingleFiletReportTest.FILE_12,
SingleFiletReportTest.FILE_21, SingleFiletReportTest.FILE_22));
var report = new TextReport(source, files, coverage, "HEADER", filter);
report.report(reportFile);
var content = Files.readAllLines(reportFile);
assertTrue(content.contains("HEADER"));
assertTrue(content.stream().anyMatch("total 1/2"::equals));
assertTrue(content.stream().anyMatch("4:-4"::equals));
assertTrue(content.stream().anyMatch("6:+6"::equals));
}
}
| 3,608 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SingleFiletReportTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/view/SingleFiletReportTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.FileCoverage;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import openjdk.codetools.jcov.report.source.SourcePath;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class SingleFiletReportTest {
public static final String FILE_11 = "dir1/file1.java";
public static final String FILE_12 = "dir1/file2.java";
public static final String FILE_21 = "dir2/file1.java";
public static final String FILE_22 = "dir2/file2.java";
static SourceHierarchy source;
static FileCoverage coverage;
static Path reportFile;
public static Path createFiles() throws IOException {
Path root = Files.createTempDirectory("source");
Files.createDirectories(root);
for (var dir : List.of("dir1", "dir2")) Files.createDirectories(root.resolve(dir));
for (var file : List.of(FILE_11, FILE_12, FILE_21, FILE_22))
Files.write(root.resolve(file), List.of("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"));
return root;
}
@BeforeClass
static void init() throws IOException {
Path root = createFiles();
source = new SourcePath(root, root);
coverage = new FileCoverage() {
@Override
public List<CoveredLineRange> ranges(String file) {
return file.equals(FILE_11) ? List.of(
new CoveredLineRange(1, 1, Coverage.COVERED),
new CoveredLineRange(3, 4, Coverage.UNCOVERED),
new CoveredLineRange(6, 8, Coverage.COVERED)
) : List.of();
}
};
reportFile = Files.createTempFile("report", ".html");
}
@Test
void everyOdd() throws Exception {
var fileSet = new FileSet(Set.of(FILE_11, FILE_12, FILE_21, FILE_22));
SourceFilter filter = file -> List.of(
// new LineRange(0, 0),
new LineRange(2, 2),
new LineRange(4, 4),
new LineRange(6, 6),
new LineRange(8, 8)
);
var report = new SingleHTMLReport(source, fileSet,
coverage, "TITLE", "<h1>HEADER</h1>", filter, filter);
report.report(reportFile);
System.out.println("Report: " + reportFile.toString());
List<String> content = Files.readAllLines(reportFile);
assertTrue(content.contains("<title>TITLE</title>"));
assertTrue(content.contains("<h1>HEADER</h1>"));
assertTrue(content.stream().anyMatch("<tr><td><a href=\"#total\">total</a></td><td>1/2</td></tr>"::equals));
assertTrue(content.stream().anyMatch("<a class=\"uncovered\">4: 4</a>"::equals));
assertTrue(content.stream().anyMatch("<a class=\"covered\">6: 6</a>"::equals));
}
}
| 4,537 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CoverageCacheTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/view/CoverageCacheTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.FileCoverage;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class CoverageCacheTest {
static final Set<String> files = Set.of("dir1/file1", "dir1/file2", "dir2/file1", "dir2/file2");
static FileCoverage coverage;
static Path reportFile;
@BeforeClass
static void init() throws IOException {
coverage = file -> List.of(
new CoveredLineRange(1, 1, Coverage.COVERED),
new CoveredLineRange(3, 4, Coverage.COVERED),
new CoveredLineRange(6, 8, Coverage.COVERED)
);
reportFile = Files.createTempFile("report", "txt");
}
@Test
void everyEven() throws IOException {
var cache = new CoverageHierarchy(files,
new SourceHierarchy() {
@Override
public List<String> readFile(String file) throws IOException {
return Files.readAllLines(Path.of(file));
}
@Override
public String toClass(String file) {
return file;
}
},
coverage,
file -> file.endsWith("file1") ?
List.of(
new LineRange(0, 0),
new LineRange(2, 2),
new LineRange(4, 4),
new LineRange(6, 6),
new LineRange(8, 8)
) :
List.of());
assertTrue(cache.get("").equals(new Coverage(4, 4)));
assertTrue(cache.get("dir1").equals(new Coverage(2, 2)));
assertTrue(cache.get("dir1/file1").equals(new Coverage(2, 2)));
}
@Test
void getLineCoverage() throws IOException {
var cache = new CoverageHierarchy(files,
new SourceHierarchy() {
@Override
public List<String> readFile(String file) throws IOException {
return Files.readAllLines(Path.of(file));
}
@Override
public String toClass(String file) {
return file;
}
},
coverage,
file -> file.endsWith("file1") ?
List.of(
new LineRange(0, 0),
new LineRange(2, 2),
new LineRange(4, 4),
new LineRange(6, 6),
new LineRange(8, 8)
) :
List.of());
var lc = cache.getLineRanges("dir1/file1");
assertEquals(lc.size(), 3);
assertEquals(lc.get(4).coverage(), Coverage.COVERED);
assertEquals(lc.get(6).coverage(), Coverage.COVERED);
assertEquals(lc.get(8).coverage(), Coverage.COVERED);
}
}
| 4,688 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
JCovLoadTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/jcov/JCovLoadTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.jcov;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.GitDifFilterTest;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataRoot;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.*;
public class JCovLoadTest {
static JCovLineCoverage coverage;
@BeforeClass
static void init() throws FileFormatException, IOException {
var xmlName = JCovLoadTest.class.getName().replace('.', '/');
xmlName = "/" + xmlName.substring(0, xmlName.lastIndexOf('/')) + "/ObjectInputStream.xml";
coverage = new JCovLineCoverage(DataRoot.read(GitDifFilterTest.cp(xmlName).toString()));
}
private static Boolean covered(List<CoveredLineRange> ranges, int line) {
var range = ranges.stream()
.filter(e -> e.compare(line) == 0).findAny();
if (range.isEmpty()) {
System.out.println("Nothing for line " + line);
return null;
}
var e = range.get();
System.out.printf("For line %d found (%d,%d) -> %s\n", line, e.first(), e.last(), e.coverage());
return e.coverage().covered() > 0;
}
/*
1454: * @throws StreamCorruptedException if arrayLength is negative
...
1458: if (! arrayType.isArray()) {
1459: throw new IllegalArgumentException("not an array type");
1460: }
...
1462: if (arrayLength < 0) {
1463: throw new StreamCorruptedException("Array length is negative");
1464: }
...
2141: if (len < 0) {
2142: throw new StreamCorruptedException("Array length is negative");
2143: }
*/
@Test
void basic() {
var ranges = coverage.ranges("java/io/ObjectInputStream.java");
assertNull(covered(ranges, 1454));
assertTrue(covered(ranges, 1458));
assertFalse(covered(ranges, 1459));
assertNull(covered(ranges, 1460));
assertTrue(covered(ranges, 2141));
assertTrue(covered(ranges, 2142));
assertNull(covered(ranges, 2143));
}
@Test
void innerClass() {
var ranges = coverage.ranges("java/io/ObjectInputStream.java");
assertTrue(covered(ranges, 3035));
assertTrue(covered(ranges, 3036));
assertNull(covered(ranges, 3038));
}
}
| 3,805 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
JCovReportTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/jcov/JCovReportTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.jcov;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.GitDifFilterTest;
import openjdk.codetools.jcov.report.filter.GitDiffFilter;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.ContextFilter;
import openjdk.codetools.jcov.report.source.SourcePath;
import openjdk.codetools.jcov.report.view.SingleHTMLReport;
import openjdk.codetools.jcov.report.view.TextReport;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataRoot;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.testng.Assert.assertTrue;
public class JCovReportTest {
private FileSet files;
private JCovLineCoverage rawCoverage;
private Path src;
@BeforeClass
void init() throws IOException, FileFormatException {
String pkg = "/" + GitDifFilterTest.class.getPackageName().replace('.', '/') + "/";
src = GitDifFilterTest.cp("src", Map.of(
pkg + "JavaObjectInputStreamAccess.java.txt", "java/io/JavaObjectInputStreamAccess.java",
pkg + "ObjectInputStream.java.txt", "java/io/ObjectInputStream.java"));
files = new FileSet(Set.of("src/java/io/JavaObjectInputStreamAccess.java", "src/java/io/ObjectInputStream.java"));
var xmlName = JCovLoadTest.class.getName().replace('.', '/');
xmlName = "/" + xmlName.substring(0, xmlName.lastIndexOf('/')) + "/ObjectInputStream.xml";
rawCoverage = new JCovLineCoverage(DataRoot.read(GitDifFilterTest.cp(xmlName).toString()));
}
@Test
void report() throws Exception {
String diffPkg = "/" + JCovReportTest.class.getPackageName().replace('.', '/') + "/";
var filter = GitDiffFilter.parseDiff(GitDifFilterTest.cp(diffPkg + "negative_array_size.diff")/*, Set.of("src")*/);
Path textReport = Files.createTempFile("report", ".txt");
new TextReport(new SourcePath(src, src.resolve("src")),
files,
rawCoverage,
"negative array size fix",
new ContextFilter(filter, 10)).report(textReport);
List<String> reportLines = Files.readAllLines(textReport);
assertTrue(reportLines.contains("1454: * @throws StreamCorruptedException if arrayLength is negative"));
assertTrue(reportLines.contains("1457: private void checkArray(Class<?> arrayType, int arrayLength) throws ObjectStreamException {"));
assertTrue(reportLines.contains("1463:+ throw new StreamCorruptedException(\"Array length is negative\");"));
assertTrue(reportLines.contains("2141:+ if (len < 0) {"));
assertTrue(reportLines.contains("2142:+ throw new StreamCorruptedException(\"Array length is negative\");"));
assertTrue(reportLines.contains("2143: }"));
assertTrue(reportLines.contains("2142:+ throw new StreamCorruptedException(\"Array length is negative\");"));
Path htmlReport = Files.createTempFile("report", ".html");
new SingleHTMLReport(new SourcePath(src, src.resolve("src")),
files,
rawCoverage,
"negative array size fix",
"negative array size fix",
filter,
new ContextFilter(filter, 10)).report(htmlReport);
System.out.println("Report: " + htmlReport);
reportLines = Files.readAllLines(htmlReport);
assertTrue(reportLines.contains("<a class=\"highlight\">1454: * @throws StreamCorruptedException if arrayLength is negative</a>"));
assertTrue(reportLines.contains("<a class=\"highlight\">1457: private void checkArray(Class<?> arrayType, int arrayLength) throws ObjectStreamException {</a>"));
assertTrue(reportLines.contains("<a class=\"covered\">1463: throw new StreamCorruptedException(\"Array length is negative\");</a>"));
assertTrue(reportLines.contains("<a class=\"covered\">2141: if (len < 0) {</a>"));
assertTrue(reportLines.contains("<a class=\"covered\">2142: throw new StreamCorruptedException(\"Array length is negative\");</a>"));
assertTrue(reportLines.contains("<a class=\"highlight\">2143: }</a>"));
assertTrue(reportLines.contains("<a class=\"covered\">2142: throw new StreamCorruptedException(\"Array length is negative\");</a>"));
}
@Test
void innerClass() throws Exception {
var filter = new SourceFilter() {
@Override
public List<LineRange> ranges(String file) {
return List.of(new LineRange(2987,3838));
}
};
Path textReport = Files.createTempFile("report", ".txt");
new TextReport(new SourcePath(src, src.resolve("src")),
files,
rawCoverage,
"negative array size fix",
filter).report(textReport);
List<String> reportLines = Files.readAllLines(textReport);
assertTrue(reportLines.contains("3035:+ this.in = new PeekInputStream(in);"));
}
//2987,3838
}
| 6,628 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SameLineMethods.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/jcov/SameLineMethods.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.jcov;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataRoot;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.filter.GitDifFilterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import static org.testng.Assert.*;
public class SameLineMethods {
static JCovLineCoverage coverage;
@BeforeClass
static void init() throws FileFormatException, IOException {
var xmlName = SameLineMethods.class.getName().replace('.', '/');
xmlName = "/" + xmlName.substring(0, xmlName.lastIndexOf('/')) + "/Fake.xml";
coverage = new JCovLineCoverage(DataRoot.read(GitDifFilterTest.cp(xmlName).toString()));
}
@Test
void basic() {
var ranges = coverage.ranges("my/package/AB.java");
assertTrue(ranges.stream().filter(clr -> clr.first() == 1).findAny().get().coverage().covered() > 0);
}
}
| 2,254 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ObjectInputStream.java.txt | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/filter/ObjectInputStream.java.txt | /*
* Copyright (c) 1996, 2023, 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 java.io;
import java.io.ObjectInputFilter.Config;
import java.io.ObjectStreamClass.RecordSupport;
import java.lang.System.Logger;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import jdk.internal.access.SharedSecrets;
import jdk.internal.event.DeserializationEvent;
import jdk.internal.misc.Unsafe;
import jdk.internal.util.ByteArray;
import sun.reflect.misc.ReflectUtil;
import sun.security.action.GetBooleanAction;
import sun.security.action.GetIntegerAction;
/**
* An ObjectInputStream deserializes primitive data and objects previously
* written using an ObjectOutputStream.
*
* <p><strong>Warning: Deserialization of untrusted data is inherently dangerous
* and should be avoided. Untrusted data should be carefully validated according to the
* "Serialization and Deserialization" section of the
* {@extLink secure_coding_guidelines_javase Secure Coding Guidelines for Java SE}.
* {@extLink serialization_filter_guide Serialization Filtering} describes best
* practices for defensive use of serial filters.
* </strong></p>
*
* <p>The key to disabling deserialization attacks is to prevent instances of
* arbitrary classes from being deserialized, thereby preventing the direct or
* indirect execution of their methods.
* {@link ObjectInputFilter} describes how to use filters and
* {@link ObjectInputFilter.Config} describes how to configure the filter and filter factory.
* Each stream has an optional deserialization filter
* to check the classes and resource limits during deserialization.
* The JVM-wide filter factory ensures that a filter can be set on every {@link ObjectInputStream}
* and every object read from the stream can be checked.
* The {@linkplain #ObjectInputStream() ObjectInputStream constructors} invoke the filter factory
* to select the initial filter which may be updated or replaced by {@link #setObjectInputFilter}.
* <p>
* If an ObjectInputStream has a filter, the {@link ObjectInputFilter} can check that
* the classes, array lengths, number of references in the stream, depth, and
* number of bytes consumed from the input stream are allowed and
* if not, can terminate deserialization.
*
* <p>ObjectOutputStream and ObjectInputStream can provide an application with
* persistent storage for graphs of objects when used with a FileOutputStream
* and FileInputStream respectively. ObjectInputStream is used to recover
* those objects previously serialized. Other uses include passing objects
* between hosts using a socket stream or for marshaling and unmarshaling
* arguments and parameters in a remote communication system.
*
* <p>ObjectInputStream ensures that the types of all objects in the graph
* created from the stream match the classes present in the Java Virtual
* Machine. Classes are loaded as required using the standard mechanisms.
*
* <p>Only objects that support the java.io.Serializable or
* java.io.Externalizable interface can be read from streams.
*
* <p>The method {@code readObject} is used to read an object from the
* stream. Java's safe casting should be used to get the desired type. In
* Java, strings and arrays are objects and are treated as objects during
* serialization. When read they need to be cast to the expected type.
*
* <p>Primitive data types can be read from the stream using the appropriate
* method on DataInput.
*
* <p>The default deserialization mechanism for objects restores the contents
* of each field to the value and type it had when it was written. Fields
* declared as transient or static are ignored by the deserialization process.
* References to other objects cause those objects to be read from the stream
* as necessary. Graphs of objects are restored correctly using a reference
* sharing mechanism. New objects are always allocated when deserializing,
* which prevents existing objects from being overwritten.
*
* <p>Reading an object is analogous to running the constructors of a new
* object. Memory is allocated for the object and initialized to zero (NULL).
* No-arg constructors are invoked for the non-serializable classes and then
* the fields of the serializable classes are restored from the stream starting
* with the serializable class closest to java.lang.object and finishing with
* the object's most specific class.
*
* <p>For example to read from a stream as written by the example in
* {@link ObjectOutputStream}:
* <br>
* {@snippet lang="java" :
* try (FileInputStream fis = new FileInputStream("t.tmp");
* ObjectInputStream ois = new ObjectInputStream(fis)) {
* String label = (String) ois.readObject();
* LocalDateTime dateTime = (LocalDateTime) ois.readObject();
* // Use label and dateTime
* } catch (Exception ex) {
* // handle exception
* }
* }
*
* <p>Classes control how they are serialized by implementing either the
* java.io.Serializable or java.io.Externalizable interfaces.
*
* <p>Implementing the Serializable interface allows object serialization to
* save and restore the entire state of the object and it allows classes to
* evolve between the time the stream is written and the time it is read. It
* automatically traverses references between objects, saving and restoring
* entire graphs.
*
* <p>Serializable classes that require special handling during the
* serialization and deserialization process should implement methods
* with the following signatures:
*
* {@snippet lang="java":
* private void writeObject(java.io.ObjectOutputStream stream)
* throws IOException;
* private void readObject(java.io.ObjectInputStream stream)
* throws IOException, ClassNotFoundException;
* private void readObjectNoData()
* throws ObjectStreamException;
* }
*
* <p>The method name, modifiers, return type, and number and type of
* parameters must match exactly for the method to be used by
* serialization or deserialization. The methods should only be
* declared to throw checked exceptions consistent with these
* signatures.
*
* <p>The readObject method is responsible for reading and restoring the state
* of the object for its particular class using data written to the stream by
* the corresponding writeObject method. The method does not need to concern
* itself with the state belonging to its superclasses or subclasses. State is
* restored by reading data from the ObjectInputStream for the individual
* fields and making assignments to the appropriate fields of the object.
* Reading primitive data types is supported by DataInput.
*
* <p>Any attempt to read object data which exceeds the boundaries of the
* custom data written by the corresponding writeObject method will cause an
* OptionalDataException to be thrown with an eof field value of true.
* Non-object reads which exceed the end of the allotted data will reflect the
* end of data in the same way that they would indicate the end of the stream:
* bytewise reads will return -1 as the byte read or number of bytes read, and
* primitive reads will throw EOFExceptions. If there is no corresponding
* writeObject method, then the end of default serialized data marks the end of
* the allotted data.
*
* <p>Primitive and object read calls issued from within a readExternal method
* behave in the same manner--if the stream is already positioned at the end of
* data written by the corresponding writeExternal method, object reads will
* throw OptionalDataExceptions with eof set to true, bytewise reads will
* return -1, and primitive reads will throw EOFExceptions. Note that this
* behavior does not hold for streams written with the old
* {@code ObjectStreamConstants.PROTOCOL_VERSION_1} protocol, in which the
* end of data written by writeExternal methods is not demarcated, and hence
* cannot be detected.
*
* <p>The readObjectNoData method is responsible for initializing the state of
* the object for its particular class in the event that the serialization
* stream does not list the given class as a superclass of the object being
* deserialized. This may occur in cases where the receiving party uses a
* different version of the deserialized instance's class than the sending
* party, and the receiver's version extends classes that are not extended by
* the sender's version. This may also occur if the serialization stream has
* been tampered; hence, readObjectNoData is useful for initializing
* deserialized objects properly despite a "hostile" or incomplete source
* stream.
*
* <p>Serialization does not read or assign values to the fields of any object
* that does not implement the java.io.Serializable interface. Subclasses of
* Objects that are not serializable can be serializable. In this case the
* non-serializable class must have a no-arg constructor to allow its fields to
* be initialized. In this case it is the responsibility of the subclass to
* save and restore the state of the non-serializable class. It is frequently
* the case that the fields of that class are accessible (public, package, or
* protected) or that there are get and set methods that can be used to restore
* the state.
*
* <p>Any exception that occurs while deserializing an object will be caught by
* the ObjectInputStream and abort the reading process.
*
* <p>Implementing the Externalizable interface allows the object to assume
* complete control over the contents and format of the object's serialized
* form. The methods of the Externalizable interface, writeExternal and
* readExternal, are called to save and restore the objects state. When
* implemented by a class they can write and read their own state using all of
* the methods of ObjectOutput and ObjectInput. It is the responsibility of
* the objects to handle any versioning that occurs.
*
* <p>Enum constants are deserialized differently than ordinary serializable or
* externalizable objects. The serialized form of an enum constant consists
* solely of its name; field values of the constant are not transmitted. To
* deserialize an enum constant, ObjectInputStream reads the constant name from
* the stream; the deserialized constant is then obtained by calling the static
* method {@code Enum.valueOf(Class, String)} with the enum constant's
* base type and the received constant name as arguments. Like other
* serializable or externalizable objects, enum constants can function as the
* targets of back references appearing subsequently in the serialization
* stream. The process by which enum constants are deserialized cannot be
* customized: any class-specific readObject, readObjectNoData, and readResolve
* methods defined by enum types are ignored during deserialization.
* Similarly, any serialPersistentFields or serialVersionUID field declarations
* are also ignored--all enum types have a fixed serialVersionUID of 0L.
*
* <a id="record-serialization"></a>
* <p>Records are serialized differently than ordinary serializable or externalizable
* objects. During deserialization the record's canonical constructor is invoked
* to construct the record object. Certain serialization-related methods, such
* as readObject and writeObject, are ignored for serializable records. See
* <a href="{@docRoot}/../specs/serialization/serial-arch.html#serialization-of-records">
* <cite>Java Object Serialization Specification,</cite> Section 1.13,
* "Serialization of Records"</a> for additional information.
*
* @spec serialization/index.html Java Object Serialization Specification
* @author Mike Warres
* @author Roger Riggs
* @see java.io.DataInput
* @see java.io.ObjectOutputStream
* @see java.io.Serializable
* @see <a href="{@docRoot}/../specs/serialization/input.html">
* <cite>Java Object Serialization Specification,</cite> Section 3, "Object Input Classes"</a>
* @since 1.1
*/
public class ObjectInputStream
extends InputStream implements ObjectInput, ObjectStreamConstants
{
/** handle value representing null */
private static final int NULL_HANDLE = -1;
/** marker for unshared objects in internal handle table */
private static final Object unsharedMarker = new Object();
/**
* immutable table mapping primitive type names to corresponding
* class objects
*/
private static final Map<String, Class<?>> primClasses =
Map.of("boolean", boolean.class,
"byte", byte.class,
"char", char.class,
"short", short.class,
"int", int.class,
"long", long.class,
"float", float.class,
"double", double.class,
"void", void.class);
private static class Caches {
/** cache of subclass security audit results */
static final ClassValue<Boolean> subclassAudits =
new ClassValue<>() {
@Override
protected Boolean computeValue(Class<?> type) {
return auditSubclass(type);
}
};
/**
* Property to permit setting a filter after objects
* have been read.
* See {@link #setObjectInputFilter(ObjectInputFilter)}
*/
static final boolean SET_FILTER_AFTER_READ = GetBooleanAction
.privilegedGetProperty("jdk.serialSetFilterAfterRead");
/**
* Property to control {@link GetField#get(String, Object)} conversion of
* {@link ClassNotFoundException} to {@code null}. If set to {@code true}
* {@link GetField#get(String, Object)} returns null otherwise
* throwing {@link ClassNotFoundException}.
*/
private static final boolean GETFIELD_CNFE_RETURNS_NULL = GetBooleanAction
.privilegedGetProperty("jdk.serialGetFieldCnfeReturnsNull");
/**
* Property to override the implementation limit on the number
* of interfaces allowed for Proxies. The property value is clamped to 0..65535.
* The maximum number of interfaces allowed for a proxy is limited to 65535 by
* {@link java.lang.reflect.Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)}.
*/
static final int PROXY_INTERFACE_LIMIT = Math.clamp(GetIntegerAction
.privilegedGetProperty("jdk.serialProxyInterfaceLimit", 65535), 0, 65535);
}
/*
* Separate class to defer initialization of logging until needed.
*/
private static class Logging {
/*
* Logger for ObjectInputFilter results.
* Setup the filter logger if it is set to DEBUG or TRACE.
* (Assuming it will not change).
*/
static final System.Logger filterLogger;
static {
Logger filterLog = System.getLogger("java.io.serialization");
filterLogger = (filterLog.isLoggable(Logger.Level.DEBUG)
|| filterLog.isLoggable(Logger.Level.TRACE)) ? filterLog : null;
}
}
/** filter stream for handling block data conversion */
private final BlockDataInputStream bin;
/** validation callback list */
private final ValidationList vlist;
/** recursion depth */
private long depth;
/** Total number of references to any type of object, class, enum, proxy, etc. */
private long totalObjectRefs;
/** whether stream is closed */
private boolean closed;
/** wire handle -> obj/exception map */
private final HandleTable handles;
/** scratch field for passing handle values up/down call stack */
private int passHandle = NULL_HANDLE;
/** flag set when at end of field value block with no TC_ENDBLOCKDATA */
private boolean defaultDataEnd = false;
/** if true, invoke readObjectOverride() instead of readObject() */
private final boolean enableOverride;
/** if true, invoke resolveObject() */
private boolean enableResolve;
/**
* Context during upcalls to class-defined readObject methods; holds
* object currently being deserialized and descriptor for current class.
* Null when not during readObject upcall.
*/
private SerialCallbackContext curContext;
/**
* Filter of class descriptors and classes read from the stream;
* may be null.
*/
private ObjectInputFilter serialFilter;
/**
* True if the stream-specific filter has been set; initially false.
*/
private boolean streamFilterSet;
/**
* Creates an ObjectInputStream that reads from the specified InputStream.
* A serialization stream header is read from the stream and verified.
* This constructor will block until the corresponding ObjectOutputStream
* has written and flushed the header.
*
* <p>The constructor initializes the deserialization filter to the filter returned
* by invoking the serial filter factory returned from {@link Config#getSerialFilterFactory()}
* with {@code null} for the current filter
* and the {@linkplain Config#getSerialFilter() static JVM-wide filter} for the requested filter.
* If the serial filter or serial filter factory properties are invalid
* an {@link IllegalStateException} is thrown.
* When the filter factory {@code apply} method is invoked it may throw a runtime exception
* preventing the {@code ObjectInputStream} from being constructed.
*
* <p>If a security manager is installed, this constructor will check for
* the "enableSubclassImplementation" SerializablePermission when invoked
* directly or indirectly by the constructor of a subclass which overrides
* the ObjectInputStream.readFields or ObjectInputStream.readUnshared
* methods.
*
* @param in input stream to read from
* @throws StreamCorruptedException if the stream header is incorrect
* @throws IOException if an I/O error occurs while reading stream header
* @throws SecurityException if untrusted subclass illegally overrides
* security-sensitive methods
* @throws IllegalStateException if the initialization of {@link ObjectInputFilter.Config}
* fails due to invalid serial filter or serial filter factory properties.
* @throws NullPointerException if {@code in} is {@code null}
* @see ObjectInputStream#ObjectInputStream()
* @see ObjectInputStream#readFields()
* @see ObjectOutputStream#ObjectOutputStream(OutputStream)
*/
public ObjectInputStream(InputStream in) throws IOException {
verifySubclass();
bin = new BlockDataInputStream(in);
handles = new HandleTable(10);
vlist = new ValidationList();
streamFilterSet = false;
serialFilter = Config.getSerialFilterFactorySingleton().apply(null, Config.getSerialFilter());
enableOverride = false;
readStreamHeader();
bin.setBlockDataMode(true);
}
/**
* Provide a way for subclasses that are completely reimplementing
* ObjectInputStream to not have to allocate private data just used by this
* implementation of ObjectInputStream.
*
* <p>The constructor initializes the deserialization filter to the filter returned
* by invoking the serial filter factory returned from {@link Config#getSerialFilterFactory()}
* with {@code null} for the current filter
* and the {@linkplain Config#getSerialFilter() static JVM-wide filter} for the requested filter.
* If the serial filter or serial filter factory properties are invalid
* an {@link IllegalStateException} is thrown.
* When the filter factory {@code apply} method is invoked it may throw a runtime exception
* preventing the {@code ObjectInputStream} from being constructed.
*
* <p>If there is a security manager installed, this method first calls the
* security manager's {@code checkPermission} method with the
* {@code SerializablePermission("enableSubclassImplementation")}
* permission to ensure it's ok to enable subclassing.
*
* @throws SecurityException if a security manager exists and its
* {@code checkPermission} method denies enabling
* subclassing.
* @throws IOException if an I/O error occurs while creating this stream
* @throws IllegalStateException if the initialization of {@link ObjectInputFilter.Config}
* fails due to invalid serial filter or serial filter factory properties.
* @see SecurityManager#checkPermission
* @see java.io.SerializablePermission
*/
protected ObjectInputStream() throws IOException, SecurityException {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
bin = null;
handles = null;
vlist = null;
streamFilterSet = false;
serialFilter = Config.getSerialFilterFactorySingleton().apply(null, Config.getSerialFilter());
enableOverride = true;
}
/**
* Read an object from the ObjectInputStream. The class of the object, the
* signature of the class, and the values of the non-transient and
* non-static fields of the class and all of its supertypes are read.
* Default deserializing for a class can be overridden using the writeObject
* and readObject methods. Objects referenced by this object are read
* transitively so that a complete equivalent graph of objects is
* reconstructed by readObject.
*
* <p>The root object is completely restored when all of its fields and the
* objects it references are completely restored. At this point the object
* validation callbacks are executed in order based on their registered
* priorities. The callbacks are registered by objects (in the readObject
* special methods) as they are individually restored.
*
* <p>The deserialization filter, when not {@code null}, is invoked for
* each object (regular or class) read to reconstruct the root object.
* See {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter} for details.
*
* <p>Exceptions are thrown for problems with the InputStream and for
* classes that should not be deserialized. All exceptions are fatal to
* the InputStream and leave it in an indeterminate state; it is up to the
* caller to ignore or recover the stream state.
*
* @throws ClassNotFoundException Class of a serialized object cannot be
* found.
* @throws InvalidClassException Something is wrong with a class used by
* deserialization.
* @throws StreamCorruptedException Control information in the
* stream is inconsistent.
* @throws OptionalDataException Primitive data was found in the
* stream instead of objects.
* @throws IOException Any of the usual Input/Output related exceptions.
*/
public final Object readObject()
throws IOException, ClassNotFoundException {
return readObject(Object.class);
}
/**
* Reads a String and only a string.
*
* @return the String read
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
private String readString() throws IOException {
try {
return (String) readObject(String.class);
} catch (ClassNotFoundException cnf) {
throw new IllegalStateException(cnf);
}
}
/**
* Internal method to read an object from the ObjectInputStream of the expected type.
* Called only from {@code readObject()} and {@code readString()}.
* Only {@code Object.class} and {@code String.class} are supported.
*
* @param type the type expected; either Object.class or String.class
* @return an object of the type
* @throws IOException Any of the usual Input/Output related exceptions.
* @throws ClassNotFoundException Class of a serialized object cannot be
* found.
*/
private final Object readObject(Class<?> type)
throws IOException, ClassNotFoundException
{
if (enableOverride) {
return readObjectOverride();
}
if (! (type == Object.class || type == String.class))
throw new AssertionError("internal error");
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(type, false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
freeze();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}
/**
* This method is called by trusted subclasses of ObjectInputStream that
* constructed ObjectInputStream using the protected no-arg constructor.
* The subclass is expected to provide an override method with the modifier
* "final".
*
* @return the Object read from the stream.
* @throws ClassNotFoundException Class definition of a serialized object
* cannot be found.
* @throws OptionalDataException Primitive data was found in the stream
* instead of objects.
* @throws IOException if I/O errors occurred while reading from the
* underlying stream
* @see #ObjectInputStream()
* @see #readObject()
* @since 1.2
*/
protected Object readObjectOverride()
throws IOException, ClassNotFoundException
{
return null;
}
/**
* Reads an "unshared" object from the ObjectInputStream. This method is
* identical to readObject, except that it prevents subsequent calls to
* readObject and readUnshared from returning additional references to the
* deserialized instance obtained via this call. Specifically:
* <ul>
* <li>If readUnshared is called to deserialize a back-reference (the
* stream representation of an object which has been written
* previously to the stream), an ObjectStreamException will be
* thrown.
*
* <li>If readUnshared returns successfully, then any subsequent attempts
* to deserialize back-references to the stream handle deserialized
* by readUnshared will cause an ObjectStreamException to be thrown.
* </ul>
* Deserializing an object via readUnshared invalidates the stream handle
* associated with the returned object. Note that this in itself does not
* always guarantee that the reference returned by readUnshared is unique;
* the deserialized object may define a readResolve method which returns an
* object visible to other parties, or readUnshared may return a Class
* object or enum constant obtainable elsewhere in the stream or through
* external means. If the deserialized object defines a readResolve method
* and the invocation of that method returns an array, then readUnshared
* returns a shallow clone of that array; this guarantees that the returned
* array object is unique and cannot be obtained a second time from an
* invocation of readObject or readUnshared on the ObjectInputStream,
* even if the underlying data stream has been manipulated.
*
* <p>The deserialization filter, when not {@code null}, is invoked for
* each object (regular or class) read to reconstruct the root object.
* See {@link #setObjectInputFilter(ObjectInputFilter) setObjectInputFilter} for details.
*
* <p>ObjectInputStream subclasses which override this method can only be
* constructed in security contexts possessing the
* "enableSubclassImplementation" SerializablePermission; any attempt to
* instantiate such a subclass without this permission will cause a
* SecurityException to be thrown.
*
* @return reference to deserialized object
* @throws ClassNotFoundException if class of an object to deserialize
* cannot be found
* @throws StreamCorruptedException if control information in the stream
* is inconsistent
* @throws ObjectStreamException if object to deserialize has already
* appeared in stream
* @throws OptionalDataException if primitive data is next in stream
* @throws IOException if an I/O error occurs during deserialization
* @since 1.4
*/
public Object readUnshared() throws IOException, ClassNotFoundException {
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(Object.class, true);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
freeze();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}
/**
* Read the non-static and non-transient fields of the current class from
* this stream. This may only be called from the readObject method of the
* class being deserialized. It will throw the NotActiveException if it is
* called otherwise.
*
* @throws ClassNotFoundException if the class of a serialized object
* could not be found.
* @throws IOException if an I/O error occurs.
* @throws NotActiveException if the stream is not currently reading
* objects.
*/
public void defaultReadObject()
throws IOException, ClassNotFoundException
{
SerialCallbackContext ctx = curContext;
if (ctx == null) {
throw new NotActiveException("not in call to readObject");
}
Object curObj = ctx.getObj();
ObjectStreamClass curDesc = ctx.getDesc();
bin.setBlockDataMode(false);
// Read fields of the current descriptor into a new FieldValues
FieldValues values = new FieldValues(curDesc, true);
if (curObj != null) {
values.defaultCheckFieldValues(curObj);
values.defaultSetFieldValues(curObj);
}
bin.setBlockDataMode(true);
if (!curDesc.hasWriteObjectData()) {
/*
* Fix for 4360508: since stream does not contain terminating
* TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
* knows to simulate end-of-custom-data behavior.
*/
defaultDataEnd = true;
}
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
}
/**
* Reads the persistent fields from the stream and makes them available by
* name.
*
* @return the {@code GetField} object representing the persistent
* fields of the object being deserialized
* @throws ClassNotFoundException if the class of a serialized object
* could not be found.
* @throws IOException if an I/O error occurs.
* @throws NotActiveException if the stream is not currently reading
* objects.
* @since 1.2
*/
public ObjectInputStream.GetField readFields()
throws IOException, ClassNotFoundException
{
SerialCallbackContext ctx = curContext;
if (ctx == null) {
throw new NotActiveException("not in call to readObject");
}
ctx.checkAndSetUsed();
ObjectStreamClass curDesc = ctx.getDesc();
bin.setBlockDataMode(false);
// Read fields of the current descriptor into a new FieldValues
FieldValues values = new FieldValues(curDesc, false);
bin.setBlockDataMode(true);
if (!curDesc.hasWriteObjectData()) {
/*
* Fix for 4360508: since stream does not contain terminating
* TC_ENDBLOCKDATA tag, set flag so that reading code elsewhere
* knows to simulate end-of-custom-data behavior.
*/
defaultDataEnd = true;
}
return values;
}
/**
* Register an object to be validated before the graph is returned. While
* similar to resolveObject these validations are called after the entire
* graph has been reconstituted. Typically, a readObject method will
* register the object with the stream so that when all of the objects are
* restored a final set of validations can be performed.
*
* @param obj the object to receive the validation callback.
* @param prio controls the order of callbacks; zero is a good default.
* Use higher numbers to be called back earlier, lower numbers for
* later callbacks. Within a priority, callbacks are processed in
* no particular order.
* @throws NotActiveException The stream is not currently reading objects
* so it is invalid to register a callback.
* @throws InvalidObjectException The validation object is null.
*/
public void registerValidation(ObjectInputValidation obj, int prio)
throws NotActiveException, InvalidObjectException
{
if (depth == 0) {
throw new NotActiveException("stream inactive");
}
vlist.register(obj, prio);
}
/**
* Load the local class equivalent of the specified stream class
* description. Subclasses may implement this method to allow classes to
* be fetched from an alternate source.
*
* <p>The corresponding method in {@code ObjectOutputStream} is
* {@code annotateClass}. This method will be invoked only once for
* each unique class in the stream. This method can be implemented by
* subclasses to use an alternate loading mechanism but must return a
* {@code Class} object. Once returned, if the class is not an array
* class, its serialVersionUID is compared to the serialVersionUID of the
* serialized class, and if there is a mismatch, the deserialization fails
* and an {@link InvalidClassException} is thrown.
*
* <p>The default implementation of this method in
* {@code ObjectInputStream} returns the result of calling
* {@snippet lang="java":
* Class.forName(desc.getName(), false, loader)
* }
* where {@code loader} is the first class loader on the current
* thread's stack (starting from the currently executing method) that is
* neither the {@linkplain ClassLoader#getPlatformClassLoader() platform
* class loader} nor its ancestor; otherwise, {@code loader} is the
* <em>platform class loader</em>. If this call results in a
* {@code ClassNotFoundException} and the name of the passed
* {@code ObjectStreamClass} instance is the Java language keyword
* for a primitive type or void, then the {@code Class} object
* representing that primitive type or void will be returned
* (e.g., an {@code ObjectStreamClass} with the name
* {@code "int"} will be resolved to {@code Integer.TYPE}).
* Otherwise, the {@code ClassNotFoundException} will be thrown to
* the caller of this method.
*
* @param desc an instance of class {@code ObjectStreamClass}
* @return a {@code Class} object corresponding to {@code desc}
* @throws IOException any of the usual Input/Output exceptions.
* @throws ClassNotFoundException if class of a serialized object cannot
* be found.
*/
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException
{
String name = desc.getName();
try {
return Class.forName(name, false, latestUserDefinedLoader());
} catch (ClassNotFoundException ex) {
Class<?> cl = primClasses.get(name);
if (cl != null) {
return cl;
} else {
throw ex;
}
}
}
/**
* Returns a proxy class that implements the interfaces named in a proxy
* class descriptor; subclasses may implement this method to read custom
* data from the stream along with the descriptors for dynamic proxy
* classes, allowing them to use an alternate loading mechanism for the
* interfaces and the proxy class.
*
* <p>This method is called exactly once for each unique proxy class
* descriptor in the stream.
*
* <p>The corresponding method in {@code ObjectOutputStream} is
* {@code annotateProxyClass}. For a given subclass of
* {@code ObjectInputStream} that overrides this method, the
* {@code annotateProxyClass} method in the corresponding subclass of
* {@code ObjectOutputStream} must write any data or objects read by
* this method.
*
* <p>The default implementation of this method in
* {@code ObjectInputStream} returns the result of calling
* {@code Proxy.getProxyClass} with the list of {@code Class}
* objects for the interfaces that are named in the {@code interfaces}
* parameter. The {@code Class} object for each interface name
* {@code i} is the value returned by calling
* {@snippet lang="java":
* Class.forName(i, false, loader)
* }
* where {@code loader} is the first class loader on the current
* thread's stack (starting from the currently executing method) that is
* neither the {@linkplain ClassLoader#getPlatformClassLoader() platform
* class loader} nor its ancestor; otherwise, {@code loader} is the
* <em>platform class loader</em>.
* Unless any of the resolved interfaces are non-public, this same value
* of {@code loader} is also the class loader passed to
* {@code Proxy.getProxyClass}; if non-public interfaces are present,
* their class loader is passed instead (if more than one non-public
* interface class loader is encountered, an
* {@code IllegalAccessError} is thrown).
* If {@code Proxy.getProxyClass} throws an
* {@code IllegalArgumentException}, {@code resolveProxyClass}
* will throw a {@code ClassNotFoundException} containing the
* {@code IllegalArgumentException}.
*
* @param interfaces the list of interface names that were
* deserialized in the proxy class descriptor
* @return a proxy class for the specified interfaces
* @throws IOException any exception thrown by the underlying
* {@code InputStream}
* @throws ClassNotFoundException if the proxy class or any of the
* named interfaces could not be found
* @see ObjectOutputStream#annotateProxyClass(Class)
* @since 1.3
*/
protected Class<?> resolveProxyClass(String[] interfaces)
throws IOException, ClassNotFoundException
{
ClassLoader latestLoader = latestUserDefinedLoader();
ClassLoader nonPublicLoader = null;
boolean hasNonPublicInterface = false;
// define proxy in class loader of non-public interface(s), if any
Class<?>[] classObjs = new Class<?>[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
Class<?> cl = Class.forName(interfaces[i], false, latestLoader);
if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
if (hasNonPublicInterface) {
if (nonPublicLoader != cl.getClassLoader()) {
throw new IllegalAccessError(
"conflicting non-public interface class loaders");
}
} else {
nonPublicLoader = cl.getClassLoader();
hasNonPublicInterface = true;
}
}
classObjs[i] = cl;
}
try {
@SuppressWarnings("deprecation")
Class<?> proxyClass = Proxy.getProxyClass(
hasNonPublicInterface ? nonPublicLoader : latestLoader,
classObjs);
return proxyClass;
} catch (IllegalArgumentException e) {
throw new ClassNotFoundException(null, e);
}
}
/**
* This method will allow trusted subclasses of ObjectInputStream to
* substitute one object for another during deserialization. Replacing
* objects is disabled until enableResolveObject is called. The
* enableResolveObject method checks that the stream requesting to resolve
* object can be trusted. Every reference to serializable objects is passed
* to resolveObject. To ensure that the private state of objects is not
* unintentionally exposed only trusted streams may use resolveObject.
*
* <p>This method is called after an object has been read but before it is
* returned from readObject. The default resolveObject method just returns
* the same object.
*
* <p>When a subclass is replacing objects it must ensure that the
* substituted object is compatible with every field where the reference
* will be stored. Objects whose type is not a subclass of the type of the
* field or array element abort the deserialization by raising an exception
* and the object is not be stored.
*
* <p>This method is called only once when each object is first
* encountered. All subsequent references to the object will be redirected
* to the new object.
*
* @param obj object to be substituted
* @return the substituted object
* @throws IOException Any of the usual Input/Output exceptions.
*/
protected Object resolveObject(Object obj) throws IOException {
return obj;
}
/**
* Enables the stream to do replacement of objects read from the stream. When
* enabled, the {@link #resolveObject} method is called for every object being
* deserialized.
*
* <p>If object replacement is currently not enabled, and
* {@code enable} is true, and there is a security manager installed,
* this method first calls the security manager's
* {@code checkPermission} method with the
* {@code SerializablePermission("enableSubstitution")} permission to
* ensure that the caller is permitted to enable the stream to do replacement
* of objects read from the stream.
*
* @param enable true for enabling use of {@code resolveObject} for
* every object being deserialized
* @return the previous setting before this method was invoked
* @throws SecurityException if a security manager exists and its
* {@code checkPermission} method denies enabling the stream
* to do replacement of objects read from the stream.
* @see SecurityManager#checkPermission
* @see java.io.SerializablePermission
*/
protected boolean enableResolveObject(boolean enable)
throws SecurityException
{
if (enable == enableResolve) {
return enable;
}
if (enable) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SUBSTITUTION_PERMISSION);
}
}
enableResolve = enable;
return !enableResolve;
}
/**
* The readStreamHeader method is provided to allow subclasses to read and
* verify their own stream headers. It reads and verifies the magic number
* and version number.
*
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws StreamCorruptedException if control information in the stream
* is inconsistent
*/
protected void readStreamHeader()
throws IOException, StreamCorruptedException
{
short s0 = bin.readShort();
short s1 = bin.readShort();
if (s0 != STREAM_MAGIC || s1 != STREAM_VERSION) {
throw new StreamCorruptedException(
String.format("invalid stream header: %04X%04X", s0, s1));
}
}
/**
* Read a class descriptor from the serialization stream. This method is
* called when the ObjectInputStream expects a class descriptor as the next
* item in the serialization stream. Subclasses of ObjectInputStream may
* override this method to read in class descriptors that have been written
* in non-standard formats (by subclasses of ObjectOutputStream which have
* overridden the {@code writeClassDescriptor} method). By default,
* this method reads class descriptors according to the format defined in
* the Object Serialization specification.
*
* @return the class descriptor read
* @throws IOException If an I/O error has occurred.
* @throws ClassNotFoundException If the Class of a serialized object used
* in the class descriptor representation cannot be found
* @see java.io.ObjectOutputStream#writeClassDescriptor(java.io.ObjectStreamClass)
* @since 1.3
*/
protected ObjectStreamClass readClassDescriptor()
throws IOException, ClassNotFoundException
{
ObjectStreamClass desc = new ObjectStreamClass();
desc.readNonProxy(this);
return desc;
}
/**
* Reads a byte of data. This method will block if no input is available.
*
* @return the byte read, or -1 if the end of the stream is reached.
* @throws IOException {@inheritDoc}
*/
@Override
public int read() throws IOException {
return bin.read();
}
/**
* Reads into an array of bytes. This method will block until some input
* is available. Consider using java.io.DataInputStream.readFully to read
* exactly 'length' bytes.
*
* @param buf the buffer into which the data is read
* @param off the start offset in the destination array {@code buf}
* @param len the maximum number of bytes read
* @return the total number of bytes read into the buffer, or
* {@code -1} if there is no more data because the end of
* the stream has been reached.
* @throws NullPointerException if {@code buf} is {@code null}.
* @throws IndexOutOfBoundsException if {@code off} is negative,
* {@code len} is negative, or {@code len} is greater than
* {@code buf.length - off}.
* @throws IOException If an I/O error has occurred.
* @see java.io.DataInputStream#readFully(byte[],int,int)
*/
@Override
public int read(byte[] buf, int off, int len) throws IOException {
if (buf == null) {
throw new NullPointerException();
}
Objects.checkFromIndexSize(off, len, buf.length);
return bin.read(buf, off, len, false);
}
/**
* Returns the number of bytes that can be read without blocking.
*
* @return the number of available bytes.
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
*/
@Override
public int available() throws IOException {
return bin.available();
}
/**
* {@inheritDoc}
*
* @throws IOException {@inheritDoc}
*/
@Override
public void close() throws IOException {
/*
* Even if stream already closed, propagate redundant close to
* underlying stream to stay consistent with previous implementations.
*/
closed = true;
if (depth == 0) {
clear();
}
bin.close();
}
/**
* Reads in a boolean.
*
* @return the boolean read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public boolean readBoolean() throws IOException {
return bin.readBoolean();
}
/**
* Reads an 8-bit byte.
*
* @return the 8-bit byte read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public byte readByte() throws IOException {
return bin.readByte();
}
/**
* Reads an unsigned 8-bit byte.
*
* @return the 8-bit byte read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public int readUnsignedByte() throws IOException {
return bin.readUnsignedByte();
}
/**
* Reads a 16-bit char.
*
* @return the 16-bit char read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public char readChar() throws IOException {
return bin.readChar();
}
/**
* Reads a 16-bit short.
*
* @return the 16-bit short read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public short readShort() throws IOException {
return bin.readShort();
}
/**
* Reads an unsigned 16-bit short.
*
* @return the 16-bit short read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public int readUnsignedShort() throws IOException {
return bin.readUnsignedShort();
}
/**
* Reads a 32-bit int.
*
* @return the 32-bit integer read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public int readInt() throws IOException {
return bin.readInt();
}
/**
* Reads a 64-bit long.
*
* @return the read 64-bit long.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public long readLong() throws IOException {
return bin.readLong();
}
/**
* Reads a 32-bit float.
*
* @return the 32-bit float read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public float readFloat() throws IOException {
return bin.readFloat();
}
/**
* Reads a 64-bit double.
*
* @return the 64-bit double read.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public double readDouble() throws IOException {
return bin.readDouble();
}
/**
* Reads bytes, blocking until all bytes are read.
*
* @param buf the buffer into which the data is read
* @throws NullPointerException If {@code buf} is {@code null}.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public void readFully(byte[] buf) throws IOException {
bin.readFully(buf, 0, buf.length, false);
}
/**
* Reads bytes, blocking until all bytes are read.
*
* @param buf the buffer into which the data is read
* @param off the start offset into the data array {@code buf}
* @param len the maximum number of bytes to read
* @throws NullPointerException If {@code buf} is {@code null}.
* @throws IndexOutOfBoundsException If {@code off} is negative,
* {@code len} is negative, or {@code len} is greater than
* {@code buf.length - off}.
* @throws EOFException If end of file is reached.
* @throws IOException If other I/O error has occurred.
*/
public void readFully(byte[] buf, int off, int len) throws IOException {
Objects.checkFromIndexSize(off, len, buf.length);
bin.readFully(buf, off, len, false);
}
/**
* Skips bytes.
*
* @param len the number of bytes to be skipped
* @return the actual number of bytes skipped.
* @throws IOException If an I/O error has occurred.
*/
@Override
public int skipBytes(int len) throws IOException {
return bin.skipBytes(len);
}
/**
* Reads in a line that has been terminated by a \n, \r, \r\n or EOF.
*
* @return a String copy of the line.
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @deprecated This method does not properly convert bytes to characters.
* see DataInputStream for the details and alternatives.
*/
@Deprecated
public String readLine() throws IOException {
return bin.readLine();
}
/**
* Reads a String in
* <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
* format.
*
* @return the String.
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws UTFDataFormatException if read bytes do not represent a valid
* modified UTF-8 encoding of a string
*/
public String readUTF() throws IOException {
return bin.readUTF();
}
/**
* Returns the deserialization filter for this stream.
* The filter is the result of invoking the
* {@link Config#getSerialFilterFactory() JVM-wide filter factory}
* either by the {@linkplain #ObjectInputStream() constructor} or the most recent invocation of
* {@link #setObjectInputFilter setObjectInputFilter}.
*
* @return the deserialization filter for the stream; may be null
* @since 9
*/
public final ObjectInputFilter getObjectInputFilter() {
return serialFilter;
}
/**
* Set the deserialization filter for the stream.
*
* The deserialization filter is set to the filter returned by invoking the
* {@linkplain Config#getSerialFilterFactory() JVM-wide filter factory}
* with the {@linkplain #getObjectInputFilter() current filter} and the {@code filter} parameter.
* The current filter was set in the
* {@linkplain #ObjectInputStream() ObjectInputStream constructors} by invoking the
* {@linkplain Config#getSerialFilterFactory() JVM-wide filter factory} and may be {@code null}.
* {@linkplain #setObjectInputFilter(ObjectInputFilter)} This method} can be called
* once and only once before reading any objects from the stream;
* for example, by calling {@link #readObject} or {@link #readUnshared}.
*
* <p>It is not permitted to replace a {@code non-null} filter with a {@code null} filter.
* If the {@linkplain #getObjectInputFilter() current filter} is {@code non-null},
* the value returned from the filter factory must be {@code non-null}.
*
* <p>The filter's {@link ObjectInputFilter#checkInput checkInput} method is called
* for each class and reference in the stream.
* The filter can check any or all of the class, the array length, the number
* of references, the depth of the graph, and the size of the input stream.
* The depth is the number of nested {@linkplain #readObject readObject}
* calls starting with the reading of the root of the graph being deserialized
* and the current object being deserialized.
* The number of references is the cumulative number of objects and references
* to objects already read from the stream including the current object being read.
* The filter is invoked only when reading objects from the stream and not for
* primitives.
* <p>
* If the filter returns {@link ObjectInputFilter.Status#REJECTED Status.REJECTED},
* {@code null} or throws a {@link RuntimeException},
* the active {@code readObject} or {@code readUnshared}
* throws {@link InvalidClassException}, otherwise deserialization
* continues uninterrupted.
*
* @implSpec
* The filter, when not {@code null}, is invoked during {@link #readObject readObject}
* and {@link #readUnshared readUnshared} for each object (regular or class) in the stream.
* Strings are treated as primitives and do not invoke the filter.
* The filter is called for:
* <ul>
* <li>each object reference previously deserialized from the stream
* (class is {@code null}, arrayLength is -1),
* <li>each regular class (class is not {@code null}, arrayLength is -1),
* <li>each interface class explicitly referenced in the stream
* (it is not called for interfaces implemented by classes in the stream),
* <li>each interface of a dynamic proxy and the dynamic proxy class itself
* (class is not {@code null}, arrayLength is -1),
* <li>each array is filtered using the array type and length of the array
* (class is the array type, arrayLength is the requested length),
* <li>each object replaced by its class' {@code readResolve} method
* is filtered using the replacement object's class, if not {@code null},
* and if it is an array, the arrayLength, otherwise -1,
* <li>and each object replaced by {@link #resolveObject resolveObject}
* is filtered using the replacement object's class, if not {@code null},
* and if it is an array, the arrayLength, otherwise -1.
* </ul>
*
* When the {@link ObjectInputFilter#checkInput checkInput} method is invoked
* it is given access to the current class, the array length,
* the current number of references already read from the stream,
* the depth of nested calls to {@link #readObject readObject} or
* {@link #readUnshared readUnshared},
* and the implementation dependent number of bytes consumed from the input stream.
* <p>
* Each call to {@link #readObject readObject} or
* {@link #readUnshared readUnshared} increases the depth by 1
* before reading an object and decreases by 1 before returning
* normally or exceptionally.
* The depth starts at {@code 1} and increases for each nested object and
* decrements when each nested call returns.
* The count of references in the stream starts at {@code 1} and
* is increased before reading an object.
*
* @param filter the filter, may be null
* @throws SecurityException if there is security manager and the
* {@code SerializablePermission("serialFilter")} is not granted
* @throws IllegalStateException if an object has been read,
* if the filter factory returns {@code null} when the
* {@linkplain #getObjectInputFilter() current filter} is non-null, or
* if the filter has already been set.
* @since 9
*/
public final void setObjectInputFilter(ObjectInputFilter filter) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(ObjectStreamConstants.SERIAL_FILTER_PERMISSION);
}
if (totalObjectRefs > 0 && !Caches.SET_FILTER_AFTER_READ) {
throw new IllegalStateException(
"filter can not be set after an object has been read");
}
if (streamFilterSet) {
throw new IllegalStateException("filter can not be set more than once");
}
streamFilterSet = true;
// Delegate to serialFilterFactory to compute stream filter
ObjectInputFilter next = Config.getSerialFilterFactory()
.apply(serialFilter, filter);
if (serialFilter != null && next == null) {
throw new IllegalStateException("filter can not be replaced with null filter");
}
serialFilter = next;
}
/**
* Invokes the deserialization filter if non-null.
*
* If the filter rejects or an exception is thrown, throws InvalidClassException.
*
* Logs and/or commits a {@code DeserializationEvent}, if configured.
*
* @param clazz the class; may be null
* @param arrayLength the array length requested; use {@code -1} if not creating an array
* @throws InvalidClassException if it rejected by the filter or
* a {@link RuntimeException} is thrown
*/
private void filterCheck(Class<?> clazz, int arrayLength)
throws InvalidClassException {
// Info about the stream is not available if overridden by subclass, return 0
long bytesRead = (bin == null) ? 0 : bin.getBytesRead();
RuntimeException ex = null;
ObjectInputFilter.Status status = null;
if (serialFilter != null) {
try {
status = serialFilter.checkInput(new FilterValues(clazz, arrayLength,
totalObjectRefs, depth, bytesRead));
} catch (RuntimeException e) {
// Preventive interception of an exception to log
status = ObjectInputFilter.Status.REJECTED;
ex = e;
}
if (Logging.filterLogger != null) {
// Debug logging of filter checks that fail; Tracing for those that succeed
Logging.filterLogger.log(status == null || status == ObjectInputFilter.Status.REJECTED
? Logger.Level.DEBUG
: Logger.Level.TRACE,
"ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
status, clazz, arrayLength, totalObjectRefs, depth, bytesRead,
Objects.toString(ex, "n/a"));
}
}
DeserializationEvent event = new DeserializationEvent();
if (event.shouldCommit()) {
event.filterConfigured = serialFilter != null;
event.filterStatus = status != null ? status.name() : null;
event.type = clazz;
event.arrayLength = arrayLength;
event.objectReferences = totalObjectRefs;
event.depth = depth;
event.bytesRead = bytesRead;
event.exceptionType = ex != null ? ex.getClass() : null;
event.exceptionMessage = ex != null ? ex.getMessage() : null;
event.commit();
}
if (serialFilter != null && (status == null || status == ObjectInputFilter.Status.REJECTED)) {
throw new InvalidClassException("filter status: " + status, ex);
}
}
/**
* Checks the given array type and length to ensure that creation of such
* an array is permitted by this ObjectInputStream. The arrayType argument
* must represent an actual array type.
*
* This private method is called via SharedSecrets.
*
* @param arrayType the array type
* @param arrayLength the array length
* @throws NullPointerException if arrayType is null
* @throws IllegalArgumentException if arrayType isn't actually an array type
* @throws StreamCorruptedException if arrayLength is negative
* @throws InvalidClassException if the filter rejects creation
*/
private void checkArray(Class<?> arrayType, int arrayLength) throws ObjectStreamException {
if (! arrayType.isArray()) {
throw new IllegalArgumentException("not an array type");
}
if (arrayLength < 0) {
throw new StreamCorruptedException("Array length is negative");
}
filterCheck(arrayType, arrayLength);
}
/**
* Provide access to the persistent fields read from the input stream.
*/
public abstract static class GetField {
/**
* Constructor for subclasses to call.
*/
public GetField() {}
/**
* Get the ObjectStreamClass that describes the fields in the stream.
*
* @return the descriptor class that describes the serializable fields
*/
public abstract ObjectStreamClass getObjectStreamClass();
/**
* Return true if the named field is defaulted and has no value in this
* stream.
*
* @param name the name of the field
* @return true, if and only if the named field is defaulted
* @throws IOException if there are I/O errors while reading from
* the underlying {@code InputStream}
* @throws IllegalArgumentException if {@code name} does not
* correspond to a serializable field
*/
public abstract boolean defaulted(String name) throws IOException;
/**
* Get the value of the named boolean field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code boolean} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract boolean get(String name, boolean val)
throws IOException;
/**
* Get the value of the named byte field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code byte} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract byte get(String name, byte val) throws IOException;
/**
* Get the value of the named char field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code char} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract char get(String name, char val) throws IOException;
/**
* Get the value of the named short field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code short} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract short get(String name, short val) throws IOException;
/**
* Get the value of the named int field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code int} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract int get(String name, int val) throws IOException;
/**
* Get the value of the named long field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code long} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract long get(String name, long val) throws IOException;
/**
* Get the value of the named float field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code float} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract float get(String name, float val) throws IOException;
/**
* Get the value of the named double field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code double} field
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract double get(String name, double val) throws IOException;
/**
* Get the value of the named Object field from the persistent field.
*
* @param name the name of the field
* @param val the default value to use if {@code name} does not
* have a value
* @return the value of the named {@code Object} field
* @throws ClassNotFoundException Class of a serialized object cannot be found.
* @throws IOException if there are I/O errors while reading from the
* underlying {@code InputStream}
* @throws IllegalArgumentException if type of {@code name} is
* not serializable or if the field type is incorrect
*/
public abstract Object get(String name, Object val) throws IOException, ClassNotFoundException;
}
/**
* Verifies that this (possibly subclass) instance can be constructed
* without violating security constraints: the subclass must not override
* security-sensitive non-final methods, or else the
* "enableSubclassImplementation" SerializablePermission is checked.
*/
private void verifySubclass() {
Class<?> cl = getClass();
if (cl == ObjectInputStream.class) {
return;
}
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
return;
}
boolean result = Caches.subclassAudits.get(cl);
if (!result) {
sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
/**
* Performs reflective checks on given subclass to verify that it doesn't
* override security-sensitive non-final methods. Returns TRUE if subclass
* is "safe", FALSE otherwise.
*/
@SuppressWarnings("removal")
private static Boolean auditSubclass(Class<?> subcl) {
return AccessController.doPrivileged(
new PrivilegedAction<Boolean>() {
public Boolean run() {
for (Class<?> cl = subcl;
cl != ObjectInputStream.class;
cl = cl.getSuperclass())
{
try {
cl.getDeclaredMethod(
"readUnshared", (Class[]) null);
return Boolean.FALSE;
} catch (NoSuchMethodException ex) {
}
try {
cl.getDeclaredMethod("readFields", (Class[]) null);
return Boolean.FALSE;
} catch (NoSuchMethodException ex) {
}
}
return Boolean.TRUE;
}
}
);
}
/**
* Clears internal data structures.
*/
private void clear() {
handles.clear();
vlist.clear();
}
/**
* Underlying readObject implementation.
* @param type a type expected to be deserialized; non-null
* @param unshared true if the object can not be a reference to a shared object, otherwise false
*/
private Object readObject0(Class<?> type, boolean unshared) throws IOException {
boolean oldMode = bin.getBlockDataMode();
if (oldMode) {
int remain = bin.currentBlockRemaining();
if (remain > 0) {
throw new OptionalDataException(remain);
} else if (defaultDataEnd) {
/*
* Fix for 4360508: stream is currently at the end of a field
* value block written via default serialization; since there
* is no terminating TC_ENDBLOCKDATA tag, simulate
* end-of-custom-data behavior explicitly.
*/
throw new OptionalDataException(true);
}
bin.setBlockDataMode(false);
}
byte tc;
while ((tc = bin.peekByte()) == TC_RESET) {
bin.readByte();
handleReset();
}
depth++;
totalObjectRefs++;
try {
switch (tc) {
case TC_NULL:
return readNull();
case TC_REFERENCE:
// check the type of the existing object
return type.cast(readHandle(unshared));
case TC_CLASS:
if (type == String.class) {
throw new ClassCastException("Cannot cast a class to java.lang.String");
}
return readClass(unshared);
case TC_CLASSDESC:
case TC_PROXYCLASSDESC:
if (type == String.class) {
throw new ClassCastException("Cannot cast a class to java.lang.String");
}
return readClassDesc(unshared);
case TC_STRING:
case TC_LONGSTRING:
return checkResolve(readString(unshared));
case TC_ARRAY:
if (type == String.class) {
throw new ClassCastException("Cannot cast an array to java.lang.String");
}
return checkResolve(readArray(unshared));
case TC_ENUM:
if (type == String.class) {
throw new ClassCastException("Cannot cast an enum to java.lang.String");
}
return checkResolve(readEnum(unshared));
case TC_OBJECT:
if (type == String.class) {
throw new ClassCastException("Cannot cast an object to java.lang.String");
}
return checkResolve(readOrdinaryObject(unshared));
case TC_EXCEPTION:
if (type == String.class) {
throw new ClassCastException("Cannot cast an exception to java.lang.String");
}
IOException ex = readFatalException();
throw new WriteAbortedException("writing aborted", ex);
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
if (oldMode) {
bin.setBlockDataMode(true);
bin.peek(); // force header read
throw new OptionalDataException(
bin.currentBlockRemaining());
} else {
throw new StreamCorruptedException(
"unexpected block data");
}
case TC_ENDBLOCKDATA:
if (oldMode) {
throw new OptionalDataException(true);
} else {
throw new StreamCorruptedException(
"unexpected end of block data");
}
default:
throw new StreamCorruptedException(
String.format("invalid type code: %02X", tc));
}
} finally {
depth--;
bin.setBlockDataMode(oldMode);
}
}
/**
* If resolveObject has been enabled and given object does not have an
* exception associated with it, calls resolveObject to determine
* replacement for object, and updates handle table accordingly. Returns
* replacement object, or echoes provided object if no replacement
* occurred. Expects that passHandle is set to given object's handle prior
* to calling this method.
*/
private Object checkResolve(Object obj) throws IOException {
if (!enableResolve || handles.lookupException(passHandle) != null) {
return obj;
}
Object rep = resolveObject(obj);
if (rep != obj) {
// The type of the original object has been filtered but resolveObject
// may have replaced it; filter the replacement's type
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, rep);
}
return rep;
}
/**
* Reads string without allowing it to be replaced in stream. Called from
* within ObjectStreamClass.read().
*/
String readTypeString() throws IOException {
int oldHandle = passHandle;
try {
byte tc = bin.peekByte();
return switch (tc) {
case TC_NULL -> (String) readNull();
case TC_REFERENCE -> (String) readHandle(false);
case TC_STRING, TC_LONGSTRING -> readString(false);
default -> throw new StreamCorruptedException(
String.format("invalid type code: %02X", tc));
};
} finally {
passHandle = oldHandle;
}
}
/**
* Reads in null code, sets passHandle to NULL_HANDLE and returns null.
*/
private Object readNull() throws IOException {
if (bin.readByte() != TC_NULL) {
throw new InternalError();
}
passHandle = NULL_HANDLE;
return null;
}
/**
* Reads in object handle, sets passHandle to the read handle, and returns
* object associated with the handle.
*/
private Object readHandle(boolean unshared) throws IOException {
if (bin.readByte() != TC_REFERENCE) {
throw new InternalError();
}
passHandle = bin.readInt() - baseWireHandle;
if (passHandle < 0 || passHandle >= handles.size()) {
throw new StreamCorruptedException(
String.format("invalid handle value: %08X", passHandle +
baseWireHandle));
}
if (unshared) {
// REMIND: what type of exception to throw here?
throw new InvalidObjectException(
"cannot read back reference as unshared");
}
Object obj = handles.lookupObject(passHandle);
if (obj == unsharedMarker) {
// REMIND: what type of exception to throw here?
throw new InvalidObjectException(
"cannot read back reference to unshared object");
}
filterCheck(null, -1); // just a check for number of references, depth, no class
return obj;
}
/**
* Reads in and returns class object. Sets passHandle to class object's
* assigned handle. Returns null if class is unresolvable (in which case a
* ClassNotFoundException will be associated with the class' handle in the
* handle table).
*/
private Class<?> readClass(boolean unshared) throws IOException {
if (bin.readByte() != TC_CLASS) {
throw new InternalError();
}
ObjectStreamClass desc = readClassDesc(false);
Class<?> cl = desc.forClass();
passHandle = handles.assign(unshared ? unsharedMarker : cl);
ClassNotFoundException resolveEx = desc.getResolveException();
if (resolveEx != null) {
handles.markException(passHandle, resolveEx);
}
handles.finish(passHandle);
return cl;
}
/**
* Reads in and returns (possibly null) class descriptor. Sets passHandle
* to class descriptor's assigned handle. If class descriptor cannot be
* resolved to a class in the local VM, a ClassNotFoundException is
* associated with the class descriptor's handle.
*/
private ObjectStreamClass readClassDesc(boolean unshared)
throws IOException
{
byte tc = bin.peekByte();
return switch (tc) {
case TC_NULL -> (ObjectStreamClass) readNull();
case TC_PROXYCLASSDESC -> readProxyDesc(unshared);
case TC_CLASSDESC -> readNonProxyDesc(unshared);
case TC_REFERENCE -> {
var d = (ObjectStreamClass) readHandle(unshared);
// Should only reference initialized class descriptors
d.checkInitialized();
yield d;
}
default -> throw new StreamCorruptedException(
String.format("invalid type code: %02X", tc));
};
}
private boolean isCustomSubclass() {
// Return true if this class is a custom subclass of ObjectInputStream
return getClass().getClassLoader()
!= ObjectInputStream.class.getClassLoader();
}
/**
* Reads in and returns class descriptor for a dynamic proxy class. Sets
* passHandle to proxy class descriptor's assigned handle. If proxy class
* descriptor cannot be resolved to a class in the local VM, a
* ClassNotFoundException is associated with the descriptor's handle.
*/
private ObjectStreamClass readProxyDesc(boolean unshared)
throws IOException
{
if (bin.readByte() != TC_PROXYCLASSDESC) {
throw new InternalError();
}
ObjectStreamClass desc = new ObjectStreamClass();
int descHandle = handles.assign(unshared ? unsharedMarker : desc);
passHandle = NULL_HANDLE;
int numIfaces = bin.readInt();
if (numIfaces > 65535) {
// Report specification limit exceeded
throw new InvalidObjectException("interface limit exceeded: " +
numIfaces +
", limit: " + Caches.PROXY_INTERFACE_LIMIT);
}
String[] ifaces = new String[numIfaces];
for (int i = 0; i < numIfaces; i++) {
ifaces[i] = bin.readUTF();
}
// Recheck against implementation limit and throw with interface names
if (numIfaces > Caches.PROXY_INTERFACE_LIMIT) {
throw new InvalidObjectException("interface limit exceeded: " +
numIfaces +
", limit: " + Caches.PROXY_INTERFACE_LIMIT +
"; " + Arrays.toString(ifaces));
}
Class<?> cl = null;
ClassNotFoundException resolveEx = null;
bin.setBlockDataMode(true);
try {
if ((cl = resolveProxyClass(ifaces)) == null) {
resolveEx = new ClassNotFoundException("null class");
} else if (!Proxy.isProxyClass(cl)) {
throw new InvalidClassException("Not a proxy");
} else {
// ReflectUtil.checkProxyPackageAccess makes a test
// equivalent to isCustomSubclass so there's no need
// to condition this call to isCustomSubclass == true here.
ReflectUtil.checkProxyPackageAccess(
getClass().getClassLoader(),
cl.getInterfaces());
// Filter the interfaces
for (Class<?> clazz : cl.getInterfaces()) {
filterCheck(clazz, -1);
}
}
} catch (ClassNotFoundException ex) {
resolveEx = ex;
} catch (IllegalAccessError aie) {
throw new InvalidClassException(aie.getMessage(), aie);
} catch (OutOfMemoryError memerr) {
throw new InvalidObjectException("Proxy interface limit exceeded: " +
Arrays.toString(ifaces), memerr);
}
// Call filterCheck on the class before reading anything else
filterCheck(cl, -1);
skipCustomData();
try {
totalObjectRefs++;
depth++;
desc.initProxy(cl, resolveEx, readClassDesc(false));
} catch (OutOfMemoryError memerr) {
throw new InvalidObjectException("Proxy interface limit exceeded: " +
Arrays.toString(ifaces), memerr);
} finally {
depth--;
}
handles.finish(descHandle);
passHandle = descHandle;
return desc;
}
/**
* Reads in and returns class descriptor for a class that is not a dynamic
* proxy class. Sets passHandle to class descriptor's assigned handle. If
* class descriptor cannot be resolved to a class in the local VM, a
* ClassNotFoundException is associated with the descriptor's handle.
*/
private ObjectStreamClass readNonProxyDesc(boolean unshared)
throws IOException
{
if (bin.readByte() != TC_CLASSDESC) {
throw new InternalError();
}
ObjectStreamClass desc = new ObjectStreamClass();
int descHandle = handles.assign(unshared ? unsharedMarker : desc);
passHandle = NULL_HANDLE;
ObjectStreamClass readDesc;
try {
readDesc = readClassDescriptor();
} catch (ClassNotFoundException ex) {
throw new InvalidClassException("failed to read class descriptor",
ex);
}
Class<?> cl = null;
ClassNotFoundException resolveEx = null;
bin.setBlockDataMode(true);
final boolean checksRequired = isCustomSubclass();
try {
if ((cl = resolveClass(readDesc)) == null) {
resolveEx = new ClassNotFoundException("null class");
} else if (checksRequired) {
ReflectUtil.checkPackageAccess(cl);
}
} catch (ClassNotFoundException ex) {
resolveEx = ex;
}
// Call filterCheck on the class before reading anything else
filterCheck(cl, -1);
skipCustomData();
try {
totalObjectRefs++;
depth++;
desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));
if (cl != null) {
// Check that serial filtering has been done on the local class descriptor's superclass,
// in case it does not appear in the stream.
// Find the next super descriptor that has a local class descriptor.
// Descriptors for which there is no local class are ignored.
ObjectStreamClass superLocal = null;
for (ObjectStreamClass sDesc = desc.getSuperDesc(); sDesc != null; sDesc = sDesc.getSuperDesc()) {
if ((superLocal = sDesc.getLocalDesc()) != null) {
break;
}
}
// Scan local descriptor superclasses for a match with the local descriptor of the super found above.
// For each super descriptor before the match, invoke the serial filter on the class.
// The filter is invoked for each class that has not already been filtered
// but would be filtered if the instance had been serialized by this Java runtime.
for (ObjectStreamClass lDesc = desc.getLocalDesc().getSuperDesc();
lDesc != null && lDesc != superLocal;
lDesc = lDesc.getSuperDesc()) {
filterCheck(lDesc.forClass(), -1);
}
}
} finally {
depth--;
}
handles.finish(descHandle);
passHandle = descHandle;
return desc;
}
/**
* Reads in and returns new string. Sets passHandle to new string's
* assigned handle.
*/
private String readString(boolean unshared) throws IOException {
byte tc = bin.readByte();
String str = switch (tc) {
case TC_STRING -> bin.readUTF();
case TC_LONGSTRING -> bin.readLongUTF();
default -> throw new StreamCorruptedException(
String.format("invalid type code: %02X", tc));
};
passHandle = handles.assign(unshared ? unsharedMarker : str);
handles.finish(passHandle);
return str;
}
/**
* Reads in and returns array object, or null if array class is
* unresolvable. Sets passHandle to array's assigned handle.
*/
private Object readArray(boolean unshared) throws IOException {
if (bin.readByte() != TC_ARRAY) {
throw new InternalError();
}
ObjectStreamClass desc = readClassDesc(false);
int len = bin.readInt();
if (len < 0) {
throw new StreamCorruptedException("Array length is negative");
}
filterCheck(desc.forClass(), len);
Object array = null;
Class<?> cl, ccl = null;
if ((cl = desc.forClass()) != null) {
ccl = cl.getComponentType();
array = Array.newInstance(ccl, len);
}
int arrayHandle = handles.assign(unshared ? unsharedMarker : array);
ClassNotFoundException resolveEx = desc.getResolveException();
if (resolveEx != null) {
handles.markException(arrayHandle, resolveEx);
}
if (ccl == null) {
for (int i = 0; i < len; i++) {
readObject0(Object.class, false);
}
} else if (ccl.isPrimitive()) {
if (ccl == Integer.TYPE) {
bin.readInts((int[]) array, 0, len);
} else if (ccl == Byte.TYPE) {
bin.readFully((byte[]) array, 0, len, true);
} else if (ccl == Long.TYPE) {
bin.readLongs((long[]) array, 0, len);
} else if (ccl == Float.TYPE) {
bin.readFloats((float[]) array, 0, len);
} else if (ccl == Double.TYPE) {
bin.readDoubles((double[]) array, 0, len);
} else if (ccl == Short.TYPE) {
bin.readShorts((short[]) array, 0, len);
} else if (ccl == Character.TYPE) {
bin.readChars((char[]) array, 0, len);
} else if (ccl == Boolean.TYPE) {
bin.readBooleans((boolean[]) array, 0, len);
} else {
throw new InternalError();
}
} else {
Object[] oa = (Object[]) array;
for (int i = 0; i < len; i++) {
oa[i] = readObject0(Object.class, false);
handles.markDependency(arrayHandle, passHandle);
}
}
handles.finish(arrayHandle);
passHandle = arrayHandle;
return array;
}
/**
* Reads in and returns enum constant, or null if enum type is
* unresolvable. Sets passHandle to enum constant's assigned handle.
*/
private Enum<?> readEnum(boolean unshared) throws IOException {
if (bin.readByte() != TC_ENUM) {
throw new InternalError();
}
ObjectStreamClass desc = readClassDesc(false);
if (!desc.isEnum()) {
throw new InvalidClassException("non-enum class: " + desc);
}
int enumHandle = handles.assign(unshared ? unsharedMarker : null);
ClassNotFoundException resolveEx = desc.getResolveException();
if (resolveEx != null) {
handles.markException(enumHandle, resolveEx);
}
String name = readString(false);
Enum<?> result = null;
Class<?> cl = desc.forClass();
if (cl != null) {
try {
@SuppressWarnings("unchecked")
Enum<?> en = Enum.valueOf((Class)cl, name);
result = en;
} catch (IllegalArgumentException ex) {
throw new InvalidObjectException("enum constant " +
name + " does not exist in " + cl, ex);
}
if (!unshared) {
handles.setObject(enumHandle, result);
}
}
handles.finish(enumHandle);
passHandle = enumHandle;
return result;
}
/**
* Reads and returns "ordinary" (i.e., not a String, Class,
* ObjectStreamClass, array, or enum constant) object, or null if object's
* class is unresolvable (in which case a ClassNotFoundException will be
* associated with object's handle). Sets passHandle to object's assigned
* handle.
*/
private Object readOrdinaryObject(boolean unshared)
throws IOException
{
if (bin.readByte() != TC_OBJECT) {
throw new InternalError();
}
ObjectStreamClass desc = readClassDesc(false);
desc.checkDeserialize();
Class<?> cl = desc.forClass();
if (cl == String.class || cl == Class.class
|| cl == ObjectStreamClass.class) {
throw new InvalidClassException("invalid class descriptor");
}
Object obj;
try {
obj = desc.isInstantiable() ? desc.newInstance() : null;
} catch (Exception ex) {
throw new InvalidClassException(desc.forClass().getName(),
"unable to create instance", ex);
}
passHandle = handles.assign(unshared ? unsharedMarker : obj);
ClassNotFoundException resolveEx = desc.getResolveException();
if (resolveEx != null) {
handles.markException(passHandle, resolveEx);
}
final boolean isRecord = desc.isRecord();
if (isRecord) {
assert obj == null;
obj = readRecord(desc);
if (!unshared)
handles.setObject(passHandle, obj);
} else if (desc.isExternalizable()) {
readExternalData((Externalizable) obj, desc);
} else {
readSerialData(obj, desc);
}
handles.finish(passHandle);
if (obj != null &&
handles.lookupException(passHandle) == null &&
desc.hasReadResolveMethod())
{
Object rep = desc.invokeReadResolve(obj);
if (unshared && rep.getClass().isArray()) {
rep = cloneArray(rep);
}
if (rep != obj) {
// Filter the replacement object
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, obj = rep);
}
}
return obj;
}
/**
* If obj is non-null, reads externalizable data by invoking readExternal()
* method of obj; otherwise, attempts to skip over externalizable data.
* Expects that passHandle is set to obj's handle before this method is
* called.
*/
private void readExternalData(Externalizable obj, ObjectStreamClass desc)
throws IOException
{
SerialCallbackContext oldContext = curContext;
if (oldContext != null)
oldContext.check();
curContext = null;
try {
boolean blocked = desc.hasBlockExternalData();
if (blocked) {
bin.setBlockDataMode(true);
}
if (obj != null) {
try {
obj.readExternal(this);
} catch (ClassNotFoundException ex) {
/*
* In most cases, the handle table has already propagated
* a CNFException to passHandle at this point; this mark
* call is included to address cases where the readExternal
* method has cons'ed and thrown a new CNFException of its
* own.
*/
handles.markException(passHandle, ex);
}
}
if (blocked) {
skipCustomData();
}
} finally {
if (oldContext != null)
oldContext.check();
curContext = oldContext;
}
/*
* At this point, if the externalizable data was not written in
* block-data form and either the externalizable class doesn't exist
* locally (i.e., obj == null) or readExternal() just threw a
* CNFException, then the stream is probably in an inconsistent state,
* since some (or all) of the externalizable data may not have been
* consumed. Since there's no "correct" action to take in this case,
* we mimic the behavior of past serialization implementations and
* blindly hope that the stream is in sync; if it isn't and additional
* externalizable data remains in the stream, a subsequent read will
* most likely throw a StreamCorruptedException.
*/
}
/** Reads a record. */
private Object readRecord(ObjectStreamClass desc) throws IOException {
ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
if (slots.length != 1) {
// skip any superclass stream field values
for (int i = 0; i < slots.length-1; i++) {
if (slots[i].hasData) {
new FieldValues(slots[i].desc, true);
}
}
}
FieldValues fieldValues = new FieldValues(desc, true);
// get canonical record constructor adapted to take two arguments:
// - byte[] primValues
// - Object[] objValues
// and return Object
MethodHandle ctrMH = RecordSupport.deserializationCtr(desc);
try {
return (Object) ctrMH.invokeExact(fieldValues.primValues, fieldValues.objValues);
} catch (Exception e) {
throw new InvalidObjectException(e.getMessage(), e);
} catch (Error e) {
throw e;
} catch (Throwable t) {
throw new InvalidObjectException("ReflectiveOperationException " +
"during deserialization", t);
}
}
/**
* Reads (or attempts to skip, if obj is null or is tagged with a
* ClassNotFoundException) instance data for each serializable class of
* object in stream, from superclass to subclass. Expects that passHandle
* is set to obj's handle before this method is called.
*/
private void readSerialData(Object obj, ObjectStreamClass desc)
throws IOException
{
ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
// Best effort Failure Atomicity; slotValues will be non-null if field
// values can be set after reading all field data in the hierarchy.
// Field values can only be set after reading all data if there are no
// user observable methods in the hierarchy, readObject(NoData). The
// top most Serializable class in the hierarchy can be skipped.
FieldValues[] slotValues = null;
boolean hasSpecialReadMethod = false;
for (int i = 1; i < slots.length; i++) {
ObjectStreamClass slotDesc = slots[i].desc;
if (slotDesc.hasReadObjectMethod()
|| slotDesc.hasReadObjectNoDataMethod()) {
hasSpecialReadMethod = true;
break;
}
}
// No special read methods, can store values and defer setting.
if (!hasSpecialReadMethod)
slotValues = new FieldValues[slots.length];
for (int i = 0; i < slots.length; i++) {
ObjectStreamClass slotDesc = slots[i].desc;
if (slots[i].hasData) {
if (obj == null || handles.lookupException(passHandle) != null) {
// Read fields of the current descriptor into a new FieldValues and discard
new FieldValues(slotDesc, true);
} else if (slotDesc.hasReadObjectMethod()) {
SerialCallbackContext oldContext = curContext;
if (oldContext != null)
oldContext.check();
try {
curContext = new SerialCallbackContext(obj, slotDesc);
bin.setBlockDataMode(true);
slotDesc.invokeReadObject(obj, this);
} catch (ClassNotFoundException ex) {
/*
* In most cases, the handle table has already
* propagated a CNFException to passHandle at this
* point; this mark call is included to address cases
* where the custom readObject method has cons'ed and
* thrown a new CNFException of its own.
*/
handles.markException(passHandle, ex);
} finally {
curContext.setUsed();
if (oldContext!= null)
oldContext.check();
curContext = oldContext;
}
/*
* defaultDataEnd may have been set indirectly by custom
* readObject() method when calling defaultReadObject() or
* readFields(); clear it to restore normal read behavior.
*/
defaultDataEnd = false;
} else {
// Read fields of the current descriptor into a new FieldValues
FieldValues values = new FieldValues(slotDesc, true);
if (slotValues != null) {
slotValues[i] = values;
} else if (obj != null) {
values.defaultCheckFieldValues(obj);
values.defaultSetFieldValues(obj);
}
}
if (slotDesc.hasWriteObjectData()) {
skipCustomData();
} else {
bin.setBlockDataMode(false);
}
} else {
if (obj != null &&
slotDesc.hasReadObjectNoDataMethod() &&
handles.lookupException(passHandle) == null)
{
slotDesc.invokeReadObjectNoData(obj);
}
}
}
if (obj != null && slotValues != null) {
// Check that the non-primitive types are assignable for all slots
// before assigning.
for (int i = 0; i < slots.length; i++) {
if (slotValues[i] != null)
slotValues[i].defaultCheckFieldValues(obj);
}
for (int i = 0; i < slots.length; i++) {
if (slotValues[i] != null)
slotValues[i].defaultSetFieldValues(obj);
}
}
}
/**
* Skips over all block data and objects until TC_ENDBLOCKDATA is
* encountered.
*/
private void skipCustomData() throws IOException {
int oldHandle = passHandle;
for (;;) {
if (bin.getBlockDataMode()) {
bin.skipBlockData();
bin.setBlockDataMode(false);
}
switch (bin.peekByte()) {
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
bin.setBlockDataMode(true);
break;
case TC_ENDBLOCKDATA:
bin.readByte();
passHandle = oldHandle;
return;
default:
readObject0(Object.class, false);
break;
}
}
}
/**
* Reads in and returns IOException that caused serialization to abort.
* All stream state is discarded prior to reading in fatal exception. Sets
* passHandle to fatal exception's handle.
*/
private IOException readFatalException() throws IOException {
if (bin.readByte() != TC_EXCEPTION) {
throw new InternalError();
}
clear();
// Check that an object follows the TC_EXCEPTION typecode
byte tc = bin.peekByte();
if (tc != TC_OBJECT &&
tc != TC_REFERENCE) {
throw new StreamCorruptedException(
String.format("invalid type code: %02X", tc));
}
return (IOException) readObject0(Object.class, false);
}
/**
* If recursion depth is 0, clears internal data structures; otherwise,
* throws a StreamCorruptedException. This method is called when a
* TC_RESET typecode is encountered.
*/
private void handleReset() throws StreamCorruptedException {
if (depth > 0) {
throw new StreamCorruptedException(
"unexpected reset; recursion depth: " + depth);
}
clear();
}
/**
* Returns the first non-null and non-platform class loader (not counting
* class loaders of generated reflection implementation classes) up the
* execution stack, or the platform class loader if only code from the
* bootstrap and platform class loader is on the stack.
*/
private static ClassLoader latestUserDefinedLoader() {
return jdk.internal.misc.VM.latestUserDefinedLoader();
}
/**
* Default GetField implementation.
*/
private final class FieldValues extends GetField {
/** class descriptor describing serializable fields */
private final ObjectStreamClass desc;
/** primitive field values */
final byte[] primValues;
/** object field values */
final Object[] objValues;
/** object field value handles */
private final int[] objHandles;
/**
* Creates FieldValues object for reading fields defined in given
* class descriptor.
* @param desc the ObjectStreamClass to read
* @param recordDependencies if true, record the dependencies
* from current PassHandle and the object's read.
*/
FieldValues(ObjectStreamClass desc, boolean recordDependencies) throws IOException {
this.desc = desc;
int primDataSize = desc.getPrimDataSize();
primValues = (primDataSize > 0) ? new byte[primDataSize] : null;
if (primDataSize > 0) {
bin.readFully(primValues, 0, primDataSize, false);
}
int numObjFields = desc.getNumObjFields();
objValues = (numObjFields > 0) ? new Object[numObjFields] : null;
objHandles = (numObjFields > 0) ? new int[numObjFields] : null;
if (numObjFields > 0) {
int objHandle = passHandle;
ObjectStreamField[] fields = desc.getFields(false);
int numPrimFields = fields.length - objValues.length;
for (int i = 0; i < objValues.length; i++) {
ObjectStreamField f = fields[numPrimFields + i];
objValues[i] = readObject0(Object.class, f.isUnshared());
objHandles[i] = passHandle;
if (recordDependencies && f.getField() != null) {
handles.markDependency(objHandle, passHandle);
}
}
passHandle = objHandle;
}
}
public ObjectStreamClass getObjectStreamClass() {
return desc;
}
public boolean defaulted(String name) {
return (getFieldOffset(name, null) < 0);
}
public boolean get(String name, boolean val) {
int off = getFieldOffset(name, Boolean.TYPE);
return (off >= 0) ? ByteArray.getBoolean(primValues, off) : val;
}
public byte get(String name, byte val) {
int off = getFieldOffset(name, Byte.TYPE);
return (off >= 0) ? primValues[off] : val;
}
public char get(String name, char val) {
int off = getFieldOffset(name, Character.TYPE);
return (off >= 0) ? ByteArray.getChar(primValues, off) : val;
}
public short get(String name, short val) {
int off = getFieldOffset(name, Short.TYPE);
return (off >= 0) ? ByteArray.getShort(primValues, off) : val;
}
public int get(String name, int val) {
int off = getFieldOffset(name, Integer.TYPE);
return (off >= 0) ? ByteArray.getInt(primValues, off) : val;
}
public float get(String name, float val) {
int off = getFieldOffset(name, Float.TYPE);
return (off >= 0) ? ByteArray.getFloat(primValues, off) : val;
}
public long get(String name, long val) {
int off = getFieldOffset(name, Long.TYPE);
return (off >= 0) ? ByteArray.getLong(primValues, off) : val;
}
public double get(String name, double val) {
int off = getFieldOffset(name, Double.TYPE);
return (off >= 0) ? ByteArray.getDouble(primValues, off) : val;
}
public Object get(String name, Object val) throws ClassNotFoundException {
int off = getFieldOffset(name, Object.class);
if (off >= 0) {
int objHandle = objHandles[off];
handles.markDependency(passHandle, objHandle);
ClassNotFoundException ex = handles.lookupException(objHandle);
if (ex == null)
return objValues[off];
if (Caches.GETFIELD_CNFE_RETURNS_NULL) {
// Revert to the prior behavior; return null instead of CNFE
return null;
}
throw ex;
} else {
return val;
}
}
/** Throws ClassCastException if any value is not assignable. */
void defaultCheckFieldValues(Object obj) {
if (objValues != null)
desc.checkObjFieldValueTypes(obj, objValues);
}
private void defaultSetFieldValues(Object obj) {
if (primValues != null)
desc.setPrimFieldValues(obj, primValues);
if (objValues != null)
desc.setObjFieldValues(obj, objValues);
}
/**
* Returns offset of field with given name and type. A specified type
* of null matches all types, Object.class matches all non-primitive
* types, and any other non-null type matches assignable types only.
* If no matching field is found in the (incoming) class
* descriptor but a matching field is present in the associated local
* class descriptor, returns -1. Throws IllegalArgumentException if
* neither incoming nor local class descriptor contains a match.
*/
private int getFieldOffset(String name, Class<?> type) {
ObjectStreamField field = desc.getField(name, type);
if (field != null) {
return field.getOffset();
} else if (desc.getLocalDesc().getField(name, type) != null) {
return -1;
} else {
throw new IllegalArgumentException("no such field " + name +
" with type " + type);
}
}
}
/**
* Prioritized list of callbacks to be performed once object graph has been
* completely deserialized.
*/
private static class ValidationList {
private static class Callback {
final ObjectInputValidation obj;
final int priority;
Callback next;
@SuppressWarnings("removal")
final AccessControlContext acc;
Callback(ObjectInputValidation obj, int priority, Callback next,
@SuppressWarnings("removal") AccessControlContext acc)
{
this.obj = obj;
this.priority = priority;
this.next = next;
this.acc = acc;
}
}
/** linked list of callbacks */
private Callback list;
/**
* Creates new (empty) ValidationList.
*/
ValidationList() {
}
/**
* Registers callback. Throws InvalidObjectException if callback
* object is null.
*/
void register(ObjectInputValidation obj, int priority)
throws InvalidObjectException
{
if (obj == null) {
throw new InvalidObjectException("null callback");
}
Callback prev = null, cur = list;
while (cur != null && priority < cur.priority) {
prev = cur;
cur = cur.next;
}
@SuppressWarnings("removal")
AccessControlContext acc = AccessController.getContext();
if (prev != null) {
prev.next = new Callback(obj, priority, cur, acc);
} else {
list = new Callback(obj, priority, list, acc);
}
}
/**
* Invokes all registered callbacks and clears the callback list.
* Callbacks with higher priorities are called first; those with equal
* priorities may be called in any order. If any of the callbacks
* throws an InvalidObjectException, the callback process is terminated
* and the exception propagated upwards.
*/
@SuppressWarnings("removal")
void doCallbacks() throws InvalidObjectException {
try {
while (list != null) {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>()
{
public Void run() throws InvalidObjectException {
list.obj.validateObject();
return null;
}
}, list.acc);
list = list.next;
}
} catch (PrivilegedActionException ex) {
list = null;
throw (InvalidObjectException) ex.getException();
}
}
/**
* Resets the callback list to its initial (empty) state.
*/
public void clear() {
list = null;
}
}
/**
* Hold a snapshot of values to be passed to an ObjectInputFilter.
*/
static class FilterValues implements ObjectInputFilter.FilterInfo {
final Class<?> clazz;
final long arrayLength;
final long totalObjectRefs;
final long depth;
final long streamBytes;
public FilterValues(Class<?> clazz, long arrayLength, long totalObjectRefs,
long depth, long streamBytes) {
this.clazz = clazz;
this.arrayLength = arrayLength;
this.totalObjectRefs = totalObjectRefs;
this.depth = depth;
this.streamBytes = streamBytes;
}
@Override
public Class<?> serialClass() {
return clazz;
}
@Override
public long arrayLength() {
return arrayLength;
}
@Override
public long references() {
return totalObjectRefs;
}
@Override
public long depth() {
return depth;
}
@Override
public long streamBytes() {
return streamBytes;
}
}
/**
* Input stream supporting single-byte peek operations.
*/
private static class PeekInputStream extends InputStream {
/** underlying stream */
private final InputStream in;
/** peeked byte */
private int peekb = -1;
/** total bytes read from the stream */
private long totalBytesRead = 0;
/**
* Creates new PeekInputStream on top of given underlying stream.
*/
PeekInputStream(InputStream in) {
this.in = in;
}
/**
* Peeks at next byte value in stream. Similar to read(), except
* that it does not consume the read value.
*/
int peek() throws IOException {
if (peekb >= 0) {
return peekb;
}
peekb = in.read();
totalBytesRead += peekb >= 0 ? 1 : 0;
return peekb;
}
public int read() throws IOException {
if (peekb >= 0) {
int v = peekb;
peekb = -1;
return v;
} else {
int nbytes = in.read();
totalBytesRead += nbytes >= 0 ? 1 : 0;
return nbytes;
}
}
public int read(byte[] b, int off, int len) throws IOException {
int nbytes;
if (len == 0) {
return 0;
} else if (peekb < 0) {
nbytes = in.read(b, off, len);
totalBytesRead += nbytes >= 0 ? nbytes : 0;
return nbytes;
} else {
b[off++] = (byte) peekb;
len--;
peekb = -1;
nbytes = in.read(b, off, len);
totalBytesRead += nbytes >= 0 ? nbytes : 0;
return (nbytes >= 0) ? (nbytes + 1) : 1;
}
}
void readFully(byte[] b, int off, int len) throws IOException {
int n = 0;
while (n < len) {
int count = read(b, off + n, len - n);
if (count < 0) {
throw new EOFException();
}
n += count;
}
}
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
int skipped = 0;
if (peekb >= 0) {
peekb = -1;
skipped++;
n--;
}
n = skipped + in.skip(n);
totalBytesRead += n;
return n;
}
public int available() throws IOException {
return in.available() + ((peekb >= 0) ? 1 : 0);
}
public void close() throws IOException {
in.close();
}
public long getBytesRead() {
return totalBytesRead;
}
}
private static final Unsafe UNSAFE = Unsafe.getUnsafe();
/**
* Performs a "freeze" action, required to adhere to final field semantics.
*
* <p> This method can be called unconditionally before returning the graph,
* from the topmost readObject call, since it is expected that the
* additional cost of the freeze action is negligible compared to
* reconstituting even the most simple graph.
*
* <p> Nested calls to readObject do not issue freeze actions because the
* sub-graph returned from a nested call is not guaranteed to be fully
* initialized yet (possible cycles).
*/
private void freeze() {
// Issue a StoreStore|StoreLoad fence, which is at least sufficient
// to provide final-freeze semantics.
UNSAFE.storeFence();
}
/**
* Input stream with two modes: in default mode, inputs data written in the
* same format as DataOutputStream; in "block data" mode, inputs data
* bracketed by block data markers (see object serialization specification
* for details). Buffering depends on block data mode: when in default
* mode, no data is buffered in advance; when in block data mode, all data
* for the current data block is read in at once (and buffered).
*/
private class BlockDataInputStream
extends InputStream implements DataInput
{
/** maximum data block length */
private static final int MAX_BLOCK_SIZE = 1024;
/** maximum data block header length */
private static final int MAX_HEADER_SIZE = 5;
/** (tunable) length of char buffer (for reading strings) */
private static final int CHAR_BUF_SIZE = 256;
/** readBlockHeader() return value indicating header read may block */
private static final int HEADER_BLOCKED = -2;
/** buffer for reading general/block data */
private final byte[] buf = new byte[MAX_BLOCK_SIZE];
/** buffer for reading block data headers */
private final byte[] hbuf = new byte[MAX_HEADER_SIZE];
/** char buffer for fast string reads */
private final char[] cbuf = new char[CHAR_BUF_SIZE];
/** block data mode */
private boolean blkmode = false;
// block data state fields; values meaningful only when blkmode true
/** current offset into buf */
private int pos = 0;
/** end offset of valid data in buf, or -1 if no more block data */
private int end = -1;
/** number of bytes in current block yet to be read from stream */
private int unread = 0;
/** underlying stream (wrapped in peekable filter stream) */
private final PeekInputStream in;
/** loopback stream (for data reads that span data blocks) */
private final DataInputStream din;
/**
* Creates new BlockDataInputStream on top of given underlying stream.
* Block data mode is turned off by default.
*/
BlockDataInputStream(InputStream in) {
this.in = new PeekInputStream(in);
din = new DataInputStream(this);
}
/**
* Sets block data mode to the given mode (true == on, false == off)
* and returns the previous mode value. If the new mode is the same as
* the old mode, no action is taken. Throws IllegalStateException if
* block data mode is being switched from on to off while unconsumed
* block data is still present in the stream.
*/
boolean setBlockDataMode(boolean newmode) throws IOException {
if (blkmode == newmode) {
return blkmode;
}
if (newmode) {
pos = 0;
end = 0;
unread = 0;
} else if (pos < end) {
throw new IllegalStateException("unread block data");
}
blkmode = newmode;
return !blkmode;
}
/**
* Returns true if the stream is currently in block data mode, false
* otherwise.
*/
boolean getBlockDataMode() {
return blkmode;
}
/**
* If in block data mode, skips to the end of the current group of data
* blocks (but does not unset block data mode). If not in block data
* mode, throws an IllegalStateException.
*/
void skipBlockData() throws IOException {
if (!blkmode) {
throw new IllegalStateException("not in block data mode");
}
while (end >= 0) {
refill();
}
}
/**
* Attempts to read in the next block data header (if any). If
* canBlock is false and a full header cannot be read without possibly
* blocking, returns HEADER_BLOCKED, else if the next element in the
* stream is a block data header, returns the block data length
* specified by the header, else returns -1.
*/
private int readBlockHeader(boolean canBlock) throws IOException {
if (defaultDataEnd) {
/*
* Fix for 4360508: stream is currently at the end of a field
* value block written via default serialization; since there
* is no terminating TC_ENDBLOCKDATA tag, simulate
* end-of-custom-data behavior explicitly.
*/
return -1;
}
try {
for (;;) {
int avail = canBlock ? Integer.MAX_VALUE : in.available();
if (avail == 0) {
return HEADER_BLOCKED;
}
int tc = in.peek();
switch (tc) {
case TC_BLOCKDATA:
if (avail < 2) {
return HEADER_BLOCKED;
}
in.readFully(hbuf, 0, 2);
return hbuf[1] & 0xFF;
case TC_BLOCKDATALONG:
if (avail < 5) {
return HEADER_BLOCKED;
}
in.readFully(hbuf, 0, 5);
int len = ByteArray.getInt(hbuf, 1);
if (len < 0) {
throw new StreamCorruptedException(
"illegal block data header length: " +
len);
}
return len;
/*
* TC_RESETs may occur in between data blocks.
* Unfortunately, this case must be parsed at a lower
* level than other typecodes, since primitive data
* reads may span data blocks separated by a TC_RESET.
*/
case TC_RESET:
in.read();
handleReset();
break;
default:
if (tc >= 0 && (tc < TC_BASE || tc > TC_MAX)) {
throw new StreamCorruptedException(
String.format("invalid type code: %02X",
tc));
}
return -1;
}
}
} catch (EOFException ex) {
throw new StreamCorruptedException(
"unexpected EOF while reading block data header");
}
}
/**
* Refills internal buffer buf with block data. Any data in buf at the
* time of the call is considered consumed. Sets the pos, end, and
* unread fields to reflect the new amount of available block data; if
* the next element in the stream is not a data block, sets pos and
* unread to 0 and end to -1.
*/
private void refill() throws IOException {
try {
do {
pos = 0;
if (unread > 0) {
int n =
in.read(buf, 0, Math.min(unread, MAX_BLOCK_SIZE));
if (n >= 0) {
end = n;
unread -= n;
} else {
throw new StreamCorruptedException(
"unexpected EOF in middle of data block");
}
} else {
int n = readBlockHeader(true);
if (n >= 0) {
end = 0;
unread = n;
} else {
end = -1;
unread = 0;
}
}
} while (pos == end);
} catch (IOException ex) {
pos = 0;
end = -1;
unread = 0;
throw ex;
}
}
/**
* If in block data mode, returns the number of unconsumed bytes
* remaining in the current data block. If not in block data mode,
* throws an IllegalStateException.
*/
int currentBlockRemaining() {
if (blkmode) {
return (end >= 0) ? (end - pos) + unread : 0;
} else {
throw new IllegalStateException();
}
}
/**
* Peeks at (but does not consume) and returns the next byte value in
* the stream, or -1 if the end of the stream/block data (if in block
* data mode) has been reached.
*/
int peek() throws IOException {
if (blkmode) {
if (pos == end) {
refill();
}
return (end >= 0) ? (buf[pos] & 0xFF) : -1;
} else {
return in.peek();
}
}
/**
* Peeks at (but does not consume) and returns the next byte value in
* the stream, or throws EOFException if end of stream/block data has
* been reached.
*/
byte peekByte() throws IOException {
int val = peek();
if (val < 0) {
throw new EOFException();
}
return (byte) val;
}
/* ----------------- generic input stream methods ------------------ */
/*
* The following methods are equivalent to their counterparts in
* InputStream, except that they interpret data block boundaries and
* read the requested data from within data blocks when in block data
* mode.
*/
public int read() throws IOException {
if (blkmode) {
if (pos == end) {
refill();
}
return (end >= 0) ? (buf[pos++] & 0xFF) : -1;
} else {
return in.read();
}
}
public int read(byte[] b, int off, int len) throws IOException {
return read(b, off, len, false);
}
public long skip(long len) throws IOException {
long remain = len;
while (remain > 0) {
if (blkmode) {
if (pos == end) {
refill();
}
if (end < 0) {
break;
}
int nread = (int) Math.min(remain, end - pos);
remain -= nread;
pos += nread;
} else {
int nread = (int) Math.min(remain, MAX_BLOCK_SIZE);
if ((nread = in.read(buf, 0, nread)) < 0) {
break;
}
remain -= nread;
}
}
return len - remain;
}
public int available() throws IOException {
if (blkmode) {
if ((pos == end) && (unread == 0)) {
int n;
while ((n = readBlockHeader(false)) == 0) ;
switch (n) {
case HEADER_BLOCKED:
break;
case -1:
pos = 0;
end = -1;
break;
default:
pos = 0;
end = 0;
unread = n;
break;
}
}
// avoid unnecessary call to in.available() if possible
int unreadAvail = (unread > 0) ?
Math.min(in.available(), unread) : 0;
return (end >= 0) ? (end - pos) + unreadAvail : 0;
} else {
return in.available();
}
}
public void close() throws IOException {
if (blkmode) {
pos = 0;
end = -1;
unread = 0;
}
in.close();
}
/**
* Attempts to read len bytes into byte array b at offset off. Returns
* the number of bytes read, or -1 if the end of stream/block data has
* been reached. If copy is true, reads values into an intermediate
* buffer before copying them to b (to avoid exposing a reference to
* b).
*/
int read(byte[] b, int off, int len, boolean copy) throws IOException {
if (len == 0) {
return 0;
} else if (blkmode) {
if (pos == end) {
refill();
}
if (end < 0) {
return -1;
}
int nread = Math.min(len, end - pos);
System.arraycopy(buf, pos, b, off, nread);
pos += nread;
return nread;
} else if (copy) {
int nread = in.read(buf, 0, Math.min(len, MAX_BLOCK_SIZE));
if (nread > 0) {
System.arraycopy(buf, 0, b, off, nread);
}
return nread;
} else {
return in.read(b, off, len);
}
}
/* ----------------- primitive data input methods ------------------ */
/*
* The following methods are equivalent to their counterparts in
* DataInputStream, except that they interpret data block boundaries
* and read the requested data from within data blocks when in block
* data mode.
*/
public void readFully(byte[] b) throws IOException {
readFully(b, 0, b.length, false);
}
public void readFully(byte[] b, int off, int len) throws IOException {
readFully(b, off, len, false);
}
public void readFully(byte[] b, int off, int len, boolean copy)
throws IOException
{
while (len > 0) {
int n = read(b, off, len, copy);
if (n < 0) {
throw new EOFException();
}
off += n;
len -= n;
}
}
public int skipBytes(int n) throws IOException {
return din.skipBytes(n);
}
public boolean readBoolean() throws IOException {
int v = read();
if (v < 0) {
throw new EOFException();
}
return (v != 0);
}
public byte readByte() throws IOException {
int v = read();
if (v < 0) {
throw new EOFException();
}
return (byte) v;
}
public int readUnsignedByte() throws IOException {
int v = read();
if (v < 0) {
throw new EOFException();
}
return v;
}
public char readChar() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 2);
} else if (end - pos < 2) {
return din.readChar();
}
char v = ByteArray.getChar(buf, pos);
pos += 2;
return v;
}
public short readShort() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 2);
} else if (end - pos < 2) {
return din.readShort();
}
short v = ByteArray.getShort(buf, pos);
pos += 2;
return v;
}
public int readUnsignedShort() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 2);
} else if (end - pos < 2) {
return din.readUnsignedShort();
}
int v = ByteArray.getShort(buf, pos) & 0xFFFF;
pos += 2;
return v;
}
public int readInt() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 4);
} else if (end - pos < 4) {
return din.readInt();
}
int v = ByteArray.getInt(buf, pos);
pos += 4;
return v;
}
public float readFloat() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 4);
} else if (end - pos < 4) {
return din.readFloat();
}
float v = ByteArray.getFloat(buf, pos);
pos += 4;
return v;
}
public long readLong() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 8);
} else if (end - pos < 8) {
return din.readLong();
}
long v = ByteArray.getLong(buf, pos);
pos += 8;
return v;
}
public double readDouble() throws IOException {
if (!blkmode) {
pos = 0;
in.readFully(buf, 0, 8);
} else if (end - pos < 8) {
return din.readDouble();
}
double v = ByteArray.getDouble(buf, pos);
pos += 8;
return v;
}
public String readUTF() throws IOException {
return readUTFBody(readUnsignedShort());
}
@SuppressWarnings("deprecation")
public String readLine() throws IOException {
return din.readLine(); // deprecated, not worth optimizing
}
/* -------------- primitive data array input methods --------------- */
/*
* The following methods read in spans of primitive data values.
* Though equivalent to calling the corresponding primitive read
* methods repeatedly, these methods are optimized for reading groups
* of primitive data values more efficiently.
*/
void readBooleans(boolean[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE);
in.readFully(buf, 0, span);
stop = off + span;
pos = 0;
} else if (end - pos < 1) {
v[off++] = din.readBoolean();
continue;
} else {
stop = Math.min(endoff, off + end - pos);
}
while (off < stop) {
v[off++] = ByteArray.getBoolean(buf, pos++);
}
}
}
void readChars(char[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1);
in.readFully(buf, 0, span << 1);
stop = off + span;
pos = 0;
} else if (end - pos < 2) {
v[off++] = din.readChar();
continue;
} else {
stop = Math.min(endoff, off + ((end - pos) >> 1));
}
while (off < stop) {
v[off++] = ByteArray.getChar(buf, pos);
pos += 2;
}
}
}
void readShorts(short[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 1);
in.readFully(buf, 0, span << 1);
stop = off + span;
pos = 0;
} else if (end - pos < 2) {
v[off++] = din.readShort();
continue;
} else {
stop = Math.min(endoff, off + ((end - pos) >> 1));
}
while (off < stop) {
v[off++] = ByteArray.getShort(buf, pos);
pos += 2;
}
}
}
void readInts(int[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
in.readFully(buf, 0, span << 2);
stop = off + span;
pos = 0;
} else if (end - pos < 4) {
v[off++] = din.readInt();
continue;
} else {
stop = Math.min(endoff, off + ((end - pos) >> 2));
}
while (off < stop) {
v[off++] = ByteArray.getInt(buf, pos);
pos += 4;
}
}
}
void readFloats(float[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
in.readFully(buf, 0, span << 2);
stop = off + span;
pos = 0;
} else if (end - pos < 4) {
v[off++] = din.readFloat();
continue;
} else {
stop = Math.min(endoff, ((end - pos) >> 2));
}
while (off < stop) {
v[off++] = ByteArray.getFloat(buf, pos);
pos += 4;
}
}
}
void readLongs(long[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
in.readFully(buf, 0, span << 3);
stop = off + span;
pos = 0;
} else if (end - pos < 8) {
v[off++] = din.readLong();
continue;
} else {
stop = Math.min(endoff, off + ((end - pos) >> 3));
}
while (off < stop) {
v[off++] = ByteArray.getLong(buf, pos);
pos += 8;
}
}
}
void readDoubles(double[] v, int off, int len) throws IOException {
int stop, endoff = off + len;
while (off < endoff) {
if (!blkmode) {
int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
in.readFully(buf, 0, span << 3);
stop = off + span;
pos = 0;
} else if (end - pos < 8) {
v[off++] = din.readDouble();
continue;
} else {
stop = Math.min(endoff - off, ((end - pos) >> 3));
}
while (off < stop) {
v[off++] = ByteArray.getDouble(buf, pos);
pos += 8;
}
}
}
/**
* Reads in string written in "long" UTF format. "Long" UTF format is
* identical to standard UTF, except that it uses an 8 byte header
* (instead of the standard 2 bytes) to convey the UTF encoding length.
*/
String readLongUTF() throws IOException {
return readUTFBody(readLong());
}
/**
* Reads in the "body" (i.e., the UTF representation minus the 2-byte
* or 8-byte length header) of a UTF encoding, which occupies the next
* utflen bytes.
*/
private String readUTFBody(long utflen) throws IOException {
StringBuilder sbuf;
if (utflen > 0 && utflen < Integer.MAX_VALUE) {
// a reasonable initial capacity based on the UTF length
int initialCapacity = Math.min((int)utflen, 0xFFFF);
sbuf = new StringBuilder(initialCapacity);
} else {
sbuf = new StringBuilder();
}
if (!blkmode) {
end = pos = 0;
}
while (utflen > 0) {
int avail = end - pos;
if (avail >= 3 || (long) avail == utflen) {
utflen -= readUTFSpan(sbuf, utflen);
} else {
if (blkmode) {
// near block boundary, read one byte at a time
utflen -= readUTFChar(sbuf, utflen);
} else {
// shift and refill buffer manually
if (avail > 0) {
System.arraycopy(buf, pos, buf, 0, avail);
}
pos = 0;
end = (int) Math.min(MAX_BLOCK_SIZE, utflen);
in.readFully(buf, avail, end - avail);
}
}
}
return sbuf.toString();
}
/**
* Reads span of UTF-encoded characters out of internal buffer
* (starting at offset pos and ending at or before offset end),
* consuming no more than utflen bytes. Appends read characters to
* sbuf. Returns the number of bytes consumed.
*/
private long readUTFSpan(StringBuilder sbuf, long utflen)
throws IOException
{
int cpos = 0;
int start = pos;
int avail = Math.min(end - pos, CHAR_BUF_SIZE);
// stop short of last char unless all of utf bytes in buffer
int stop = pos + ((utflen > avail) ? avail - 2 : (int) utflen);
boolean outOfBounds = false;
try {
while (pos < stop) {
int b1, b2, b3;
b1 = buf[pos++] & 0xFF;
switch (b1 >> 4) {
case 0, 1, 2, 3, 4, 5, 6, 7 -> // 1 byte format: 0xxxxxxx
cbuf[cpos++] = (char) b1;
case 12, 13 -> { // 2 byte format: 110xxxxx 10xxxxxx
b2 = buf[pos++];
if ((b2 & 0xC0) != 0x80) {
throw new UTFDataFormatException();
}
cbuf[cpos++] = (char) (((b1 & 0x1F) << 6) |
((b2 & 0x3F) << 0));
}
case 14 -> { // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
b3 = buf[pos + 1];
b2 = buf[pos + 0];
pos += 2;
if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
throw new UTFDataFormatException();
}
cbuf[cpos++] = (char) (((b1 & 0x0F) << 12) |
((b2 & 0x3F) << 6) |
((b3 & 0x3F) << 0));
}
default -> throw new UTFDataFormatException(); // 10xx xxxx, 1111 xxxx
}
}
} catch (ArrayIndexOutOfBoundsException ex) {
outOfBounds = true;
} finally {
if (outOfBounds || (pos - start) > utflen) {
/*
* Fix for 4450867: if a malformed utf char causes the
* conversion loop to scan past the expected end of the utf
* string, only consume the expected number of utf bytes.
*/
pos = start + (int) utflen;
throw new UTFDataFormatException();
}
}
sbuf.append(cbuf, 0, cpos);
return pos - start;
}
/**
* Reads in single UTF-encoded character one byte at a time, appends
* the character to sbuf, and returns the number of bytes consumed.
* This method is used when reading in UTF strings written in block
* data mode to handle UTF-encoded characters which (potentially)
* straddle block-data boundaries.
*/
private int readUTFChar(StringBuilder sbuf, long utflen)
throws IOException
{
int b1, b2, b3;
b1 = readByte() & 0xFF;
switch (b1 >> 4) {
case 0, 1, 2, 3, 4, 5, 6, 7 -> { // 1 byte format: 0xxxxxxx
sbuf.append((char) b1);
return 1;
}
case 12, 13 -> { // 2 byte format: 110xxxxx 10xxxxxx
if (utflen < 2) {
throw new UTFDataFormatException();
}
b2 = readByte();
if ((b2 & 0xC0) != 0x80) {
throw new UTFDataFormatException();
}
sbuf.append((char) (((b1 & 0x1F) << 6) |
((b2 & 0x3F) << 0)));
return 2;
}
case 14 -> { // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
if (utflen < 3) {
if (utflen == 2) {
readByte(); // consume remaining byte
}
throw new UTFDataFormatException();
}
b2 = readByte();
b3 = readByte();
if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
throw new UTFDataFormatException();
}
sbuf.append((char) (((b1 & 0x0F) << 12) |
((b2 & 0x3F) << 6) |
((b3 & 0x3F) << 0)));
return 3;
}
default -> throw new UTFDataFormatException(); // 10xx xxxx, 1111 xxxx
}
}
/**
* Returns the number of bytes read from the input stream.
* @return the number of bytes read from the input stream
*/
long getBytesRead() {
return in.getBytesRead();
}
}
/**
* Unsynchronized table which tracks wire handle to object mappings, as
* well as ClassNotFoundExceptions associated with deserialized objects.
* This class implements an exception-propagation algorithm for
* determining which objects should have ClassNotFoundExceptions associated
* with them, taking into account cycles and discontinuities (e.g., skipped
* fields) in the object graph.
*
* <p>General use of the table is as follows: during deserialization, a
* given object is first assigned a handle by calling the assign method.
* This method leaves the assigned handle in an "open" state, wherein
* dependencies on the exception status of other handles can be registered
* by calling the markDependency method, or an exception can be directly
* associated with the handle by calling markException. When a handle is
* tagged with an exception, the HandleTable assumes responsibility for
* propagating the exception to any other objects which depend
* (transitively) on the exception-tagged object.
*
* <p>Once all exception information/dependencies for the handle have been
* registered, the handle should be "closed" by calling the finish method
* on it. The act of finishing a handle allows the exception propagation
* algorithm to aggressively prune dependency links, lessening the
* performance/memory impact of exception tracking.
*
* <p>Note that the exception propagation algorithm used depends on handles
* being assigned/finished in LIFO order; however, for simplicity as well
* as memory conservation, it does not enforce this constraint.
*/
// REMIND: add full description of exception propagation algorithm?
private static final class HandleTable {
/* status codes indicating whether object has associated exception */
private static final byte STATUS_OK = 1;
private static final byte STATUS_UNKNOWN = 2;
private static final byte STATUS_EXCEPTION = 3;
/** array mapping handle -> object status */
byte[] status;
/** array mapping handle -> object/exception (depending on status) */
Object[] entries;
/** array mapping handle -> list of dependent handles (if any) */
HandleList[] deps;
/** lowest unresolved dependency */
int lowDep = -1;
/** number of handles in table */
int size = 0;
/**
* Creates handle table with the given initial capacity.
*/
HandleTable(int initialCapacity) {
status = new byte[initialCapacity];
entries = new Object[initialCapacity];
deps = new HandleList[initialCapacity];
}
/**
* Assigns next available handle to given object, and returns assigned
* handle. Once object has been completely deserialized (and all
* dependencies on other objects identified), the handle should be
* "closed" by passing it to finish().
*/
int assign(Object obj) {
if (size >= entries.length) {
grow();
}
status[size] = STATUS_UNKNOWN;
entries[size] = obj;
return size++;
}
/**
* Registers a dependency (in exception status) of one handle on
* another. The dependent handle must be "open" (i.e., assigned, but
* not finished yet). No action is taken if either dependent or target
* handle is NULL_HANDLE. Additionally, no action is taken if the
* dependent and target are the same.
*/
void markDependency(int dependent, int target) {
if (dependent == target || dependent == NULL_HANDLE || target == NULL_HANDLE) {
return;
}
switch (status[dependent]) {
case STATUS_UNKNOWN:
switch (status[target]) {
case STATUS_OK:
// ignore dependencies on objs with no exception
break;
case STATUS_EXCEPTION:
// eagerly propagate exception
markException(dependent,
(ClassNotFoundException) entries[target]);
break;
case STATUS_UNKNOWN:
// add to dependency list of target
if (deps[target] == null) {
deps[target] = new HandleList();
}
deps[target].add(dependent);
// remember lowest unresolved target seen
if (lowDep < 0 || lowDep > target) {
lowDep = target;
}
break;
default:
throw new InternalError();
}
break;
case STATUS_EXCEPTION:
break;
default:
throw new InternalError();
}
}
/**
* Associates a ClassNotFoundException (if one not already associated)
* with the currently active handle and propagates it to other
* referencing objects as appropriate. The specified handle must be
* "open" (i.e., assigned, but not finished yet).
*/
void markException(int handle, ClassNotFoundException ex) {
switch (status[handle]) {
case STATUS_UNKNOWN:
status[handle] = STATUS_EXCEPTION;
entries[handle] = ex;
// propagate exception to dependents
HandleList dlist = deps[handle];
if (dlist != null) {
int ndeps = dlist.size();
for (int i = 0; i < ndeps; i++) {
markException(dlist.get(i), ex);
}
deps[handle] = null;
}
break;
case STATUS_EXCEPTION:
break;
default:
throw new InternalError();
}
}
/**
* Marks given handle as finished, meaning that no new dependencies
* will be marked for handle. Calls to the assign and finish methods
* must occur in LIFO order.
*/
void finish(int handle) {
int end;
if (lowDep < 0) {
// no pending unknowns, only resolve current handle
end = handle + 1;
} else if (lowDep >= handle) {
// pending unknowns now clearable, resolve all upward handles
end = size;
lowDep = -1;
} else {
// unresolved backrefs present, can't resolve anything yet
return;
}
// change STATUS_UNKNOWN -> STATUS_OK in selected span of handles
for (int i = handle; i < end; i++) {
switch (status[i]) {
case STATUS_UNKNOWN:
status[i] = STATUS_OK;
deps[i] = null;
break;
case STATUS_OK:
case STATUS_EXCEPTION:
break;
default:
throw new InternalError();
}
}
}
/**
* Assigns a new object to the given handle. The object previously
* associated with the handle is forgotten. This method has no effect
* if the given handle already has an exception associated with it.
* This method may be called at any time after the handle is assigned.
*/
void setObject(int handle, Object obj) {
switch (status[handle]) {
case STATUS_UNKNOWN:
case STATUS_OK:
entries[handle] = obj;
break;
case STATUS_EXCEPTION:
break;
default:
throw new InternalError();
}
}
/**
* Looks up and returns object associated with the given handle.
* Returns null if the given handle is NULL_HANDLE, or if it has an
* associated ClassNotFoundException.
*/
Object lookupObject(int handle) {
return (handle != NULL_HANDLE &&
status[handle] != STATUS_EXCEPTION) ?
entries[handle] : null;
}
/**
* Looks up and returns ClassNotFoundException associated with the
* given handle. Returns null if the given handle is NULL_HANDLE, or
* if there is no ClassNotFoundException associated with the handle.
*/
ClassNotFoundException lookupException(int handle) {
return (handle != NULL_HANDLE &&
status[handle] == STATUS_EXCEPTION) ?
(ClassNotFoundException) entries[handle] : null;
}
/**
* Resets table to its initial state.
*/
void clear() {
Arrays.fill(status, 0, size, (byte) 0);
Arrays.fill(entries, 0, size, null);
Arrays.fill(deps, 0, size, null);
lowDep = -1;
size = 0;
}
/**
* Returns number of handles registered in table.
*/
int size() {
return size;
}
/**
* Expands capacity of internal arrays.
*/
private void grow() {
int newCapacity = (entries.length << 1) + 1;
byte[] newStatus = new byte[newCapacity];
Object[] newEntries = new Object[newCapacity];
HandleList[] newDeps = new HandleList[newCapacity];
System.arraycopy(status, 0, newStatus, 0, size);
System.arraycopy(entries, 0, newEntries, 0, size);
System.arraycopy(deps, 0, newDeps, 0, size);
status = newStatus;
entries = newEntries;
deps = newDeps;
}
/**
* Simple growable list of (integer) handles.
*/
private static class HandleList {
private int[] list = new int[4];
private int size = 0;
public HandleList() {
}
public void add(int handle) {
if (size >= list.length) {
int[] newList = new int[list.length << 1];
System.arraycopy(list, 0, newList, 0, list.length);
list = newList;
}
list[size++] = handle;
}
public int get(int index) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException();
}
return list[index];
}
public int size() {
return size;
}
}
}
/**
* Method for cloning arrays in case of using unsharing reading
*/
private static Object cloneArray(Object array) {
if (array instanceof Object[]) {
return ((Object[]) array).clone();
} else if (array instanceof boolean[]) {
return ((boolean[]) array).clone();
} else if (array instanceof byte[]) {
return ((byte[]) array).clone();
} else if (array instanceof char[]) {
return ((char[]) array).clone();
} else if (array instanceof double[]) {
return ((double[]) array).clone();
} else if (array instanceof float[]) {
return ((float[]) array).clone();
} else if (array instanceof int[]) {
return ((int[]) array).clone();
} else if (array instanceof long[]) {
return ((long[]) array).clone();
} else if (array instanceof short[]) {
return ((short[]) array).clone();
} else {
throw new AssertionError();
}
}
static {
SharedSecrets.setJavaObjectInputStreamAccess(ObjectInputStream::checkArray);
SharedSecrets.setJavaObjectInputStreamReadString(ObjectInputStream::readString);
}
}
| 167,714 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
JavaObjectInputStreamAccess.java.txt | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/filter/JavaObjectInputStreamAccess.java.txt | /*
* Copyright (c) 2017, 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 jdk.internal.access;
import java.io.ObjectStreamException;
import java.io.ObjectInputStream;
/**
* Interface to specify methods for accessing {@code ObjectInputStream}.
*/
@FunctionalInterface
public interface JavaObjectInputStreamAccess {
void checkArray(ObjectInputStream ois, Class<?> arrayType, int arrayLength)
throws ObjectStreamException;
}
| 1,586 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
GitDifFilterTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/filter/GitDifFilterTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.filter;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.jcov.JCovLoadTest;
import openjdk.codetools.jcov.report.source.SourcePath;
import openjdk.codetools.jcov.report.view.TextReport;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class GitDifFilterTest {
public static Path cp(String resource) throws IOException {
Path res = Files.createTempFile(resource.substring(resource.lastIndexOf('/') + 1),
resource.substring(resource.lastIndexOf('.') + 1));
Files.createDirectories(res.getParent());
try (var in = new BufferedReader(new InputStreamReader(JCovLoadTest.class.getResourceAsStream(resource)));
var out = Files.newBufferedWriter(res)) {
String line;
while ((line = in.readLine()) != null) {
out.write(line); out.newLine(); out.flush();
}
}
return res;
}
public static Path cp(String dir, Map<String, String> resources) throws IOException {
var res = Files.createTempDirectory("");
var root = res.resolve(dir);
Files.createDirectories(root);
for (var r : resources.keySet()) {
Path file = root.resolve(resources.get(r));
Files.createDirectories(file.getParent());
try (var in = new BufferedReader(new InputStreamReader(JCovLoadTest.class.getResourceAsStream(r)));
var out = Files.newBufferedWriter(file)) {
String line;
while ((line = in.readLine()) != null) {
out.write(line); out.newLine(); out.flush();
}
}
}
return res;
}
static SourceFilter filter;
@BeforeClass
static void init() throws IOException {
String pkg = "/" + GitDifFilterTest.class.getPackageName().replace('.', '/') + "/";
filter = GitDiffFilter.parseDiff(cp(pkg + "negative_array_size.diff")/*, Set.of("src")*/);
}
@Test
void basic() {
assertTrue(filter.includes("src/JavaObjectInputStreamAccess.java", 37));
var oisRanges = filter.ranges("src/ObjectInputStream.java");
assertEquals(oisRanges.get(oisRanges.size() - 1).first(), 2141);
assertEquals(oisRanges.get(oisRanges.size() - 1).last(), 2143);
}
@Test
void report() throws Exception {
String pkg = "/" + GitDifFilterTest.class.getPackageName().replace('.', '/') + "/";
Path src = cp("src", Map.of(
pkg + "JavaObjectInputStreamAccess.java.txt", "JavaObjectInputStreamAccess.java",
pkg + "ObjectInputStream.java.txt", "ObjectInputStream.java"));
var files = new FileSet(Set.of("src/JavaObjectInputStreamAccess.java", "src/ObjectInputStream.java"));
Path report = Files.createTempFile("report", ".txt");
new TextReport(new SourcePath(src, src.resolve("src")),
files,
file -> {
var res = new ArrayList<CoveredLineRange>();
var line = 0;
var chunkSize = 1;
while (line < 10000) {
res.add(new CoveredLineRange(line, line + chunkSize - 1, Coverage.UNCOVERED));
line += chunkSize;
res.add(new CoveredLineRange(line, line + chunkSize - 1, Coverage.COVERED));
line += chunkSize;
line += chunkSize;
}
return res;
},
"ObjectInputStream coverage",
filter).report(report);
List<String> reportLines = Files.readAllLines(report);
assertTrue(reportLines.contains("src/ObjectInputStream.java 1/2"));
assertTrue(reportLines.contains("2142:- throw new StreamCorruptedException(\"Array length is negative\");"));
}
}
| 5,616 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ContextFilterTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/test/openjdk/codetools/jcov/report/source/ContextFilterTest.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.source;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static org.testng.Assert.assertEquals;
public class ContextFilterTest {
@Test
public void sparse() {
var filter = new ContextFilter(new SourceFilter() {
@Override
public List<LineRange> ranges(String file) {
return List.of(
new LineRange(1, 3),
new LineRange(7, 10),
new LineRange(50, 50),
new LineRange(98, 99)
);
}
}, 2);
var ranges = filter.ranges("");
assertEquals(ranges.size(), 3);
Assert.assertEquals(ranges.get(0).first(), 1);
Assert.assertEquals(ranges.get(0).last(), 12);
}
}
| 2,165 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
LineRange.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/LineRange.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report;
import java.util.Objects;
/**
* Range of a file lines. Used in filters and in coverage.
*/
public class LineRange implements Comparable<LineRange> {
private final int first;
private final int last;
public LineRange(int first, int last) {
this.first = first;
this.last = last;
}
public int first() {
return first;
}
public int last() {
return last;
}
public int compare(int line) {
if (line < first) return -1;
else if (line > last) return 1;
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LineRange range = (LineRange) o;
return first == range.first && last == range.last;
}
@Override
public int hashCode() {
return Objects.hash(first, last);
}
@Override
public int compareTo(LineRange o) {
return Integer.compare(first, o.first);
}
@Override
public String toString() {
return "[" + first + "," + last + "]";
}
}
| 2,367 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Coverage.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/Coverage.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report;
import java.util.Collection;
import java.util.Objects;
/**
* There is a fixed number of items of some sort. Some of those items can be covered.
* @see CoveredLineRange
*/
public class Coverage {
public static final Coverage COVERED = new Coverage(1,1);
public static final Coverage UNCOVERED = new Coverage(0, 1);
private final int covered;
private final int total;
public Coverage(int covered, int total) {
this.covered = covered;
this.total = total;
}
public int covered() {
return covered;
}
public int total() {
return total;
}
public static Coverage sum(Collection<Coverage> coverages) {
int covered = 0, total = 0;
for (Coverage one : coverages) {
covered += one.covered();
total += one.total();
}
return new Coverage(covered, total);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coverage coverage = (Coverage) o;
return covered == coverage.covered && total == coverage.total;
}
@Override
public int hashCode() {
return Objects.hash(covered, total);
}
@Override
public String toString() {
return covered + "/" + total;
}
}
| 2,595 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
FileSet.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/FileSet.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toSet;
/**
* Used to define for which files, within a hierarchy, to generate report for.
*/
public class FileSet {
private final Set<String> files;
private final Set<String> folders;
public FileSet(Set<String> files) {
this.files = files;
folders = new HashSet<>();
folders.add("");
files.forEach(f -> {
var parts = f.split("/");
var path = "";
for (int i = 0; i < parts.length - 1; i++) {
path += (path.isEmpty() ? "" : "/") + parts[i];
folders.add(path);
}
});
}
public Set<String> files() {
return files;
}
public Set<String> files(String parent) {
return files.stream().filter(f ->
parent.isEmpty() && f.indexOf('/') < 0 ||
f.startsWith(parent + "/") &&
f.substring(parent.length() + 1).indexOf('/') < 0).collect(toSet());
}
public Set<String> folders(String parent) {
if (parent.isEmpty()) return folders.stream().filter(f -> !f.isEmpty() && f.indexOf('/') < 0).collect(toSet());
else return folders.stream().filter(f -> f.startsWith(parent + "/") &&
f.substring(parent.length() + 1).indexOf('/') < 0).collect(toSet());
}
public boolean isFile(String file) {return files.contains(file);}
}
| 2,736 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CoveredLineRange.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/CoveredLineRange.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report;
/**
* The assumption is that some coverage information can be linked to a portion of source code.
* @see Coverage
* @see FileCoverage
*/
public class CoveredLineRange extends LineRange {
private final Coverage coverage;
public CoveredLineRange(int first, int last, Coverage coverage) {
super(first, last);
this.coverage = coverage;
}
public Coverage coverage() {
return coverage;
}
}
| 1,680 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
FileCoverage.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/FileCoverage.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report;
import java.util.List;
/**
* Presents a coverage of a file in terms of line ranges.
* @see LineRange
* @see CoveredLineRange
* @see Coverage
*/
public interface FileCoverage {
List<CoveredLineRange> ranges(String file);
}
| 1,479 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
JDKReport.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/view/JDKReport.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import com.sun.tdk.jcov.instrument.DataRoot;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.filter.GitDiffFilter;
import openjdk.codetools.jcov.report.jcov.JCovLineCoverage;
import openjdk.codetools.jcov.report.source.ContextFilter;
import openjdk.codetools.jcov.report.source.SourcePath;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
/**
* This is a utility class to generate report for openjdk.
*/
public class JDKReport {
public static void main(String[] args) throws Exception {
try {
var coverage = new JCovLineCoverage(DataRoot.read(args[0]));
var source = jdkSource(List.of(Path.of(args[1])));
var diff = GitDiffFilter.parseDiff(Path.of(args[2])/*, source.roots(List.of(Path.of(args[1])))*/);
String reportFile = args[3];
boolean isHTML = reportFile.endsWith("html");
String title = args.length >= 5 ? args[4] : "";
String header = args.length >= 6 ? args[5] : "";
if (isHTML)
new SingleHTMLReport(source, new FileSet(diff.files()), coverage,
title, header,
diff, new ContextFilter(diff, 10))
.report(Path.of(reportFile));
else
new TextReport(source, new FileSet(diff.files()), coverage, header, diff)
.report(Path.of(reportFile));
} catch (Throwable e) {
System.out.println("Usage: java ... openjdk.codetools.jcov.report.view.JDKReport \\");
System.out.println(" <JCov coderage file produced for the tip of the repository> \\");
System.out.println(" <JDK source hierarchy> \\");
System.out.println(" <git diff file from the tip to a revision in the past produced with -U0 option> \\");
System.out.println(" <output file> \\");
System.out.println(" <report title> <report header>");
throw e;
}
}
private static SourcePath jdkSource(List<Path> repos) {
//TODO add platform specific - one platform or many?
//TODO - what about closed?
return new SourcePath(repos.stream().collect(Collectors.toMap(
repo -> repo,
repo -> {
try {
return Files.list(repo.resolve("src")).map(module -> module.resolve("share/classes")).
filter(Files::exists).collect(Collectors.toList());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})));
}
}
| 4,058 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SingleHTMLReport.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/view/SingleHTMLReport.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.FileCoverage;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Implements a hierarchical report in a single html file.
*/
public class SingleHTMLReport extends HightlightFilteredReport {
private String title;
private String header;
public SingleHTMLReport(SourceHierarchy source, FileSet files, FileCoverage coverage,
String title, String header,
SourceFilter highlight, SourceFilter include) {
//TODO a builder
super(source, files, new CoverageHierarchy(files.files(), source, coverage, highlight),
highlight, include);
this.title = title;
this.header = header;
}
public void report(Path dest) throws Exception {
try (BufferedWriter out = Files.newBufferedWriter(dest)) {
var rout = new HtmlOut(out);
out.write("<html><head>"); out.newLine();
out.write("<title>" + title + "</title>"); out.newLine();
out.write("<style>\n" +
".context {\n" +
" font-weight: lighter;\n" +
"}\n" +
".highlight {\n" +
" font-weight: bold;\n" +
"}\n" +
".covered {\n" +
" font-weight: bold;\n" +
" background-color: palegreen;\n" +
"}\n" +
".uncovered {\n" +
" font-weight: bold;\n" +
" background-color: salmon;\n" +
"}\n" +
".filename {\n" +
" font-weight: bold;\n" +
" font-size: larger;\n" +
"}\n" +
"</style>"); out.newLine();
out.write("</head><body>\n"); out.newLine();
out.write(header + "\n"); out.newLine();
out.write("<table><tbody>"); out.newLine();
toc(rout, "");
out.write("</tbody></table>"); out.newLine();
out.write("<hr>"); out.newLine();
code(rout, "");
out.write("<body></html>");out.newLine();
}
}
private class HtmlOut implements TOCOut, FileOut {
private final BufferedWriter out;
private HtmlOut(BufferedWriter out) {
this.out = out;
}
@Override
public void printFileLine(String s) throws IOException {
var cov = coverage().get(s);
out.write("<tr><td><a href=\"#" + s.replace('/', '_') + "\">" + s + "</a></td><td>" +
cov + "</td></tr>");
out.newLine();
}
@Override
public void printFolderLine(String s, Coverage cov) throws IOException {
if (s.isEmpty()) s = "total";
out.write("<tr><td><a href=\"#" + s.replace('/', '_') + "\">" + s + "</a></td><td>" +
cov + "</td></tr>");
out.newLine();
}
@Override
public void startFile(String file) throws IOException {
out.write("<hr/>"); out.newLine();
out.write("<a class=\"filename\" id=\"" +
file.replace('/', '_') + "\">" + file + ":" +
coverage().get(file) + "</a></br>"); out.newLine();
}
@Override
public void startLineRange(LineRange range) throws IOException {
out.write("<pre>"); out.newLine();
}
@Override
public void printSourceLine(int lineNo, String line, boolean highlight, Coverage coverage) throws IOException {
out.write("<a");
if (coverage != null) {
if (coverage.covered() > 0)
out.write(" class=\"covered\"");
else
out.write(" class=\"uncovered\"");
} else if (highlight) {
out.write(" class=\"highlight\"");
} else
out.write(" class=\"context\"");
out.write(">");
out.write((lineNo + 1) + ": ");
out.write(line.replaceAll("</?\\s*pre\\s*>", ""));
out.write("</a>");
out.newLine();
}
@Override
public void endLineRange(LineRange range) throws IOException {
out.write("</pre>"); out.newLine();
out.write("<hr/>"); out.newLine();
}
@Override
public void endFile(String s) throws IOException {
}
@Override
public void startDir(String s, Coverage cov) throws IOException {
if (s.isEmpty()) s = "total";
out.write("<a id=\"" + s.replace('/', '_') + "\"/>");
}
}
}
| 6,322 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
HightlightFilteredReport.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/view/HightlightFilteredReport.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import java.util.stream.Collectors;
abstract class HightlightFilteredReport {
private final FileSet files;
private final CoverageHierarchy coverage;
private final SourceHierarchy source;
private final SourceFilter highlight;
private final SourceFilter include;
protected HightlightFilteredReport(SourceHierarchy source, FileSet files, CoverageHierarchy coverage,
SourceFilter highlight, SourceFilter include) {
this.files = files;
this.coverage = coverage;
this.source = source;
this.highlight = highlight;
this.include = include;
}
protected void toc(TOCOut out, String s) throws Exception {
Coverage cov = coverage.get(s);
if (cov != null) {
out.printFolderLine(s.isEmpty() ? "" : s, cov);
for (var f : files.folders(s).stream().sorted().collect(Collectors.toList())) {
toc(out, f);
}
for (var f : files.files(s).stream().sorted().collect(Collectors.toList())) {
out.printFileLine(f);
}
}
}
protected void code(FileOut out, String s) throws Exception {
Coverage cov = coverage.get(s);
if (cov != null) {
out.startDir(s, cov);
for (var f : files.folders(s).stream().sorted().collect(Collectors.toList())) {
code(out, f);
}
for (var file : files.files(s).stream().sorted().collect(Collectors.toList())) {
var fileCov = coverage.getLineRanges(file);
if (fileCov != null) {
out.startFile(file);
var source = this.source.readFile(file);
var highlightRanges = highlight.ranges(file).iterator();
var highlightRange = highlightRanges.next();
for (var range : include.ranges(file)) {
out.startLineRange(range);
for (int line = range.first() - 1; line < range.last() && line < source.size(); line++) {
while (highlightRange != null && highlightRange.compare(line) > 0)
highlightRange = highlightRanges.hasNext() ? highlightRanges.next() : null;
boolean highlight = highlightRange != null && highlightRange.compare(line + 1) == 0;
out.printSourceLine(line, source.get(line), highlight,
fileCov.containsKey(line + 1) ? fileCov.get(line + 1).coverage() : null);
}
out.endLineRange(range);
}
out.endFile(s);
}
}
}
}
protected CoverageHierarchy coverage() {
return coverage;
}
protected interface TOCOut {
void printFileLine(String f) throws Exception;
void printFolderLine(String s, Coverage cov) throws Exception;
}
protected interface FileOut {
void startFile(String s) throws Exception;
void startLineRange(LineRange range) throws Exception;
void printSourceLine(int line, String s, boolean highlight, Coverage coverage) throws Exception;
void endLineRange(LineRange range) throws Exception;
void endFile(String s) throws Exception;
void startDir(String s, Coverage cov) throws Exception;
}
}
| 4,974 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
TextReport.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/view/TextReport.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.FileCoverage;
import openjdk.codetools.jcov.report.FileSet;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Implements a hierarchical report in a single text file.
*/
public class TextReport extends HightlightFilteredReport {
private static final String SEPARATOR_LINE = "-".repeat(80);
private String header;
public TextReport(SourceHierarchy source, FileSet files, FileCoverage coverage, String header, SourceFilter filter) {
super(source, files, new CoverageHierarchy(files.files(), source, coverage, filter), filter, filter);
this.header = header;
}
public void report(Path dest) throws Exception {
try (BufferedWriter out = Files.newBufferedWriter(dest)) {
out.write(header); out.newLine(); out.newLine();
super.toc(new TOCOut() {
@Override
public void printFileLine(String file) throws Exception {
out.write(file + " " + coverage().get(file));
out.newLine();
}
@Override
public void printFolderLine(String folder, Coverage cov) throws Exception {
out.write((folder.isEmpty() ? "total" : folder) + " " + cov);
out.newLine();
}
}, "");
code(new FileOut() {
@Override
public void startFile(String file) throws Exception {
out.write("file:" + file + " " + coverage().get(file));
out.newLine();
out.write(SEPARATOR_LINE);
out.newLine();
}
@Override
public void startLineRange(LineRange range) throws Exception {
}
@Override
public void printSourceLine(int line, String s, boolean highlight, Coverage coverage) throws Exception {
out.write((line + 1) + ":" + (coverage == null ? " " : coverage.covered() > 0 ? "+" : "-") + s);
out.newLine();
}
@Override
public void endLineRange(LineRange range) throws Exception {
out.write(SEPARATOR_LINE);
out.newLine();
}
@Override
public void endFile(String s) throws Exception {
}
@Override
public void startDir(String s, Coverage cov) throws Exception {
}
}, "");
}
}
}
| 4,111 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CoverageHierarchy.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/view/CoverageHierarchy.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.view;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.FileCoverage;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import openjdk.codetools.jcov.report.source.SourceHierarchy;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.stream.Collectors;
public class CoverageHierarchy {
private final Map<String, Coverage> data;
private final Map<String, Map<Integer, CoveredLineRange>> lineCoverage;
private final FileCoverage coverage;
private final SourceFilter filter;
private final SourceHierarchy source;
public CoverageHierarchy(Collection<String> files, SourceHierarchy source, FileCoverage coverage, SourceFilter filter) {
data = new HashMap<>();
lineCoverage = new HashMap<>();
this.source = source;
data.put("", null);
for (String file : files) {
lineCoverage.put(file, null);
var components = file.split("/");
String path = "";
for (var component : file.split("/")) {
data.put(path += (path.isEmpty() ? "" : "/") + component, null);
}
}
this.coverage = coverage;
this.filter = filter;
}
public Map<Integer, CoveredLineRange> getLineRanges(String file) {
if (lineCoverage.containsKey(file) && lineCoverage.get(file) != null)
return lineCoverage.get(file);
String className = source.toClass(file);
if (className == null) return null;
var coverage = this.coverage.ranges(className);
var coverageIt = coverage.iterator();
CoveredLineRange lastCoverageRange = null;
var fileCoverage = new HashMap<Integer, CoveredLineRange>();
var used = new HashSet<CoveredLineRange>();
for (var range : filter.ranges(file)) {
for (int line = range.first(); line <= range.last() ; line++) {
if (lastCoverageRange == null || lastCoverageRange.last() < line) {
while (coverageIt.hasNext() && (lastCoverageRange == null || lastCoverageRange.last() < line))
lastCoverageRange = coverageIt.next();
}
if (lastCoverageRange != null && lastCoverageRange.last() >= line && lastCoverageRange.first() <= line) {
fileCoverage.put(line, lastCoverageRange);
used.add(lastCoverageRange);
}
}
}
data.put(file, Coverage.sum(used.stream().map(CoveredLineRange::coverage).collect(Collectors.toList())));
lineCoverage.put(file, fileCoverage);
return fileCoverage;
}
public Coverage get(String fileOrDir) {
var res = data.get(fileOrDir);
if (res != null) return res;
if (lineCoverage.containsKey(fileOrDir)) {
return getLineRanges(fileOrDir) == null ? null : data.get(fileOrDir);
}
int[] coverage = {0, 0};
boolean[] someCoverageFound = {false};
data.entrySet().stream()
.filter(e -> e.getKey().startsWith(fileOrDir + "/") && e.getKey().substring(fileOrDir.length() + 1).indexOf('/') < 0 ||
fileOrDir.isEmpty() && !e.getKey().isEmpty() && e.getKey().indexOf('/') < 0)
.forEach(e -> {
var c = (e.getValue() == null) ? get(e.getKey()) : e.getValue();
if (c != null) {
someCoverageFound[0] = true;
coverage[0] += c.covered();
coverage[1] += c.total();
}
});
if (someCoverageFound[0]) {
res = new Coverage(coverage[0], coverage[1]);
data.put(fileOrDir, res);
return res;
} else return null;
}
}
| 5,174 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
JCovLineCoverage.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/jcov/JCovLineCoverage.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.jcov;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataMethod;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.DataRoot;
import com.sun.tdk.jcov.instrument.LocationRef;
import com.sun.tdk.jcov.report.MethodCoverage;
import openjdk.codetools.jcov.report.Coverage;
import openjdk.codetools.jcov.report.CoveredLineRange;
import openjdk.codetools.jcov.report.FileCoverage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.lang.Math.max;
/**
* This uses JCov output to determine line coverage of classes
*/
public class JCovLineCoverage implements FileCoverage {
private final DataRoot root;
private final Map<String, List<CoveredLineRange>> cache = new HashMap<>();
public JCovLineCoverage(DataRoot root) {
this.root = root;
}
@Override
public List<CoveredLineRange> ranges(String file) {
var result = new ArrayList<CoveredLineRange>();
String className = file.substring(0, file.length() - ".java".length());
root.getClasses().stream()
.filter(dc -> dc.getFullname().equals(className) || dc.getFullname().startsWith(className + "$"))
.forEach(dc -> result.addAll(ranges(dc)));
Collections.sort(result);
return result;
}
private List<CoveredLineRange> ranges(DataClass cls) {
var result = new HashMap<Integer, Boolean>();
for (DataMethod m : cls.getMethods()) if (m instanceof DataMethodWithBlocks) {
var lc = new MethodCoverage(m, true).getLineCoverage();
// boolean methodCovered = false;
for (int i = (int)lc.firstLine(); i <= lc.lastLine(); i++) {
if (lc.isCode(i)) {
if (result.get(i) == null || !result.get(i).booleanValue())
result.put(i, lc.isLineCovered(i));
// methodCovered |= lc.isLineCovered(i);
}
}
//mmm but also the method declaration
//this is unreliable
//var lineTable = m.getLineTable().stream().sorted(Comparator.comparingInt(l -> l.bci))
// .collect(toList());
//int methodLine = getLine(lineTable, 0) - 1; //can not do better without code parsing
//if (methodLine >= 0) result.put(methodLine, methodCovered);
}
//below is an unsuccessful attempt to replicate the content of getLineCovreage
//keep it around, return to it later and figure out what is wrong
//currently the whole code marked as covered because of fallthough in clinit which
//starts in the beginning and ends in the end of the file
// for (DataMethod m : cls.getMethods()) if (m instanceof DataMethodWithBlocks) {
// var added = new HashMap<DataBlock, Item>();
// var items = new ArrayList<Item>();
// for (DataBlock db : m.getBlocks()) {
// if (db instanceof DataBlockTarget) {
// continue;
// }
// Item item = new Item(db, db.getCount() > 0);
//
// boolean isNew = true;
// for (DataBlock d : added.keySet()) {
// if (d.startBCI() == db.startBCI()) {
// if (db.getCount() > 0) added.get(d).cover();
// isNew = false;
// break;
// }
// }
// if (isNew) {
// added.put(db, item);
// items.add(item);
// }
// }
// for (DataBlock db : m.getBranchTargets()) {
// Item item = new Item(db, db.getCount() > 0);
//
// boolean isNew = true;
// for (DataBlock d : added.keySet()) {
// if (d.startBCI() == db.startBCI()) {
// if (db.getCount() > 0) added.get(d).cover();
// isNew = false;
// break;
// }
// }
// if (isNew) {
// added.put(db, item);
// items.add(item);
// }
// }
// var lineTable = m.getLineTable().stream().sorted(Comparator.comparingInt(l -> l.bci))
// .collect(Collectors.toList());
// for (var item : items) {
// int startLine = getLine(lineTable, item.startBCI());
// int endLine = getLine(lineTable, min(item.endBCI(), ((DataMethodWithBlocks) m).getBytecodeLength()));
// for (int l = startLine; l <= endLine; l++) {
// var lineCovered = result.containsKey(l) && result.get(l);
// if (!lineCovered) result.put(l, item.covered);
// }
// }
// }
return result.entrySet().stream()
.sorted(Comparator.comparingInt(Map.Entry::getKey))
.map(le -> new CoveredLineRange(le.getKey(), le.getKey(), le.getValue() ? Coverage.COVERED : Coverage.UNCOVERED))
.collect(Collectors.toList());
}
// private static int getLine(List<DataMethod.LineEntry> lineTable, int bci) {
// int maxLine = 0;
// for (var le : lineTable) {
// if (le.bci > bci) return maxLine;
// else maxLine = max(maxLine, le.line);
// }
// return maxLine;
// }
// private static class Item {
// private final LocationRef loc;
// private volatile boolean covered;
//
// private Item(LocationRef loc, boolean covered) {
// this.loc = loc;
// this.covered = covered;
// }
// public void cover() {this.covered = true;}
//
// public int startBCI() {return loc.startBCI();}
// public int endBCI() {return loc.endBCI();}
// }
}
| 7,310 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SourceFileFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/filter/SourceFileFilter.java | package openjdk.codetools.jcov.report.filter;
import java.util.Set;
/**
* A source filter which is also aware of what files need to be included.
*/
public interface SourceFileFilter extends SourceFilter {
Set<String> files();
}
| 236 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
GitDiffFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/filter/GitDiffFilter.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.filter;
import openjdk.codetools.jcov.report.LineRange;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* An implementation of the source filter which is coming from parsing git diff.
* @see #parseDiff(Path)
*/
public class GitDiffFilter implements SourceFileFilter {
private final Map<String, List<LineRange>> lines;
private GitDiffFilter(Map<String, List<LineRange>> lines) {
this.lines = lines;
}
/**
* Parses git diff into a source filter. The diff is supposed to be produced with <code>-U0</code> option.
* @param diffFile the File to parse
* @return
* @throws IOException
*/
public static SourceFileFilter parseDiff(Path diffFile) throws IOException {
Map<String, List<LineRange>> lines = new HashMap<>();
try(BufferedReader in = Files.newBufferedReader(diffFile)) {
String line = null;
while(true) {
if (line == null)
while ((line = in.readLine()) != null && !line.startsWith("+++ b/")) {}
if (line == null) break;;
String fileName = line.substring("+++ b/".length());
if (fileName.endsWith(".java")) {
List<LineRange> fragments = new ArrayList<>();
String lineNumbers = in.readLine();
while (lineNumbers != null && !lineNumbers.startsWith("+++ b/")) {
lineNumbers = lineNumbers.substring("@@ ".length());
lineNumbers = lineNumbers.substring(lineNumbers.indexOf(" +") + 2, lineNumbers.indexOf(" @@"));
int commaIndex = lineNumbers.indexOf(',');
int firstLine, lastLine;
if (commaIndex > -1) {
firstLine = Integer.parseInt(lineNumbers.substring(0, commaIndex));
lastLine = firstLine + Integer.parseInt(lineNumbers.substring(commaIndex + 1)) - 1;
} else {
lastLine = firstLine = Integer.parseInt(lineNumbers);
}
fragments.add(new LineRange(firstLine, lastLine));
while ((lineNumbers = in.readLine()) != null && !lineNumbers.startsWith("@@ ")
&& !lineNumbers.startsWith("+++ b/")) {
}
if (lineNumbers == null) break;
if (lineNumbers.startsWith("+++ b/")) {
line = lineNumbers;
continue;
}
}
lines.put(fileName, fragments);
if (lineNumbers == null) break;
} else line = null;
}
}
return new GitDiffFilter(lines);
}
@Override
public Set<String> files() {
return lines.keySet();
}
@Override
public List<LineRange> ranges(String file) {
return lines.get(file);
}
}
| 4,507 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SourceFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/filter/SourceFilter.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.filter;
import openjdk.codetools.jcov.report.LineRange;
import java.util.List;
/**
* Filters a source file by providing a list of line ranges which needs not be included.
* @see LineRange
*/
public interface SourceFilter {
/**
* Line ranges to be included. Any implementaiton is assumed to return a list of line that is ordered
* by beginning line.
* @param file
* @return
*/
List<LineRange> ranges(String file);
default boolean includes(String file, int line) {
return ranges(file).stream().anyMatch(r -> r.compare(line) == 0);
}
}
| 1,835 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SourceHierarchy.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/source/SourceHierarchy.java | package openjdk.codetools.jcov.report.source;
import java.io.IOException;
import java.util.List;
/**
* An abstraction for source hierarchy.
*/
public interface SourceHierarchy {
/**
* Delivers the file source code.
* @param file - file name within the source hierarchy.
*/
List<String> readFile(String file) throws IOException;
/**
* Maps a file name (as present in source) to a class file name.
* Example: <code>src/main/java/my/company/product/Main.hava</code> to <code>my/company/product/Main.hava</code>.
* @param file - file name within the source hierarchy.
*/
String toClass(String file);
}
| 654 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SourcePath.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/source/SourcePath.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.source;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
/**
* When the source code is available locally.
*/
public class SourcePath implements SourceHierarchy {
private final Map<Path, List<Path>> roots;
/**
* Single source repository, Single class hierarchy.
*/
public SourcePath(Path srcRoot, Path classRoot) {
this(srcRoot, List.of(classRoot));
}
/**
* Single source repository, multiple class hierarchies.
*/
public SourcePath(Path srcRoot, List<Path> classRoots) {
this(Map.of(srcRoot, classRoots));
}
/**
* There could be multiple repositories which multiple class hierarchies within each.
*/
public SourcePath(Map<Path, List<Path>> roots) {
this.roots = roots;
}
protected Path resolveFile(Path root, String file) {
return root.resolve(file);
}
@Override
public List<String> readFile(String file) throws IOException {
Path res;
for (var root : roots.keySet()) {
res = resolveFile(root, file);
if (Files.exists(res)) return Files.readAllLines(res);
}
return null;
}
public Path resolveClass(String file) {
Path res;
for (var sourceRoot : roots.keySet()) {
for (var classRoot : roots.get(sourceRoot)) {
res = resolveFile(classRoot, file);
if (Files.exists(res)) return res;
}
}
return null;
}
@Override
public String toClass(String file) {
for (var sourceRoot : roots.keySet()) {
var path = sourceRoot.resolve(file);
if (Files.exists(path)) {
for (var classRoot : roots.get(sourceRoot))
if (path.startsWith(classRoot))
return classRoot.relativize(path).toString();
}
}
return null;
}
}
| 3,234 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ContextFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coverage_reports/src/openjdk/codetools/jcov/report/source/ContextFilter.java | /*
* Copyright (c) 2023, 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 openjdk.codetools.jcov.report.source;
import openjdk.codetools.jcov.report.LineRange;
import openjdk.codetools.jcov.report.filter.SourceFilter;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.max;
/**
* Adds "context lines" to a filter. See <code>man diff</code>
*/
public class ContextFilter implements SourceFilter {
private final SourceFilter filter;
private final int contextLines;
public ContextFilter(SourceFilter filter, int context) {
this.filter = filter;
contextLines = context;
}
@Override
public List<LineRange> ranges(String file) {
var ranges = new ArrayList<LineRange>();
var origRanges = filter.ranges(file);
LineRange last = null;
int lastEnded = -1;
for (int i = 0; i < origRanges.size(); i++) {
if (last == null)
last = expandRange(origRanges, i);
else {
if (last.last() < origRanges.get(i).first() - contextLines) {
ranges.add(last);
last = expandRange(origRanges, i);
} else
last = new LineRange(last.first(),
origRanges.get(i).last() + contextLines);
}
}
ranges.add(last);
return ranges;
}
private LineRange expandRange(List<LineRange> origRanges, int i) {
return new LineRange(
max(origRanges.get(i).first() - contextLines, 1),
origRanges.get(i).last() + contextLines);
}
}
| 2,781 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MainTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/MainTest.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 openjdk.jcov.filter.simplemethods;
import org.testng.annotations.Test;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class MainTest {
@Test
public void testJRTFS() throws IOException, URISyntaxException {
Path getters = Files.createTempFile("getters", ".lst");
System.out.println("testJRTFS output file: " + getters.toAbsolutePath().toString());
Scanner.main(new String[]{
"--getters", getters.toAbsolutePath().toString(),
"--include", "java.util",
"jrt:/"
});
assertTrue(Files.lines(getters).anyMatch(l -> l.equals("java/util/ArrayList#size()I")));
assertTrue(Files.lines(getters).noneMatch(l -> l.equals("java/io/File#getPath()Ljava/lang/String;")));
Files.delete(getters);
}
@Test
public void testJRTFSNoJavaUtil() throws IOException, URISyntaxException {
Path getters = Files.createTempFile("throwers", ".lst");
System.out.println("testJRTFSNoJavaUtil output file: " + getters.toAbsolutePath().toString());
Scanner.main(new String[]{
"--throwers", getters.toAbsolutePath().toString(),
"--exclude", "java.util",
"jrt:/"
});
assertTrue(Files.lines(getters).noneMatch(l -> l.equals("java/util/AbstractList#add(ILjava/lang/Object;)V")));
assertTrue(Files.lines(getters).anyMatch("java/io/InputStream#reset()V"::equals));
Files.delete(getters);
}
@Test
public void testDir() throws IOException, URISyntaxException {
String dir = System.getProperty("test.classes");
Path delegators = Files.createTempFile("delegators", ".lst");
System.out.println("testDir output file: " + delegators.toAbsolutePath().toString());
Scanner.main(new String[]{
"--delegators", delegators.toAbsolutePath().toString(),
"file://" + dir
});
assertTrue(Files.lines(delegators).anyMatch(l ->
l.equals(DelegatorsTest.class.getName().replace('.', '/') + "#foo(I)I")));
Files.delete(delegators);
}
@Test
public void testJAR() throws IOException, URISyntaxException {
String jar = System.getProperty("test.jar");
Path setters = Files.createTempFile("setters", ".lst");
System.out.println("testJAR output file: " + setters.toAbsolutePath().toString());
Scanner.main(new String[]{
"--setters", setters.toAbsolutePath().toString(),
"jar:file:" + jar});
assertTrue(Files.lines(setters).anyMatch(l ->
l.equals(SettersTest.class.getName().replace('.', '/') + "#setField(I)V")));
}
@Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Unknown filter.*")
public void testWrongFilter() throws IOException, URISyntaxException {
Scanner.main(new String[]{
"--a-non-existing-filter", "a_file",
"file:///a/path"});
}
@Test
public void testNoFilter() throws IOException, URISyntaxException {
try {
Scanner.main(new String[]{
"file:///a/path"});
fail("No RuntimeException when no filters specified");
} catch (RuntimeException e) {
assertTrue(Arrays.stream(Scanner.Filter.values()).map(f -> "--" + f.name())
.allMatch(f -> e.getMessage().contains(f)), "Incorrect error message: " + e.getMessage());
}
}
@Test
public void testTwoFilters() throws IOException, URISyntaxException {
String dir = System.getProperty("test.classes");
Path setters = Files.createTempFile("setters2_", ".lst");
Path getters = Files.createTempFile("getters2_", ".lst");
System.out.println("testDir output file: " + setters.toAbsolutePath().toString());
System.out.println("testDir output file: " + getters.toAbsolutePath().toString());
Scanner.main(new String[]{
"--setters", setters.toAbsolutePath().toString(),
"--getters", getters.toAbsolutePath().toString(),
"file://" + dir
});
assertTrue(Files.lines(setters).anyMatch(l ->
l.equals(SettersTest.class.getName().replace('.', '/') + "#setField(I)V")));
assertTrue(Files.lines(getters).anyMatch(l ->
l.equals(GettersTest.class.getName().replace('.', '/') + "#getField()I")));
Files.delete(setters);
Files.delete(getters);
}
}
| 6,000 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SettersTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/SettersTest.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
public class SettersTest {
Setters tested;
ClassNode cls;
@BeforeTest
public void init() throws IOException {
tested = new Setters();
cls = TestUtils.findTestClass(this.getClass());
}
@DataProvider(name = "cases")
public Object[][] cases() {
return new Object[][] {
{"setObjectField(Ljava/lang/String;)V", true, "An object setter"},
{"setFieldToToString(Ljava/lang/Object;)V", false, "Assigning toString() to a field"},
{"setField(I)V", true, "A setter"},
{"setStaticField(Ljava/lang/Object;)V", true, "A static setter"},
{"setOtherField(J)V", true, "A setter for other field object"},
{"empty()V", false, "Empty"}
};
}
@Test(dataProvider = "cases")
public void test(String method, boolean result, String description) {
assertEquals(tested.test(cls, TestUtils.findTestMethod(cls, method)), result, description);
}
//test data
int aField;
String anObjectField;
static Object aStaticField;
class Other {
long aField;
}
Other other;
void setField(int v) { aField = v; }
void setOtherField(long v) {
other.aField = v;
}
void setObjectField(String v) {
anObjectField = v;
}
void setFieldToToString(Object v) {
anObjectField = v.toString();
}
static void setStaticField(Object v) {
aStaticField = v;
}
void empty() {
}
}
| 3,010 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ThrowersTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/ThrowersTest.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static openjdk.jcov.filter.simplemethods.TestUtils.findTestMethod;
import static org.testng.Assert.assertEquals;
public class ThrowersTest {
Throwers tested;
ClassNode cls;
@BeforeTest
public void init() throws IOException {
tested = new Throwers();
cls = TestUtils.findTestClass(this.getClass());
}
@DataProvider(name = "cases")
public Object[][] cases() {
return new Object[][] {
{"notImplemented()V", true, "A thrower"},
{"compoundMessage()V", false, "A thrower with a computed message"},
{"empty()V", false, "Empty"}
};
}
@Test(dataProvider = "cases")
public void test(String method, boolean result, String description) {
assertEquals(tested.test(cls, findTestMethod(cls, method)), result, description);
}
//test data
String message = "not ";
void empty() {}
void notImplemented(){throw new RuntimeException(message);}
void compoundMessage(){throw new RuntimeException(message + "implemented");}
}
| 2,510 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
GettersTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/GettersTest.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static openjdk.jcov.filter.simplemethods.TestUtils.findTestMethod;
import static org.testng.Assert.assertEquals;
public class GettersTest {
Getters tested;
ClassNode cls;
@BeforeTest
public void init() throws IOException {
tested = new Getters();
cls = TestUtils.findTestClass(this.getClass());
}
@DataProvider(name = "cases")
public Object[][] cases() {
return new Object[][] {
{"getField()I", true, "A getter"},
{"getConstant()Ljava/lang/Object;", true, "A constant getter"},
{"getObjectField()Ljava/lang/String;", true, "An object getter"},
{"getStaticConstant()I", true, "A constant getter using LDC"},
{"getStaticField()Ljava/lang/Object;", true, "A static getter"},
{"getFieldToString()Ljava/lang/String;", false, "Returning toString() of a field"},
{"getOtherField()J", true, "A getter for other field object"},
{"empty()V", false, "Empty"}
};
}
@Test(dataProvider = "cases")
public void test(String method, boolean result, String description) {
assertEquals(tested.test(cls, findTestMethod(cls, method)), result, description);
}
//test data
int aField;
String anObjectField;
static Object aStaticField;
static final int CONSTANT=7532957;
class Other {
long aField;
}
Other other;
int getField() {
return aField;
}
Object getConstant() {
return null;
}
int getStaticConstant() {
return CONSTANT;
}
long getOtherField() {
return other.aField;
}
String getObjectField() {
return anObjectField;
}
String getFieldToString() {
return anObjectField.toString();
}
static Object getStaticField() {
return aStaticField;
}
void empty() {
}
}
| 3,377 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EmptyMethodsTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/EmptyMethodsTest.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
public class EmptyMethodsTest {
EmptyMethods tested;
ClassNode cls;
@BeforeTest
public void init() throws IOException {
tested = new EmptyMethods();
cls = TestUtils.findTestClass(this.getClass());
}
@DataProvider(name = "cases")
public Object[][] cases() {
return new Object[][] {
{"empty()V", true, "Empty"},
{"get()I", false, "A getter"},
{"init()V", false, "init()"}
};
}
@Test(dataProvider = "cases")
public void test(String method, boolean result, String description) {
assertEquals(tested.test(cls, TestUtils.findTestMethod(cls, method)), result, description);
}
//test data
void empty() {
//doing nothing
}
int get(){return 0;}
}
| 2,288 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DelegatorsTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/DelegatorsTest.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
public class DelegatorsTest {
Delegators any_name_delegator;
Delegators same_name_delegator;
ClassNode cls;
@BeforeTest
public void init() throws IOException {
any_name_delegator = new Delegators();
same_name_delegator = new Delegators(true);
cls = TestUtils.findTestClass(this.getClass());
}
@DataProvider(name = "cases")
public Object[][] cases() {
return new Object[][] {
{same_name_delegator, "foo(Ljava/lang/String;I)I", false, "Simple getter"},
{same_name_delegator, "foo(I)I", true, "Using constants or parameters"},
{same_name_delegator, "foo(J)I", true, "Using fields"},
{same_name_delegator, "foo(Z)I", false, "Having condition"},
{same_name_delegator, "foo(F)I", false, "Calling other methods"},
{same_name_delegator, "bar(I)I", false, "Different method"},
{any_name_delegator, "bar(I)I", true, "Different method"},
{any_name_delegator, "empty()V", false, "Empty"}
};
}
@Test(dataProvider = "cases")
public void test(Delegators delegator, String method, boolean result, String description) throws IOException {
assertEquals(delegator.test(cls, TestUtils.findTestMethod(cls, method)), result, description);
}
//test data
int aField = 0;
static String aStaticField = null;
int foo(String i, int j) {return j;}
int foo(int j) {
return foo("", j);
}
int foo(long s) {
return foo(aStaticField, aField);
}
int foo(boolean s) {
if(s)
return foo(1);
else
return foo(0);
}
int foo(float s) {
foo(null, 0);
return foo(null, 1);
}
int bar(int j) {
return foo(null, j);
}
void empty() {
}
}
| 3,360 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
TestUtils.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/test/openjdk/jcov/filter/simplemethods/TestUtils.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
public class TestUtils {
static ClassNode findTestClass(Class cls) throws IOException {
ClassNode result = new ClassNode();
ClassReader reader = new ClassReader(cls.getClassLoader().
getResourceAsStream(cls.getName().replace('.','/') + ".class"));
reader.accept(result, 0);
return result;
}
static MethodNode findTestMethod(ClassNode cls, String methodSig) {
for(Object mo: cls.methods) {
MethodNode m = (MethodNode) mo;
if((m.name + m.desc).equals(methodSig)) {
return m;
}
}
throw new IllegalStateException("Method does not exist: " + methodSig + " in class " + cls.name);
}
}
| 2,123 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Getters.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/Getters.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.function.BiPredicate;
import static org.objectweb.asm.Opcodes.RETURN;
public class Getters implements BiPredicate<ClassNode, MethodNode> {
/**
* Identifies simple getters. A simple getter is a method obtaining a value with a "simple" code and returning it.
* @see Utils#isSimpleInstruction(int)
*/
@Override
public boolean test(ClassNode clazz, MethodNode m) {
int index = 0;
int opCode = -1;
//skip all instructions allowed to get values
for(; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
if (!Utils.isSimpleInstruction(opCode)) {
break;
}
}
}
//that should be a return instruction, but returning a value
return Utils.isReturnInstruction(opCode) && opCode != RETURN;
}
}
| 2,263 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Setters.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/Setters.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.function.BiPredicate;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
/**
* Identifies simple setters. A simple setter is a method obtaining a value with a "simple" code and
* assigning a field with it.
* @see Utils#isSimpleInstruction(int)
*/
public class Setters implements BiPredicate<ClassNode, MethodNode> {
@Override
public boolean test(ClassNode clazz, MethodNode m) {
int index = 0;
int opCode = -1;
//skip all instructions allowed to get values
for(; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
if (!Utils.isSimpleInstruction(opCode)) {
break;
}
}
}
//that should be an instruction setting a field
if(opCode != PUTFIELD && opCode != PUTSTATIC) {
return false;
}
//find next
for(index++; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
if (!Utils.isSimpleInstruction(opCode)) {
break;
}
}
}
//and that should be a return
return opCode == RETURN;
}
}
| 2,743 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EmptyMethods.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/EmptyMethods.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.function.BiPredicate;
import static org.objectweb.asm.Opcodes.RETURN;
public class EmptyMethods implements BiPredicate<ClassNode, MethodNode> {
@Override
public boolean test(ClassNode node, MethodNode m) {
int index = 0;
int opCode = -1;
//skip all instructions allowed to get values
for(; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
if (!Utils.isSimpleInstruction(opCode)) {
break;
}
}
}
//that should be a return
return opCode == RETURN;
}
}
| 2,017 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Scanner.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/Scanner.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 openjdk.jcov.filter.simplemethods;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiPredicate;
import static java.util.stream.Collectors.joining;
public class Scanner {
private static String USAGE =
"java -classpath jcov.jar:SimpleMethods.jar " + Scanner.class.getName() + " --usage\n" +
"\n" +
"java -classpath jcov.jar:SimpleMethods.jar " + Scanner.class.getName() +
" [--include|-i <include patern>] [--exclude|-e <exclude pattern>] \\\n" +
"[--getters <output file name>] " +
"[--setters <output file name>] " +
"[--delegators <output file name>] " +
"[--throwers <output file name>] " +
"[--empty <output file name>] \\\n" +
"jrt:/ | jar:file:/<jar file> | file:/<class hierarchy>\n" +
"\n" +
" Options\n" +
" --include - what classes to scan for simple methods.\n" +
" --exclude - what classes to exclude from scanning.\n" +
" Next options specify file names where to collect this or that type of methods. " +
"Only those which specified are detected. At least one kind of methods should be requested. " +
"Please consult the source code for exact details.\n" +
" --getters - methods which are just returning a value.\n" +
" --setters - methods which are just setting a field.\n" +
" --delegators - methods which are just calling another method.\n" +
" --throwers - methods which are just throwing an exception.\n" +
" --empty - methods with an empty body.\n" +
"\n" +
" Parameters define where to look for classes which are to be scanned.\n" +
" jrt:/ - scan JDK classes\n" +
" jar:file:/ - scan a jar file\n" +
" file:/ - scan a directory containing compiled classes.";
private Utils.Pattern[] includes;
private Utils.Pattern[] excludes;
private final List<Filter> filters = new ArrayList<>();
private final List<URI> filesystems = new ArrayList<>();
public static void main(String[] args) throws IOException, URISyntaxException {
if (args.length == 1 && args[0].equals("--usage")) {
usage();
return;
}
Scanner scanner = new Scanner();
final List<Utils.Pattern> class_includes = new ArrayList<>();
final List<Utils.Pattern> class_excludes = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--include":
case "-i":
i++;
class_includes.add(new Utils.Pattern(args[i], true, false));
break;
case "--exclude":
case "-e":
i++;
class_excludes.add(new Utils.Pattern(args[i], false, false));
break;
default:
//the only other options allowed are -<filter name>
//see usage
if (args[i].startsWith("--")) {
Filter filter = Filter.get(args[i].substring(2));
scanner.filters.add(filter);
i++;
filter.setOutputFile(args[i]);
} else {
try {
scanner.filesystems.add(new URI(args[i]));
} catch (URISyntaxException e) {
usage();
throw e;
}
}
}
}
if (scanner.filters.size() == 0) {
usage();
String filtersList =
Arrays.stream(Filter.values()).map(f -> "--" + f.name()).collect(joining(","));
throw new IllegalArgumentException("One or more of " + filtersList + " options must be specified");
}
scanner.includes = class_includes.toArray(new Utils.Pattern[0]);
scanner.excludes = class_excludes.toArray(new Utils.Pattern[0]);
scanner.run();
}
private static void usage() {
System.out.println(USAGE);
}
public void run() throws IOException {
try {
for (Filter f : filters) {
f.openFile();
}
for (URI uri : filesystems) {
FileSystem fs;
Iterator<Path> roots;
String scheme = uri.getScheme();
if(scheme == null) {
throw new IllegalStateException("No scheme in " + uri.toString());
}
switch (scheme) {
case "jrt":
fs = FileSystems.getFileSystem(uri);
roots = Files.newDirectoryStream(fs.getPath("./modules")).iterator();
break;
case "jar":
fs = FileSystems.newFileSystem(uri, new HashMap<>());
roots = fs.getRootDirectories().iterator();
break;
case "file":
fs = FileSystems.getDefault();
roots = List.of(fs.getPath(uri.getPath())).iterator();
break;
default:
throw new RuntimeException("TRI not supported: " + uri.toString());
}
while (roots.hasNext()) {
Path root = roots.next();
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(".class")) {
visitClass(root, file);
}
return FileVisitResult.CONTINUE;
}
});
}
}
} finally {
for (Filter f : filters) {
f.closeFile();
}
}
}
private void visitClass(Path root, Path file) throws IOException {
try (InputStream in = Files.newInputStream(file)) {
ClassReader reader;
reader = new ClassReader(in);
if (included(reader.getClassName())) {
ClassNode clazz = new ClassNode();
reader.accept(clazz, 0);
for (Object methodObject : clazz.methods) {
MethodNode method = (MethodNode) methodObject;
for (Filter f : filters) {
if (f.filter.test(clazz, method)) {
f.add(clazz.name + "#" + method.name + method.desc);
}
}
}
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Exception while parsing file " + file + " from " + root, e);
}
}
private boolean included(String clazz) {
return Utils.accept(includes, null, "/" + clazz, null) &&
Utils.accept(excludes, null, "/" + clazz, null);
}
enum Filter {
getters("simple getter", new Getters()),
setters("simple setter", new Setters()),
delegators("simple delegator", new Delegators()),
throwers("simple thrower", new Throwers()),
empty("empty methods", new EmptyMethods());
private String description;
private BiPredicate<ClassNode, MethodNode> filter;
private String outputFile;
private BufferedWriter output;
Filter(String description, BiPredicate<ClassNode, MethodNode> filter) {
this.description = description;
this.filter = filter;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public void openFile() throws IOException {
output = Files.newBufferedWriter(Paths.get(outputFile));
output.write("#" + description);
output.newLine();
output.flush();
}
public void closeFile() throws IOException {
if (outputFile != null) {
output.flush();
output.close();
}
}
public void add(String s) throws IOException {
output.write(s);
output.newLine();
output.flush();
}
static Filter get(String name) {
for(Filter f : values()) {
if(f.name().equals(name)) {
return f;
}
}
throw new RuntimeException("Unknown filter: " + name);
}
}
}
| 11,112 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Utils.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/Utils.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 openjdk.jcov.filter.simplemethods;
import java.util.Arrays;
import static org.objectweb.asm.Opcodes.*;
public class Utils {
private final static int[] SIMPLE_INSTRUCTIONS = new int[]{DUP, LDC,
BALOAD, CALOAD, AALOAD, DALOAD, FALOAD, IALOAD, SALOAD,
ACONST_NULL,
ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5, ICONST_M1,
LCONST_0, LCONST_1,
FCONST_0, FCONST_1, FCONST_2,
DCONST_0, DCONST_1,
ALOAD, ILOAD, FLOAD, LLOAD, DLOAD,
GETFIELD, GETSTATIC,
BIPUSH, SIPUSH};
private final static int[] INVOKE_INSTRUCTIONS = new int[]{INVOKEVIRTUAL, INVOKEINTERFACE, INVOKESTATIC,
INVOKEDYNAMIC, INVOKESPECIAL};
private final static int[] RETURN_INSTRUCTIONS = new int[]{RETURN, ARETURN, IRETURN, FRETURN, LRETURN, DRETURN};
static {
Arrays.sort(SIMPLE_INSTRUCTIONS);
Arrays.sort(INVOKE_INSTRUCTIONS);
Arrays.sort(RETURN_INSTRUCTIONS);
}
/**
* An instruction is called "simple" if its only effect is to bring values onto the stack from stack, variables, fields, constants, etc.
* @param opCode
* @return
*/
public static boolean isSimpleInstruction(int opCode) {
return Arrays.binarySearch(SIMPLE_INSTRUCTIONS, opCode) >= 0;
}
public static boolean isReturnInstruction(int opCode) {
return Arrays.binarySearch(RETURN_INSTRUCTIONS, opCode) >= 0;
}
public static boolean isInvokeInstruction(int opCode) {
return Arrays.binarySearch(INVOKE_INSTRUCTIONS, opCode) >= 0;
}
}
| 2,825 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Delegators.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/Delegators.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.function.BiPredicate;
import static java.util.Arrays.binarySearch;
import static openjdk.jcov.filter.simplemethods.Utils.isInvokeInstruction;
import static openjdk.jcov.filter.simplemethods.Utils.isReturnInstruction;
import static openjdk.jcov.filter.simplemethods.Utils.isSimpleInstruction;
public class Delegators implements BiPredicate<ClassNode, MethodNode> {
private final boolean sameNameDelegationOnly;
public Delegators(boolean sameNameDelegationOnly) {
this.sameNameDelegationOnly = sameNameDelegationOnly;
}
public Delegators() {
this(false);
}
/**
* Identifies simple delegation. A simple delegator is a method obtaining any number of values with a "simple" code
* and then calling a method with the obtained values.
* @see Utils#isSimpleInstruction(int)
*/
@Override
public boolean test(ClassNode clazz, MethodNode m) {
int index = 0;
int opCode = -1;
//skip all instructions allowed to get values
for(; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
if (!isSimpleInstruction(opCode)) {
break;
}
}
}
//that should be an invocation instruction
if(!isInvokeInstruction(opCode)) {
return false;
}
if(sameNameDelegationOnly) {
//check name
AbstractInsnNode node = m.instructions.get(index);
String name;
if (node instanceof MethodInsnNode) {
name = ((MethodInsnNode) node).name;
} else if (node instanceof InvokeDynamicInsnNode) {
name = ((InvokeDynamicInsnNode) node).name;
} else {
throw new IllegalStateException("Unknown node type: " + node.getClass().getName());
}
if(!m.name.equals(name)) {
return false;
}
}
//scroll to next instruction
for(index++; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
break;
}
}
//that should be a return instruction
return isReturnInstruction(opCode);
}
}
| 3,842 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Throwers.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/simple_methods_anc/src/openjdk/jcov/filter/simplemethods/Throwers.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 openjdk.jcov.filter.simplemethods;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.function.BiPredicate;
public class Throwers implements BiPredicate<ClassNode, MethodNode> {
@Override
public boolean test(ClassNode cnode, MethodNode m) {
int index = 0;
int opCode = -1;
//find first instruction
for(; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
break;
}
}
//should be NEW
if(opCode != Opcodes.NEW) {
return false;
}
//next is DUP
index++;
opCode = m.instructions.get(index).getOpcode();
if(opCode != Opcodes.DUP) {
return false;
}
//some more simple code
for(index++; index < m.instructions.size(); index++) {
opCode = m.instructions.get(index).getOpcode();
if(opCode >=0) {
if (!Utils.isSimpleInstruction(opCode)) {
break;
}
}
}
//should be a constructor
if(opCode != Opcodes.INVOKESPECIAL) {
return false;
}
AbstractInsnNode node = m.instructions.get(index);
if(!(node instanceof MethodInsnNode)) {
return false;
}
if(!((MethodInsnNode)node).name.equals("<init>")) {
return false;
}
index++;
opCode = m.instructions.get(index).getOpcode();
return opCode == Opcodes.ATHROW;
}
}
| 2,972 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EnvTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/EnvTest.java | /*
* Copyright (c) 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 openjdk.jcov.data;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class EnvTest {
public static final String TEST_PROPERTY = "jcov.data.test.property";
public static final String IUNDEFINED_TEST_PROPERTY = "jcov.data.test.property.undefined";
@Test
public void defaultsTest() {
assertEquals(Env.getStringEnv(TEST_PROPERTY, "three"), "one");
System.setProperty(TEST_PROPERTY, "two");
assertEquals(Env.getStringEnv(TEST_PROPERTY, "three"), "two");
assertEquals(Env.getStringEnv(IUNDEFINED_TEST_PROPERTY, "three"), "three");
System.setProperty(IUNDEFINED_TEST_PROPERTY, "two");
assertEquals(Env.getStringEnv(IUNDEFINED_TEST_PROPERTY, "three"), "two");
}
}
| 1,981 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CoverageTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/CoverageTest.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments;
import openjdk.jcov.data.arguments.runtime.Coverage;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class CoverageTest {
public static final String CLASS1 = "class1";
public static final String CLASS2 = "class2";
public static final String METHOD11 = "method11(Ljava/lang/Object;Ljava/lang/Object;)";
public static final String PARAM1 = "param1";
public static final String PARAM2 = "param2";
public static final String PARAM3 = "param3";
public static final String PARAM4 = "param4";
private Coverage cov = new Coverage();
private void assertContent(Coverage cov) {
assertEquals(cov.coverage().size(), 1);
assertEquals(cov.coverage().keySet().iterator().next(), CLASS1);
Map<String, List<List<?>>> class1Cov = cov.coverage().values().iterator().next();
assertEquals(class1Cov.size(), 1);
assertEquals(class1Cov.keySet().iterator().next(), METHOD11);
List<List<?>> method11Cov = class1Cov.values().iterator().next();
assertEquals(method11Cov.size(), 2);
assertEquals(method11Cov.get(0).get(0), PARAM1);
assertEquals(method11Cov.get(0).get(1), PARAM2);
assertEquals(method11Cov.get(1).get(0), PARAM3);
assertEquals(method11Cov.get(1).get(1), PARAM4);
}
@Test
public void addThings() {
cov.get(CLASS1, METHOD11)
.add(List.of(PARAM1, PARAM2));
cov.get(CLASS1, METHOD11)
.add(List.of(PARAM3, PARAM4));
assertContent(cov);
}
@Test(dependsOnMethods = "addThings")
public void saveAndLoad() throws IOException {
Path temp1 = Files.createTempFile("coverage1.", ".lst");
Path temp2 = Files.createTempFile("coverage2.", ".lst");
Path temp3 = Files.createTempFile("coverage2.", ".lst");
Coverage.write(cov, temp1);
Coverage loaded1 = Coverage.read(temp1);
assertContent(loaded1);
Coverage.write(loaded1, temp2);
Coverage loaded2 = Coverage.read(temp2);
assertContent(loaded2);
Coverage.write(loaded2, temp3);
List<String> lines1 = Files.readAllLines(temp1);
List<String> lines2 = Files.readAllLines(temp2);
List<String> lines3 = Files.readAllLines(temp3);
assertEquals(lines1.toArray(), lines2.toArray());
assertEquals(lines1.toArray(), lines3.toArray());
Files.deleteIfExists(temp1);
Files.deleteIfExists(temp2);
Files.deleteIfExists(temp3);
}
@Test(dependsOnMethods = "saveAndLoad")
public void add() {
cov.add(CLASS1, METHOD11, List.of(PARAM1, PARAM2));
assertContent(cov);
Coverage newCov = new Coverage();
newCov.add(CLASS1, METHOD11, List.of(PARAM1, PARAM2));
newCov.add(CLASS1, METHOD11, List.of(PARAM3, PARAM4));
assertContent(newCov);
newCov.add(CLASS2, METHOD11, List.of(PARAM1));
assertEquals(newCov.coverage().size(), 2);
assertTrue(newCov.coverage().keySet().contains(CLASS2));
Map<String, List<List<?>>> class1Cov = newCov.coverage().get(CLASS2);
assertEquals(class1Cov.size(), 1);
assertEquals(class1Cov.keySet().iterator().next(), METHOD11);
List<List<?>> method11Cov = class1Cov.values().iterator().next();
assertEquals(method11Cov.size(), 1);
assertEquals(method11Cov.get(0).size(), 1);
assertEquals(method11Cov.get(0).get(0), PARAM1);
}
}
| 4,905 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
PermissionMethodFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/jreinstr/filepermission/PermissionMethodFilter.java | package openjdk.jcov.data.arguments.jreinstr.filepermission;
import openjdk.jcov.data.arguments.instrument.MethodFilter;
import java.io.FilePermission;
public class PermissionMethodFilter implements MethodFilter {
@Override
public boolean accept(int access, String owner, String name, String desc) throws Exception {
// return false;
return openjdk.jcov.data.arguments.instrument.MethodFilter.parseDesc(desc).stream()
.anyMatch(td -> td.cls().equals(FilePermission.class.getName().replace('.', '/')));
}
}
| 552 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Main.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/jreinstr/filepermission/Main.java | package openjdk.jcov.data.arguments.jreinstr.filepermission;
import openjdk.jcov.data.Env;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import static java.util.stream.Collectors.toMap;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
System.getProperties().storeToXML(System.out, "");
System.out.println("" + Env.getSPIEnv(openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER, null));
System.getProperties().entrySet().stream()
.forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));
System.out.println(openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER + " = " + System.getProperties().entrySet().stream()
.collect(toMap(Object::toString, Object::toString)).get(openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER));
Path file = Files.createTempFile("test", ".txt");
FilePermission filePermission = new FilePermission(file.toString(), "read");
FilePermission dirPermission = new FilePermission(file.getParent().toString() + "/-", "read,write");
System.out.println(dirPermission.implies(filePermission));
Files.delete(file);
}
}
| 1,490 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Serializer.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/jreinstr/filepermission/Serializer.java | package openjdk.jcov.data.arguments.jreinstr.filepermission;
import openjdk.jcov.data.arguments.runtime.Collect;
import openjdk.jcov.data.arguments.runtime.Implantable;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
public class Serializer implements openjdk.jcov.data.arguments.runtime.Serializer {
@Override
public String apply(Object o) {
if(o instanceof FilePermission) {
return ((FilePermission)o).getActions();
} else return null;
}
@Override
public Collection<Class> runtime() {
return Set.of(Serializer.class,
Implantable.class);
}
public static void main(String[] args) throws IOException {
File file = File.createTempFile("test", ".txt");
file.delete();
}
}
| 857 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Plugin.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/jreinstr/filepermission/Plugin.java | package openjdk.jcov.data.arguments.jreinstr.filepermission;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
public class Plugin extends openjdk.jcov.data.arguments.instrument.Plugin {
public Plugin() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
super();
}
@Override
protected List<Class> runtimeClasses() {
ArrayList<Class> result = new ArrayList<>(super.runtimeClasses());
result.add(Serializer.class);
return result;
}
}
| 620 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Test.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/jreinstr/filepermission/Test.java | package openjdk.jcov.data.arguments.jreinstr.filepermission;
import openjdk.jcov.data.JREInstr;
import openjdk.jcov.data.arguments.runtime.Coverage;
import openjdk.jcov.data.arguments.runtime.Saver;
import openjdk.jcov.data.lib.TestStatusListener;
import openjdk.jcov.data.lib.Util;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static openjdk.jcov.data.arguments.instrument.Plugin.METHOD_FILTER;
import static openjdk.jcov.data.arguments.runtime.Collect.COVERAGE_OUT;
import static openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER;
import static openjdk.jcov.data.lib.Util.copyJRE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Listeners({TestStatusListener.class})
public class Test {
private Path data_dir;
private Path template;
private Path jcov_template;
private Path jcov_result;
private Path jre;
private Path main;
private FileTime templateCreated;
@BeforeClass
public void setup() throws IOException {
jre = copyJRE(Paths.get(System.getProperty("test.jre", System.getProperty("java.home"))));
data_dir = Paths.get(System.getProperty("user.dir"));
template = data_dir.resolve("template.lst");
jcov_template = data_dir.resolve("template.xml");
jcov_result = data_dir.resolve("result.xml");
main = data_dir.resolve("Main.java");
}
@org.testng.annotations.Test
public void instrument() throws IOException, InterruptedException {
Files.deleteIfExists(jcov_template);
Files.deleteIfExists(template);
String runtime = Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
.filter(s -> s.endsWith("jcov_file_saver.jar")).findAny().get();
int status = new JREInstr()
.clearEnv()
.setEnv(Map.of(
COVERAGE_OUT, template.toString(),
METHOD_FILTER, PermissionMethodFilter.class.getName(),
SERIALIZER, Serializer.class.getName()))
.pluginClass(Plugin.class.getName())
.jcovRuntime(runtime)
.jcovTemplate(jcov_template.toString())
.instrument(jre.toString());
assertEquals(status, 0);
assertTrue(Files.exists(jcov_template), "Template file: " + jcov_template);
assertTrue(Files.exists(template), "Template file: " + template);
templateCreated = Files.readAttributes(template, BasicFileAttributes.class).lastModifiedTime();
}
@org.testng.annotations.Test(dependsOnMethods = "instrument")
public void testInstrumentation() throws IOException, InterruptedException {
Files.write(main, List.of(
"package openjdk.jcov.data.arguments.jreinstr.filepermission;",
"import java.io.FilePermission;",
"import java.io.IOException;",
"import java.nio.file.Files;",
"import java.nio.file.Path;",
"public class Main {",
" public static void main(String[] args) throws IOException {",
" Path file = Files.createTempFile(\"test\", \".txt\");",
" FilePermission filePermission = new FilePermission(file.toString(), \"read\");",
" FilePermission dirPermission = new FilePermission(file.getParent().toString() + \"/-\", \"read,write\");",
" System.out.println(dirPermission.implies(filePermission));",
" Files.delete(file);",
" }",
"}"
));
Files.deleteIfExists(jcov_result);
//no classpath necessary for the next call because the class is implanted
List<String> command = List.of(
jre.toString() + File.separator + "bin" + File.separator + "java",
"-Djcov.data-saver=" + Saver.class.getName(),
main.toString());
System.out.println(command.stream().collect(Collectors.joining(" ")));
Process p = new ProcessBuilder()
.directory(data_dir.toFile())
.command(command)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.start();
int status = p.waitFor();
assertEquals(status, 0);
assertTrue(Files.exists(jcov_result), "Result file: " + jcov_result);
assertTrue(Files.readAttributes(template, BasicFileAttributes.class).lastModifiedTime()
.compareTo(templateCreated) > 0);
}
@org.testng.annotations.Test(dependsOnMethods = "testInstrumentation")
public void testCoverage() throws IOException, InterruptedException {
Coverage cov = Coverage.read(template, a -> a);
assertEquals(cov.coverage().get(FilePermission.class.getName().replace('.', '/'))
.entrySet().stream().filter(e -> e.getKey().startsWith("impliesIgnoreMask"))
.findAny().get().getValue().get(0).get(0), "read");
}
@AfterClass
public void tearDown() throws IOException {
List<Path> artifacts = List.of(template, jcov_template, template, jcov_result, jre, main);
if(TestStatusListener.status)
for(Path file : artifacts) Util.rfrm(file);
else {
System.out.println("Test failed, keeping the artifacts:");
artifacts.forEach(System.out::println);
}
}
}
| 5,955 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
VoidPlugin.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/jreinstr/filepermission/VoidPlugin.java | package openjdk.jcov.data.arguments.jreinstr.filepermission;
import com.sun.tdk.jcov.instrument.asm.ASMInstrumentationPlugin;
import org.objectweb.asm.MethodVisitor;
import java.nio.file.Path;
public class VoidPlugin implements ASMInstrumentationPlugin {
public VoidPlugin() {
super();
}
@Override
public MethodVisitor methodVisitor(int i, String s, String s1, String s2, MethodVisitor visitor) {
return visitor;
}
@Override
public void instrumentationComplete() throws Exception {
}
@Override
public Path runtime() throws Exception {
return null;
}
@Override
public String collectorPackage() {
return null;
}
}
| 709 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
UserCode.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/test/UserCode.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.test;
public class UserCode {
public static void method(int i, long j, float f, double d, boolean z, byte b, String s) {
System.out.println("Calling with: " + i + "," + j + "," + f + "," + d + "," + z + "," + b + "," + s);
}
public static void main(String[] args) {
method(0, 1, 2f, 3., true, (byte)5, "6");
method(7, 8, 9f, 10d, false, (byte)12, "13");
}
}
| 1,643 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ArgumentsTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/test/ArgumentsTest.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.test;
import openjdk.jcov.data.Instrument;
import openjdk.jcov.data.arguments.runtime.Collect;
import openjdk.jcov.data.arguments.runtime.Coverage;
import openjdk.jcov.data.arguments.instrument.Plugin;
import openjdk.jcov.data.arguments.runtime.Saver;
import openjdk.jcov.data.Env;
import openjdk.jcov.data.lib.TestStatusListener;
import openjdk.jcov.data.lib.Util;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.joining;
import static openjdk.jcov.data.Env.JCOV_DATA_ENV_PREFIX;
import static openjdk.jcov.data.Instrument.JCOV_TEMPLATE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@Listeners({openjdk.jcov.data.lib.TestStatusListener.class})
public class ArgumentsTest {
Path test_dir;
Path template;
@BeforeClass
public void clean() throws IOException {
Path data_dir = Paths.get(System.getProperty("user.dir"));
test_dir = data_dir.resolve("arguments_test");
Util.rfrm(test_dir);
template = test_dir.resolve("template.lst");
}
@Test
public void instrument() throws IOException, InterruptedException {
Env.clear(JCOV_DATA_ENV_PREFIX);
Env.setSystemProperties(Map.of(
Collect.COVERAGE_OUT, template.toString(),
JCOV_TEMPLATE, test_dir.resolve("template.xml").toString()));
new Instrument().pluginClass(Plugin.class.getName()).
instrument(new Util(test_dir).copyBytecode(UserCode.class.getName()));
Coverage tmpl = Coverage.read(template);
System.out.println("Data:");
tmpl.coverage().entrySet().forEach(e -> {
System.out.println(e.getKey() + "->");
e.getValue().entrySet().forEach(ee -> {
System.out.println(" " + ee.getKey());
ee.getValue().forEach(l -> {
System.out.println(l.stream().map(Object::toString).collect(joining(",")));
});
});
});
assertNotNull(tmpl.coverage().get(UserCode.class.getName().replace('.', '/')).
get("method(IJFDZBLjava/lang/String;)V"));
}
@Test(dependsOnMethods = "instrument")
public void run() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
IllegalAccessException, IOException, InstantiationException {
Env.clear(JCOV_DATA_ENV_PREFIX);
Env.setSystemProperties(Map.of(
Collect.COVERAGE_OUT, template.toString()));
new Util(test_dir).runClass(UserCode.class, new String[0], new Saver());
Coverage coverage = Coverage.read(template);
List<List<?>> calls = coverage.get(UserCode.class.getName().replace('.', '/'),
"method(IJFDZBLjava/lang/String;)V");
assertEquals(calls.size(), 2);
assertEquals(calls.get(0).get(6), "6");
assertEquals(calls.get(1).get(0), "7");
}
@AfterClass
public void tearDown() throws IOException {
if(TestStatusListener.status)
Util.rfrm(test_dir);
}
}
| 4,623 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MainTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/main/MainTest.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.main;
import openjdk.jcov.data.Env;
import openjdk.jcov.data.Instrument;
import openjdk.jcov.data.arguments.enums.EnumTest;
import openjdk.jcov.data.arguments.instrument.Plugin;
import openjdk.jcov.data.arguments.runtime.Collect;
import openjdk.jcov.data.arguments.runtime.Coverage;
import openjdk.jcov.data.arguments.runtime.Saver;
import openjdk.jcov.data.lib.TestStatusListener;
import openjdk.jcov.data.lib.Util;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static openjdk.jcov.data.Env.JCOV_DATA_ENV_PREFIX;
import static openjdk.jcov.data.Instrument.JCOV_TEMPLATE;
import static openjdk.jcov.data.arguments.instrument.Plugin.*;
import static openjdk.jcov.data.arguments.runtime.Collect.*;
import static org.testng.Assert.assertEquals;
@Listeners({TestStatusListener.class})
public class MainTest {
private Path test_dir;
private Path coverage;
@BeforeClass
public void clean() throws IOException {
Path data_dir = Paths.get(System.getProperty("user.dir"));
test_dir = data_dir.resolve("main_test");
Util.rfrm(test_dir);
Files.createDirectories(test_dir);
coverage = test_dir.resolve("coverage.lst");
}
private Coverage instrument(Class cls) throws IOException, InterruptedException {
Env.clear(JCOV_DATA_ENV_PREFIX);
Env.setSystemProperties(Map.of(
COVERAGE_OUT, coverage.toString(),
JCOV_TEMPLATE, test_dir.resolve("template.xml").toString(),
METHOD_FILTER, MainFilter.class.getName()));
new Instrument().pluginClass(Plugin.class.getName())
.instrument(new Util(test_dir).
copyBytecode(cls.getName()));
return Coverage.read(coverage);
}
@Test
public void instrument() throws IOException, InterruptedException {
Coverage tmplt = instrument(UserCode.class);
assertEquals(tmplt.coverage().size(), 0);
}
@Test(dependsOnMethods = "instrument")
public void instrumentStatic() throws IOException, InterruptedException {
Coverage tmplt = instrument(UserCodeStatic.class);
Map<String, List<List<?>>> userCode = tmplt.coverage().get(UserCodeStatic.class.getName().replace('.', '/'));
assertEquals(userCode.size(), 1);
assertEquals(userCode.keySet().iterator().next(), "main([Ljava/lang/String;)V");
}
@Test(dependsOnMethods = "instrumentStatic")
public void run() throws
ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException,
IOException, InstantiationException {
Env.clear(JCOV_DATA_ENV_PREFIX);
Env.setSystemProperties(Map.of(
COVERAGE_IN, coverage.toString(),
COVERAGE_OUT, coverage.toString(),
SERIALIZER, StringArraySerializer.class.getName()));
new Util(test_dir).runClass(UserCodeStatic.class, new String[] {"one", "two"}, new Saver());
Coverage res = Coverage.read(coverage, Objects::toString);
List<List<?>> method =
res.get(UserCodeStatic.class.getName().replace('.', '/'),
"main([Ljava/lang/String;)V");
assertEquals(method.size(), 1);
assertEquals(method.get(0).size(), 2);
assertEquals(method.get(0).get(0), "one");
assertEquals(method.get(0).get(1), "two");
}
@AfterClass
public void tearDown() throws IOException {
if(TestStatusListener.status) Util.rfrm(test_dir);
}
}
| 5,108 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
UserCode.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/main/UserCode.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.main;
public class UserCode {
public void main(String[] args) {}
public void main(String arg) {}
public void main() {}
}
| 1,377 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
StringArrayDeserializer.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/main/StringArrayDeserializer.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.main;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static java.util.stream.Collectors.toList;
//TODO move this to the source after figuring out TypeDescriptor for arrays
public class StringArrayDeserializer implements Function<String, List<String>> {
@Override
public List<String> apply(String s) {
return Arrays.stream(s.split(",")).collect(toList());
}
}
| 1,669 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
UserCodeStatic.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/main/UserCodeStatic.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.main;
public class UserCodeStatic {
public static void main(String[] args) {}
public static void main(String arg) {}
public static void main() {}
}
| 1,404 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MainFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/main/MainFilter.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.main;
import openjdk.jcov.data.arguments.instrument.MethodFilter;
import openjdk.jcov.data.arguments.instrument.Plugin;
import java.lang.reflect.Modifier;
import java.util.List;
public class MainFilter implements MethodFilter {
@Override
public boolean accept(int access, String owner, String method, String desc) throws ClassNotFoundException {
List<Plugin.TypeDescriptor> params = MethodFilter.parseDesc(desc);
return method.equals("main") &&
params.size() == 1 &&
(access & Modifier.STATIC) > 0 &&
(access & Modifier.PUBLIC) > 0 &&
desc.endsWith(")V") &&
params.stream().anyMatch(td -> td.id().equals("["));
}
}
| 1,969 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
StringArraySerializer.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/main/StringArraySerializer.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.main;
import java.util.Arrays;
import java.util.function.Function;
import static java.util.stream.Collectors.joining;
//TODO move this to the source after figuring out TypeDescriptor for arrays
public class StringArraySerializer implements Function<Object, String> {
@Override
public String apply(Object o) {
if(o.getClass().isArray() && o.getClass().getComponentType().equals(String.class)) {
return Arrays.stream((String[])o).collect(joining(","));
} else return null;
}
}
| 1,761 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
UserCode.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/enums/UserCode.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.enums;
public class UserCode {
public enum ENum {ONE, TWO, THREE};
public void method(ENum e) {
System.out.println(e);
}
public static void staticMethod(ENum e) {
System.out.println(e);
}
public static void main(String[] args) {
new UserCode().method(ENum.ONE);
UserCode.staticMethod(ENum.TWO);
}
}
| 1,604 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EnumTest.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/enums/EnumTest.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.enums;
import openjdk.jcov.data.Instrument;
import openjdk.jcov.data.arguments.runtime.Collect;
import openjdk.jcov.data.arguments.runtime.Coverage;
import openjdk.jcov.data.arguments.instrument.Plugin;
import openjdk.jcov.data.arguments.runtime.Saver;
import openjdk.jcov.data.Env;
import openjdk.jcov.data.lib.TestStatusListener;
import openjdk.jcov.data.lib.Util;
import openjdk.jcov.data.serialization.EnumDeserializer;
import openjdk.jcov.data.serialization.EnumSerializer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import static openjdk.jcov.data.Env.JCOV_DATA_ENV_PREFIX;
import static openjdk.jcov.data.Instrument.JCOV_TEMPLATE;
import static openjdk.jcov.data.arguments.instrument.Plugin.*;
import static openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertSame;
@Listeners({openjdk.jcov.data.lib.TestStatusListener.class})
public class EnumTest {
private Path test_dir;
private Path template;
private EnumDeserializer deserializer = new EnumDeserializer(UserCode.ENum.class);
@BeforeClass
public void clean() throws IOException {
Path data_dir = Paths.get(System.getProperty("user.dir"));
test_dir = data_dir.resolve("enum_test");
Util.rfrm(test_dir);
Files.createDirectories(test_dir);
template = test_dir.resolve("template.lst");
}
@Test
public void serialization() {
assertSame(UserCode.ENum.THREE,
new EnumDeserializer(UserCode.ENum.class).apply(new EnumSerializer().apply(UserCode.ENum.THREE)));
}
@Test
public void instrument() throws IOException, InterruptedException {
Env.clear(JCOV_DATA_ENV_PREFIX);
Env.setSystemProperties(Map.of(
Collect.COVERAGE_OUT, template.toString(),
JCOV_TEMPLATE, test_dir.resolve("template.xml").toString(),
METHOD_FILTER, EnumMethodsFilter.class.getName()));
new Instrument().pluginClass(Plugin.class.getName())
.instrument(new Util(test_dir).
copyBytecode(openjdk.jcov.data.arguments.enums.UserCode.class.getName()));
Coverage tmplt = Coverage.read(template);
assertEquals(tmplt.coverage().get(UserCode.class.getName().replace('.', '/')).size(), 2);
}
@Test(dependsOnMethods = "instrument")
public void run() throws
ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException,
IOException, InstantiationException {
Env.clear(JCOV_DATA_ENV_PREFIX);
Env.setSystemProperties(Map.of(
Collect.COVERAGE_IN, template.toString(),
Collect.COVERAGE_OUT, template.toString(),
SERIALIZER, EnumSerializer.class.getName()));
new Util(test_dir).runClass(UserCode.class, new String[0], new Saver());
Coverage res = Coverage.read(template, deserializer);
List<List<?>> method =
res.get(UserCode.class.getName().replace('.', '/'),
"method(Lopenjdk/jcov/data/arguments/enums/UserCode$ENum;)V");
assertEquals(method.size(), 1);
assertEquals(method.get(0).size(), 1);
assertEquals(method.get(0).get(0), UserCode.ENum.ONE);
List<List<?>> staticMethod =
res.get(UserCode.class.getName().replace('.', '/'),
"staticMethod(Lopenjdk/jcov/data/arguments/enums/UserCode$ENum;)V");
assertEquals(staticMethod.size(), 1);
assertEquals(staticMethod.get(0).size(), 1);
assertEquals(staticMethod.get(0).get(0), UserCode.ENum.TWO);
}
@AfterClass
public void tearDown() throws IOException {
if(TestStatusListener.status) {
Util.rfrm(test_dir);
}
}
}
| 5,404 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EnumMethodsFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/arguments/enums/EnumMethodsFilter.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.enums;
import openjdk.jcov.data.arguments.instrument.MethodFilter;
public class EnumMethodsFilter implements MethodFilter {
@Override
public boolean accept(int access, String owner, String method, String desc) throws ClassNotFoundException {
return MethodFilter.parseDesc(desc).stream().anyMatch(td -> {
try {
return Enum.class.isAssignableFrom(Class.forName(td.cls().replace('/', '.')));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
});
}
}
| 1,808 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
TestStatusListener.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/lib/TestStatusListener.java | package openjdk.jcov.data.lib;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestStatusListener implements ITestListener {
public static volatile boolean status = true;
@Override
public void onTestStart(ITestResult result) { }
@Override
public void onTestSuccess(ITestResult result) { }
@Override
public void onTestFailure(ITestResult result) {
status = false;
}
@Override
public void onTestSkipped(ITestResult result) { }
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }
@Override
public void onStart(ITestContext context) { status = true; }
@Override
public void onFinish(ITestContext context) { }
}
| 784 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Util.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/test/openjdk/jcov/data/lib/Util.java | /*
* Copyright (c) 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 openjdk.jcov.data.lib;
import com.sun.tdk.jcov.runtime.JCovSaver;
import openjdk.jcov.data.Env;
import openjdk.jcov.data.arguments.runtime.Collect;
import openjdk.jcov.data.arguments.runtime.Saver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import static openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER;
public class Util {
private final Path outputDir;
public Util(Path dir) {
outputDir = dir;
}
public List<Path> copyBytecode(String... classes) throws IOException {
byte[] buf = new byte[1024];
List<Path> result = new ArrayList<>();
for(String c : classes) {
String classFile = classFile(c);
try(InputStream in = getClass().getClassLoader().getResourceAsStream(classFile)) {
Path o = outputDir.resolve(classFile);
result.add(o);
if(!Files.exists(o.getParent())) Files.createDirectories(o.getParent());
try(OutputStream out = Files.newOutputStream(o)) {
int read;
while((read = in.read(buf)) > 0)
out.write(buf, 0, read);
}
}
};
return result;
}
public static Path copyJRE(Path src) throws IOException {
Path dest = Files.createTempDirectory("JDK");
System.out.println("Copying a JDK from " + src + " to " + dest);
Files.walk(src).forEach(s -> {
try {
Files.copy(s, dest.resolve(src.relativize(s)), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
return dest;
}
public static Path createRtJar(String prefix, Class collect) throws IOException {
Path dest = Files.createTempFile(prefix, ".jar");
System.out.println(prefix + " jar: " + dest);
try(JarOutputStream jar = new JarOutputStream(Files.newOutputStream(dest))) {
jar.putNextEntry(new JarEntry(collect.getName().replace(".", File.separator) + ".class"));
try (InputStream ci = collect.getClassLoader()
.getResourceAsStream(collect.getName().replace('.', '/') + ".class")) {
byte[] buffer = new byte[1024];
int read;
while((read = ci.read(buffer)) > 0) {
jar.write(buffer, 0, read);
}
}
}
return dest;
}
public static String classFile(String className) {
return className.replace('.', '/') + ".class";
}
public Class runClass(Class className, String[] argv, JCovSaver saver)
throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return runClass(className.getName(), argv, saver);
}
public Class runClass(String className, String[] argv, JCovSaver saver)
throws ClassNotFoundException, NoSuchMethodException,
InvocationTargetException, IllegalAccessException, InstantiationException {
Collect.clearData();
//TODO an API is really needed for this kind of usage
Collect.serializer(new Saver.NoRuntimeSerializer(Env.getSPIEnv(SERIALIZER, Objects::toString)));
ClassLoader offOutputDir = new InstrumentedClassLoader();
Class cls = offOutputDir.loadClass(className);
Method m = cls.getMethod("main", new String[0].getClass());
m.invoke(null, (Object)argv);
//have to do this because normally it only works on system exit
saver.saveResults();
return cls;
}
private class InstrumentedClassLoader extends ClassLoader {
protected InstrumentedClassLoader() {
super(Util.class.getClassLoader());
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
Path classFile = outputDir.resolve(classFile(name));
if(Files.exists(classFile)) {
byte[] buf = new byte[1024];
try(InputStream in = Files.newInputStream(classFile)) {
try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
int read;
while((read = in.read(buf)) > 0)
out.write(buf, 0, read);
return defineClass(name, out.toByteArray(), 0, out.size());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return super.loadClass(name);
}
}
public static void rfrm(Path jre) throws IOException {
System.out.println("Removing " + jre);
if(Files.isRegularFile(jre))
Files.deleteIfExists(jre);
else
Files.walkFileTree(jre, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
| 7,654 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Env.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/Env.java | /*
* Copyright (c) 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 openjdk.jcov.data;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Much of the functionality in this plugin is controlled through system properties. This class defines some shortcuts
* which makes it a bit easier.
*/
public class Env {
public static final String PROP_FILE =
Env.class.getPackageName().replace('.', '/') +
"/instrumentation.properties";
/**
* Prefix for all system property names which will be passed to the VM running JCov calls.
*/
public static final String JCOV_DATA_ENV_PREFIX = "jcov.data.";
public static final String JCOV_DATA_SAVER = "jcov.data.saver";
private static final String JCOV_OPTION_FOR_DATA_SAVER = "jcov.data-saver";
private static volatile Properties SAVED;
public static void setSystemProperties(Map<String, String> properties) {
properties.forEach((k, v) -> System.setProperty(k, v));
}
public static void clear(String prefix) {
Set<String> keys = System.getProperties().stringPropertyNames();
keys.stream().filter(k -> k.startsWith(prefix))
.forEach(k -> System.clearProperty(k));
}
public static String getStringEnv(String property, String defaultValue) {
synchronized(Env.class) {
if (SAVED == null) {
try {
SAVED = new Properties();
InputStream in = Env.class.getResourceAsStream("/" + PROP_FILE);
if(in != null) {
SAVED.load(in);
if(System.getProperty(JCOV_OPTION_FOR_DATA_SAVER) == null) {
String saver = SAVED.getProperty(JCOV_DATA_SAVER);
if(saver != null)
System.setProperty(JCOV_OPTION_FOR_DATA_SAVER, saver);
}
System.out.println("Using property definitions from " + PROP_FILE + ":");
SAVED.list(System.out);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (Throwable e) {
e.printStackTrace();
throw e;
}
}
}
String override = System.getProperty(property);
return (override != null) ? override : SAVED.getProperty(property, defaultValue);
}
public static Path getPathEnv(String property, Path defaultValue) {
String propValue = getStringEnv(property, null);
if(propValue != null) return Path.of(propValue);
else return defaultValue;
}
public static <SPI> SPI getSPIEnv(String property, SPI defaultValue) throws ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
String propValue = getStringEnv(property, null);
if(propValue != null) {
if (!propValue.contains("("))
return (SPI) Class.forName(propValue).getConstructor().newInstance();
else {
int ob = propValue.indexOf('(');
int cb = propValue.indexOf(')');
Class cls = Class.forName(propValue.substring(0, ob));
String[] params = propValue.substring(ob + 1, cb).split(",");
Class[] paramTypes = new Class[params.length];
Arrays.fill(paramTypes, String.class);
return (SPI) cls.getConstructor(paramTypes).newInstance(params);
}
} else return defaultValue;
}
}
| 5,042 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Instrument.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/Instrument.java | /*
* Copyright (c) 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 openjdk.jcov.data;
import com.sun.tdk.jcov.Instr;
import openjdk.jcov.data.arguments.instrument.Plugin;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static openjdk.jcov.data.Env.JCOV_DATA_ENV_PREFIX;
/**
* Some API which makes it easier to run JCov instrumentation while setting specific options to use an instrumentation
* plugin. Could be used in tests or other java code.<br/>
* Also provides a main method so it is easier to run the instrumentation from the command line.<br/>
* Current implementaion runs JCov code in the same VM.
*/
public class Instrument {
/**
* Name of a system property which contains class name of an instrumentation plugin.
*/
public static final String PLUGIN_CLASS = JCOV_DATA_ENV_PREFIX + "plugin";
public static final String JCOV_TEMPLATE = JCOV_DATA_ENV_PREFIX + "jcov.template";
private String pluginClass;
private Path jcovTemplate;
public Instrument() {
pluginClass = Env.getStringEnv(PLUGIN_CLASS, Plugin.class.getName());
jcovTemplate = Env.getPathEnv(JCOV_TEMPLATE, Paths.get("template.xml"));
}
public Instrument pluginClass(String pluginClass) {
this.pluginClass = pluginClass;
return this;
}
public Instrument jcovTemplate(Path jcovTemplate) {
this.jcovTemplate = jcovTemplate;
return this;
}
public boolean instrument(List<Path> classes) throws IOException, InterruptedException {
List<String> params = new ArrayList<>();
params.add("-instr_plugin");
params.add(pluginClass);
params.add("-t");
params.add(jcovTemplate.toString());
params.addAll(classes.stream().map(Path::toString).collect(toList()));
return new Instr().run(params.toArray(new String[0])) == 0;
}
public static void main(String[] args) throws IOException, InterruptedException {
new Instrument().instrument(Arrays.stream(args).map(Paths::get).collect(toList()));
}
}
| 3,361 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
JREInstr.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/JREInstr.java | /*
* Copyright (c) 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 openjdk.jcov.data;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.Objects.requireNonNull;
import static openjdk.jcov.data.Env.JCOV_DATA_ENV_PREFIX;
public class JREInstr {
private String pluginClass;
private String jcovTemplate;
private String jcovRuntime;
public JREInstr() {
}
public JREInstr clearEnv() {
Env.clear(JCOV_DATA_ENV_PREFIX);
return this;
}
public JREInstr setEnv(Map<String, String> env) {
Env.setSystemProperties(env);
return this;
}
public JREInstr pluginClass(String pluginClass) {
this.pluginClass = pluginClass;
return this;
}
public JREInstr jcovTemplate(String jcovTemplate) {
this.jcovTemplate = jcovTemplate;
return this;
}
public JREInstr jcovRuntime(String jcovRuntime) {
this.jcovRuntime = jcovRuntime;
return this;
}
public int instrument(String jre) throws IOException, InterruptedException {
requireNonNull(jcovRuntime, "Must specify JCov runtime.");
requireNonNull(pluginClass, "Must specify an instrumentation plugin.");
requireNonNull(jcovTemplate, "Must specify jcov template location.");
String[] params = new String[] {
"-implantrt", jcovRuntime,
"-instr_plugin", pluginClass,
"-template", jcovTemplate,
jre};
System.out.println("Instrumentation parameters: " +
Arrays.stream(params).collect(Collectors.joining(" ")));
return new com.sun.tdk.jcov.JREInstr().run(params);
}
}
| 2,901 | 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/plugins/data_coverage/src/openjdk/jcov/data/arguments/runtime/package-info.java | /*
* Copyright (c) 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.
*/
/**
* This package contains core classes which are needed at runtime.
*/
package openjdk.jcov.data.arguments.runtime; | 1,326 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Coverage.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/runtime/Coverage.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.runtime;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
/**
* Data container for the values collected in runtime. Same class is used to store template as a file with no
* values and just method descriptions.
*/
public class Coverage {
public static final String DATA_PREFIX = " -> ";
private final Map<String, Map<String, List<List<? extends Object>>>> data;
public static Coverage read(Path path) throws IOException {
return readImpl(path, s -> s);
}
private static List<String> split(String s) {
List<String> result = new ArrayList<>();
int lci = -1;
for (int ci = 0; ci < s.length(); ci++) {
if(s.charAt(ci) == ',') {
result.add(s.substring(lci + 1, ci));
lci = ci;
}
}
result.add(s.substring(lci + 1));
return result;
}
private static List<? extends Object> parse(String s, Function<String, ? extends Object> deserialize) {
return split(s).stream()
.map(v -> v.isEmpty() ? "" : deserialize.apply(v))
.collect(toList());
}
//TODO move to an SPI class
public static Coverage read(Path path, Function<String, ? extends Object> deserializer) throws IOException {
return readImpl(path, deserializer);
}
/**
* Loads the data from a file in a custom plain text format.
*/
private static Coverage readImpl(Path path, Function<String, ? extends Object> deserializer) throws IOException {
Coverage result = new Coverage();
List<List<? extends Object>> lastData = null;
String desc = null, name = null, owner = null;
for (String l : Files.readAllLines(path)) {
if (!l.startsWith(DATA_PREFIX)) {
int descStart = l.indexOf('(');
int classEnd = l.lastIndexOf('#', descStart);
owner = l.substring(0, classEnd);
name = l.substring(classEnd + 1, descStart);
desc = l.substring(descStart);
lastData = result.get(owner, name + desc);
} else {
List<? extends Object> values = parse(l.substring(DATA_PREFIX.length()), deserializer);
//TODO this needs to be fixed for arrays
// if(Collect.countParams(desc) != values.size()) {
// throw new IllegalStateException("Incorrect number of parameters for " +
// owner + "#" + name + desc + ": " + values.size());
// }
lastData.add(values);
}
}
return result;
}
//TODO move to an SPI class
/**
* Saves the data into a file in a custom plain text format.
*/
public static final void write(Coverage coverage, Path path/*, Function<Object, String> serializer*/)
throws IOException {
try(BufferedWriter out = Files.newBufferedWriter(path)) {
coverage.data.entrySet().forEach(ce -> {
ce.getValue().entrySet().forEach(me -> {
try {
out.write(ce.getKey() + "#" + me.getKey());
out.newLine();
me.getValue().forEach(dl -> {
try {
String desc = me.getKey().substring(me.getKey().indexOf("("));
List<String> values = dl.stream().map(o -> (String)o)
.collect(toList());
if(Collect.countParams(desc) != values.size()) {
System.err.println("Incorect number of params for " + me.getKey());
System.out.println(values.stream().map(Objects::toString)
.collect(Collectors.joining(",")));
throw new IllegalStateException("Incorrect number of parameters for " +
me.getKey() + ": " + values.size());
}
out.write(DATA_PREFIX +
values.stream()//.map(d -> serializer.apply(d))
.collect(Collectors.joining(",")));
out.newLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
out.flush();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
private final boolean selfCompacting = true;
public Coverage() {
data = new HashMap<>();
}
/**
* Obtains a structure for the data, adding an empty one, if necessary.
*/
public List<List<? extends Object>> get(String owner, String method) {
Map<String, List<List<? extends Object>>> methods = data.get(owner);
if(methods == null) {
methods = new HashMap<>();
data.put(owner, methods);
}
List<List<? extends Object>> result = methods.get(method);
if(result == null) {
result = new ArrayList<>();
methods.put(method, result);
}
return result;
}
public void add(String owner, String method, List<? extends Object> params) {
List<List<? extends Object>> methodCov = get(owner, method);
if(methodCov.stream().noneMatch(call -> {
if(call.size() != params.size()) return false;
for (int i = 0; i < call.size(); i++)
if(!Objects.equals(call.get(i), params.get(i))) return false;
return true;
})) methodCov.add(params);
}
public Map<String, Map<String, List<List<? extends Object>>>> coverage() {
return data;
}
}
| 7,804 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Saver.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/runtime/Saver.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.runtime;
import com.sun.tdk.jcov.runtime.JCovSaver;
import openjdk.jcov.data.Env;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.function.Function;
public class Saver implements JCovSaver {
/**
* Name of a property containing a class name of a class of type <code>Function<Object, String></code> which will
* be used during the serialization. <code>Object::toString</code> is used by default.
*/
// public static final String SERIALIZER = Env.JCOV_DATA_ENV_PREFIX +
// Collect.ARGUMENTS_PREFIX + "serializer";
private Path resultFile;
// private Serializer serializer;
public Saver() throws
ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
IllegalAccessException {
resultFile = Env.getPathEnv(Collect.COVERAGE_OUT, Paths.get("result.lst"));
// serializer = wrap(Env.getSPIEnv(SERIALIZER, Object::toString));
}
public Saver resultFile(Path resultFile) {
this.resultFile = resultFile;
return this;
}
// public Saver serializer(Function<Object, String> function) {
// this.serializer = wrap(function);
// return this;
// }
//
// public Saver serializer(Serializer serializer) {
// this.serializer = serializer;
// return this;
// }
//
// private static Serializer wrap(Function<Object, String> function) {
// if(function instanceof Serializer)
// return (Serializer) function;
// else
// return new NoRuntimeSerializer(function);
// }
public void saveResults() {
try {
System.out.println("Saving the data info " + resultFile);
Coverage.write(Collect.data, resultFile/*, serializer*/);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static class NoRuntimeSerializer implements Serializer {
private final Function<Object, String> function;
public NoRuntimeSerializer(Function<Object, String> function) {
this.function = function;
}
@Override
public String apply(Object o) {
return function.apply(o);
}
@Override
public Collection<Class> runtime() {
return null;
}
}
}
| 3,670 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Serializer.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/runtime/Serializer.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.runtime;
import java.util.function.Function;
public interface Serializer extends Implantable, Function<Object, String> {
}
| 1,368 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Collect.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/runtime/Collect.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.runtime;
import openjdk.jcov.data.Env;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Calls to this class' collect(...) methods are injected in the beginning of every instrumented method.
*/
public class Collect {
/**
* Property name prefix for all properties used by this plugin. The property names are started with
* <code>Instrument.JCOV_DATA_ENV_PREFIX + ARGUMENTS_PREFIX</code>
*/
public static final String ARGUMENTS_PREFIX = "args.";
/**
* Specifies where to save collected data or instrumentation information.
*/
public static final String COVERAGE_OUT = Env.JCOV_DATA_ENV_PREFIX + ARGUMENTS_PREFIX +
"coverage";
/**
* Specifies where to load previously collected data from. A non-empty value of this property will
* make Collect class to load the data on class loading.
*/
public static final String COVERAGE_IN = Env.JCOV_DATA_ENV_PREFIX + ARGUMENTS_PREFIX +
"coverage.in";
/**
* Name of a property containing a class name of a class of type <code>Function<Object, String></code> which will
* be used during the serialization. <code>Object::toString</code> is used by default.
*/
public static final String SERIALIZER = Env.JCOV_DATA_ENV_PREFIX +
Collect.ARGUMENTS_PREFIX + "serializer";
static volatile Coverage data;
private volatile static Serializer serializer;
static {
if (!Env.getStringEnv(COVERAGE_IN, "").isEmpty()) {
try {
Path coverageFile = Env.getPathEnv(COVERAGE_IN, null);
System.out.println("Loading data coverage from " + coverageFile);
data = Coverage.read(coverageFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} else data = new Coverage();
try {
serializer = wrap(Env.getSPIEnv(SERIALIZER, Object::toString));
} catch (ClassNotFoundException|NoSuchMethodException|IllegalAccessException|InvocationTargetException|InstantiationException e) {
throw new RuntimeException(e);
}
}
private static Serializer wrap(Function<Object, String> function) {
if(function instanceof Serializer)
return (Serializer) function;
else
return new Saver.NoRuntimeSerializer(function);
}
public static synchronized void collect(String owner, String name, String desc, Object... params) {
// keep these lines, it is useful for debugging in hard cases
// System.out.printf("%s.%s%s: %s\n", owner, name, desc, (params == null) ? "null" :
// Arrays.stream(params).map(Object::getClass).map(Class::getName)
// .collect(java.util.stream.Collectors.joining(",")));
// System.out.println(Arrays.stream(params).map(Objects::toString)
// .collect(Collectors.joining(",")));
data.add(owner, name + desc, Arrays.stream(params).map(serializer::apply)
.collect(Collectors.toList()));
}
static int countParams(String desc) {
if(!desc.startsWith("(")) throw new IllegalArgumentException("Not a method descriptor: " + desc);
int pos = 1;
int count = 0;
while(desc.charAt(pos) != ')') {
char next = desc.charAt(pos);
if(next == 'L') {
int l = pos;
pos = desc.indexOf(";", pos) + 1;
count++;
} else if(next == '[') {
//TODO can we do better?
count++;
if(desc.charAt(pos + 1) == 'L') pos = desc.indexOf(";", pos) + 1;
else pos = pos + 2;
} else {
count++;
pos++;
}
}
return count;
}
public static void clearData() {
data.coverage().clear();
}
public static void serializer(Serializer serializer) {
Collect.serializer = serializer;
}
}
| 5,477 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Implantable.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/runtime/Implantable.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.runtime;
import java.util.Collection;
public interface Implantable {
Collection<Class> runtime();
}
| 1,349 | 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/plugins/data_coverage/src/openjdk/jcov/data/arguments/instrument/package-info.java | /*
* Copyright (c) 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.
*/
/**
* API package for classes used during the instrumentation time.
*/
package openjdk.jcov.data.arguments.instrument; | 1,327 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MethodFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/instrument/MethodFilter.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.instrument;
import java.util.ArrayList;
import java.util.List;
import static org.objectweb.asm.Opcodes.ALOAD;
/**
* When used defines which methods to instrument for argument collection.
*/
public interface MethodFilter {
static List<Plugin.TypeDescriptor> parseDesc(String desc) throws ClassNotFoundException {
if(!desc.startsWith("(")) throw new IllegalArgumentException("Not a method descriptor: " + desc);
int pos = 1;
List<Plugin.TypeDescriptor> res = new ArrayList<>();
while(desc.charAt(pos) != ')') {
char next = desc.charAt(pos);
if(next == 'L') {
int l = pos;
pos = desc.indexOf(";", pos) + 1;
res.add(new Plugin.TypeDescriptor("L", desc.substring(l + 1, pos - 1), ALOAD));
} else if(next == '[') {
//TODO can we do better?
res.add(new Plugin.TypeDescriptor("[", "java/lang/Object", ALOAD));
if(desc.charAt(pos + 1) == 'L') pos = desc.indexOf(";", pos) + 1;
else pos = pos + 2;
} else {
res.add(Plugin.primitiveTypes.get(new String(new char[] {next})));
pos++;
}
}
return res;
}
boolean accept(int access, String owner, String name, String desc) throws Exception;
}
| 2,589 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Plugin.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/instrument/Plugin.java | /*
* Copyright (c) 2021, 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 openjdk.jcov.data.arguments.instrument;
import com.sun.tdk.jcov.instrument.asm.ASMInstrumentationPlugin;
import openjdk.jcov.data.arguments.runtime.Collect;
import openjdk.jcov.data.arguments.runtime.Coverage;
import openjdk.jcov.data.Env;
import openjdk.jcov.data.arguments.runtime.Implantable;
import openjdk.jcov.data.arguments.runtime.Saver;
import openjdk.jcov.data.arguments.runtime.Serializer;
import org.objectweb.asm.MethodVisitor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import static openjdk.jcov.data.Env.JCOV_DATA_ENV_PREFIX;
import static openjdk.jcov.data.arguments.runtime.Collect.SERIALIZER;
import static org.objectweb.asm.Opcodes.*;
/**
* An instrumention plugin responsible for adding necessary bytecode instructions to collect and pass argument values to
* a specified collector.
*/
public class Plugin implements ASMInstrumentationPlugin {
/**
* Classname of a collector class which will be called from every instrumented method.
*/
public static final String COLLECTOR_CLASS = Collect.class.getName()
.replace('.', '/');
/**
* Name of the methods which will be called from every instrumented method.
*/
public static final String COLLECTOR_METHOD = "collect";
/**
* Signature of the method which will be called from every instrumented method.
*/
public static final String COLLECTOR_DESC =
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V";
/**
* Name of a property which contains class name for the method filter.
*/
public static final String METHOD_FILTER =
JCOV_DATA_ENV_PREFIX + Collect.ARGUMENTS_PREFIX + "method.filter";
/**
* Aux class responsible for code generation for different types.
*/
public static class TypeDescriptor extends openjdk.jcov.data.instrument.TypeDescriptor {
public TypeDescriptor(String id, String cls, int loadOpcode) {
super(id, cls, loadOpcode);
}
public TypeDescriptor(String id, Class cls, int loadOpcode, boolean longOrDouble, boolean isPrimitive) {
super(id, cls, loadOpcode, longOrDouble, isPrimitive);
}
//returns new stack index increased by 1 or 2
int visit(int paramIndex, int stackIndex, MethodVisitor visitor) {
visitor.visitInsn(DUP);
visitor.visitIntInsn(BIPUSH, paramIndex);
visitor.visitIntInsn(loadOpcode(), stackIndex);
if(isPrimitive())
visitor.visitMethodInsn(INVOKESTATIC, cls(), "valueOf",
"(" + id() + ")L" + cls() + ";", false);
visitor.visitInsn(AASTORE);
return stackIndex + (isLongOrDouble() ? 2 : 1);
}
}
final static Map<String, TypeDescriptor> primitiveTypes;
static {
primitiveTypes = new HashMap<>();
primitiveTypes.put("S", new TypeDescriptor("S", Short.class, ILOAD, false, true));
primitiveTypes.put("I", new TypeDescriptor("I", Integer.class, ILOAD, false, true));
primitiveTypes.put("J", new TypeDescriptor("J", Long.class, LLOAD, true, true));
primitiveTypes.put("F", new TypeDescriptor("F", Float.class, FLOAD, false, true));
primitiveTypes.put("D", new TypeDescriptor("D", Double.class, DLOAD, true, true));
primitiveTypes.put("Z", new TypeDescriptor("Z", Boolean.class, ILOAD, false, true));
primitiveTypes.put("B", new TypeDescriptor("B", Byte.class, ILOAD, false, true));
primitiveTypes.put("C", new TypeDescriptor("C", Character.class, ILOAD, false, true));
}
final static TypeDescriptor objectType = new TypeDescriptor("L", Object.class, ALOAD, false, false);
private final Coverage template;
private MethodFilter methodFilter;
private Path templateFile;
private Function<Object, String> serializer;
public Plugin() throws
ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException,
IllegalAccessException {
template = new Coverage();
methodFilter = Env.getSPIEnv(METHOD_FILTER, (a, o, m, d) -> true);
templateFile = Env.getPathEnv(Collect.COVERAGE_OUT, Paths.get("template.lst"));
serializer = Env.getSPIEnv(SERIALIZER, Object::toString);
}
/**
* Injects necessary instructions to place all the arguments into an array which is then passed tp the collector's
* method.
*/
@Override
public MethodVisitor methodVisitor(int access, String owner, String name, String desc, MethodVisitor visitor) {
try {
String method = name + desc;
try {
if (methodFilter.accept(access, owner, name, desc)) {
template.get(owner, method);
return new MethodVisitor(ASM6, visitor) {
@Override
public void visitCode() {
try {
List<TypeDescriptor> params = MethodFilter.parseDesc(desc);
if (params.size() > 0) {
super.visitLdcInsn(owner);
super.visitLdcInsn(name);
super.visitLdcInsn(desc);
super.visitIntInsn(BIPUSH, params.size());
super.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int stackIndex = ((access & ACC_STATIC) > 0) ? 0 : 1;
for (int i = 0; i < params.size(); i++) {
stackIndex = params.get(i).visit(i, stackIndex, this);
}
visitor.visitMethodInsn(INVOKESTATIC, COLLECTOR_CLASS, COLLECTOR_METHOD,
COLLECTOR_DESC, false);
}
} catch (Exception e) {
e.printStackTrace();
}
super.visitCode();
}
};
} else return visitor;
} catch (Exception e) {
throw new RuntimeException(e);
}
} catch(Throwable e) {
//JCov is known for swallowing exceptions
e.printStackTrace();
throw e;
}
}
@Override
public void instrumentationComplete() throws IOException {
try {
Coverage.write(template, templateFile);
} catch(Throwable e) {
//JCov is known for swallowing exceptions
e.printStackTrace();
throw e;
}
}
private static final Set<Class> runtimeClasses = Set.of(
Collect.class, Coverage.class, Saver.class, Saver.NoRuntimeSerializer.class, Env.class,
Implantable.class, Serializer.class
);
protected List<Class> runtimeClasses() {
return runtimeClasses();
}
@Override
public Path runtime() throws Exception {
try {
Path dest = Files.createTempFile("jcov-data", ".jar");
Properties toSave = new Properties();
System.getProperties().forEach((k, v) -> {
if(k.toString().startsWith(JCOV_DATA_ENV_PREFIX))
toSave.setProperty(k.toString(), v.toString());
});
Set<Class> allRuntime = runtimeClasses;
Function<Object, String> serializer = Env.getSPIEnv(SERIALIZER, null);
if(serializer != null && serializer instanceof Implantable) {
allRuntime = new HashSet<>(runtimeClasses);
allRuntime.addAll(((Implantable)serializer).runtime());
}
try(JarOutputStream jar = new JarOutputStream(Files.newOutputStream(dest))) {
jar.putNextEntry(new JarEntry(Env.PROP_FILE));
toSave.store(jar, "");
jar.closeEntry();
for(Class rc : allRuntime) {
String fileName = rc.getName().replace(".", "/") + ".class";
jar.putNextEntry(new JarEntry(fileName));
try (InputStream ci = rc.getClassLoader().getResourceAsStream(fileName)) {
byte[] buffer = new byte[1024];
int read;
while ((read = ci.read(buffer)) > 0) {
jar.write(buffer, 0, read);
}
}
jar.closeEntry();
}
}
return dest;
} catch(Throwable e) {
//JCov is known for swallowing exceptions
e.printStackTrace();
throw e;
}
}
@Override
public String collectorPackage() {
try {
return Collect.class.getPackage().getName();
} catch(Throwable e) {
//JCov is known for swallowing exceptions
e.printStackTrace();
throw e;
}
}
}
| 10,776 | 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/plugins/data_coverage/src/openjdk/jcov/data/arguments/analysis/package-info.java | /*
* Copyright (c) 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.
*/
/**
* This package will contain API useful for loading, parsing and analizing data coverage data.
*/
package openjdk.jcov.data.arguments.analysis; | 1,355 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Reader.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/arguments/analysis/Reader.java | /*
* Copyright (c) 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 openjdk.jcov.data.arguments.analysis;
public class Reader {
}
| 1,278 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EnumDeserializer.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/serialization/EnumDeserializer.java | /*
* Copyright (c) 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 openjdk.jcov.data.serialization;
import java.util.Arrays;
import java.util.function.Function;
/**
* Restores enum object from its name.
*/
public class EnumDeserializer implements Function<String, Object> {
private final Class<? extends Enum> enumClass;
public EnumDeserializer(String enumClassName) throws ClassNotFoundException {
this((Class<? extends Enum>) Class.forName(enumClassName));
}
public EnumDeserializer(Class<? extends Enum> aClass) {
enumClass = aClass;
}
@Override
public Object apply(String s) {
return Arrays.stream(enumClass.getEnumConstants()).filter(e -> e.name().equals(s))
.findAny().get();
}
}
| 1,912 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EnumSerializer.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/serialization/EnumSerializer.java | /*
* Copyright (c) 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 openjdk.jcov.data.serialization;
import openjdk.jcov.data.arguments.runtime.Implantable;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
/**
* Serializes an enum into its name.
*/
public class EnumSerializer implements Function<Object, String>, Implantable {
private final String defaultValue;
public EnumSerializer(String value) {
defaultValue = value;
}
public EnumSerializer() {
this("NOT_AN_ENUM");
}
@Override
public String apply(Object anEnum) {
if (anEnum instanceof Enum)
return ((Enum) anEnum).name();
else
return defaultValue;
}
public Collection<Class> runtime() {
return List.of(EnumSerializer.class);
}
}
| 1,987 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
TypeDescriptor.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/data_coverage/src/openjdk/jcov/data/instrument/TypeDescriptor.java | /*
* Copyright (c) 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 openjdk.jcov.data.instrument;
/**
* Contains necessary type information for code generation, etc. Should be extended as needed with the actual code
* generation logic.
*/
public class TypeDescriptor {
private final String id;
private final String cls;
private final int loadOpcode;
private final boolean longOrDouble;
private final boolean isPrimitive;
public static String toVMClassName(Class cls) {
return toVMClassName(cls.getName());
}
public static String toVMClassName(String className) {
return className.replace('.','/');
}
public TypeDescriptor(String id, Class cls, int loadOpcode) {
this(id, toVMClassName(cls), loadOpcode);
}
public TypeDescriptor(String id, String cls, int loadOpcode) {
this(id, cls, loadOpcode, false, false);
}
public TypeDescriptor(String id, Class cls, int loadOpcode, boolean longOrDouble, boolean isPrimitive) {
this(id, toVMClassName(cls), loadOpcode, longOrDouble, isPrimitive);
}
public TypeDescriptor(String id, String cls, int loadOpcode, boolean longOrDouble, boolean isPrimitive) {
this.id = id;
this.cls = cls;
this.loadOpcode = loadOpcode;
this.longOrDouble = longOrDouble;
this.isPrimitive = isPrimitive;
}
public String id() {
return id;
}
public String cls() { return cls; }
public int loadOpcode() {
return loadOpcode;
}
public boolean isLongOrDouble() {
return longOrDouble;
}
public boolean isPrimitive() {
return isPrimitive;
}
}
| 2,824 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CoberturaReportGenerator.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coberturaXML/src/openjdk/codetools/jcov/plugin/coberturaxml/CoberturaReportGenerator.java | /*
* Copyright (c) 2018, Eric L. McCorkle. All rights reserved.
* 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 openjdk.codetools.jcov.plugin.coberturaxml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Runnable;
import com.sun.tdk.jcov.instrument.XmlContext;
import com.sun.tdk.jcov.report.AbstractCoverage.CoverageFormatter;
import com.sun.tdk.jcov.report.*;
public class CoberturaReportGenerator implements ReportGenerator {
private static final String XML_HEADER =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
private static final String XML_DTD =
"<!DOCTYPE coverage SYSTEM \"http://cobertura.sourceforge" +
".net/xml/coverage-04.dtd\">";
private static final String COVERAGE_NODE = "coverage";
private static final String LINE_RATE_ATTR = "line-rate";
private static final String LINES_COVERED_ATTR = "lines-covered";
private static final String LINES_VALID_ATTR = "lines-valid";
private static final String BRANCH_RATE_ATTR = "branch-rate";
private static final String BRANCHES_COVERED_ATTR = "branches-covered";
private static final String BRANCHES_VALID_ATTR = "branches-valid";
private static final String BRANCHES_RATE_ATTR = "branches-rate";
private static final String TIMESTAMP_ATTR = "timestamp";
private static final String COMPLEXITY_ATTR = "complexity";
private static final String VERSION_ATTR = "version";
private static final String SOURCES_NODE = "sources";
private static final String SOURCE_NODE = "source";
private static final String PACKAGES_NODE = "packages";
private static final String PACKAGE_NODE = "package";
private static final String CLASSES_NODE = "classes";
private static final String CLASS_NODE = "class";
private static final String NAME_ATTR = "name";
private static final String FILENAME_ATTR = "filename";
private static final String METHODS_NODE = "methods";
private static final String METHOD_NODE = "method";
private static final String SIGNATURE_ATTR = "signature";
private static final String HITS_ATTR = "hits";
private static final String LINES_NODE = "lines";
private static final String LINE_NODE = "line";
private static final String NUMBER_ATTR = "number";
private static final String BRANCH_ATTR = "branch";
private static final String CONDITION_COVERAGE_ATTR = "condition-coverage";
private static final String CONDITIONS_NODE = "conditions";
private static final String CONDITION_NODE = "condition";
private static final String COVERAGE_ATTR = "coverage";
private static final CoverageFormatter formatter = new FloatFormatter();
private XmlContext ctx;
/**
* {@inheritDoc}
*/
@Override
public void init(final String outputPath) throws IOException {
this.ctx = new XmlContext(new FileOutputStream(outputPath));
}
private void startNode(final String name) {
startNode(name,
new Runnable() {
@Override public void run() {}
});
}
private <T> void startNode(final String name,
final Runnable attrs) {
ctx.indent();
ctx.print("<");
ctx.print(name);
attrs.run();
ctx.println(">");
ctx.incIndent();
}
private <T> void singletonNode(final String name,
final Runnable attrs) {
ctx.indent();
ctx.print("<");
ctx.print(name);
attrs.run();
ctx.println("/>");
}
private void endNode(final String name) {
ctx.decIndent();
ctx.indent();
ctx.print("</");
ctx.print(name);
ctx.println(">");
}
private void writeXMLHeader() {
ctx.println(XML_HEADER);
ctx.println(XML_DTD);
ctx.println();
}
private void writeSource(final String srcRootPath) {
ctx.indent();
ctx.print("<");
ctx.print(SOURCE_NODE);
ctx.print(">");
ctx.writeEscaped(srcRootPath);
ctx.print("</");
ctx.print(SOURCE_NODE);
ctx.println(">");
}
private void writeSources(final Options options) {
startNode(SOURCES_NODE);
if (options.getSrcRootPaths() != null) {
for (final String srcRootPath : options.getSrcRootPaths()) {
writeSource(srcRootPath);
}
}
endNode(SOURCES_NODE);
}
private void itemNodeAttrs(final ItemCoverage item) {
ctx.attr(NUMBER_ATTR, item.getSourceLine());
ctx.attr(HITS_ATTR, item.getCount());
ctx.attr(BRANCH_ATTR, !item.isBlock());
if (!item.isBlock()) {
ctx.attr(CONDITION_COVERAGE_ATTR,
item.getCoverageString(DataType.BRANCH));
}
}
private void writeItem(final ItemCoverage item) {
singletonNode(LINE_NODE,
new Runnable() {
@Override
public void run() {
itemNodeAttrs(item);
}
});
}
private void writeItems(final Iterable<ItemCoverage> items) {
startNode(LINES_NODE);
for(final ItemCoverage item : items) {
writeItem(item);
}
endNode(LINES_NODE);
}
private void methodNodeAttrs(final MethodCoverage method) {
ctx.attr(NAME_ATTR, method.getName());
ctx.attr(SIGNATURE_ATTR, method.getSignature());
ctx.attr(LINE_RATE_ATTR, method.getCoverageString(DataType.LINE,
formatter));
ctx.attr(BRANCH_RATE_ATTR, method.getCoverageString(DataType.BRANCH,
formatter));
// See comments below
ctx.attr(COMPLEXITY_ATTR, "1.0");
}
private void writeMethod(final MethodCoverage method) {
startNode(METHOD_NODE,
new Runnable() {
@Override
public void run() {
methodNodeAttrs(method);
}
});
writeItems(method);
endNode(METHOD_NODE);
}
private void writeMethods(final Iterable<MethodCoverage> methods) {
startNode(METHODS_NODE);
for(final MethodCoverage method : methods) {
writeMethod(method);
}
endNode(METHODS_NODE);
}
private void fieldNodeAttrs(final FieldCoverage field) {
ctx.attr(NUMBER_ATTR, field.getStartLine());
ctx.attr(HITS_ATTR, field.getHitCount());
ctx.attr(BRANCH_ATTR, false);
}
private void writeField(final FieldCoverage field) {
startNode(LINE_NODE,
new Runnable() {
@Override
public void run() {
fieldNodeAttrs(field);
}
});
endNode(LINE_NODE);
}
/* Cobertura doesn't have fields, so we output these as line coverage. */
private void writeClassLines(final ClassCoverage cls) {
startNode(LINES_NODE);
for(final MethodCoverage method : cls.getMethods()) {
for(final ItemCoverage item : method) {
writeItem(item);
}
}
for(final FieldCoverage field : cls.getFields()) {
writeField(field);
}
endNode(LINES_NODE);
}
private String trimPath(final String path,
final Options options) {
if (options.getSrcRootPaths() != null) {
for (final String srcRootPath : options.getSrcRootPaths()) {
if (path.startsWith(srcRootPath)) {
int idx;
for (idx = srcRootPath.length();
path.charAt(idx) == File.separatorChar;
idx++);
return path.substring(idx);
}
}
}
return path;
}
private void classNodeAttrs(final ClassCoverage cls,
final Options options) {
ctx.attr(NAME_ATTR, cls.getName());
ctx.attr(FILENAME_ATTR, trimPath(cls.getSource(), options));
ctx.attr(LINE_RATE_ATTR, cls.getCoverageString(DataType.LINE,
formatter));
ctx.attr(BRANCH_RATE_ATTR, cls.getCoverageString(DataType.BRANCH,
formatter));
// See comments below
ctx.attr(COMPLEXITY_ATTR, "1.0");
}
private void writeClass(final ClassCoverage cls,
final Options options) {
startNode(CLASS_NODE,
new Runnable() {
@Override
public void run() {
classNodeAttrs(cls, options);
}
});
writeMethods(cls.getMethods());
writeClassLines(cls);
endNode(CLASS_NODE);
}
private void packageNodeAttrs(final PackageCoverage pack) {
ctx.attr(NAME_ATTR, pack.getName());
ctx.attr(LINE_RATE_ATTR, pack.getCoverageString(DataType.LINE,
formatter));
ctx.attr(BRANCH_RATE_ATTR, pack.getCoverageString(DataType.BRANCH,
formatter));
// It's not clear what this actually is supposed to mean, but
// other tools just set it to 1.0
ctx.attr(COMPLEXITY_ATTR, "1.0");
}
private void writeClasses(final Iterable<ClassCoverage> classes,
final Options options) {
startNode(CLASSES_NODE);
for(final ClassCoverage cls : classes) {
writeClass(cls, options);
}
endNode(CLASSES_NODE);
}
private void writePackage(final PackageCoverage pack,
final Options options) {
startNode(PACKAGE_NODE,
new Runnable() {
@Override
public void run() {
packageNodeAttrs(pack);
}
});
writeClasses(pack, options);
endNode(PACKAGE_NODE);
}
private void writePackages(final Iterable<PackageCoverage> packs,
final Options options) {
startNode(PACKAGES_NODE);
for(final PackageCoverage pack : packs) {
writePackage(pack, options);
}
endNode(PACKAGES_NODE);
}
private void coverageNodeAttrs(final ProductCoverage coverage) {
ctx.attr(LINES_COVERED_ATTR, coverage.getData(DataType.LINE).getCovered());
ctx.attr(LINES_VALID_ATTR, coverage.getData(DataType.LINE).getTotal());
ctx.attr(LINE_RATE_ATTR, coverage.getCoverageString(DataType.LINE,
formatter));
ctx.attr(BRANCHES_COVERED_ATTR, coverage.getData(DataType.BRANCH).getCovered());
ctx.attr(BRANCHES_VALID_ATTR, coverage.getData(DataType.BRANCH).getTotal());
ctx.attr(BRANCH_RATE_ATTR, coverage.getCoverageString(DataType.BRANCH,
formatter));
ctx.attr(TIMESTAMP_ATTR, Long.toString(System.currentTimeMillis() /
1000L));
// See comments below
ctx.attr(COMPLEXITY_ATTR, "1.0");
ctx.attr(VERSION_ATTR, "1.0");
}
/**
* {@inheritDoc}
*/
@Override
public void generateReport(final ProductCoverage coverage,
final Options options)
throws IOException {
writeXMLHeader();
startNode(COVERAGE_NODE,
new Runnable() {
@Override
public void run() {
coverageNodeAttrs(coverage);
}
});
writeSources(options);
writePackages(coverage, options);
endNode(COVERAGE_NODE);
ctx.flush();
}
/**
* Simple formatter that outputs a floating point number. This is
* used for Cobertura XML reports.
*/
public static class FloatFormatter implements CoverageFormatter {
@Override
public String format(CoverageData data) {
if (data.getTotal() != 0) {
final double total = data.getTotal();
final double covered = data.getCovered();
return Double.toString(covered / total);
} else {
return "0.0";
}
}
}
}
| 14,080 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CoberturaReportGeneratorSPI.java | /FileExtraction/Java_unseen/openjdk_jcov/plugins/coberturaXML/src/openjdk/codetools/jcov/plugin/coberturaxml/CoberturaReportGeneratorSPI.java | /*
* Copyright (c) 2018, Eric L. McCorkle. 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 openjdk.codetools.jcov.plugin.coberturaxml;
import com.sun.tdk.jcov.report.ReportGenerator;
import com.sun.tdk.jcov.report.ReportGeneratorSPI;
import com.sun.tdk.jcov.tools.EnvHandler;
import com.sun.tdk.jcov.tools.EnvServiceProvider;
import com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException;
public class CoberturaReportGeneratorSPI implements ReportGeneratorSPI, EnvServiceProvider {
/**
* {@inheritDoc}
*/
@Override
public ReportGenerator getReportGenerator(final String formatName) {
if (formatName.equalsIgnoreCase("cobertura")) {
final ReportGenerator out = new CoberturaReportGenerator();
return out;
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public int handleEnv(final EnvHandler opts) throws EnvHandlingException {
return 0;
}
@Override
public void extendEnvHandler(final EnvHandler handler) {
}
}
| 2,170 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
RangeElectionTest2.java | /FileExtraction/Java_unseen/dessalines_referendum/src/test/java/com/dd/test/RangeElectionTest2.java | package com.dd.test;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.codehaus.jackson.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.db.Actions;
import com.referendum.db.Transformations;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RangeBallot;
import com.referendum.voting.candidate.RangeCandidate;
import com.referendum.voting.election.RangeElection;
import com.referendum.voting.voting_system.choice_type.RangeVotingSystem.RangeVotingSystemType;
import static com.referendum.db.Tables.*;
public class RangeElectionTest2 extends TestCase {
static final Logger log = LoggerFactory.getLogger(RangeElectionTest2.class);
public void testRangeElection() {
Tools.dbInit();
// String json = Actions.rangePollResults("1");
// log.info(json);
String json = Actions.rangePollResults("1");
System.out.println(json);
Tools.dbClose();
}
}
| 993 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
RangeElectionTest.java | /FileExtraction/Java_unseen/dessalines_referendum/src/test/java/com/dd/test/RangeElectionTest.java | package com.dd.test;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RangeBallot;
import com.referendum.voting.candidate.RangeCandidate;
import com.referendum.voting.election.RangeElection;
import com.referendum.voting.voting_system.choice_type.RangeVotingSystem.RangeVotingSystemType;
public class RangeElectionTest extends TestCase {
static final Logger log = LoggerFactory.getLogger(RangeElectionTest.class);
Integer orange = 1, pear = 2, chocolate = 3, strawberry = 4, mixed = 5;
private List<RangeBallot> setupBallots() {
List<RangeBallot> ballots = new ArrayList<>();
for (int i = 0; i < 4; i++) {
RangeBallot b = new RangeBallot(new RangeCandidate(orange, Double.valueOf(i)));
ballots.add(b);
}
for (int i = 0; i < 5; i++) {
RangeBallot b = new RangeBallot(new RangeCandidate(pear, Double.valueOf(i)));
ballots.add(b);
}
for (int i = 0; i < 2; i++) {
RangeBallot b = new RangeBallot(new RangeCandidate(chocolate, Double.valueOf(i)));
ballots.add(b);
}
for (int i = 10; i > 7; i--) {
RangeBallot b = new RangeBallot(new RangeCandidate(strawberry, Double.valueOf(i)));
ballots.add(b);
}
for (int i = 10; i > 4; i--) {
RangeBallot b = new RangeBallot(new RangeCandidate(mixed, Double.valueOf(i)));
ballots.add(b);
}
for (int i = 0; i < 22; i++) {
RangeBallot b = new RangeBallot(new RangeCandidate(orange, Double.valueOf(2)));
ballots.add(b);
}
return ballots;
}
public void testRangeElection() {
List<RangeBallot> ballots = setupBallots();
RangeElection re = new RangeElection(1, RangeVotingSystemType.AVERAGE, ballots, 10);
log.info(Tools.GSON2.toJson(re.getRankings()));
}
}
| 1,865 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
DerpTests.java | /FileExtraction/Java_unseen/dessalines_referendum/src/test/java/com/dd/test/DerpTests.java | package com.dd.test;
import static com.referendum.db.Tables.*;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.DataSources;
import com.referendum.db.Transformations;
import com.referendum.db.Transformations.CommentObj;
import com.referendum.tools.Tools;
import junit.framework.TestCase;
public class DerpTests extends TestCase {
static final Logger log = LoggerFactory.getLogger(DerpTests.class);
public void derp() {
Tools.dbInit();
String json = POLL_VIEW.findFirst("id = ?", 1).toJson(false).replace("\r", "").replace("\\\n", "\\u000a");
System.out.println(json);
// System.out.println(StringEscapeUtils.escapeJava(json));
Tools.dbClose();
}
public void commentView() {
Tools.dbInit();
// String cv = COMMENT_VIEW.findAll().toJson(true);
// CommentView. = COMMENT_VIEW.findBySQL(COMMENT_VIEW_SQL(1,0,1)).toJson(true);
List<CommentView> cvs = COMMENT_VIEW.find("discussion_id = ?", 1);
List<CommentObj> cos = Transformations.convertCommentsToEmbeddedObjects(cvs);
log.info(Tools.GSON2.toJson(cos));
Tools.dbClose();
}
public void testAlphaTest() {
System.out.println(Tools.ALPHA_ID.encode(new BigInteger("10")));
}
public void testReplaceQuotes() {
System.out.println(Tools.replaceQuotes("This asdfasdf"));
}
public void testFileWalk() {
try {
List<String> test = Files.walk(Paths.get(DataSources.WEB_HTML()))
.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith("template"))
.map(Path::toFile)
.map(File::getAbsolutePath)
.collect(Collectors.toList());
log.info(test.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 2,169 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
STVTest.java | /FileExtraction/Java_unseen/dessalines_referendum/src/test/java/com/dd/test/STVTest.java | package com.dd.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.candidate.RankedCandidate;
import com.referendum.voting.election.ElectionRoundItem;
import com.referendum.voting.election.STVElection;
import com.referendum.voting.election.STVElection.Quota;
// test from
// https://en.wikipedia.org/wiki/Single_transferable_vote#Counting_the_votes
public class STVTest extends TestCase {
static final Logger log = LoggerFactory.getLogger(STVTest.class);
Integer orange = 1, pear = 2, chocolate = 3, strawberry = 4, mixed = 5;
private List<RankedBallot> setupBallots() {
List<RankedBallot> ballots = new ArrayList<>();
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(orange, 1);
RankedBallot rb = new RankedBallot(Arrays.asList(rc));
ballots.add(rb);
}
for (int i = 0; i < 2; i++) {
RankedCandidate rc = new RankedCandidate(pear, 1);
RankedCandidate rc2 = new RankedCandidate(orange, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
// Weird thing with the test, do 4 with second choice strawberries,
// then 4 with second choice sweets, then another 4 with second choice strawberries
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(chocolate, 1);
RankedCandidate rc2 = new RankedCandidate(strawberry, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(chocolate, 1);
RankedCandidate rc2 = new RankedCandidate(mixed, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(chocolate, 1);
RankedCandidate rc2 = new RankedCandidate(strawberry, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 1; i++) {
RankedCandidate rc = new RankedCandidate(strawberry, 1);
RankedBallot rb = new RankedBallot(Arrays.asList(rc));
ballots.add(rb);
}
for (int i = 0; i < 1; i++) {
RankedCandidate rc = new RankedCandidate(mixed, 1);
RankedBallot rb = new RankedBallot(Arrays.asList(rc));
ballots.add(rb);
}
return ballots;
}
public void testSTVElection() {
Integer seats = 3;
List<RankedBallot> ballots = setupBallots();
STVElection stv = new STVElection(Quota.DROOP, ballots, seats);
log.info(Tools.GSON2.toJson(stv.getRounds()));
Integer rn = 0, c;
// first round
c = 0;
assertEquals(Integer.valueOf(4), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(2), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(12), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(1), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(1), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED, stv.getRounds().get(rn++).getRoundItems().get(2).getStatus());
// second round
c = 0;
assertEquals(Integer.valueOf(4), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(2), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(5), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(3), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(2).getStatus());
assertEquals(ElectionRoundItem.Status.DEFEATED, stv.getRounds().get(rn++).getRoundItems().get(1).getStatus());
// third round
c = 0;
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(5), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(3), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(1).getStatus());
assertEquals(ElectionRoundItem.Status.ELECTED, stv.getRounds().get(rn++).getRoundItems().get(0).getStatus());
// fourth round
c = 0;
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(5), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(3), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(0).getStatus());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(1).getStatus());
assertEquals(ElectionRoundItem.Status.DEFEATED, stv.getRounds().get(rn++).getRoundItems().get(3).getStatus());
// fifth round
c = 0;
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(6), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(5), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(0).getStatus());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(1).getStatus());
assertEquals(ElectionRoundItem.Status.ELECTED, stv.getRounds().get(rn++).getRoundItems().get(2).getStatus());
}
}
| 6,629 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
STVTest2.java | /FileExtraction/Java_unseen/dessalines_referendum/src/test/java/com/dd/test/STVTest2.java | package com.dd.test;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.candidate.RankedCandidate;
import com.referendum.voting.election.ElectionRoundItem;
import com.referendum.voting.election.STVElection;
import com.referendum.voting.election.STVElection.Quota;
import junit.framework.TestCase;
public class STVTest2 extends TestCase {
static final Logger log = LoggerFactory.getLogger(STVTest2.class);
Integer andrea = 1, brad = 2, carter = 3, delilah = 4;
private List<RankedBallot> setupBallots() {
List<RankedBallot> ballots = new ArrayList<>();
for (int i = 0; i < 3; i++) {
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(new RankedCandidate(andrea, 1));
candidates.add(new RankedCandidate(brad, 2));
candidates.add(new RankedCandidate(carter, 3));
candidates.add(new RankedCandidate(delilah, 4));
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 8; i++) {
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(new RankedCandidate(andrea, 1));
candidates.add(new RankedCandidate(carter, 2));
candidates.add(new RankedCandidate(brad, 3));
candidates.add(new RankedCandidate(delilah, 4));
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 2; i++) {
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(new RankedCandidate(andrea, 1));
candidates.add(new RankedCandidate(brad, 2));
candidates.add(new RankedCandidate(carter, 3));
candidates.add(new RankedCandidate(delilah, 4));
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 9; i++) {
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(new RankedCandidate(andrea, 1));
candidates.add(new RankedCandidate(carter, 2));
candidates.add(new RankedCandidate(brad, 3));
candidates.add(new RankedCandidate(delilah, 4));
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 8; i++) {
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(new RankedCandidate(delilah, 1));
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
return ballots;
}
public void testSTVElection() {
Integer seats = 2;
List<RankedBallot> ballots = setupBallots();
STVElection stv = new STVElection(Quota.DROOP, ballots, seats);
log.info(Tools.GSON2.toJson(stv.getRounds()));
Integer rn = 0, c;
// first round
c = 0;
assertEquals(Integer.valueOf(22), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(8), stv.getRounds().get(rn).getRoundItems().get(3).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED, stv.getRounds().get(rn++).getRoundItems().get(0).getStatus());
// second round
c = 0;
assertEquals(Integer.valueOf(11), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(3), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(8), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(8), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(0).getStatus());
assertEquals(ElectionRoundItem.Status.DEFEATED, stv.getRounds().get(rn++).getRoundItems().get(1).getStatus());
// third round
c = 0;
assertEquals(Integer.valueOf(11), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(11), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(Integer.valueOf(8), stv.getRounds().get(rn).getRoundItems().get(c++).getVotes());
assertEquals(ElectionRoundItem.Status.ELECTED_PREVIOUSLY, stv.getRounds().get(rn).getRoundItems().get(0).getStatus());
assertEquals(ElectionRoundItem.Status.ELECTED, stv.getRounds().get(rn).getRoundItems().get(1).getStatus());
assertEquals(ElectionRoundItem.Status.DEFEATED, stv.getRounds().get(rn++).getRoundItems().get(2).getStatus());
}
}
| 4,362 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
DataSources.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/DataSources.java | package com.referendum;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.referendum.tools.Tools;
public class DataSources {
public static String APP_NAME = "referendum";
public static Integer EXTERNAL_SPARK_WEB_PORT() {return (SSL) ? 443 : 80;} // Main is port 80, dev is port 4567
public static Boolean SSL = false;
// iptables are used to route all requests to 80 to 4567.
public static Integer INTERNAL_SPARK_WEB_PORT = 4567;
public static final String WEB_SERVICE_URL = "http://localhost:" + INTERNAL_SPARK_WEB_PORT + "/";
public static String EXTERNAL_IP = Tools.httpGetString("http://api.ipify.org/").trim();
public static String EXTERNAL_URL = "http://" + EXTERNAL_IP + ":" + EXTERNAL_SPARK_WEB_PORT() + "/";
public static final String DD_DOMAIN_NAME = "referendum.ml";
public static final String DD_URL(){
String domain = (SSL) ? "https:" : "http:";
domain += "//" + DD_DOMAIN_NAME + "/";
return domain;
}
public static final String DD_INTERNAL_URL = "http://" + DD_DOMAIN_NAME + ":" + INTERNAL_SPARK_WEB_PORT + "/";
// The path to the ytm dir
public static String HOME_DIR() {
String userHome = System.getProperty( "user.home" ) + "/." + APP_NAME;
return userHome;
}
public static final String KEYSTORE() { return HOME_DIR() + "/keystore.jks";}
// This should not be used, other than for unzipping to the home dir
public static final String CODE_DIR = System.getProperty("user.dir");
public static final String SOURCE_CODE_HOME() {return HOME_DIR() + "/src";}
public static final String SQL_FILE() {return SOURCE_CODE_HOME() + "/ddl_server.sql";}
public static final String SQL_VIEWS_FILE() {return SOURCE_CODE_HOME() + "/views_server.sql";}
public static final String SQL_FAST_TABLES_FILE() {return SOURCE_CODE_HOME() + "/fast_tables.sql";}
public static final String SHADED_JAR_FILE = CODE_DIR + "/target/" + APP_NAME + ".jar";
public static final String SHADED_JAR_FILE_2 = CODE_DIR + "/" + APP_NAME + ".jar";
public static final String ZIP_FILE() {return HOME_DIR() + "/" + APP_NAME + ".zip";}
public static final String TOOLS_JS() {return SOURCE_CODE_HOME() + "/web/js/tools.js";}
// Web pages
public static final String WEB_HOME() {return SOURCE_CODE_HOME() + "/web";}
public static final String WEB_HTML() {return WEB_HOME() + "/html";}
// public static final String MAIN_PAGE_URL_EN() {return WEB_HTML() + "/main_en.html";}
//
// public static final String MAIN_PAGE_URL_ES() {return WEB_HTML() + "/main_es.html";}
public static final String MAINTENANCE_PAGE_URL() {return WEB_HTML() + "/maintenance.html";}
// public static String BASE_ENDPOINT = MAIN_PAGE_URL_EN();
public static String BASE_ENDPOINT = WEB_HTML() + "/home.html";
public static final String PAGES(String pageName) {
return WEB_HTML() + "/" + pageName + ".html";
}
public static final String TEMPLATES(String pageName) {
return WEB_HTML() + "/" + pageName + ".template";
}
public static final List<String> HEAD_TEMPLATES = new ArrayList<>(Arrays.asList(
"home",
"tag",
"private_poll",
"poll",
"trending_polls",
"trending_tags",
"user",
"comment"));
public static final List<String> SUB_TEMPLATES = new ArrayList<>(Arrays.asList(
"header",
"navbar",
"footer",
"modals",
"scripts"));
public static final Date APP_START_DATE = new Date();
public static final String DB_PROP_FILE = HOME_DIR() + "/db.properties";
public static final Properties DB_PROP = Tools.loadProperties(DB_PROP_FILE);
public static final Integer EXPIRE_SECONDS = 86400 * 7; // stays logged in for 7 days
public static final String KEYSTORE_FILE() {return HOME_DIR() + "/keystore.jks";}
}
| 3,890 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Main.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/Main.java | package com.referendum;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.referendum.scheduled.ScheduledJobs;
import com.referendum.tools.Tools;
import com.referendum.webservice.WebService;
public class Main {
static Logger log = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
@Option(name="-uninstall",usage="Uninstall referendum.(WARNING, this deletes your library)")
private boolean uninstall;
@Option(name="-loglevel", usage="Sets the log level [INFO, DEBUG, etc.]")
private String loglevel = "INFO";
@Option(name="-maintenance", usage="Redirects to the maintenance page")
private boolean maintenanceRedirect;
@Option(name="-local", usage="Use the local webservice")
private boolean local;
@Option(name="-ssl",usage="Uses SSL")
private boolean ssl;
public void doMain(String[] args) {
parseArguments(args);
// See if the user wants to uninstall it
if (uninstall) {
Tools.uninstall();
}
if (maintenanceRedirect) {
DataSources.BASE_ENDPOINT = DataSources.MAINTENANCE_PAGE_URL();
}
DataSources.SSL = ssl;
log.setLevel(Level.toLevel(loglevel));
// log.getLoggerContext().getLogger("org.eclipse.jetty").setLevel(Level.OFF);
// log.getLoggerContext().getLogger("spark.webserver").setLevel(Level.OFF);
Tools.setupDirectories();
Tools.copyResourcesToHomeDir(true);
Tools.addExternalWebServiceVarToTools(local);
ScheduledJobs.start();
// Startup the web service
WebService.start();
}
private void parseArguments(String[] args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
// if there's a problem in the command line,
// you'll get this exception. this will report
// an error message.
System.err.println(e.getMessage());
System.err.println("java -jar referendum.jar [options...] arguments...");
// print the list of available options
parser.printUsage(System.err);
System.err.println();
System.exit(0);
return;
}
}
public static void main(String[] args) {
new Main().doMain(args);
}
}
| 2,290 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Actions.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/db/Actions.java | package com.referendum.db;
import static com.referendum.db.Tables.*;
import static com.referendum.tools.Tools.ALPHA_ID;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.DBException;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.referendum.DataSources;
import com.referendum.db.Tables.Ballot;
import com.referendum.db.Tables.CommentView;
import com.referendum.db.Tables.Discussion;
import com.referendum.db.Tables.Poll;
import com.referendum.db.Tables.User;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RangeBallot;
import com.referendum.voting.candidate.RangeCandidate;
import com.referendum.voting.candidate.RangeCandidateResult;
import com.referendum.voting.election.RangeElection;
import com.referendum.voting.voting_system.choice_type.RangeVotingSystem;
import com.referendum.voting.voting_system.choice_type.RangeVotingSystem.RangeVotingSystemType;
// http://ondras.zarovi.cz/sql/demo/?keyword=dd_tyhou
public class Actions {
static final Logger log = LoggerFactory.getLogger(Actions.class);
public static String createEmptyPoll(String userId) {
// First create a discussion
Discussion d = DISCUSSION.createIt();
Poll p = POLL.createIt("discussion_id", d.getId().toString(),
"user_id", userId,
"poll_type_id", 1,
"poll_sum_type_id", 1);
p.set("aid", Tools.ALPHA_ID.encode(BigInteger.valueOf(p.getLong("id"))),
"modified", "0000-00-00 00:00:00").saveIt();
return p.getId().toString();
}
public static String savePoll(String userId, String pollId,
String subject, String text, String password,
String pollSumTypeId, Boolean fullUsersOnly,
Timestamp expireTime, Timestamp addCandidatesExpireTime,
Integer pctThreshold, Response res) {
Poll p = POLL.findFirst("id = ? and user_id = ?", pollId, userId);
if (p == null) {
throw new NoSuchElementException("Wrong User");
}
String passwordEncrypted = Tools.PASS_ENCRYPT.encryptPassword(password);
p.set("private_password", passwordEncrypted,
"poll_sum_type_id", pollSumTypeId,
"full_user_only", fullUsersOnly,
"expire_time", expireTime,
"add_candidates_expire_time", addCandidatesExpireTime,
"pct_threshold", pctThreshold).saveIt();
Discussion d = DISCUSSION.findFirst("id = ?", p.getString("discussion_id"));
d.set("subject", Tools.replaceQuotes(subject),
"text", Tools.replaceQuotes(text)).saveIt();
if (password != null) {
res.removeCookie("poll_password_" + pollId);
res.cookie("poll_password_" + pollId, password);
}
return "Poll Saved";
}
public static String unlockPoll(String pollId, String password, Response res) {
Poll p = POLL.findFirst("id = ? ", pollId);
Boolean correctPass = Tools.PASS_ENCRYPT.checkPassword(password, p.getString("private_password"));
if (correctPass) {
res.removeCookie("poll_password_" + pollId);
res.cookie("poll_password_" + pollId, password);
} else {
throw new NoSuchElementException("Incorrect password");
}
return "Poll Unlocked";
}
public static String deletePoll(String userId, String pollId) {
Poll p = POLL.findFirst("id = ? and user_id = ?", pollId, userId);
if (p == null) {
throw new NoSuchElementException("Wrong User");
}
Discussion d = DISCUSSION.findFirst("id = ?", p.getString("discussion_id"));
d.delete();
p.delete();
return "Poll Deleted";
}
public static String deleteCandidate(String userId, String candidateId) {
Candidate c = CANDIDATE.findFirst("id = ? and user_id = ?", candidateId, userId);
if (c == null) {
throw new NoSuchElementException("Wrong User");
}
Discussion d = DISCUSSION.findFirst("id = ?", c.getString("discussion_id"));
d.delete();
c.delete();
return "Candidate Deleted";
}
public static String createCandidate(String userId, String pollId, String subject, String text) {
Poll p = POLL.findFirst("id = ?", pollId);
Date now = new Date();
// Make sure the poll isn't expired
if (p.getTimestamp("add_candidates_expire_time") != null &&
p.getTimestamp("add_candidates_expire_time").before(now)) {
throw new NoSuchElementException("Adding candidates time period has expired");
}
if (p.getTimestamp("expire_time") != null &&
p.getTimestamp("expire_time").before(now)) {
throw new NoSuchElementException("Candidate not saved, poll has expired");
}
// First create a discussion
Discussion d = DISCUSSION.createIt("subject", Tools.replaceQuotes(subject),
"text", Tools.replaceQuotes(text));
CANDIDATE.createIt("poll_id", pollId,
"discussion_id", d.getId().toString(),
"user_id", userId);
return "Candidate created";
}
public static String saveCandidate(String userId, String candidateId, String subject, String text) {
// find the candidate
Candidate c = CANDIDATE.findFirst("id = ? and user_id = ?", candidateId, userId);
if (c == null) {
throw new NoSuchElementException("Wrong User");
}
// Update the discussion
Discussion d = DISCUSSION.findFirst("id = ?", c.getInteger("discussion_id"));
d.set("subject", Tools.replaceQuotes(subject),
"text", Tools.replaceQuotes(text)).saveIt();
return "Candidate updated";
}
public static String editComment(String userId, String commentId, String text) {
// find the candidate
Comment c = COMMENT.findFirst("id = ? and user_id = ?", commentId, userId);
if (c == null) {
throw new NoSuchElementException("Wrong User");
}
c.set("text", Tools.replaceQuotes(text),
"modified", new Timestamp(new Date().getTime())).saveIt();
return "Comment updated";
}
public static String deleteComment(String userId, String commentId) {
// find the candidate
Comment c = COMMENT.findFirst("id = ? and user_id = ?", commentId, userId);
if (c == null) {
throw new NoSuchElementException("Wrong User");
}
c.set("deleted", true).saveIt();
return "Comment deleted";
}
public static String createComment(String userId, String discussionId,
List<String> parentBreadCrumbs, String text) {
List<String> pbs = (parentBreadCrumbs != null) ? new ArrayList<String>(parentBreadCrumbs) :
new ArrayList<String>();
// find the candidate
Comment c = COMMENT.createIt("discussion_id", discussionId,
"text", Tools.replaceQuotes(text),
"user_id", userId);
c.set("aid", Tools.ALPHA_ID.encode(BigInteger.valueOf(c.getLong("id"))),
"modified", "0000-00-00 00:00:00").saveIt();
String childId = c.getId().toString();
// This is necessary, because of the 0 path length to itself one
pbs.add(childId);
Collections.reverse(pbs);
// Create the comment_tree
for (int i = 0; i < pbs.size(); i++) {
String parentId = pbs.get(i);
// i is the path length
COMMENT_TREE.createIt("parent_id", parentId,
"child_id", childId,
"path_length", i);
}
return "Comment created";
}
public static String saveBallot(String userId, String pollId, String candidateId,
String rank) {
String message = null;
// fetch the vote if it exists
Ballot b = BALLOT.findFirst("poll_id = ? and user_id = ? and candidate_id = ?",
pollId,
userId,
candidateId);
Poll p = POLL.findFirst("id = ?", pollId);
// Make sure the poll isn't expired
if (p.getTimestamp("expire_time") != null &&
p.getTimestamp("expire_time").before(new Date())) {
throw new NoSuchElementException("Vote not saved, poll has expired");
}
if (b == null) {
if (rank != null) {
b = BALLOT.createIt(
"poll_id", pollId,
"user_id", userId,
"candidate_id", candidateId,
"rank", rank);
message = "Ballot Created";
} else {
message = "Ballot not created";
}
} else {
if (rank != null) {
b.set("rank", rank).saveIt();
message = "Ballot updated";
}
// If the rank is null, then delete the ballot
else {
b.delete();
message = "Ballot deleted";
}
}
return message;
}
public static String saveCommentVote(String userId, String commentId, String rank) {
String message = null;
// fetch the vote if it exists
CommentRank c = COMMENT_RANK.findFirst("user_id = ? and comment_id = ?",
userId, commentId);
if (c == null) {
if (rank != null) {
c = COMMENT_RANK.createIt(
"comment_id", commentId,
"user_id", userId,
"rank", rank);
message = "Comment Vote Created";
} else {
message = "Comment Vote not created";
}
} else {
if (rank != null) {
c.set("rank", rank).saveIt();
message = "Comment Vote updated";
}
// If the rank is null, then delete the ballot
else {
c.delete();
message = "Comment Vote deleted";
}
}
return message;
}
public static String setCookiesForLogin(FullUser fu, String auth, Response res) {
Boolean secure = DataSources.SSL;
res.cookie("auth",null, 0);
res.cookie("uid",null, 0);
res.cookie("uaid",null, 0);
res.cookie("username",null, 0);
res.cookie("auth", auth, DataSources.EXPIRE_SECONDS, secure);
res.cookie("uid", fu.getString("user_id"), DataSources.EXPIRE_SECONDS, secure);
res.cookie("uaid", Tools.ALPHA_ID.encode(new BigInteger(fu.getString("user_id"))),
DataSources.EXPIRE_SECONDS, secure);
res.cookie("username", fu.getString("name"), DataSources.EXPIRE_SECONDS, secure);
return "Logged in";
}
public static String setCookiesForLogin(User user, String auth, Response res) {
Boolean secure = DataSources.SSL;
res.cookie("auth",null, 0);
res.cookie("uid",null, 0);
res.cookie("uaid",null, 0);
res.cookie("auth", auth, DataSources.EXPIRE_SECONDS, secure);
res.cookie("uid", user.getId().toString(), DataSources.EXPIRE_SECONDS, secure);
res.cookie("uaid", user.getString("aid"), DataSources.EXPIRE_SECONDS, secure);
return "Logged in";
}
public static UserLoginView getUserFromCookie(Request req, Response res) {
String auth = req.cookie("auth");
UserLoginView uv = null;
uv = USER_LOGIN_VIEW.findFirst("auth = ?" , auth);
return uv;
}
public static UserLoginView getOrCreateUserFromCookie(Request req, Response res) {
String auth = req.cookie("auth");
UserLoginView uv = null;
// If no cookie, fetch user by ip address
if (auth == null) {
User user = USER.findFirst("ip_address = ?", req.ip());
// It found a user row
if (user != null) {
// See if you have a login that hasn't expired yet
Login login = LOGIN.findFirst("user_id = ? and expire_time > ?", user.getId(),
Tools.newCurrentTimestamp().toString());
// log.info(Tools.newCurrentTimestamp().toString());
// log.info(login.toJson(false));
// It found a login item for that user row, so the cookie, like u shoulda
if (login != null) {
auth = login.getString("auth");
Actions.setCookiesForLogin(user, auth, res);
}
// Need to login for that user and set the cookie
else {
auth = Tools.generateSecureRandom();
login = LOGIN.createIt("user_id", user.getId(),
"auth", auth,
"expire_time", Tools.newExpireTimestamp());
Actions.setCookiesForLogin(user, auth, res);
}
// The login is either there or created now, so find it and return out
uv = USER_LOGIN_VIEW.findFirst("auth = ?" , auth);
return uv;
}
}
// The auth cookie is there, so find the user from the login
else {
uv = USER_LOGIN_VIEW.findFirst("auth = ?" , auth);
}
// The user doesn't exist, so you need to create the user and login
if (uv == null) {
User user = USER.createIt("ip_address", req.ip());
user.set("aid", Tools.ALPHA_ID.encode(BigInteger.valueOf(user.getLong("id"))),
"modified", "0000-00-00 00:00:00").saveIt();
auth = Tools.generateSecureRandom();
LOGIN.createIt("user_id", user.getId(),
"auth", auth,
"expire_time", Tools.newExpireTimestamp());
uv = USER_LOGIN_VIEW.findFirst("auth = ?" , auth);
Actions.setCookiesForLogin(user, auth, res);
}
return uv;
}
public static List<RangeBallot> convertDBBallots(List<Ballot> dbBallots) {
List<RangeBallot> ballots = new ArrayList<>();
for (Ballot dbBallot : dbBallots) {
Integer candidateId = dbBallot.getInteger("candidate_id");
Double rank = dbBallot.getDouble("rank");
RangeBallot rb = new RangeBallot(new RangeCandidate(candidateId, rank));
ballots.add(rb);
}
return ballots;
}
public static String rangePollResults(String pollId) {
List<Ballot> dbBallots = BALLOT.find("poll_id = ?", pollId);
List<RangeBallot> ballots = convertDBBallots(dbBallots);
Poll p = POLL.findFirst("id = ?", pollId);
RangeElection re = new RangeElection(Integer.valueOf(pollId),
sumIdToRangeVotingSystemType().get(p.getInteger("poll_sum_type_id")),
ballots,
p.getInteger("pct_threshold"));
return Tools.nodeToJson(Transformations.rangeResultsJson(re));
}
public static Map<Integer, RangeVotingSystemType> sumIdToRangeVotingSystemType() {
Map<Integer, RangeVotingSystemType> map = new HashMap<>();
map.put(1, RangeVotingSystemType.AVERAGE);
map.put(2, RangeVotingSystemType.MEDIAN);
map.put(3, RangeVotingSystemType.NORMALIZED);
return map;
}
public static String fetchPollComments(Integer userId, Integer discussionId) {
List<CommentView> cvs = COMMENT_VIEW.findBySQL(
COMMENT_VIEW_SQL(userId, discussionId, null, null, null, null, null, null, null, null, null));
return commentObjectsToJson(cvs);
}
public static String fetchComments(Integer userId, Integer commentId) {
List<CommentView> cvs = COMMENT_VIEW.findBySQL(
COMMENT_VIEW_SQL(userId, null, commentId, null, null, null, null, null, null, null, null));
return commentObjectsToJson(cvs);
}
public static String fetchUserComments(Integer userId, Integer commentUserId, String orderBy,
Integer pageNum, Integer pageSize) {
LazyList<Model> cvs = COMMENT_VIEW.findBySQL(
COMMENT_VIEW_SQL(userId, null, null, null, null, orderBy, commentUserId, null,
pageNum, pageSize, null));
String json = Tools.wrapPaginatorArray(
Tools.replaceNewlines(cvs.toJson(false)),
Long.valueOf(cvs.size()));
return json;
}
public static String fetchUserMessages(Integer userId, Integer parentUserId, String orderBy,
Integer pageNum, Integer pageSize, Boolean read) {
LazyList<CommentView> cvs = fetchUserMessageList(userId, parentUserId, orderBy, pageNum, pageSize, read);
String json = Tools.wrapPaginatorArray(
Tools.replaceNewlines(cvs.toJson(false)),
Long.valueOf(cvs.size()));
return json;
}
public static LazyList<CommentView> fetchUserMessageList(Integer userId, Integer parentUserId, String orderBy,
Integer pageNum, Integer pageSize, Boolean read) {
LazyList<CommentView> cvs = COMMENT_VIEW.findBySQL(
COMMENT_VIEW_SQL(userId, null, null, 1, 1, orderBy, null, parentUserId, null, null, read));
return cvs;
}
public static String markMessagesAsRead(Integer userId) {
// Fetch fetch the user unreadmessage list
String joinSQL = fetchUserMessageList(userId, userId, null, null, null, false).toSql(false);
joinSQL = joinSQL.substring(0,joinSQL.length()-1); // remove the semicolon;
StringBuilder s = new StringBuilder();
s.append("update comment a\n");
s.append("join (" + joinSQL + ") k \n");
s.append("on a.id = k.id \n");
s.append("set a.read = 1 \n");
String updateSQL = s.toString();
Base.exec(updateSQL);
return "success";
}
public static String commentObjectsToJson(List<CommentView> cvs) {
// return Tools.GSON.toJson(Transformations.convertCommentsToEmbeddedObjects(cvs));
try {
return Tools.MAPPER.writeValueAsString(Transformations.convertCommentsToEmbeddedObjects(cvs));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String login(String userOrEmail, String password,
String recaptchaResponse, Request req, Response res) {
// First verify the recaptchaResponse
Boolean recaptchaPassed = Tools.verifyRecaptcha(recaptchaResponse, req.ip());
if (!recaptchaPassed) {
throw new NoSuchElementException("Recaptcha failed");
}
// Find the user, then create a login for them
FullUser fu = FULL_USER.findFirst("name = ? or email = ?", userOrEmail, userOrEmail);
if (fu == null) {
throw new NoSuchElementException("Incorrect user/email");
} else {
String encryptedPassword = fu.getString("password_encrypted");
Boolean correctPass = Tools.PASS_ENCRYPT.checkPassword(password, encryptedPassword);
if (correctPass) {
String auth = Tools.generateSecureRandom();
LOGIN.createIt("user_id", fu.getInteger("user_id"),
"auth", auth,
"expire_time", Tools.newExpireTimestamp());
return Actions.setCookiesForLogin(fu, auth, res);
} else {
throw new NoSuchElementException("Incorrect Password");
}
}
}
public static String signup(String userName, String password, String email,
String recaptchaResponse, Request req, Response res) {
// First verify the recaptchaResponse
Boolean recaptchaPassed = Tools.verifyRecaptcha(recaptchaResponse, req.ip());
if (!recaptchaPassed) {
throw new NoSuchElementException("Recaptcha failed");
}
// Find the user, then create a login for them
FullUser fu = FULL_USER.findFirst("name = ? or email = ?", userName, userName);
if (fu == null) {
// Create the user and full user
User user = USER.createIt("ip_address", req.ip());
user.set("aid", Tools.ALPHA_ID.encode(BigInteger.valueOf(user.getLong("id"))),
"modified", "0000-00-00 00:00:00").saveIt();
log.info("encrypting the user password");
String encryptedPassword = Tools.PASS_ENCRYPT.encryptPassword(password);
fu = FULL_USER.createIt("user_id", user.getId(),
"name", userName,
"email", email,
"password_encrypted", encryptedPassword);
// now login that user
String auth = Tools.generateSecureRandom();
LOGIN.createIt("user_id", user.getId(),
"auth", auth,
"expire_time", Tools.newExpireTimestamp());
Actions.setCookiesForLogin(fu, auth, res);
return "Logged in";
} else {
throw new NoSuchElementException("Username/Password already exists");
}
}
public static void addPollVisit(String userId, Integer pollId) {
POLL_VISIT.createIt("user_id", userId,
"poll_id", pollId);
}
public static void addTagVisit(String userId, Integer tagId) {
TAG_VISIT.createIt("user_id", userId,
"tag_id", tagId);
}
public static String savePollTag(String userId, String pollId, String tagId, String newTagName) {
String message = null;
// If the tag isn't there, then add it
if (tagId == null) {
// Fetch to see if the tag exists first
Tag tag = TAG.findFirst("name = ?", newTagName);
if (tag == null) {
tag = TAG.createIt("user_id", userId,
"name", Tools.replaceQuotes(newTagName));
tag.set("aid", Tools.ALPHA_ID.encode(BigInteger.valueOf(tag.getLong("id"))),
"modified", "0000-00-00 00:00:00").saveIt();
message = "New tag added";
}
tagId = tag.getId().toString();
} else {
message = "Tag added";
}
try {
POLL_TAG.createIt("poll_id", pollId,
"tag_id", tagId);
} catch (DBException e) {
throw new NoSuchElementException("Tag already added");
}
return message;
}
public static String clearTags(String userId, String pollId) {
// Make sure its the correct user
Poll p = POLL.findFirst("id = ? and user_id = ?", pollId, userId);
if (p == null) {
throw new NoSuchElementException("Wrong user");
}
POLL_TAG.delete("poll_id = ?", pollId);
return "Tags deleted";
}
}
| 20,142 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Transformations.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/db/Transformations.java | package com.referendum.db;
import static com.referendum.db.Tables.BALLOT;
import static com.referendum.db.Tables.CANDIDATE_VIEW;
import static com.referendum.db.Tables.POLL;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.referendum.db.Tables.Ballot;
import com.referendum.db.Tables.CandidateView;
import com.referendum.db.Tables.CommentView;
import com.referendum.db.Tables.Poll;
import com.referendum.tools.Tools;
import com.referendum.voting.ballot.RangeBallot;
import com.referendum.voting.candidate.RangeCandidateResult;
import com.referendum.voting.candidate.RankedCandidate;
import com.referendum.voting.election.RangeElection;
public class Transformations {
static final Logger log = LoggerFactory.getLogger(Transformations.class);
public static ObjectNode rangeResultsJson(RangeElection re) {
List<CandidateView> allCandidates = CANDIDATE_VIEW.find("poll_id = ?", re.getId());
Map<Integer, CandidateView> cMap = new HashMap<>();
for (CandidateView c : allCandidates) {
cMap.put(c.getInteger("id"), c);
}
ObjectNode a = Tools.MAPPER.createObjectNode();
ArrayNode an = a.putArray("results");
for (RangeCandidateResult rank : re.getRankings()) {
ObjectNode on = Tools.MAPPER.valueToTree(rank);
JsonNode cm = Tools.jsonToNode(Tools.replaceNewlines(cMap.get(rank.getId()).toJson(false)));
on.put("candidate_obj", cm);
an.add(on);
}
return a;
}
public static List<CommentObj> convertCommentsToEmbeddedObjects(List<CommentView> cvs) {
List<CommentObj> cos = new ArrayList<>();
for (CommentView cv : cvs) {
// Create the comment object
CommentObj co = new CommentObj(cv.getInteger("id"),
cv.getString("aid"),
cv.getInteger("discussion_id"),
cv.getInteger("poll_id"),
cv.getString("poll_aid"),
cv.getInteger("user_id"),
cv.getString("user_aid"),
cv.getString("user_name"),
cv.getBoolean("deleted"),
cv.getBoolean("read"),
cv.getDouble("avg_rank"),
cv.getInteger("user_rank"),
cv.getString("text"),
cv.getString("breadcrumbs"),
cv.getTimestamp("created"),
cv.getTimestamp("modified"));
// log.info(co.getModified());
// If there's no parent, add it to the top level
if (co.getParentId() == null) {
cos.add(co);
}
else {
// Get the correct level
CommentObj topParent = CommentObj.findInEmbeddedById(cos, co);
CommentObj parentObj = topParent;
// If its down more than a single level, you have to do a recursive loop to
// fetch the correct parent object
if (co.getBreadCrumbsList().size() > 2) {
for (int i = 1; i < co.getBreadCrumbsList().size() - 1; i++) {
Integer parent = co.getBreadCrumbsList().get(i);
parentObj = parentObj.findInEmbeddedById(parent);
}
}
// Add this commentobj to the embedded comments of its parent
parentObj.getEmbedded().add(co);
Collections.sort(parentObj.getEmbedded(), new CommentObj.CommentObjComparator());
}
}
Collections.sort(cos, new CommentObj.CommentObjComparator());
return cos;
}
public static class CommentObj {
private Integer id, discussionId, pollId, userId, userRank, parentId, topParentId;
private Double avgRank;
private String aid, pollAid, userAid, text, userName;
private Timestamp created, modified;
private List<CommentObj> embedded;
private Boolean deleted, read;
private List<Integer> breadCrumbsList;
public CommentObj(Integer id, String aid, Integer discussionId,
Integer pollId, String pollAid, Integer userId, String userAid,
String userName, Boolean deleted, Boolean read,
Double avgRank, Integer userRank, String text, String breadCrumbs,
Timestamp created, Timestamp modified) {
this.id = id;
this.aid = aid;
this.discussionId = discussionId;
this.pollId = pollId;
this.pollAid = pollAid;
this.userId = userId;
this.userAid = userAid;
this.userName = userName;
this.deleted = deleted;
this.read = read;
this.avgRank = avgRank;
this.userRank = userRank;
if (this.userRank == null) {
this.userRank = -1;
}
if (this.avgRank == null) {
this.avgRank = -1.0D;
}
this.text = text;
this.created = created;
this.modified = modified;
embedded = new ArrayList<>();
setBreadCrumbsArr(breadCrumbs);
setParentId();
}
@Override
public String toString() {
return "id : " + id;
}
public CommentObj findInEmbeddedById(Integer id) {
return findInEmbeddedById(embedded, id);
}
public static CommentObj findInEmbeddedById(List<CommentObj> cos, Integer id) {
for (CommentObj c : cos) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public static CommentObj findInEmbeddedById(List<CommentObj> cos, CommentObj co) {
Integer id = co.getTopParentId();
for (CommentObj c : cos) {
if (c.getId() == id) {
return c;
}
}
return co;
}
private void setBreadCrumbsArr(String breadCrumbs) {
breadCrumbsList = new ArrayList<>();
for (String br : breadCrumbs.split(",")) {
breadCrumbsList.add(Integer.valueOf(br));
}
}
private void setParentId() {
Integer cIndex = breadCrumbsList.indexOf(id);
if (cIndex > 0) {
parentId = breadCrumbsList.get(cIndex - 1);
}
topParentId = breadCrumbsList.get(0);
}
public List<CommentObj> getEmbedded() {
return embedded;
}
public Integer getId() {
return id;
}
public static class CommentObjComparator implements Comparator<CommentObj> {
@Override
public int compare(CommentObj o1, CommentObj o2) {
return o2.getAvgRank().compareTo(o1.getAvgRank());
}
}
public Integer getDiscussionId() {
return discussionId;
}
public Integer getPollId() {
return pollId;
}
public Integer getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public Integer getParentId() {
return parentId;
}
public Integer getTopParentId() {
return topParentId;
}
public Double getAvgRank() {
return avgRank;
}
public String getText() {
return text;
}
public Timestamp getCreated() {
return created;
}
public Timestamp getModified() {
return modified;
}
public List<Integer> getBreadCrumbsList() {
return breadCrumbsList;
}
public Integer getUserRank() {
return userRank;
}
public Boolean getDeleted() {
return deleted;
}
public Boolean getRead() {
return read;
}
public String getAid() {
return aid;
}
public String getPollAid() {
return pollAid;
}
public String getUserAid() {
return userAid;
}
}
}
| 7,082 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Tables.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/db/Tables.java | package com.referendum.db;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.Table;
public class Tables {
@Table("poll")
public static class Poll extends Model {}
public static final Poll POLL = new Poll();
@Table("poll_view")
public static class PollView extends Model {}
public static final PollView POLL_VIEW = new PollView();
@Table("poll_ungrouped_view")
public static class PollUngroupedView extends Model {}
public static final PollUngroupedView POLL_UNGROUPED_VIEW = new PollUngroupedView();
@Table("poll_type")
public static class PollType extends Model {}
public static final PollType POLL_TYPE = new PollType();
@Table("poll_tag")
public static class PollTag extends Model {}
public static final PollTag POLL_TAG = new PollTag();
@Table("poll_tag_view")
public static class PollTagView extends Model {}
public static final PollTagView POLL_TAG_VIEW = new PollTagView();
@Table("poll_visit")
public static class PollVisit extends Model {}
public static final PollVisit POLL_VISIT = new PollVisit();
@Table("tag")
public static class Tag extends Model {}
public static final Tag TAG = new Tag();
@Table("tag_view")
public static class TagView extends Model {}
public static final TagView TAG_VIEW = new TagView();
@Table("tag_visit")
public static class TagVisit extends Model {}
public static final TagVisit TAG_VISIT = new TagVisit();
@Table("candidate")
public static class Candidate extends Model {}
public static final Candidate CANDIDATE = new Candidate();
@Table("candidate_view")
public static class CandidateView extends Model {}
public static final CandidateView CANDIDATE_VIEW = new CandidateView();
@Table("ballot")
public static class Ballot extends Model {}
public static final Ballot BALLOT = new Ballot();
@Table("ballot_view")
public static class BallotView extends Model {}
public static final BallotView BALLOT_VIEW = new BallotView();
@Table("discussion")
public static class Discussion extends Model {}
public static final Discussion DISCUSSION = new Discussion();
@Table("comment")
public static class Comment extends Model {}
public static final Comment COMMENT = new Comment();
@Table("comment_view")
public static class CommentView extends Model {}
public static final CommentView COMMENT_VIEW = new CommentView();
@Table("comment_tree")
public static class CommentTree extends Model {}
public static final CommentTree COMMENT_TREE = new CommentTree();
@Table("comment_rank")
public static class CommentRank extends Model {}
public static final CommentRank COMMENT_RANK = new CommentRank();
@Table("user")
public static class User extends Model {}
public static final User USER = new User();
@Table("user_view")
public static class UserView extends Model {}
public static final UserView USER_VIEW = new UserView();
@Table("full_user")
public static class FullUser extends Model {}
public static final FullUser FULL_USER = new FullUser();
@Table("user_login_view")
public static class UserLoginView extends Model {}
public static final UserLoginView USER_LOGIN_VIEW = new UserLoginView();
@Table("login")
public static class Login extends Model {}
public static final Login LOGIN = new Login();
public static final String COMMENT_VIEW_SQL(Integer userId, Integer discussionId,
Integer parentId, Integer minPathLength, Integer maxPathLength,
String orderBy, Integer commentUserId, Integer parentUserId,
Integer pageNum, Integer pageSize, Boolean read) {
StringBuilder s = new StringBuilder("select \n"+
"comment.id,\n"+
"comment.aid,\n"+
"b.parent_id as parent_comment_id, \n"+
"parent_comment.aid as parent_comment_aid, \n"+
"comment.discussion_id,\n"+
"poll.id as poll_id,\n"+
"poll.aid as poll_aid,\n"+
"comment.text,\n"+
"comment.user_id,\n"+
"user.aid as user_aid,\n"+
"parent_user.id as parent_user_id,\n"+
"parent_user.aid as parent_user_aid,\n"+
"coalesce(full_user.name, concat('user_',user.aid)) as user_name,\n"+
"comment.deleted,\n"+
"comment.read,\n"+
"-- min(a.path_length,b.path_length),\n"+
"AVG(c.rank) as avg_rank,\n"+
"d.rank as user_rank,\n"+
"a.parent_id as parent_id,\n"+
"GROUP_CONCAT(distinct b.parent_id order by b.path_length desc) AS breadcrumbs,\n"+
"max(a.parent_id) as derp_id,\n"+
"comment.created,\n"+
"comment.modified\n"+
"from comment\n"+
"JOIN comment_tree a ON (comment.id = a.child_id) \n"+
"JOIN comment_tree b ON (b.child_id = a.child_id) \n"+
"left join comment_rank c \n"+
"on comment.id = c.comment_id\n"+
"left join comment_rank d \n"+
"on comment.id = d.comment_id\n" +
"and d.user_id = " + userId + "\n"+
"left join poll on \n"+
"comment.discussion_id = poll.discussion_id \n"+
"left join full_user \n"+
"on comment.user_id = full_user.user_id \n"+
"left join user \n"+
"on comment.user_id = user.id \n"+
"left join comment parent_comment \n"+
"on b.parent_id = parent_comment.id \n"+
"left join user parent_user \n"+
"on parent_comment.user_id = parent_user.id \n"
);
if (discussionId != null) {
s.append("WHERE comment.discussion_id = " + discussionId + "\n");
} else {
s.append("WHERE comment.discussion_id >= 0 \n");
}
if (parentId != null) {
s.append("and a.parent_id = " + parentId + " \n");
s.append("and b.parent_id >= " + parentId + "\n"); //HRM?
}
if (minPathLength != null) {
s.append("and b.path_length >= " + minPathLength + " \n");
}
if (maxPathLength != null) {
s.append("and b.path_length <= " + maxPathLength + " \n");
}
if (commentUserId != null) {
s.append("and comment.user_id = " + commentUserId + " \n");
}
if (parentUserId != null) {
s.append("and parent_user.id = " + parentUserId + " \n");
}
if (read != null) {
s.append("and comment.read = " + read + " \n");
}
s.append("GROUP BY a.child_id \n");
if (orderBy != null) {
s.append("order by " + orderBy + " \n");
}
if (pageSize != null) {
s.append("limit " + pageSize + " \n");
}
if (pageNum != null) {
s.append("offset " + ((pageNum - 1) * pageSize) + " \n");
}
s.append(";");
// System.out.println(s.toString());
return s.toString();
}
}
| 6,341 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Tools.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/tools/Tools.java | package com.referendum.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.jasypt.util.password.BasicPasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.javalite.activejdbc.DB;
import org.javalite.activejdbc.DBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import spark.utils.GzipUtils;
import com.esotericsoftware.kryo.Kryo;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.referendum.DataSources;
import de.javakaffee.kryoserializers.KryoReflectionFactorySupport;
public class Tools {
static final Logger log = LoggerFactory.getLogger(Tools.class);
public static final Kryo KRYO = new KryoReflectionFactorySupport();
public static final Gson GSON = new Gson();
public static final Gson GSON2 = new GsonBuilder().setPrettyPrinting().create();
public static final ObjectMapper MAPPER = new ObjectMapper();
public static final SimpleDateFormat RESPONSE_HEADER_DATE_FORMAT =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
public static final SimpleDateFormat DATE_PICKER_FORMAT =
new SimpleDateFormat("MM/dd/yyyy h:mm a");
public static final BaseX ALPHA_ID = new BaseX();
private static final SecureRandom RANDOM = new SecureRandom();
public static final BasicPasswordEncryptor PASS_ENCRYPT = new BasicPasswordEncryptor();
public static void allowOnlyLocalHeaders(Request req, Response res) {
log.debug("req ip = " + req.ip());
// res.header("Access-Control-Allow-Origin", "http://mozilla.com");
// res.header("Access-Control-Allow-Origin", "null");
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Credentials", "true");
if (!isLocalIP(req.ip())) {
throw new NoSuchElementException("Not a local ip, can't access");
}
}
public static Boolean isLocalIP(String ip) {
Boolean isLocalIP = (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1"));
return isLocalIP;
}
public static void allowAllHeaders(Request req, Response res) {
String origin = req.headers("Origin");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Origin", origin);
res.header("Content-Encoding", "gzip");
}
public static void set15MinuteCache(Request req, Response res) {
res.header("Cache-Control", "private,max-age=300,s-maxage=900");
res.header("Last-Modified", RESPONSE_HEADER_DATE_FORMAT.format(DataSources.APP_START_DATE));
}
public static void logRequestInfo(Request req) {
String origin = req.headers("Origin");
String origin2 = req.headers("origin");
String host = req.headers("Host");
log.debug("request host: " + host);
log.debug("request origin: " + origin);
log.debug("request origin2: " + origin2);
// System.out.println("origin = " + origin);
// if (DataSources.ALLOW_ACCESS_ADDRESSES.contains(req.headers("Origin"))) {
// res.header("Access-Control-Allow-Origin", origin);
// }
for (String header : req.headers()) {
log.debug("request header | " + header + " : " + req.headers(header));
}
log.debug("request ip = " + req.ip());
log.debug("request pathInfo = " + req.pathInfo());
log.debug("request host = " + req.host());
log.debug("request url = " + req.url());
}
public static final Map<String, String> createMapFromAjaxPost(String reqBody) {
log.debug(reqBody);
Map<String, String> postMap = new HashMap<String, String>();
String[] split = reqBody.split("&");
for (int i = 0; i < split.length; i++) {
String[] keyValue = split[i].split("=");
try {
if (keyValue.length > 1) {
postMap.put(URLDecoder.decode(keyValue[0], "UTF-8"),URLDecoder.decode(keyValue[1], "UTF-8"));
}
} catch (UnsupportedEncodingException |ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
throw new NoSuchElementException(e.getMessage());
}
}
// log.info(GSON2.toJson(postMap));
return postMap;
}
public static void setupDirectories() {
if (!new File(DataSources.HOME_DIR()).exists()) {
log.info("Setting up ~/." + DataSources.APP_NAME + " dirs");
new File(DataSources.HOME_DIR()).mkdirs();
} else {
log.info("Home directory already exists");
}
}
public static String encodeURL(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void copyResourcesToHomeDir(Boolean copyAnyway) {
String zipFile = null;
if (copyAnyway || !new File(DataSources.SOURCE_CODE_HOME()).exists()) {
log.info("Copying resources to ~/." + DataSources.APP_NAME + " dirs");
try {
if (new File(DataSources.SHADED_JAR_FILE).exists()) {
java.nio.file.Files.copy(Paths.get(DataSources.SHADED_JAR_FILE), Paths.get(DataSources.ZIP_FILE()),
StandardCopyOption.REPLACE_EXISTING);
zipFile = DataSources.SHADED_JAR_FILE;
} else if (new File(DataSources.SHADED_JAR_FILE_2).exists()) {
java.nio.file.Files.copy(Paths.get(DataSources.SHADED_JAR_FILE_2), Paths.get(DataSources.ZIP_FILE()),
StandardCopyOption.REPLACE_EXISTING);
zipFile = DataSources.SHADED_JAR_FILE_2;
} else {
log.info("you need to build the project first");
}
} catch (IOException e) {
e.printStackTrace();
}
Tools.unzip(new File(zipFile), new File(DataSources.SOURCE_CODE_HOME()));
// new Tools().copyJarResourcesRecursively("src", configHome);
WriteHTMLFiles.write();
} else {
log.info("The source directory already exists");
}
}
public static void unzip(File zipfile, File directory) {
try {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
try {
copy(in, file);
} finally {
in.close();
}
}
}
zfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copy(InputStream in, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
copy(in, out);
} finally {
out.close();
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}
public static void runSQLFile(Connection c,File sqlFile) {
try {
Statement stmt = null;
stmt = c.createStatement();
String sql;
sql = Files.toString(sqlFile, Charset.defaultCharset());
log.info(sql);
stmt.executeUpdate(sql);
stmt.close();
} catch (IOException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static final void dbInit() {
Properties prop = DataSources.DB_PROP;
try {
new DB("default").open("com.mysql.jdbc.Driver",
prop.getProperty("dburl") + "?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull",
prop.getProperty("dbuser"),
prop.getProperty("dbpassword"));
} catch (DBException e) {
e.printStackTrace();
dbClose();
dbInit();
}
}
public static final void dbClose() {
new DB("default").close();
}
public static String extractInfoHashFromMagnetLink(String magnetLink) {
// magnet:?xt=urn:btih:09c17295ccc24af400a2a91495af440b27766b5e&dn=Fugazi+-+Studio+Discography+1989-2001+%5BFLAC%5D
return magnetLink.split("btih:")[1].split("&dn")[0].toLowerCase();
}
public static String extractNameFromMagnetLink(String magnetLink) {
String encoded = magnetLink.split("&dn=")[1];
String name = null;
try {
name = URLDecoder.decode(encoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return name;
}
public static JsonNode jsonToNode(String json) {
try {
JsonNode root = MAPPER.readTree(json);
return root;
} catch (Exception e) {
log.error("json: " + json);
e.printStackTrace();
}
return null;
}
public static String nodeToJson(ObjectNode a) {
try {
return Tools.MAPPER.writeValueAsString(a);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String nodeToJsonPretty(JsonNode a) {
try {
return Tools.MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(a);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void uninstall() {
try {
FileUtils.deleteDirectory(new File(DataSources.HOME_DIR()));
log.info(DataSources.APP_NAME + " uninstalled successfully.");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String convertWikimediaCommonsURLToImageUrl(String wmLink) {
String fileName = wmLink.split("File:")[1];
String md5 = Hashing.md5().hashString(fileName, Charsets.UTF_8).toString();
String weirdPathString = md5.substring(0, 1) + "/" + md5.substring(0, 2) + "/";
String imageURL = "https://upload.wikimedia.org/wikipedia/commons/" + weirdPathString +
fileName;
return imageURL;
}
public static String readFile(String path) {
String s = null;
byte[] encoded;
try {
encoded = java.nio.file.Files.readAllBytes(Paths.get(path));
s = new String(encoded, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
throw new NoSuchElementException("Couldn't write result");
}
return s;
}
public static void writeFile(String text, String path) {
try {
java.nio.file.Files.write(Paths.get(path), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public static Boolean writeFileToResponse(File file, Request req, Response res) {
return writeFileToResponse(file.getAbsolutePath(), req, res);
}
public static Boolean writeFileToResponse(String path, Request req, Response res) {
try {
OutputStream wrappedOutputStream = GzipUtils.checkAndWrap(req.raw(),
res.raw());
IOUtils.copy(new FileInputStream(new File(path)), wrappedOutputStream);
wrappedOutputStream.flush();
wrappedOutputStream.close();
} catch (IOException e) {
log.error(e.getMessage());
}
return true;
}
public static HttpServletResponse writeFileToResponse2(String path, Response res) {
byte[] encoded;
try {
encoded = java.nio.file.Files.readAllBytes(Paths.get(path));
ServletOutputStream os = res.raw().getOutputStream();
os.write(encoded);
os.close();
return res.raw();
} catch (IOException e) {
throw new NoSuchElementException("Couldn't write response from path: " + path);
}
}
public static void addExternalWebServiceVarToTools(Boolean local) {
log.info("tools.js = " + DataSources.TOOLS_JS());
try {
List<String> lines = java.nio.file.Files.readAllLines(Paths.get(DataSources.TOOLS_JS()));
String interalServiceLine = "var localSparkService = '" +
DataSources.WEB_SERVICE_URL + "';";
String ddServiceLine = "var ddSparkService ='" +
DataSources.DD_URL() + "';";
String externalServiceLine = "var externalSparkService ='" +
DataSources.EXTERNAL_URL + "';";
String sparkServiceLine = (local) ? "var sparkService = '" + DataSources.WEB_SERVICE_URL + "';" :
"var sparkService = '" + DataSources.DD_URL() + "';";
lines.set(0, interalServiceLine);
lines.set(1, ddServiceLine);
lines.set(2, externalServiceLine);
lines.set(3, sparkServiceLine);
java.nio.file.Files.write(Paths.get(DataSources.TOOLS_JS()), lines);
Files.touch(new File(DataSources.TOOLS_JS()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static final String httpGetString(String url) {
String res = "";
try {
URL externalURL = new URL(url);
URLConnection yc = externalURL.openConnection();
// yc.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
res+="\n" + inputLine;
in.close();
return res;
} catch(IOException e) {}
return res;
}
public static void setContentTypeFromFileName(String pageName, Response res) {
if (pageName.endsWith(".css")) {
res.type("text/css; charset=UTF-8");
} else if (pageName.endsWith(".js")) {
res.type("application/javascript; charset=UTF-8");
} else if (pageName.endsWith(".png")) {
res.type("image/png");
res.header("Content-Disposition", "attachment;");
} else if (pageName.endsWith(".svg")) {
res.type("image/svg+xml");
}
}
public static Properties loadProperties(String propertiesFileLocation) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertiesFileLocation);
// load a properties file
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
public static void setJsonContentType(Response res) {
res.type("application/json; charset=utf-8");
}
public static String replaceNewlines(String text) {
return text.replace("\r", "").replace("\n", "--lb--").replace("\\", "");
}
public static String replaceQuotes(String text) {
if (text != null) {
return text.replace("\"", "&dblq;");
} else {
return null;
}
}
public static String generateSecureRandom() {
return new BigInteger(256, RANDOM).toString(32);
}
public static Timestamp newExpireTimestamp() {
return new Timestamp(new Date().getTime() + 1000 * DataSources.EXPIRE_SECONDS);
}
public static Timestamp newCurrentTimestamp() {
return new Timestamp(new Date().getTime());
}
public static final String wrapPaginatorArray(String json, Long totalRecordCount) {
String jtableJson = "{" +
"\"records\": " + json + "," +
"\"record_count\": " + totalRecordCount +
"}";
return jtableJson;
}
public static Boolean verifyRecaptcha(String recaptchaResponse, String ip) {
try {
String recaptchaSecret = DataSources.DB_PROP.getProperty("recaptcha_secret");
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://www.google.com/recaptcha/api/siteverify");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("secret", recaptchaSecret));
params.add(new BasicNameValuePair("response", recaptchaResponse));
params.add(new BasicNameValuePair("remoteip", ip));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
String responseStr = IOUtils.toString(instream, Charsets.UTF_8);
JsonNode on = jsonToNode(responseStr);
// log.info(responseStr);
Boolean success = on.get("success").asBoolean();
return success;
} finally {
instream.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
| 17,508 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
WriteHTMLFiles.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/tools/WriteHTMLFiles.java | package com.referendum.tools;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.referendum.DataSources;
public class WriteHTMLFiles {
private Map<String, String> templates;
private List<File> templateFiles;
static final Logger log = LoggerFactory.getLogger(WriteHTMLFiles.class);
public static void write() {
new WriteHTMLFiles();
}
private WriteHTMLFiles() {
fetchTemplateFiles();
readTemplatesIntoMap();
for (File file : templateFiles) {
writeFile(file.getAbsolutePath());
}
}
private void fetchTemplateFiles() {
try {
templateFiles = Files.walk(Paths.get(DataSources.WEB_HTML()))
.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith("template"))
.map(Path::toFile)
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
private void readTemplatesIntoMap() {
templates = new HashMap<>();
for (File file : templateFiles) {
templates.put(file.getName().split("\\.")[0], Tools.readFile(file.getAbsolutePath()));
}
}
private void writeFile(String headTemplateFile) {
try {
Reader reader = new FileReader(new File(headTemplateFile));
log.debug(headTemplateFile);
File outputFile = new File(headTemplateFile.split("template")[0] + "html");
Writer writer = new FileWriter(outputFile);
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(reader, "example");
mustache.execute(writer, templates);
writer.flush();
log.debug(Tools.readFile(outputFile.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
}
} | 2,120 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
SampleData.java | /FileExtraction/Java_unseen/dessalines_referendum/src/main/java/com/referendum/tools/SampleData.java | package com.referendum.tools;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.referendum.voting.ballot.RankedBallot;
import com.referendum.voting.candidate.RankedCandidate;
public class SampleData {
public static Integer orange = 1, pear = 2, chocolate = 3, strawberry = 4, mixed = 5;
public static List<RankedBallot> setupBallots() {
List<RankedBallot> ballots = new ArrayList<>();
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(orange, 1);
RankedBallot rb = new RankedBallot(Arrays.asList(rc));
ballots.add(rb);
}
for (int i = 0; i < 2; i++) {
RankedCandidate rc = new RankedCandidate(pear, 1);
RankedCandidate rc2 = new RankedCandidate(orange, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
// Weird thing with the test, do 4 with second choice strawberries,
// then 4 with second choice sweets, then another 4 with second choice strawberries
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(chocolate, 1);
RankedCandidate rc2 = new RankedCandidate(strawberry, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(chocolate, 1);
RankedCandidate rc2 = new RankedCandidate(mixed, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 4; i++) {
RankedCandidate rc = new RankedCandidate(chocolate, 1);
RankedCandidate rc2 = new RankedCandidate(strawberry, 2);
List<RankedCandidate> candidates = new ArrayList<>();
candidates.add(rc);
candidates.add(rc2);
RankedBallot rb = new RankedBallot(candidates);
ballots.add(rb);
}
for (int i = 0; i < 1; i++) {
RankedCandidate rc = new RankedCandidate(strawberry, 1);
RankedBallot rb = new RankedBallot(Arrays.asList(rc));
ballots.add(rb);
}
for (int i = 0; i < 1; i++) {
RankedCandidate rc = new RankedCandidate(mixed, 1);
RankedBallot rb = new RankedBallot(Arrays.asList(rc));
ballots.add(rb);
}
return ballots;
}
}
| 2,451 | Java | .java | dessalines/referendum | 20 | 1 | 4 | 2015-12-09T18:13:46Z | 2017-02-25T23:46:17Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.