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
3 changes: 2 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ repositories {
}

dependencies {
implementation("org.ow2.asm:asm:9.5")
implementation("org.ow2.asm:asm:9.6")
implementation("org.ow2.asm:asm-tree:9.5")
implementation("org.ow2.asm:asm-analysis:9.5")
implementation("org.ow2.asm:asm-util:9.5")
implementation("com.fasterxml.jackson.core:jackson-databind:2.16.2")

testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
Expand Down
90 changes: 83 additions & 7 deletions src/main/java/org/example/Example.java
Original file line number Diff line number Diff line change
@@ -1,29 +1,105 @@
package org.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.example.structs.ClassInfo;
import org.example.structs.MethodInfo;
import org.example.util.InheritanceDepthCalculator;
import org.example.util.OverrideDetector;
import org.example.visitor.ClassPrinter;
import org.objectweb.asm.ClassReader;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.io.InputStream;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Example {

public static void main(String[] args) throws IOException {
// var printer = new ByteCodePrinter();
// printer.printBubbleSortBytecode();
List<ClassInfo> allClasses = new ArrayList<>();

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);
ClassPrinter cp = new ClassPrinter(allClasses);
InputStream inputStream = sampleJar.getInputStream(entry);
ClassReader reader = new ClassReader(inputStream);
reader.accept(cp, 0);
}
}
}
getStats(allClasses);
}

private static void getStats(
List<ClassInfo> allClasses
)
throws IOException
{
int totalFields = 0;
int totalA = 0;
int totalB = 0;
int totalC = 0;
int totalOverrideMethods = 0;

OverrideDetector detector = new OverrideDetector(allClasses);
InheritanceDepthCalculator calc = new InheritanceDepthCalculator(allClasses);

Map<String, String> superMap = new HashMap<>();
for (ClassInfo classInfo : allClasses) {
superMap.put(classInfo.name, classInfo.superName);
}

for (ClassInfo classInfo : allClasses) {
totalFields += classInfo.fields.size();
for (MethodInfo m : classInfo.methods) {
totalA += m.assignments;
totalB += m.branches;
totalC += m.conditions;

if (detector.isOverride(classInfo, m)) {
totalOverrideMethods++;
}
}
}

double abcMetric = Math.sqrt(
totalA * totalA +
totalB * totalB +
totalC * totalC
);

int maxDepth = calc.getMaxDepth(allClasses);
int avgDepth = calc.getAverageDepth(allClasses);

int avgFields = !allClasses.isEmpty() ? (totalFields / allClasses.size()) : 0;
int avgOverride = !allClasses.isEmpty() ? (totalOverrideMethods / allClasses.size()) : 0;

System.out.println("Средняя глубина наследования: " + avgDepth);
System.out.println("Максимальная глубина наследования: " + maxDepth);
System.out.println("Среднее количество полей в классе: " + avgFields);
System.out.println("Среднее количество переопределнных методов: " + avgOverride);
System.out.println("Метрика ABC: " + abcMetric);

Map<String, Object> metrics = new HashMap<>();
metrics.put("averageInheritanceDepth", avgDepth);
metrics.put("maxInheritanceDepth", maxDepth);
metrics.put("averageFieldsPerClass", avgFields);
metrics.put("averageOverriddenMethods", avgOverride);
metrics.put("ABC_metric", Map.of(
"A", totalA,
"B", totalB,
"C", totalC,
"value", abcMetric
));

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
writer.writeValue(new File("results.json"), metrics);
}
}
114 changes: 114 additions & 0 deletions src/main/java/org/example/abc_visitor/AbcVisitor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package org.example.abc_visitor;

import org.example.structs.MethodInfo;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;


public class AbcVisitor extends MethodVisitor {

private final MethodInfo methodInfo;

public AbcVisitor(int api, MethodInfo methodInfo) {
super(api);
this.methodInfo = methodInfo;
}

/// ///// a-метрика
@Override
public void visitVarInsn(int opcode, int var) {
if (opcode >= Opcodes.ISTORE && opcode <= Opcodes.ASTORE) {
methodInfo.assignments++;
}
super.visitVarInsn(opcode, var);
}

@Override
public void visitIincInsn(int var, int increment) {
methodInfo.assignments++;
super.visitIincInsn(var, increment);
}

@Override
public void visitFieldInsn(int opcode, String owner, String name, String descriptor) {
if (opcode == Opcodes.PUTFIELD || opcode == Opcodes.PUTSTATIC) {
methodInfo.assignments++;
}
super.visitFieldInsn(opcode, owner, name, descriptor);
}

@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.IASTORE:
case Opcodes.LASTORE:
case Opcodes.FASTORE:
case Opcodes.DASTORE:
case Opcodes.AASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
methodInfo.assignments++;
break;
}
super.visitInsn(opcode);
}

/// //////// b-метрика
@Override
public void visitMethodInsn(
int opcode,
String owner,
String name,
String descriptor,
boolean isInterface
) {
methodInfo.branches++;
super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
}

@Override
public void visitInvokeDynamicInsn(
String name,
String descriptor,
Handle bootstrapMethodHandle,
Object... bootstrapMethodArguments
) {
methodInfo.branches++;
super.visitInvokeDynamicInsn(
name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments
);
}

/// ///////// c-метрика
@Override
public void visitJumpInsn(int opcode, Label label) {
if (opcode != Opcodes.GOTO) {
methodInfo.conditions++;
}
super.visitJumpInsn(opcode, label);
}

@Override
public void visitTableSwitchInsn(
int min,
int max,
Label dflt,
Label... labels
) {
methodInfo.conditions++;
super.visitTableSwitchInsn(min, max, dflt, labels);
}

@Override
public void visitLookupSwitchInsn(
Label dflt,
int[] keys,
Label[] labels
) {
methodInfo.conditions++;
super.visitLookupSwitchInsn(dflt, keys, labels);
}
}
12 changes: 12 additions & 0 deletions src/main/java/org/example/structs/ClassInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.example.structs;

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

public class ClassInfo {
public String name;
public String superName;
public List<String> fields = new ArrayList<>();
public List<MethodInfo> methods = new ArrayList<>();
public List<String> interfaces = new ArrayList<>();
}
10 changes: 10 additions & 0 deletions src/main/java/org/example/structs/MethodInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.example.structs;

public class MethodInfo {
public String name;
public boolean isOverride = false;
public int assignments = 0;
public String desc;
public int conditions;
public int branches;
}
49 changes: 49 additions & 0 deletions src/main/java/org/example/util/InheritanceDepthCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.example.util;

import org.example.structs.ClassInfo;

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

public class InheritanceDepthCalculator {

private final Map<String, String> superMap = new HashMap<>();

public InheritanceDepthCalculator(List<ClassInfo> allClasses) {
for (ClassInfo classInfo : allClasses) {
superMap.put(classInfo.name, classInfo.superName);
}
}

public int getDepth(ClassInfo cls) {
int depth = 0;
String parent = cls.superName;

while (parent != null && !parent.equals("java/lang/Object")) {
depth++;
parent = superMap.get(parent);
}

return depth;
}

public int getMaxDepth(List<ClassInfo> classes) {
int max = 0;
for (ClassInfo cls : classes) {
int d = getDepth(cls);
if (d > max) max = d;
}
return max;
}

public int getAverageDepth(List<ClassInfo> classes) {
if (classes.isEmpty()) return 0;

int sum = 0;
for (ClassInfo cls : classes) {
sum += getDepth(cls);
}
return sum / classes.size();
}
}
58 changes: 58 additions & 0 deletions src/main/java/org/example/util/OverrideDetector.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.example.util;

import org.example.structs.ClassInfo;
import org.example.structs.MethodInfo;

import java.util.List;

public class OverrideDetector {

private final List<ClassInfo> classes;

public OverrideDetector(List<ClassInfo> classes) {
this.classes = classes;
}

public boolean isOverride(ClassInfo cls, MethodInfo method) {
if (checkSuperclass(cls.superName, method)) return true;

for (String iface : cls.interfaces) {
if (checkInterface(iface, method)) return true;
}

return false;
}

private boolean checkSuperclass(String parent, MethodInfo method) {
while (parent != null && !parent.equals("java/lang/Object")) {
ClassInfo parentClass = findClass(parent);
if (parentClass == null) return false;

if (containsMethod(parentClass, method)) {
return true;
}

parent = parentClass.superName;
}
return false;
}

private boolean checkInterface(String iface, MethodInfo method) {
ClassInfo ifaceClass = findClass(iface);
if (ifaceClass == null) return false;

return containsMethod(ifaceClass, method);
}

private boolean containsMethod(ClassInfo cls, MethodInfo m) {
return cls.methods.stream()
.anyMatch(pm -> pm.name.equals(m.name) && pm.desc.equals(m.desc));
}

private ClassInfo findClass(String internalName) {
return classes.stream()
.filter(c -> c.name.equals(internalName))
.findFirst()
.orElse(null);
}
}
Loading