Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/9A22t-SS)
Разработать standalone приложение, которое имеет следующие возможности:

Принимает на вход проект в виде .jar файла
Expand Down
6 changes: 6 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")

implementation("org.slf4j:slf4j-api:2.0.16")
implementation("ch.qos.logback:logback-classic:1.5.13")
compileOnly("org.projectlombok:lombok:1.18.36")
annotationProcessor("org.projectlombok:lombok:1.18.36")
implementation("com.fasterxml.jackson.core:jackson-databind:2.0.1")
}

tasks.test {
Expand Down
7 changes: 7 additions & 0 deletions result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"maxDepthOfInheritance" : 2,
"averageInheritanceDepth" : 1.5,
"averageOverriddenMethods" : 1.0,
"averageFieldCount" : 0.7,
"averageAbcScore" : 0.7234898064243891
}
92 changes: 77 additions & 15 deletions src/main/java/org/example/Example.java
Original file line number Diff line number Diff line change
@@ -1,29 +1,91 @@
package org.example;

import org.example.visitor.ClassPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.example.dto.Result;
import org.example.model.JarMetrics;
import org.example.visitor.CustomClassVisitor;
import org.objectweb.asm.ClassReader;

import java.io.IOException;
import java.util.Enumeration;
import java.nio.file.Paths;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@Slf4j
public class Example {

public static void main(String[] args) throws IOException {
// var printer = new ByteCodePrinter();
// printer.printBubbleSortBytecode();
try (JarFile sampleJar = new JarFile("src/main/resources/sample.jar")) {
Enumeration<JarEntry> enumeration = sampleJar.entries();

while (enumeration.hasMoreElements()) {
JarEntry entry = enumeration.nextElement();
if (entry.getName().endsWith(".class")) {
ClassPrinter cp = new ClassPrinter();
ClassReader cr = new ClassReader(sampleJar.getInputStream(entry));
cr.accept(cp, 0);
}
}
if (args.length != 2) {
log.error("Ошибка чтения аргументов");
return;
}

var jarPath = args[0];
var outputFileName = args[1];

var result = processJarFile(jarPath);
writeResultAsJson(result, outputFileName);
}

private static Result processJarFile(String jarFilePath) throws IOException {
var jarMetrics = new JarMetrics();

try (var jarFile = new JarFile(jarFilePath)) {
jarFile.stream()
.filter(e -> e.getName().endsWith(".class"))
.forEach(entry -> processClass(entry, jarFile, jarMetrics));
}

jarMetrics.calculateMetrics();

var stringBuilder = new StringBuilder()
.append("Максимальная глубина наследования: ").append(jarMetrics.getMaxDepthOfInheritance()).append('\n')
.append("Средняя глубина наследования: ").append(jarMetrics.getAverageInheritanceDepth()).append('\n')
.append("Метрика ABC: ").append(jarMetrics.getAverageAbcScore()).append('\n')
.append("Сколичество переопределенных методов: ").append(jarMetrics.getAverageOverriddenMethods()).append('\n')
.append("Среднее количество полей в классе: ").append(jarMetrics.getAverageFieldCount());

log.info(stringBuilder.toString());

return buildFinalResult(jarMetrics);
}

private static void processClass(JarEntry entry, JarFile jarFile, JarMetrics metrics) {
try {
var reader = new ClassReader(jarFile.getInputStream(entry));
reader.accept(new CustomClassVisitor(metrics), 0);
} catch (IOException e) {
throw new RuntimeException("Ошибка чтения файла. Причина: " + entry.getName(), e);
}
}

private static Result buildFinalResult(JarMetrics metrics) {
return Result.builder()
.maxDepthOfInheritance(metrics.getMaxDepthOfInheritance())
.averageInheritanceDepth(metrics.getAverageInheritanceDepth())
.averageOverriddenMethods(metrics.getAverageOverriddenMethods())
.averageFieldCount(metrics.getAverageFieldCount())
.averageAbcScore(metrics.getAverageAbcScore())
.build();
}

private static void writeResultAsJson(Object result, String outputFileName) throws IOException {
var mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

var file = Paths.get(outputFileName).toFile();

if (file.getParentFile() != null && !file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}

if (!file.exists()) {
file.createNewFile();
}

mapper.writeValue(file, result);

log.info("Метрики сохранены в файл: {}", file.getAbsolutePath());
}
}
16 changes: 16 additions & 0 deletions src/main/java/org/example/dto/Result.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.example.dto;

import lombok.Builder;
import lombok.Getter;
import lombok.ToString;

@Getter
@Builder
@ToString
public class Result {
private int maxDepthOfInheritance;
private double averageInheritanceDepth;
private double averageOverriddenMethods;
private double averageFieldCount;
private double averageAbcScore;
}
41 changes: 41 additions & 0 deletions src/main/java/org/example/model/ClassMetrics.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.example.model;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public class ClassMetrics {

private String name;
private String parentClassName;
private int fieldCount;
private final List<MethodMetrics> methodMetrics = new ArrayList<>();

public void addMetrics(MethodMetrics methodMetrics) {
this.methodMetrics.add(methodMetrics);
}

@Getter
@Setter
public static class MethodMetrics {
private String signature;
private final ABCMetric abcMetric = new ABCMetric();

public void setMetricValue(double metricValue) {
this.getAbcMetric().setMetricValue(metricValue);
}

@Getter
@Setter
public static class ABCMetric {
private long assignments;
private long branches;
private long conditions;
private double metricValue;
}
}
}
105 changes: 105 additions & 0 deletions src/main/java/org/example/model/JarMetrics.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package org.example.model;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JarMetrics {

private final Map<String, String> classParent = new HashMap<>();
private final Map<String, List<String>> classMethods = new HashMap<>();
private final Map<String, Integer> classMaxDepth = new HashMap<>();
private final Map<String, Integer> classOverriddenMethods = new HashMap<>();
private final Map<String, ClassMetrics> classMetrics = new HashMap<>();

public void addParent(String className, String parent) {
classParent.put(className, parent);
}

public void addMethods(String className, List<String> methodSignatures) {
classMethods.put(className, methodSignatures);
}

public void addClassMetrics(ClassMetrics classMetrics) {
this.classMetrics.put(classMetrics.getName(), classMetrics);
}

public void calculateMetrics() {
classParent.keySet().forEach(this::calculateDepth);
classMethods.forEach(this::calculateOverriddenMethods);
}

public int getMaxDepthOfInheritance() {
return classMaxDepth.values().stream()
.max(Integer::compareTo)
.orElse(0);
}

public double getAverageInheritanceDepth() {
return classMaxDepth.values().stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}

public double getAverageAbcScore() {
return classMetrics.values().stream()
.flatMap(c -> c.getMethodMetrics().stream())
.mapToDouble(mm -> mm.getAbcMetric().getMetricValue())
.average()
.orElse(0.0);
}

public double getAverageOverriddenMethods() {
return classOverriddenMethods.values().stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}

public double getAverageFieldCount() {
return classMetrics.values().stream()
.mapToInt(ClassMetrics::getFieldCount)
.average()
.orElse(0.0);
}

private void calculateDepth(String className) {
classMaxDepth.put(className, computeDepth(className));
}

private int computeDepth(String className) {
int depth = 0;
var current = className;

while (classParent.containsKey(current)) {
depth++;
current = classParent.get(current);
}

return depth;
}

private void calculateOverriddenMethods(String className, List<String> methods) {
var inherited = collectInheritedMethods(className);
var count = methods.stream().filter(inherited::contains).count();
classOverriddenMethods.put(className, (int) count);
}

private Set<String> collectInheritedMethods(String className) {
var parent = classParent.get(className);
Set<String> inherited = new HashSet<>();

while (parent != null) {
var parentMethods = classMethods.get(parent);
if (parentMethods != null) {
inherited.addAll(parentMethods);
}
parent = classParent.get(parent);
}

return inherited;
}
}
46 changes: 0 additions & 46 deletions src/main/java/org/example/visitor/ClassPrinter.java

This file was deleted.

Loading