oblac / jodd-util

Essential Java utilities.
https://util.jodd.org
BSD 2-Clause "Simplified" License
39 stars 9 forks source link

Assignment 3 for software course. #9

Closed mkiefer10 closed 3 years ago

mkiefer10 commented 3 years ago

Hello. Just submitting my java refactoring and code improvements for this assignment here in one pull request together. You may cancel this pull request, but I needed to find test doubles, refactoring suggestions based on large classes and a fuzz test for a url parser and mutation fuzzing for a java code you have here.

package jodd.typeconverter.impl;

import jodd.time.JulianDate; import jodd.time.TimeUtil; import java.sql.Date;

public class SqlDateConverter implements TypeConverter {

public Date convert(final Object value) { if (value == null) { return null; }

if (value instanceof Date) { return (Date) value; } if (value instanceof Calendar) { return new Date(((Calendar)value).getTimeInMillis()); } if (value instanceof java.util.Date) { return new Date(((java.util.Date)value).getTime());

@Profile("fakerepair") public class FakeSQLDateConverter implements DateConverter {

Map<User, DateConverter> dateconverter = new HashMap<>();

public FakeDateConverter() { this.dateconverter.put(new User("mm-dd-yyyy"), new Localdate()); this.dateconverter.put(new User("dd-mm-yy"), new Juliandate()); }

String getfakeDateHash(User user) { return dateconverter.get(user).getfakeDateHash(); } } package jodd.typeconverter.impl; import java.sql.Time; import java.time.LocalDate; import java.time.LocalDateTime; import jodd.time.JulianDate; import jodd.time.TimeUtil;

public class SqlTimeConverter implements TypeConverter

public Time convert(final Object value) { if (value == null) { return null; }

if (value instanceof Time) { return (Time) value; } if (value instanceof Calendar) { return new Time(((Calendar) value).getTimeInMillis()); }

@Profile("fakerepair") public class FakeSQLTimeConverter implements TimeConverter {

Map<User, TimeConverter> timeconverter = new HashMap<>();

public FakeTimeFormat() { this.timeconverter.put(new User("hh-mm-ss"), new Localtime()); this.timeconverter.put(new User("hhmm-ss-ms"), new Juliantime()); }

String getfakeTimeHash(User user) { return timeconverter.get(user).getfakeTimeHash(); } }

package jodd.typeconverter.impl;

import jodd.typeconverter.TypeConversionException; import jodd.typeconverter.TypeConverter; import jodd.util.ClassLoaderUtil; import jodd.util.StringUtil;

public class ClassConverter implements TypeConverter {

public Class convert(final Object value) { if (value == null) { return null; }

if (value.getClass() == Class.class) { return (Class) value; } try { String className = value.toString().trim();

if (className.endsWith(".class")) { className = StringUtil.substring(className, 0, -6); }

return ClassLoaderUtil.loadClass(className);

public class ClassTest extends TestCase { public function testFormat(): void { String result = (new ClassTest()).format(null); self.assertSame(Service::CLASSNAME, result); } }

public class StreamGobbler extends Thread {

protected final InputStream is;
protected final String prefix;
protected final OutputStream out;
protected final Object lock = new Object();
protected boolean end = false;

public StreamGobbler(final InputStream is) {
    this(is, null, null);
}

public StreamGobbler(final InputStream is, final OutputStream output) {
    this(is, output, null);
}

public StreamGobbler(final InputStream is, final OutputStream output, final String prefix) {
    this.is = is;
    this.prefix = prefix;
    this.out = output;
}

public class StreamGobbler extends Thread {

    protected final InputStream is;
    protected final String prefix;
    protected final OutputStream out;

    public StreamGobbler(final InputStream is) {
        this(is, null, null);
    }

    public StreamGobbler(final InputStream is, final OutputStream output) {
        this(is, output, null);
    }

    public StreamGobbler(final InputStream is, final OutputStream output, final String prefix) {
        this.is = is;
        this.prefix = prefix;
        this.out = output;
    }

public class StreamGobbler extends Thread1 {

    protected final Object lock = new Object();
    protected boolean end = false;

    public StreamGobbler(final Object lock) {
        this(is, null, null);
    }

    public StreamGobbler(final Object lock, boolean end) {
        this(is, null, output);
    }

public static void unzip(final File zipFile, final File destDir, final String... patterns) throws IOException { ZipFile zip = new ZipFile(zipFile); Enumeration zipEntries = zip.entries();

    while (zipEntries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) zipEntries.nextElement();
        String entryName = entry.getName();

        if (patterns != null && patterns.length > 0) {
            if (Wildcard.matchPathOne(entryName, patterns) == -1) {
                continue;
            }
        }

        final File file = (destDir != null) ? new File(destDir, entryName) : new File(entryName);

        // check for Zip slip FLAW
        final File rootDir = destDir != null ? destDir : new File(".");
        if (!FileUtil.isAncestor(rootDir, file, true)) {
            throw new IOException("Unzipping");
        }

        if (entry.isDirectory()) {
            if (!file.mkdirs()) {
                if (!file.isDirectory()) {
                    throw new IOException("Failed to create directory: " + file);
                }
            }

public static void unzip(final File zipFile, final File destDir, final String... patterns) throws IOException { return patterns != null && patterns.length > 0 .map (zipEntries.hasMoreElements()) .flatmap (patterns != null && patterns.length > 0) .collect (!FileUtil.isAncestor(rootDir, file, true)) .filter (!file.isDirectory()) throw new IOException("Unzipping"); } public static void zip(!FileUtil.isAncestor(rootDir, file, true) throws new IOException { try { return (Wildcard.matchPathOne(entryName, patterns) .filter (entry.isDirectory()) .filter (!file.mkdirs()) .filter (!file.isDirectory()) throw new IOException("Failed to create directory: " + file); }

    public class AddContentToZip {
            private final byte[] bytes;
            private String path;
            private String comment;

            private AddContentToZip(final byte[] content) {
                this.bytes = content;
            }

            /**
             * Defines optional entry path.
             */
            public AddContentToZip path(final String path) {
                this.path = path;
                return this;
            }

            /**
             * Defines optional comment.
             */
            public AddContentToZip comment(final String comment) {
                this.comment = comment;
                return this;
            }

    public class AddContentToZip {
            private final byte[] bytes;
            private String path;
            private String comment;

            private AddContentToZip(final byte[] content) {
                this.bytes = content;
            }

    public class AddContentToZip1 {

            public AddContentToZip1 path(final String path) {
                this.path = path;
                return this;
            }

            public AddContentToZip1 comment(final String comment) {
                this.comment = comment;
                return this;
            }

class MutationCoverageFuzzer(MutationFuzzer): def reset(self): super().reset() self.coverages_seen = set()

Now empty; we fill this with seed in the first fuzz runs

    self.population = []

def run(self, jodd):
    """Run function(inp) while tracking coverage.
       If we reach new coverage,
       add inp to population and its coverage to population_coverage
    """
    result, outcome = super().run(jodd)
    new_coverage = frozenset(jodd.coverage())
    if outcome == Runner.PASS and new_coverage not in self.coverages_seen:
        # We have new coverage
        self.population.append(self.inp)
        self.coverages_seen.add(new_coverage)

    return result

def http_program(url): supported_schemes = ["http", "https"] result = urlparse(url) if result.scheme not in supported_schemes: raise ValueError("Value " + repr(supported_schemes)) if result.netloc == '': raise ValueError("Host error") return True

codecov[bot] commented 3 years ago

Codecov Report

Merging #9 (03b0457) into string-builder-pool (159a2a9) will increase coverage by 0.22%. The diff coverage is 87.70%.

Impacted file tree graph

@@                    Coverage Diff                    @@
##             string-builder-pool       #9      +/-   ##
=========================================================
+ Coverage                  74.11%   74.34%   +0.22%     
- Complexity                  2878     2897      +19     
=========================================================
  Files                        122      123       +1     
  Lines                       9179     9307     +128     
  Branches                    1920     1943      +23     
=========================================================
+ Hits                        6803     6919     +116     
- Misses                      1881     1890       +9     
- Partials                     495      498       +3     
Impacted Files Coverage Δ Complexity Δ
src/main/java/jodd/io/StreamGobbler.java 0.00% <0.00%> (ø) 0.00 <0.00> (ø)
src/main/java/jodd/util/StringTemplateMatcher.java 87.90% <87.90%> (ø) 16.00 <16.00> (?)
src/main/java/jodd/bean/BeanUtilUtil.java 86.50% <94.73%> (-0.80%) 35.00 <9.00> (-1.00)
src/main/java/jodd/bean/BeanUtilBean.java 93.54% <96.00%> (+0.05%) 83.00 <12.00> (ø)
src/main/java/jodd/bean/BeanProperty.java 100.00% <100.00%> (ø) 22.00 <4.00> (+3.00)
src/main/java/jodd/util/ClassUtil.java 62.79% <0.00%> (-0.37%) 148.00% <0.00%> (-1.00%)
...ain/java/jodd/introspector/PropertyDescriptor.java 70.32% <0.00%> (+1.09%) 37.00% <0.00%> (+1.00%)
src/main/java/jodd/util/StringPool.java 100.00% <0.00%> (+100.00%) 1.00% <0.00%> (+1.00%)

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 159a2a9...03b0457. Read the comment docs.

igr commented 3 years ago

I am sorry, I need to close this PR. I have no use of the code in the comment, sorry, it should be committed, please.