Fix most leaks

This commit is contained in:
Nico Mexis 2021-07-25 18:54:08 +02:00
parent 932d135ceb
commit 308f167553
No known key found for this signature in database
GPG Key ID: 27D6E17CE092AB78
37 changed files with 650 additions and 716 deletions

View File

@ -28,16 +28,17 @@ public class DiskReader {
if (!map.containsKey(fileName)) { if (!map.containsKey(fileName)) {
try { try {
File file = new File(fileName); File file = new File(fileName);
if (!file.exists()) // doesnt exist, return empty if (!file.exists()) // doesn't exist, return empty
return array; return array;
BufferedReader reader = new BufferedReader(new FileReader(file)); try (FileReader fr = new FileReader(file);
String add; BufferedReader reader = new BufferedReader(fr)) {
String add;
while ((add = reader.readLine()) != null) while ((add = reader.readLine()) != null)
array.add(add); array.add(add);
reader.close(); }
if (cache) if (cache)
map.put(fileName, array); map.put(fileName, array);
@ -58,14 +59,13 @@ public class DiskReader {
public synchronized static String loadAsString(String fileName) throws Exception { public synchronized static String loadAsString(String fileName) throws Exception {
StringBuilder s = new StringBuilder(); StringBuilder s = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(fileName)); try (FileReader fr = new FileReader(fileName);
BufferedReader reader = new BufferedReader(fr)) {
for (String add = reader.readLine(); add != null; add = reader.readLine()) { for (String add = reader.readLine(); add != null; add = reader.readLine()) {
s.append(EncodeUtils.unicodeToString(add)).append(System.getProperty("line.separator")); s.append(EncodeUtils.unicodeToString(add)).append(System.getProperty("line.separator"));
}
} }
reader.close();
return s.toString(); return s.toString();
} }
@ -80,13 +80,13 @@ public class DiskReader {
array = new ArrayList<>(); array = new ArrayList<>();
File file = new File(fileName); File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file)); try (FileReader fr = new FileReader(file);
String add; BufferedReader reader = new BufferedReader(fr)) {
String add;
while ((add = reader.readLine()) != null) while ((add = reader.readLine()) != null)
array.add(add); array.add(add);
}
reader.close();
if (cache) if (cache)
map.put(fileName, array); map.put(fileName, array);

View File

@ -48,7 +48,6 @@ public class DiskWriter {
public static synchronized void writeNewLine(String filename, public static synchronized void writeNewLine(String filename,
byte[] fileContents, boolean debug) { byte[] fileContents, boolean debug) {
new File(filename).getParentFile().mkdirs(); new File(filename).getParentFile().mkdirs();
PrintWriter writer = null;
String original = filename; String original = filename;
int counter = 0; int counter = 0;
@ -56,9 +55,9 @@ public class DiskWriter {
int failSafe = 0; int failSafe = 0;
while (!saved && failSafe++ <= 42069) while (!saved && failSafe++ <= 42069)
{ {
try { try (FileWriter fr = new FileWriter(filename, true);
writer = new PrintWriter(new BufferedWriter(new FileWriter( BufferedWriter bw = new BufferedWriter(fr);
filename, true))); PrintWriter writer = new PrintWriter(bw)) {
writer.println(Arrays.toString(fileContents)); writer.println(Arrays.toString(fileContents));
if (debug) if (debug)
System.out.println("Saved " + filename + " to disk"); System.out.println("Saved " + filename + " to disk");
@ -74,7 +73,6 @@ public class DiskWriter {
counter++; counter++;
} }
} }
writer.close();
} }
/** /**
@ -91,7 +89,6 @@ public class DiskWriter {
public static synchronized void writeNewLine(String filename, public static synchronized void writeNewLine(String filename,
String lineToWrite, boolean debug) { String lineToWrite, boolean debug) {
new File(filename).getParentFile().mkdirs(); new File(filename).getParentFile().mkdirs();
PrintWriter writer = null;
String original = filename; String original = filename;
int counter = 0; int counter = 0;
@ -99,9 +96,9 @@ public class DiskWriter {
int failSafe = 0; int failSafe = 0;
while (!saved && failSafe++ <= 42069) while (!saved && failSafe++ <= 42069)
{ {
try { try (FileWriter fr = new FileWriter(filename, true);
writer = new PrintWriter(new BufferedWriter(new FileWriter( BufferedWriter bw = new BufferedWriter(fr);
filename, true))); PrintWriter writer = new PrintWriter(bw)) {
writer.println(lineToWrite); writer.println(lineToWrite);
if (debug) if (debug)
System.out.println("Saved " + filename + ">" + lineToWrite System.out.println("Saved " + filename + ">" + lineToWrite
@ -118,7 +115,6 @@ public class DiskWriter {
counter++; counter++;
} }
} }
writer.close();
} }
/** /**
@ -143,7 +139,7 @@ public class DiskWriter {
int failSafe = 0; int failSafe = 0;
while (!saved && failSafe++ <= 42069) while (!saved && failSafe++ <= 42069)
{ {
try(FileOutputStream stream = new FileOutputStream(new File(filename))) try (FileOutputStream stream = new FileOutputStream(filename))
{ {
stream.write(fileContents); stream.write(fileContents);
stream.flush(); stream.flush();
@ -177,7 +173,6 @@ public class DiskWriter {
File f = new File(filename); File f = new File(filename);
if (f.exists()) if (f.exists())
f.delete(); f.delete();
PrintWriter writer = null;
String original = filename; String original = filename;
int counter = 0; int counter = 0;
@ -185,9 +180,9 @@ public class DiskWriter {
int failSafe = 0; int failSafe = 0;
while (!saved && failSafe++ <= 42069) while (!saved && failSafe++ <= 42069)
{ {
try { try (FileWriter fr = new FileWriter(filename, true);
writer = new PrintWriter(new BufferedWriter(new FileWriter( BufferedWriter bw = new BufferedWriter(fr);
filename, true))); PrintWriter writer = new PrintWriter(bw)) {
writer.println(lineToWrite); writer.println(lineToWrite);
if (debug) if (debug)
System.out.println("Saved " + filename + ">" + lineToWrite System.out.println("Saved " + filename + ">" + lineToWrite
@ -204,7 +199,6 @@ public class DiskWriter {
counter++; counter++;
} }
} }
writer.close();
} }
} }

View File

@ -97,7 +97,7 @@ public class HTTPRequest {
} }
/** /**
* By default follow redirects are enabled * By default, follow redirects are enabled
*/ */
public void setFollowRedirects(boolean setFollowRedirects) { public void setFollowRedirects(boolean setFollowRedirects) {
this.setFollowRedirects = setFollowRedirects; this.setFollowRedirects = setFollowRedirects;

View File

@ -102,34 +102,32 @@ public class BCV
try try
{ {
File f = new File(tempDirectory + fs + MiscUtils.randomString(12) + "loaded_temp.jar"); File f = new File(tempDirectory + fs + MiscUtils.randomString(12) + "loaded_temp.jar");
List<Class<?>> ret = new ArrayList<>();
JarUtils.saveAsJar(BCV.getLoadedClasses(), f.getAbsolutePath()); JarUtils.saveAsJar(BCV.getLoadedClasses(), f.getAbsolutePath());
JarFile jarFile = new JarFile("" + f.getAbsolutePath()); try (JarFile jarFile = new JarFile("" + f.getAbsolutePath())) {
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = {new URL("jar:file:" + "" + f.getAbsolutePath() + "!/")};
cl = URLClassLoader.newInstance(urls);
List<Class<?>> ret = new ArrayList<>();
while (e.hasMoreElements()) Enumeration<JarEntry> e = jarFile.entries();
{ URL[] urls = {new URL("jar:file:" + "" + f.getAbsolutePath() + "!/")};
JarEntry je = e.nextElement();
cl = URLClassLoader.newInstance(urls);
if (je.isDirectory() || !je.getName().endsWith(".class"))
continue; while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
String className = je.getName().replace("/", ".").replace(".class", "");
className = className.replace('/', '.'); if (je.isDirectory() || !je.getName().endsWith(".class"))
continue;
try {
ret.add(cl.loadClass(className)); String className = je.getName().replace("/", ".").replace(".class", "");
} catch (Exception classLoadException) { className = className.replace('/', '.');
the.bytecode.club.bytecodeviewer.BytecodeViewer.handleException(classLoadException);
try {
ret.add(cl.loadClass(className));
} catch (Exception classLoadException) {
the.bytecode.club.bytecodeviewer.BytecodeViewer.handleException(classLoadException);
}
} }
} }
jarFile.close();
return ret; return ret;
} catch (Exception e) { } catch (Exception e) {

View File

@ -1,6 +1,7 @@
package the.bytecode.club.bytecodeviewer.api; package the.bytecode.club.bytecodeviewer.api;
import java.awt.*; import java.awt.*;
import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import javax.swing.JFrame; import javax.swing.JFrame;
@ -93,11 +94,14 @@ public class ExceptionUI extends JFrameConsole
return; return;
} }
StringWriter sw = new StringWriter(); try (StringWriter sw = new StringWriter();
error.printStackTrace(new PrintWriter(sw)); PrintWriter pw = new PrintWriter(sw)) {
error.printStackTrace(); error.printStackTrace(pw);
error.printStackTrace();
setupFrame(sw.toString(), author);
setupFrame(sw.toString(), author);
} catch (IOException ignored) {
}
} }
/** /**

View File

@ -121,11 +121,9 @@ public class Boot {
setState("Bytecode Viewer Boot Screen - Downloading " + fileName + "..."); setState("Bytecode Viewer Boot Screen - Downloading " + fileName + "...");
System.out.println("Downloading " + fileName); System.out.println("Downloading " + fileName);
InputStream is = null; try (InputStream is = new URL("https://github.com/Konloch/bytecode-viewer/raw/master/libs/" + fileName)
FileOutputStream fos = null; .openConnection().getInputStream();
try { FileOutputStream fos = new FileOutputStream(file)) {
is = new URL("https://github.com/Konloch/bytecode-viewer/raw/master/libs/" + fileName).openConnection().getInputStream();
fos = new FileOutputStream(file);
System.out.println("Downloading from " + s); System.out.println("Downloading from " + s);
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
int len; int len;
@ -143,19 +141,6 @@ public class Boot {
} else } else
flag = false; flag = false;
} }
} finally {
try {
if (is != null) {
is.close();
}
} finally {
if (fos != null) {
fos.flush();
}
if (fos != null) {
fos.close();
}
}
} }
try { try {
@ -233,7 +218,7 @@ public class Boot {
try { try {
ExternalResource res = new EmptyExternalResource<>(f.toURI().toURL()); ExternalResource res = new EmptyExternalResource<>(f.toURI().toURL());
loader.bind(res); loader.bind(res);
System.out.println("Succesfully loaded " + f.getName()); System.out.println("Successfully loaded " + f.getName());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
f.delete(); f.delete();
@ -314,24 +299,22 @@ public class Boot {
setState("Bytecode Viewer Boot Screen - Extracting Krakatau"); setState("Bytecode Viewer Boot Screen - Extracting Krakatau");
System.out.println("Extracting Krakatau"); System.out.println("Extracting Krakatau");
try {
while (temp.exists()) while (temp.exists())
temp.delete(); temp.delete();
InputStream is = BytecodeViewer.class.getClassLoader().getResourceAsStream("Krakatau-" + Constants.krakatauVersion + ".zip");
FileOutputStream baos = new FileOutputStream(temp);
try (InputStream is = BytecodeViewer.class.getClassLoader().getResourceAsStream("Krakatau-"
+ Constants.krakatauVersion + ".zip");
FileOutputStream baos = new FileOutputStream(temp)) {
int r; int r;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
while ((r = Objects.requireNonNull(is).read(buffer)) >= 0) { while ((r = Objects.requireNonNull(is).read(buffer)) >= 0) {
baos.write(buffer, 0, r); baos.write(buffer, 0, r);
} }
baos.close();
ZipUtils.unzipFilesToPath(temp.getAbsolutePath(), krakatauDirectory.getAbsolutePath()); ZipUtils.unzipFilesToPath(temp.getAbsolutePath(), krakatauDirectory.getAbsolutePath());
temp.delete(); temp.delete();
System.out.println("Succesfully extracted Krakatau"); System.out.println("Successfully extracted Krakatau");
} catch (Exception e) { } catch (Exception e) {
setState("Bytecode Viewer Boot Screen - ERROR, please contact @Konloch with your stacktrace."); setState("Bytecode Viewer Boot Screen - ERROR, please contact @Konloch with your stacktrace.");
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
@ -349,25 +332,22 @@ public class Boot {
setState("Bytecode Viewer Boot Screen - Extracting Enjarify"); setState("Bytecode Viewer Boot Screen - Extracting Enjarify");
System.out.println("Extracting Enjarify"); System.out.println("Extracting Enjarify");
try {
while (temp.exists())
temp.delete();
InputStream is = while (temp.exists())
BytecodeViewer.class.getClassLoader().getResourceAsStream("enjarify-" + Constants.enjarifyVersion + ".zip"); temp.delete();
FileOutputStream baos = new FileOutputStream(temp);
try (InputStream is = BytecodeViewer.class.getClassLoader().getResourceAsStream("enjarify-" +
Constants.enjarifyVersion + ".zip");
FileOutputStream baos = new FileOutputStream(temp)) {
int r; int r;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
while ((r = Objects.requireNonNull(is).read(buffer)) >= 0) { while ((r = Objects.requireNonNull(is).read(buffer)) >= 0) {
baos.write(buffer, 0, r); baos.write(buffer, 0, r);
} }
baos.close();
ZipUtils.unzipFilesToPath(temp.getAbsolutePath(), enjarifyDirectory.getAbsolutePath()); ZipUtils.unzipFilesToPath(temp.getAbsolutePath(), enjarifyDirectory.getAbsolutePath());
temp.delete(); temp.delete();
System.out.println("Succesfully extracted Enjarify"); System.out.println("Successfully extracted Enjarify");
} catch (Exception e) { } catch (Exception e) {
setState("Bytecode Viewer Boot Screen - ERROR, please contact @Konloch with your stacktrace."); setState("Bytecode Viewer Boot Screen - ERROR, please contact @Konloch with your stacktrace.");
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
@ -388,11 +368,9 @@ public class Boot {
setState("Bytecode Viewer Boot Screen - Downloading " + fileName + "..."); setState("Bytecode Viewer Boot Screen - Downloading " + fileName + "...");
System.out.println("Downloading " + fileName); System.out.println("Downloading " + fileName);
InputStream is = null; try (InputStream is = new URL("https://github.com/Konloch/bytecode-viewer/raw/master/libs/" + fileName)
FileOutputStream fos = null; .openConnection().getInputStream();
try { FileOutputStream fos = new FileOutputStream(file)) {
is = new URL("https://github.com/Konloch/bytecode-viewer/raw/master/libs/" + fileName).openConnection().getInputStream();
fos = new FileOutputStream(file);
System.out.println("Downloading from " + s); System.out.println("Downloading from " + s);
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
int len; int len;
@ -412,19 +390,6 @@ public class Boot {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} finally {
if (fos != null) {
fos.flush();
}
if (fos != null) {
fos.close();
}
}
} }
try { try {

View File

@ -260,12 +260,9 @@ public class UpdateCheck implements Runnable
BCV.log("Downloading from: " + url); BCV.log("Downloading from: " + url);
BytecodeViewer.showMessage("Downloading the jar in the background, when it's finished you will be alerted with another message box." BytecodeViewer.showMessage("Downloading the jar in the background, when it's finished you will be alerted with another message box."
+ nl + nl + "Expect this to take several minutes."); + nl + nl + "Expect this to take several minutes.");
InputStream is = new URL(url).openConnection().getInputStream(); try (InputStream is = new URL(url).openConnection().getInputStream();
FileOutputStream fos = new FileOutputStream(saveTo); FileOutputStream fos = new FileOutputStream(saveTo)) {
try
{
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
int len; int len;
int downloaded = 0; int downloaded = 0;
@ -286,14 +283,6 @@ public class UpdateCheck implements Runnable
} else } else
flag = false; flag = false;
} }
} finally {
try {
if (is != null)
is.close();
} finally {
fos.flush();
fos.close();
}
} }
BCV.log("Download finished!"); BCV.log("Download finished!");

View File

@ -63,13 +63,13 @@ public class ExternalLibrary extends ExternalResource<JarContents<ClassNode>> {
} }
public static byte[] read(InputStream in) throws IOException { public static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); try (ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int bytesRead; int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) while ((bytesRead = in.read(buffer)) != -1)
byteArrayOut.write(buffer, 0, bytesRead); byteArrayOut.write(buffer, 0, bytesRead);
byteArrayOut.close(); return byteArrayOut.toByteArray();
return byteArrayOut.toByteArray(); }
} }
protected ClassNode create(byte[] b) { protected ClassNode create(byte[] b) {
@ -92,13 +92,15 @@ public class ExternalLibrary extends ExternalResource<JarContents<ClassNode>> {
Enumeration<JarEntry> entries = jar.entries(); Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) { while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement(); JarEntry entry = entries.nextElement();
byte[] bytes = read(jar.getInputStream(entry)); try (InputStream is = jar.getInputStream(entry)) {
if (entry.getName().endsWith(".class")) { byte[] bytes = read(is);
ClassNode cn = create(bytes); if (entry.getName().endsWith(".class")) {
contents.getClassContents().add(cn); ClassNode cn = create(bytes);
} else { contents.getClassContents().add(cn);
JarResource resource = new JarResource(entry.getName(), bytes); } else {
contents.getResourceContents().add(resource); JarResource resource = new JarResource(entry.getName(), bytes);
contents.getResourceContents().add(resource);
}
} }
} }

View File

@ -114,27 +114,24 @@ public class JavaCompiler extends InternalCompiler
int exitValue = process.waitFor(); int exitValue = process.waitFor();
//Read out dir output //Read out dir output
InputStream is = process.getInputStream(); try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr)) {
String line; String line;
while ((line = br.readLine()) != null)
while ((line = br.readLine()) != null) log.append(nl).append(line);
log.append(nl).append(line); }
br.close();
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl); log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
is = process.getErrorStream(); try (InputStream is = process.getErrorStream();
isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) while ((line = br.readLine()) != null)
log.append(nl).append(line); log.append(nl).append(line);
}
br.close();
log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS + " ").append(exitValue); log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue);
System.out.println(log); System.out.println(log);
if (!clazz.exists()) if (!clazz.exists())

View File

@ -84,28 +84,25 @@ public class KrakatauAssembler extends InternalCompiler
BytecodeViewer.createdProcesses.add(process); BytecodeViewer.createdProcesses.add(process);
//Read out dir output //Read out dir output
InputStream is = process.getInputStream(); try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr)) {
String line; String line;
while ((line = br.readLine()) != null)
while ((line = br.readLine()) != null) log.append(nl).append(line);
log.append(nl).append(line); }
br.close();
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl); log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
is = process.getErrorStream(); try (InputStream is = process.getErrorStream();
isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) while ((line = br.readLine()) != null)
log.append(nl).append(line); log.append(nl).append(line);
}
br.close();
int exitValue = process.waitFor(); int exitValue = process.waitFor();
log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS + " ").append(exitValue); log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue);
System.err.println(log); System.err.println(log);
byte[] b = FileUtils.readFileToByteArray(Objects.requireNonNull( byte[] b = FileUtils.readFileToByteArray(Objects.requireNonNull(

View File

@ -70,7 +70,7 @@ public class InstructionPrinter {
protected List<AbstractInsnNode> matchedInsns; protected List<AbstractInsnNode> matchedInsns;
protected Map<LabelNode, Integer> labels; protected Map<LabelNode, Integer> labels;
private boolean firstLabel = false; private boolean firstLabel = false;
private ArrayList<String> info = new ArrayList<>(); private final ArrayList<String> info = new ArrayList<>();
public InstructionPrinter(MethodNode m, TypeAndName[] args) { public InstructionPrinter(MethodNode m, TypeAndName[] args) {
this.args = args; this.args = args;
@ -103,15 +103,13 @@ public class InstructionPrinter {
public ArrayList<String> createPrint() { public ArrayList<String> createPrint() {
firstLabel = false; firstLabel = false;
info.clear(); info.clear();
ListIterator<?> it = mNode.instructions.iterator(); for (AbstractInsnNode ain : mNode.instructions) {
while (it.hasNext()) {
AbstractInsnNode ain = (AbstractInsnNode) it.next();
String line = printInstruction(ain); String line = printInstruction(ain);
if (!line.isEmpty()) { if (!line.isEmpty()) {
if (match) if (match)
if (matchedInsns.contains(ain)) if (matchedInsns.contains(ain))
line = " -> " + line; line = " -> " + line;
info.add(line); info.add(line);
} }
} }
@ -382,13 +380,12 @@ public class InstructionPrinter {
} }
public static void saveTo(File file, InstructionPrinter printer) { public static void saveTo(File file, InstructionPrinter printer) {
try { try (FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(new FileWriter(file)); BufferedWriter bw = new BufferedWriter(fw)) {
for (String s : printer.createPrint()) { for (String s : printer.createPrint()) {
bw.write(s); bw.write(s);
bw.newLine(); bw.newLine();
} }
bw.close();
} catch (IOException e) { } catch (IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }

View File

@ -1,6 +1,5 @@
package the.bytecode.club.bytecodeviewer.decompilers.impl; package the.bytecode.club.bytecodeviewer.decompilers.impl;
import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -96,12 +95,8 @@ public class CFRDecompiler extends InternalDecompiler
//final File tempClass = new File(windowsFun(MiscUtils.getUniqueName(fileStart, ".class") + ".class")); //final File tempClass = new File(windowsFun(MiscUtils.getUniqueName(fileStart, ".class") + ".class"));
final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class"); final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class");
try { try (FileOutputStream fos = new FileOutputStream(tempClass)) {
final FileOutputStream fos = new FileOutputStream(tempClass);
fos.write(b); fos.write(b);
fos.close();
} catch (final IOException e) { } catch (final IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }
@ -319,15 +314,12 @@ public class CFRDecompiler extends InternalDecompiler
} }
@SuppressWarnings("resource") @SuppressWarnings("resource")
public void zip(File directory, File zipfile) throws IOException { public void zip(File directory, File zipFile) throws IOException {
java.net.URI base = directory.toURI(); java.net.URI base = directory.toURI();
Deque<File> queue = new LinkedList<>(); Deque<File> queue = new LinkedList<>();
queue.push(directory); queue.push(directory);
OutputStream out = new FileOutputStream(zipfile); try (OutputStream out = new FileOutputStream(zipFile);
Closeable res = out; ZipOutputStream zout = new ZipOutputStream(out)) {
try {
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
directory = queue.pop(); directory = queue.pop();
for (File kid : MiscUtils.listFiles(directory)) { for (File kid : MiscUtils.listFiles(directory)) {
@ -343,9 +335,6 @@ public class CFRDecompiler extends InternalDecompiler
} }
} }
} }
} finally {
res.close();
out.close();
} }
} }

View File

@ -6,10 +6,8 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import me.konloch.kontainer.io.DiskReader; import me.konloch.kontainer.io.DiskReader;
import org.apache.commons.lang3.ArrayUtils;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
import the.bytecode.club.bytecodeviewer.BytecodeViewer; import the.bytecode.club.bytecodeviewer.BytecodeViewer;
import the.bytecode.club.bytecodeviewer.resources.ExternalResources;
import the.bytecode.club.bytecodeviewer.api.ExceptionUI; import the.bytecode.club.bytecodeviewer.api.ExceptionUI;
import the.bytecode.club.bytecodeviewer.decompilers.InternalDecompiler; import the.bytecode.club.bytecodeviewer.decompilers.InternalDecompiler;
import the.bytecode.club.bytecodeviewer.translation.TranslatedStrings; import the.bytecode.club.bytecodeviewer.translation.TranslatedStrings;
@ -72,10 +70,8 @@ public class FernFlowerDecompiler extends InternalDecompiler
final File tempClass = new File(start + ".class"); final File tempClass = new File(start + ".class");
String exception = ""; String exception = "";
try { try (FileOutputStream fos = new FileOutputStream(tempClass)) {
final FileOutputStream fos = new FileOutputStream(tempClass);
fos.write(b); fos.write(b);
fos.close();
} catch (final IOException e) { } catch (final IOException e) {
StringWriter exceptionWriter = new StringWriter(); StringWriter exceptionWriter = new StringWriter();
e.printStackTrace(new PrintWriter(exceptionWriter)); e.printStackTrace(new PrintWriter(exceptionWriter));

View File

@ -7,7 +7,6 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Objects;
import java.util.Random; import java.util.Random;
import me.konloch.kontainer.io.DiskReader; import me.konloch.kontainer.io.DiskReader;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
@ -45,8 +44,7 @@ import static the.bytecode.club.bytecodeviewer.translation.TranslatedStrings.*;
*/ */
public class JADXDecompiler extends InternalDecompiler public class JADXDecompiler extends InternalDecompiler
{ {
private Random r = new Random(); private final Random r = new Random();
private File f;
@Override @Override
public String decompileClassNode(ClassNode cn, byte[] b) { public String decompileClassNode(ClassNode cn, byte[] b) {
@ -55,10 +53,8 @@ public class JADXDecompiler extends InternalDecompiler
String exception = ""; String exception = "";
final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class"); final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class");
try { try (FileOutputStream fos = new FileOutputStream(tempClass)) {
final FileOutputStream fos = new FileOutputStream(tempClass);
fos.write(b); fos.write(b);
fos.close();
} catch (final IOException e) { } catch (final IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }
@ -75,7 +71,6 @@ public class JADXDecompiler extends InternalDecompiler
JadxDecompiler jadx = new JadxDecompiler(args); JadxDecompiler jadx = new JadxDecompiler(args);
jadx.load(); jadx.load();
jadx.saveSources(); jadx.saveSources();
//jadx.close();
} catch (StackOverflowError | Exception e) { } catch (StackOverflowError | Exception e) {
StringWriter exceptionWriter = new StringWriter(); StringWriter exceptionWriter = new StringWriter();
e.printStackTrace(new PrintWriter(exceptionWriter)); e.printStackTrace(new PrintWriter(exceptionWriter));
@ -102,7 +97,7 @@ public class JADXDecompiler extends InternalDecompiler
int failSafe = 0; int failSafe = 0;
while (failSafe++ <= 42069) while (failSafe++ <= 42069)
{ {
f = new File(start + r.nextInt(Integer.MAX_VALUE)); File f = new File(start + r.nextInt(Integer.MAX_VALUE));
if (!f.exists()) if (!f.exists())
return f.toString(); return f.toString();
} }

View File

@ -72,10 +72,8 @@ public class JDGUIDecompiler extends InternalDecompiler
} }
} }
try { try (FileOutputStream fos = new FileOutputStream(tempClass)) {
final FileOutputStream fos = new FileOutputStream(tempClass);
fos.write(b); fos.write(b);
fos.close();
} catch (final IOException e) { } catch (final IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }
@ -101,16 +99,14 @@ public class JDGUIDecompiler extends InternalDecompiler
//PrintStream ps = new PrintStream("test.html"); //PrintStream ps = new PrintStream("test.html");
//HtmlPrinter printer = new HtmlPrinter(ps); //HtmlPrinter printer = new HtmlPrinter(ps);
PrintStream ps = new PrintStream(tempJava.getAbsolutePath());
PlainTextPrinter printer = new PlainTextPrinter(preferences, ps);
org.jd.core.v1.api.Decompiler decompiler = new ClassFileToJavaSourceDecompiler(); org.jd.core.v1.api.Decompiler decompiler = new ClassFileToJavaSourceDecompiler();
decompiler.decompile(loader, printer, internalPath, preferences.getPreferences());
String decompiledSource; try (PrintStream ps = new PrintStream(tempJava.getAbsolutePath());
decompiledSource = DiskReader.loadAsString(tempJava.getAbsolutePath()); PlainTextPrinter printer = new PlainTextPrinter(preferences, ps)) {
decompiler.decompile(loader, printer, internalPath, preferences.getPreferences());
}
return decompiledSource; return DiskReader.loadAsString(tempJava.getAbsolutePath());
} catch (Exception e) { } catch (Exception e) {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw)); e.printStackTrace(new PrintWriter(sw));

View File

@ -112,28 +112,31 @@ public class KrakatauDecompiler extends InternalDecompiler
Process process = pb.start(); Process process = pb.start();
BytecodeViewer.createdProcesses.add(process); BytecodeViewer.createdProcesses.add(process);
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + nl + nl); StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + nl + nl);
String line;
while ((line = br.readLine()) != null) { //Read out dir output
log.append(nl).append(line); try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
}
} }
br.close();
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl); log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
is = process.getErrorStream();
isr = new InputStreamReader(is); try (InputStream is = process.getErrorStream();
br = new BufferedReader(isr); InputStreamReader isr = new InputStreamReader(is);
while ((line = br.readLine()) != null) { BufferedReader br = new BufferedReader(isr)) {
log.append(nl).append(line); String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
}
} }
br.close();
int exitValue = process.waitFor(); int exitValue = process.waitFor();
log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS + " ").append(exitValue); log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue);
s = log.toString(); s = log.toString();
//if the motherfucker failed this'll fail, aka wont set. //if the motherfucker failed this'll fail, aka wont set.
@ -196,26 +199,28 @@ public class KrakatauDecompiler extends InternalDecompiler
Process process = pb.start(); Process process = pb.start();
BytecodeViewer.createdProcesses.add(process); BytecodeViewer.createdProcesses.add(process);
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + nl + nl); StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + nl + nl);
String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
}
br.close();
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl) //Read out dir output
.append(nl); try (InputStream is = process.getInputStream();
is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is);
isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
br = new BufferedReader(isr); String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
log.append(nl).append(line); log.append(nl).append(line);
}
}
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
try (InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
}
} }
br.close();
int exitValue = process.waitFor(); int exitValue = process.waitFor();
log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS + " ").append(exitValue); log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS + " ").append(exitValue);

View File

@ -79,31 +79,34 @@ public class KrakatauDisassembler extends InternalDecompiler
Process process = pb.start(); Process process = pb.start();
BytecodeViewer.createdProcesses.add(process); BytecodeViewer.createdProcesses.add(process);
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + nl + nl); StringBuilder log = new StringBuilder(TranslatedStrings.PROCESS2 + nl + nl);
String line;
while ((line = br.readLine()) != null) { //Read out dir output
log.append(nl).append(line); try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
}
} }
br.close();
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl); log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
is = process.getErrorStream();
isr = new InputStreamReader(is); try (InputStream is = process.getErrorStream();
br = new BufferedReader(isr); InputStreamReader isr = new InputStreamReader(is);
while ((line = br.readLine()) != null) { BufferedReader br = new BufferedReader(isr)) {
log.append(nl).append(line); String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
}
} }
br.close();
int exitValue = process.waitFor(); int exitValue = process.waitFor();
log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS + " ").append(exitValue); log.append(nl).append(nl).append(TranslatedStrings.EXIT_VALUE_IS).append(" ").append(exitValue);
s = log.toString(); s = log.toString();
//if the motherfucker failed this'll fail, aka wont set. // if the motherfucker failed this'll fail, aka won't set.
s = DiskReader.loadAsString(tempDirectory.getAbsolutePath() + fs + cn.name + ".j"); s = DiskReader.loadAsString(tempDirectory.getAbsolutePath() + fs + cn.name + ".j");
} catch (Exception e) { } catch (Exception e) {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();

View File

@ -96,12 +96,8 @@ public class ProcyonDecompiler extends InternalDecompiler
final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class"); final File tempClass = new File(MiscUtils.getUniqueName(fileStart, ".class") + ".class");
try { try (FileOutputStream fos = new FileOutputStream(tempClass)) {
final FileOutputStream fos = new FileOutputStream(tempClass);
fos.write(b); fos.write(b);
fos.close();
} catch (final IOException e) { } catch (final IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }
@ -185,11 +181,12 @@ public class ProcyonDecompiler extends InternalDecompiler
|| ((resolvedType = type.resolve()) == null)) { || ((resolvedType = type.resolve()) == null)) {
throw new Exception("Unable to resolve type."); throw new Exception("Unable to resolve type.");
} }
Writer writer = new OutputStreamWriter(out); try (Writer writer = new OutputStreamWriter(out)) {
settings.getLanguage().decompileType(resolvedType, settings.getLanguage().decompileType(resolvedType,
new PlainTextOutput(writer), new PlainTextOutput(writer),
decompilationOptions); decompilationOptions);
writer.flush(); writer.flush();
}
} finally { } finally {
out.closeEntry(); out.closeEntry();
} }
@ -201,16 +198,11 @@ public class ProcyonDecompiler extends InternalDecompiler
continue; continue;
history.add(etn); history.add(etn);
out.putNextEntry(etn); out.putNextEntry(etn);
try { try (InputStream in = jfile.getInputStream(entry)) {
InputStream in = jfile.getInputStream(entry);
if (in != null) { if (in != null) {
try { int count;
int count; while ((count = in.read(data, 0, 1024)) != -1) {
while ((count = in.read(data, 0, 1024)) != -1) { out.write(data, 0, count);
out.write(data, 0, count);
}
} finally {
in.close();
} }
} }
} finally { } finally {
@ -239,7 +231,7 @@ public class ProcyonDecompiler extends InternalDecompiler
_typeLoaders.add(new InputTypeLoader()); _typeLoaders.add(new InputTypeLoader());
} }
public final List<ITypeLoader> getTypeLoaders() { public List<ITypeLoader> getTypeLoaders() {
return _typeLoaders; return _typeLoaders;
} }

View File

@ -57,12 +57,8 @@ public class SmaliDisassembler extends InternalDecompiler
final File tempDex = new File(start + ".dex"); final File tempDex = new File(start + ".dex");
final File tempSmali = new File(start + "-smali"); //output directory final File tempSmali = new File(start + "-smali"); //output directory
try { try (FileOutputStream fos = new FileOutputStream(tempClass)) {
final FileOutputStream fos = new FileOutputStream(tempClass);
fos.write(b); fos.write(b);
fos.close();
} catch (final IOException e) { } catch (final IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }

View File

@ -4,7 +4,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class CommonPreferences { public class CommonPreferences {
private Map<String, Object> preferences; private final Map<String, Object> preferences;
protected boolean showDefaultConstructor; protected boolean showDefaultConstructor;
protected boolean realignmentLineNumber; protected boolean realignmentLineNumber;
protected boolean showPrefixThis; protected boolean showPrefixThis;

View File

@ -29,9 +29,9 @@ public class DirectoryLoader implements Loader
throws LoaderException { throws LoaderException {
File file = new File(this.codebase, internalPath); File file = new File(this.codebase, internalPath);
try { try (FileInputStream fis = new FileInputStream(file);
return IOUtils.toByteArray( BufferedInputStream bis = new BufferedInputStream(fis)) {
new BufferedInputStream(new FileInputStream(file))); return IOUtils.toByteArray(bis);
} catch (IOException e) { } catch (IOException e) {
throw new LoaderException( throw new LoaderException(
"'" + file.getAbsolutePath() + "' not found."); "'" + file.getAbsolutePath() + "' not found.");

View File

@ -23,14 +23,11 @@ public class JDGUIClassFileUtil
* repoertoire de base. * repoertoire de base.
*/ */
public static String ExtractDirectoryPath(String pathToClass) { public static String ExtractDirectoryPath(String pathToClass) {
DataInputStream dis = null;
String directoryPath; String directoryPath;
try { try (FileInputStream fis = new FileInputStream(pathToClass);
dis = new DataInputStream( BufferedInputStream bis = new BufferedInputStream(fis);
new BufferedInputStream( DataInputStream dis = new DataInputStream(bis)) {
new FileInputStream(pathToClass)));
int magic = dis.readInt(); int magic = dis.readInt();
if (magic != ClassFileReader.JAVA_MAGIC_NUMBER) if (magic != ClassFileReader.JAVA_MAGIC_NUMBER)
throw new ClassFileFormatException("Invalid Java .class file"); throw new ClassFileFormatException("Invalid Java .class file");
@ -71,12 +68,6 @@ public class JDGUIClassFileUtil
} catch (IOException e) { } catch (IOException e) {
directoryPath = null; directoryPath = null;
e.printStackTrace(); e.printStackTrace();
} finally {
if (dis != null)
try {
dis.close();
} catch (IOException ignored) {
}
} }
return directoryPath; return directoryPath;

View File

@ -1,10 +1,12 @@
package the.bytecode.club.bytecodeviewer.decompilers.jdgui; package the.bytecode.club.bytecodeviewer.decompilers.jdgui;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import org.jd.core.v1.api.printer.Printer; import org.jd.core.v1.api.printer.Printer;
public class PlainTextPrinter implements Printer { public class PlainTextPrinter implements Printer, Closeable {
protected static final String TAB = " "; protected static final String TAB = " ";
protected static final String NEWLINE = "\n"; protected static final String NEWLINE = "\n";
@ -227,4 +229,10 @@ public class PlainTextPrinter implements Printer {
return left; return left;
} }
@Override
public void close() throws IOException {
if (this.printStream != null)
this.printStream.close();
}
} }

View File

@ -1,5 +1,7 @@
package the.bytecode.club.bytecodeviewer.gui.components; package the.bytecode.club.bytecodeviewer.gui.components;
import java.io.InputStream;
import java.util.Scanner;
import the.bytecode.club.bytecodeviewer.bootloader.InitialBootScreen; import the.bytecode.club.bytecodeviewer.bootloader.InitialBootScreen;
import the.bytecode.club.bytecodeviewer.Configuration; import the.bytecode.club.bytecodeviewer.Configuration;
@ -41,11 +43,15 @@ public class HTMLPane extends JEditorPane
public static HTMLPane fromResource(String resourcePath) throws IOException public static HTMLPane fromResource(String resourcePath) throws IOException
{ {
return fromString(convertStreamToString(InitialBootScreen.class.getClassLoader().getResourceAsStream(resourcePath))); try (InputStream is = InitialBootScreen.class.getClassLoader().getResourceAsStream(resourcePath)) {
return fromString(convertStreamToString(is));
}
} }
public static HTMLPane fromString(String text) public static HTMLPane fromString(String text)
{ {
if (text == null)
return null;
HTMLPane pane = new HTMLPane(); HTMLPane pane = new HTMLPane();
text = text.replace("{fatJar}", String.valueOf(FAT_JAR)); text = text.replace("{fatJar}", String.valueOf(FAT_JAR));
@ -67,12 +73,13 @@ public class HTMLPane extends JEditorPane
return pane; return pane;
} }
public static String convertStreamToString(java.io.InputStream is) throws IOException public static String convertStreamToString(InputStream is) throws IOException
{ {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); if (is == null)
String string = s.hasNext() ? s.next() : ""; return null;
is.close(); try (InputStream stream = is;
s.close(); Scanner s = new Scanner(stream).useDelimiter("\\A")) {
return string; return s.hasNext() ? s.next() : "";
}
} }
} }

View File

@ -70,7 +70,7 @@ public class JFrameConsolePrintStream extends JFrameConsole
try { try {
Thread.sleep(10); Thread.sleep(10);
} catch (InterruptedException e) { } } catch (InterruptedException ignored) { }
} }
lastUpdate = 0; lastUpdate = 0;

View File

@ -1,5 +1,7 @@
package the.bytecode.club.bytecodeviewer.gui.components; package the.bytecode.club.bytecodeviewer.gui.components;
import java.io.Closeable;
import java.io.IOException;
import javax.swing.*; import javax.swing.*;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
@ -26,7 +28,7 @@ import java.io.PrintStream;
* @author Konloch * @author Konloch
* @since 6/21/2021 * @since 6/21/2021
*/ */
public class JTextAreaOutputStream extends OutputStream public class JTextAreaOutputStream extends OutputStream implements Closeable
{ {
private StringBuilder sb = new StringBuilder(); private StringBuilder sb = new StringBuilder();
private final JTextArea textArea; private final JTextArea textArea;
@ -61,4 +63,10 @@ public class JTextAreaOutputStream extends OutputStream
{ {
return sb; return sb;
} }
@Override
public void close() throws IOException {
if (og != null)
og.close();
}
} }

View File

@ -1,6 +1,7 @@
package the.bytecode.club.bytecodeviewer.gui.theme; package the.bytecode.club.bytecodeviewer.gui.theme;
import com.github.weisj.darklaf.extensions.rsyntaxarea.DarklafRSyntaxTheme; import com.github.weisj.darklaf.extensions.rsyntaxarea.DarklafRSyntaxTheme;
import java.io.InputStream;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme; import org.fife.ui.rsyntaxtextarea.Theme;
import the.bytecode.club.bytecodeviewer.Configuration; import the.bytecode.club.bytecodeviewer.Configuration;
@ -72,14 +73,19 @@ public enum RSTATheme
switch(this) switch(this)
{ {
case THEME_MATCH: case THEME_MATCH:
if(Configuration.lafTheme == LAFTheme.SYSTEM) //on system theme force default theme if (Configuration.lafTheme == LAFTheme.SYSTEM) {
Theme.load(Constants.class.getResourceAsStream(DEFAULT.file)).apply(area); //on system theme force default theme
else try (InputStream is = Constants.class.getResourceAsStream(DEFAULT.file)) {
Theme.load(is).apply(area);
}
} else
new DarklafRSyntaxTheme().apply(area); new DarklafRSyntaxTheme().apply(area);
break; break;
default: default:
Theme.load(Constants.class.getResourceAsStream(file)).apply(area); try (InputStream is = Constants.class.getResourceAsStream(file)) {
Theme.load(is).apply(area);
}
break; break;
} }
} catch (Throwable ignored) { } catch (Throwable ignored) {

View File

@ -74,43 +74,40 @@ public class CompiledJavaPluginLaunchStrategy implements PluginLaunchStrategy {
private static Set<LoadedNodeData> loadData(File jarFile) throws Throwable private static Set<LoadedNodeData> loadData(File jarFile) throws Throwable
{ {
ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile)); try (FileInputStream fis = new FileInputStream(jarFile);
ZipEntry entry; ZipInputStream jis = new ZipInputStream(fis)) {
ZipEntry entry;
Set<LoadedNodeData> set = new HashSet<>(); Set<LoadedNodeData> set = new HashSet<>();
while ((entry = jis.getNextEntry()) != null) while ((entry = jis.getNextEntry()) != null) {
{ try {
try String name = entry.getName();
{ if (name.endsWith(".class")) {
String name = entry.getName(); byte[] bytes = MiscUtils.getBytes(jis);
if (name.endsWith(".class")) if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) {
{ try {
byte[] bytes = MiscUtils.getBytes(jis); ClassReader cr = new ClassReader(bytes);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) ClassNode cn = new ClassNode();
{ cr.accept(cn, 0);
try { LoadedNodeData data = new LoadedNodeData(bytes, cn);
ClassReader cr = new ClassReader(bytes); set.add(data);
ClassNode cn = new ClassNode(); } catch (Exception e) {
cr.accept(cn, 0); e.printStackTrace();
LoadedNodeData data = new LoadedNodeData(bytes, cn); }
set.add(data); } else {
} catch (Exception e) { System.out.println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring.");
e.printStackTrace();
} }
} else {
System.out.println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring.");
} }
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
} }
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
} }
}
jis.close();
return set; return set;
}
} }
public static class LoadedNodeData { public static class LoadedNodeData {

View File

@ -1,5 +1,6 @@
package the.bytecode.club.bytecodeviewer.resources; package the.bytecode.club.bytecodeviewer.resources;
import java.io.InputStream;
import the.bytecode.club.bytecodeviewer.BytecodeViewer; import the.bytecode.club.bytecodeviewer.BytecodeViewer;
import the.bytecode.club.bytecodeviewer.Configuration; import the.bytecode.club.bytecodeviewer.Configuration;
import the.bytecode.club.bytecodeviewer.SettingsSerializer; import the.bytecode.club.bytecodeviewer.SettingsSerializer;
@ -368,7 +369,7 @@ public class ExternalResources
//check for matching text //check for matching text
if(readProcess(p).toLowerCase().contains(matchingText)) if(readProcess(p).toLowerCase().contains(matchingText))
onMatch.run(); onMatch.run();
} catch (Exception e) { } //ignore } catch (Exception ignored) { } //ignore
} }
/** /**
@ -376,16 +377,18 @@ public class ExternalResources
*/ */
public String readProcess(Process process) throws IOException public String readProcess(Process process) throws IOException
{ {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); try (InputStream is = process.getInputStream();
StringBuilder builder = new StringBuilder(); InputStreamReader isr = new InputStreamReader(is);
String line; BufferedReader reader = new BufferedReader(isr)) {
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) String line;
{
builder.append(line); while ((line = reader.readLine()) != null) {
builder.append(System.getProperty("line.separator")); builder.append(line);
builder.append(System.getProperty("line.separator"));
}
return builder.toString();
} }
return builder.toString();
} }
} }

View File

@ -4,6 +4,7 @@ import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable; import java.io.Serializable;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
@ -111,7 +112,11 @@ public class IconResources
public static String loadResourceAsString(String resourcePath) throws IOException public static String loadResourceAsString(String resourcePath) throws IOException
{ {
return IOUtils.toString(IconResources.class.getResourceAsStream(resourcePath), StandardCharsets.UTF_8); try (InputStream is = IconResources.class.getResourceAsStream(resourcePath)) {
if (is == null)
return null;
return IOUtils.toString(is, StandardCharsets.UTF_8);
}
} }
public static BufferedImage resize(BufferedImage image, int width, int height) { public static BufferedImage resize(BufferedImage image, int width, int height) {
@ -127,9 +132,9 @@ public class IconResources
try { try {
imageByte = Base64.decodeBase64(imageString); imageByte = Base64.decodeBase64(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); try (ByteArrayInputStream bis = new ByteArrayInputStream(imageByte)) {
image = ImageIO.read(bis); image = ImageIO.read(bis);
bis.close(); }
} catch (Exception e) { } catch (Exception e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }

View File

@ -56,7 +56,9 @@ public class ResourceContainerImporter
*/ */
public ResourceContainerImporter importAsFile() throws IOException public ResourceContainerImporter importAsFile() throws IOException
{ {
return addUnknownFile(container.file.getName(), new FileInputStream(container.file), false); try (FileInputStream fis = new FileInputStream(container.file)) {
return addUnknownFile(container.file.getName(), fis, false);
}
} }
/** /**
@ -148,21 +150,21 @@ public class ResourceContainerImporter
*/ */
private ResourceContainerImporter importZipInputStream(boolean classesOnly) throws IOException private ResourceContainerImporter importZipInputStream(boolean classesOnly) throws IOException
{ {
ZipInputStream jis = new ZipInputStream(new FileInputStream(container.file)); try (ZipInputStream jis = new ZipInputStream(new FileInputStream(container.file))) {
ZipEntry entry; ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) while ((entry = jis.getNextEntry()) != null) {
{ final String name = entry.getName();
final String name = entry.getName();
//skip directories
//skip directories if (entry.isDirectory())
if(entry.isDirectory()) continue;
continue;
addUnknownFile(name, jis, classesOnly);
addUnknownFile(name, jis, classesOnly); jis.closeEntry();
jis.closeEntry(); }
return this;
} }
jis.close();
return this;
} }
/** /**

View File

@ -39,23 +39,25 @@ public class ClassResourceImporter implements Importer
public void open(File file) throws Exception public void open(File file) throws Exception
{ {
final String name = file.getName(); final String name = file.getName();
byte[] bytes = MiscUtils.getBytes(new FileInputStream(file)); try (FileInputStream fis = new FileInputStream(file)) {
ResourceContainer container = new ResourceContainer(file); byte[] bytes = MiscUtils.getBytes(fis);
ResourceContainer container = new ResourceContainer(file);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
{ if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
final ClassNode cn = JarUtils.getNode(bytes); {
final ClassNode cn = JarUtils.getNode(bytes);
container.resourceClasses.put(FilenameUtils.removeExtension(name), cn);
container.resourceClassBytes.put(name, bytes); container.resourceClasses.put(FilenameUtils.removeExtension(name), cn);
container.resourceClassBytes.put(name, bytes);
}
else
{
BytecodeViewer.showMessage(name + "\nHeader does not start with CAFEBABE\nimporting as resource instead.");
//TODO double check this
container.resourceFiles.put(name, bytes);
}
BytecodeViewer.addResourceContainer(container);
} }
else
{
BytecodeViewer.showMessage(name + "\nHeader does not start with CAFEBABE\nimporting as resource instead.");
//TODO double check this
container.resourceFiles.put(name, bytes);
}
BytecodeViewer.addResourceContainer(container);
} }
} }

View File

@ -1,13 +1,26 @@
package the.bytecode.club.bytecodeviewer.util; package the.bytecode.club.bytecodeviewer.util;
import the.bytecode.club.bytecodeviewer.BytecodeViewer; import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.Reader; import java.io.Reader;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.border.Border;
import the.bytecode.club.bytecodeviewer.BytecodeViewer;
/*************************************************************************** /***************************************************************************
* Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite * * Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite *
@ -29,8 +42,8 @@ import java.io.Reader;
/** /**
* This class makes it easy to drag and drop files from the operating system to * This class makes it easy to drag and drop files from the operating system to
* a Java program. Any <tt>java.awt.Component</tt> can be dropped onto, but only * a Java program. Any <tt>Component</tt> can be dropped onto, but only
* <tt>javax.swing.JComponent</tt>s will indicate the drop event with a changed * <tt>JComponent</tt>s will indicate the drop event with a changed
* border. * border.
* *
* To use this class, construct a new <tt>FileDrop</tt> by passing it the target * To use this class, construct a new <tt>FileDrop</tt> by passing it the target
@ -39,7 +52,7 @@ import java.io.Reader;
* *
* JPanel myPanel = new JPanel(); * JPanel myPanel = new JPanel();
* new FileDrop( myPanel, new FileDrop.Listener() * new FileDrop( myPanel, new FileDrop.Listener()
* { public void filesDropped( java.io.File[] files ) * { public void filesDropped( File[] files )
* { * {
* // handle file drop * // handle file drop
* ... * ...
@ -47,7 +60,7 @@ import java.io.Reader;
* }); // end FileDrop.Listener * }); // end FileDrop.Listener
* *
* You can specify the border that will appear when files are being dragged by * You can specify the border that will appear when files are being dragged by
* calling the constructor with a <tt>javax.swing.border.Border</tt>. Only * calling the constructor with a <tt>Border</tt>. Only
* <tt>JComponent</tt>s will show any indication with a border. * <tt>JComponent</tt>s will show any indication with a border.
* *
* You can turn on some debugging features by passing a <tt>PrintStream</tt> * You can turn on some debugging features by passing a <tt>PrintStream</tt>
@ -67,8 +80,8 @@ import java.io.Reader;
*/ */
@SuppressWarnings({"rawtypes", "unused", "unchecked"}) @SuppressWarnings({"rawtypes", "unused", "unchecked"})
public class FileDrop { public class FileDrop {
private transient javax.swing.border.Border normalBorder; private transient Border normalBorder;
private transient java.awt.dnd.DropTargetListener dropListener; private transient DropTargetListener dropListener;
/** /**
* Discover if the running JVM is modern enough to have drag and drop. * Discover if the running JVM is modern enough to have drag and drop.
@ -76,12 +89,12 @@ public class FileDrop {
private static Boolean supportsDnD; private static Boolean supportsDnD;
// Default border color // Default border color
private static final java.awt.Color defaultBorderColor = new java.awt.Color(0f, private static final Color defaultBorderColor = new Color(0f,
0f, 1f, 0.25f); 0f, 1f, 0.25f);
/** /**
* Constructs a {@link FileDrop} with a default light-blue border and, if * Constructs a {@link FileDrop} with a default light-blue border and, if
* <var>c</var> is a {@link java.awt.Container}, recursively sets all * <var>c</var> is a {@link Container}, recursively sets all
* elements contained within as drop targets, though only the top level * elements contained within as drop targets, though only the top level
* container will change borders. * container will change borders.
* *
@ -89,10 +102,10 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.awt.Component c, final Listener listener) { public FileDrop(final Component c, final Listener listener) {
this(null, // Logging stream this(null, // Logging stream
c, // Drop target c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), // Drag border defaultBorderColor), // Drag border
true, // Recursive true, // Recursive
listener); listener);
@ -100,7 +113,7 @@ public class FileDrop {
/** /**
* Constructor with a default border and the option to recursively set drop * Constructor with a default border and the option to recursively set drop
* targets. If your component is a <tt>java.awt.Container</tt>, then each of * targets. If your component is a <tt>Container</tt>, then each of
* its children components will also listen for drops, though only the * its children components will also listen for drops, though only the
* parent will change borders. * parent will change borders.
* *
@ -109,11 +122,11 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.awt.Component c, final boolean recursive, public FileDrop(final Component c, final boolean recursive,
final Listener listener) { final Listener listener) {
this(null, // Logging stream this(null, // Logging stream
c, // Drop target c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), // Drag border defaultBorderColor), // Drag border
recursive, // Recursive recursive, // Recursive
listener); listener);
@ -131,11 +144,11 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.io.PrintStream out, final java.awt.Component c, public FileDrop(final PrintStream out, final Component c,
final Listener listener) { final Listener listener) {
this(out, // Logging stream this(out, // Logging stream
c, // Drop target c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), false, // Recursive defaultBorderColor), false, // Recursive
listener); listener);
} // end constructor } // end constructor
@ -143,7 +156,7 @@ public class FileDrop {
/** /**
* Constructor with a default border, debugging optionally turned on and the * Constructor with a default border, debugging optionally turned on and the
* option to recursively set drop targets. If your component is a * option to recursively set drop targets. If your component is a
* <tt>java.awt.Container</tt>, then each of its children components will * <tt>Container</tt>, then each of its children components will
* also listen for drops, though only the parent will change borders. With * also listen for drops, though only the parent will change borders. With
* Debugging turned on, more status messages will be displayed to * Debugging turned on, more status messages will be displayed to
* <tt>out</tt>. A common way to use this constructor is with * <tt>out</tt>. A common way to use this constructor is with
@ -156,11 +169,11 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.io.PrintStream out, final java.awt.Component c, public FileDrop(final PrintStream out, final Component c,
final boolean recursive, final Listener listener) { final boolean recursive, final Listener listener) {
this(out, // Logging stream this(out, // Logging stream
c, // Drop target c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), // Drag border defaultBorderColor), // Drag border
recursive, // Recursive recursive, // Recursive
listener); listener);
@ -174,8 +187,8 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.awt.Component c, public FileDrop(final Component c,
final javax.swing.border.Border dragBorder, final Listener listener) { final Border dragBorder, final Listener listener) {
this(null, // Logging stream this(null, // Logging stream
c, // Drop target c, // Drop target
dragBorder, // Drag border dragBorder, // Drag border
@ -185,7 +198,7 @@ public class FileDrop {
/** /**
* Constructor with a specified border and the option to recursively set * Constructor with a specified border and the option to recursively set
* drop targets. If your component is a <tt>java.awt.Container</tt>, then * drop targets. If your component is a <tt>Container</tt>, then
* each of its children components will also listen for drops, though only * each of its children components will also listen for drops, though only
* the parent will change borders. * the parent will change borders.
* *
@ -195,8 +208,8 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.awt.Component c, public FileDrop(final Component c,
final javax.swing.border.Border dragBorder, final Border dragBorder,
final boolean recursive, final Listener listener) { final boolean recursive, final Listener listener) {
this(null, c, dragBorder, recursive, listener); this(null, c, dragBorder, recursive, listener);
} // end constructor } // end constructor
@ -214,8 +227,8 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.io.PrintStream out, final java.awt.Component c, public FileDrop(final PrintStream out, final Component c,
final javax.swing.border.Border dragBorder, final Listener listener) { final Border dragBorder, final Listener listener) {
this(out, // Logging stream this(out, // Logging stream
c, // Drop target c, // Drop target
dragBorder, // Drag border dragBorder, // Drag border
@ -237,21 +250,21 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>. * @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0 * @since 1.0
*/ */
public FileDrop(final java.io.PrintStream out, final java.awt.Component c, public FileDrop(final PrintStream out, final Component c,
final javax.swing.border.Border dragBorder, final Border dragBorder,
final boolean recursive, final Listener listener) { final boolean recursive, final Listener listener) {
if (supportsDnD()) { // Make a drop listener if (supportsDnD()) { // Make a drop listener
dropListener = new java.awt.dnd.DropTargetListener() { dropListener = new DropTargetListener() {
@Override @Override
public void dragEnter(final java.awt.dnd.DropTargetDragEvent evt) { public void dragEnter(final DropTargetDragEvent evt) {
log(out, "FileDrop: dragEnter event."); log(out, "FileDrop: dragEnter event.");
// Is this an acceptable drag event? // Is this an acceptable drag event?
if (isDragOk(out, evt)) { if (isDragOk(out, evt)) {
// If it's a Swing component, set its border // If it's a Swing component, set its border
if (c instanceof javax.swing.JComponent) { if (c instanceof JComponent) {
final javax.swing.JComponent jc = (javax.swing.JComponent) c; final JComponent jc = (JComponent) c;
normalBorder = jc.getBorder(); normalBorder = jc.getBorder();
log(out, "FileDrop: normal border saved."); log(out, "FileDrop: normal border saved.");
jc.setBorder(dragBorder); jc.setBorder(dragBorder);
@ -260,8 +273,8 @@ public class FileDrop {
// Acknowledge that it's okay to enter // Acknowledge that it's okay to enter
// evt.acceptDrag( // evt.acceptDrag(
// java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE ); // DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY); evt.acceptDrag(DnDConstants.ACTION_COPY);
log(out, "FileDrop: event accepted."); log(out, "FileDrop: event accepted.");
} // end if: drag ok } // end if: drag ok
else { // Reject the drag event else { // Reject the drag event
@ -271,7 +284,7 @@ public class FileDrop {
} // end dragEnter } // end dragEnter
@Override @Override
public void dragOver(final java.awt.dnd.DropTargetDragEvent evt) { // This public void dragOver(final DropTargetDragEvent evt) { // This
// is // is
// called // called
// continually // continually
@ -288,28 +301,28 @@ public class FileDrop {
} // end dragOver } // end dragOver
@Override @Override
public void drop(final java.awt.dnd.DropTargetDropEvent evt) { public void drop(final DropTargetDropEvent evt) {
log(out, "FileDrop: drop event."); log(out, "FileDrop: drop event.");
try { // Get whatever was dropped try { // Get whatever was dropped
final java.awt.datatransfer.Transferable tr = evt final Transferable tr = evt
.getTransferable(); .getTransferable();
// Is it a file list? // Is it a file list?
if (tr.isDataFlavorSupported(java.awt.datatransfer.DataFlavor.javaFileListFlavor)) { if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
// Say we'll take it. // Say we'll take it.
// evt.acceptDrop ( // evt.acceptDrop (
// java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE ); // DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY); evt.acceptDrop(DnDConstants.ACTION_COPY);
log(out, "FileDrop: file list accepted."); log(out, "FileDrop: file list accepted.");
// Get a useful list // Get a useful list
final java.util.List fileList = (java.util.List) tr final java.util.List fileList = (java.util.List) tr
.getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor); .getTransferData(DataFlavor.javaFileListFlavor);
final java.util.Iterator iterator = fileList final java.util.Iterator iterator = fileList
.iterator(); .iterator();
// Convert list to array // Convert list to array
final java.io.File[] filesTemp = new java.io.File[fileList final File[] filesTemp = new File[fileList
.size()]; .size()];
fileList.toArray(filesTemp); fileList.toArray(filesTemp);
@ -334,9 +347,9 @@ public class FileDrop {
if (flavor.isRepresentationClassReader()) { if (flavor.isRepresentationClassReader()) {
// Say we'll take it. // Say we'll take it.
// evt.acceptDrop ( // evt.acceptDrop (
// java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE // DnDConstants.ACTION_COPY_OR_MOVE
// ); // );
evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY); evt.acceptDrop(DnDConstants.ACTION_COPY);
log(out, "FileDrop: reader accepted."); log(out, "FileDrop: reader accepted.");
final Reader reader = flavor final Reader reader = flavor
@ -367,12 +380,12 @@ public class FileDrop {
// (KDE/Gnome) support added. // (KDE/Gnome) support added.
} // end else: not a file list } // end else: not a file list
} // end try } // end try
catch (final java.io.IOException io) { catch (final IOException io) {
log(out, "FileDrop: IOException - abort:"); log(out, "FileDrop: IOException - abort:");
BytecodeViewer.handleException(io); BytecodeViewer.handleException(io);
evt.rejectDrop(); evt.rejectDrop();
} // end catch IOException } // end catch IOException
catch (final java.awt.datatransfer.UnsupportedFlavorException ufe) { catch (final UnsupportedFlavorException ufe) {
log(out, log(out,
"FileDrop: UnsupportedFlavorException - abort:"); "FileDrop: UnsupportedFlavorException - abort:");
BytecodeViewer.handleException( BytecodeViewer.handleException(
@ -381,8 +394,8 @@ public class FileDrop {
} // end catch: UnsupportedFlavorException } // end catch: UnsupportedFlavorException
finally { finally {
// If it's a Swing component, reset its border // If it's a Swing component, reset its border
if (c instanceof javax.swing.JComponent) { if (c instanceof JComponent) {
final javax.swing.JComponent jc = (javax.swing.JComponent) c; final JComponent jc = (JComponent) c;
jc.setBorder(normalBorder); jc.setBorder(normalBorder);
log(out, "FileDrop: normal border restored."); log(out, "FileDrop: normal border restored.");
} // end if: JComponent } // end if: JComponent
@ -390,11 +403,11 @@ public class FileDrop {
} // end drop } // end drop
@Override @Override
public void dragExit(final java.awt.dnd.DropTargetEvent evt) { public void dragExit(final DropTargetEvent evt) {
log(out, "FileDrop: dragExit event."); log(out, "FileDrop: dragExit event.");
// If it's a Swing component, reset its border // If it's a Swing component, reset its border
if (c instanceof javax.swing.JComponent) { if (c instanceof JComponent) {
final javax.swing.JComponent jc = (javax.swing.JComponent) c; final JComponent jc = (JComponent) c;
jc.setBorder(normalBorder); jc.setBorder(normalBorder);
log(out, "FileDrop: normal border restored."); log(out, "FileDrop: normal border restored.");
} // end if: JComponent } // end if: JComponent
@ -402,13 +415,13 @@ public class FileDrop {
@Override @Override
public void dropActionChanged( public void dropActionChanged(
final java.awt.dnd.DropTargetDragEvent evt) { final DropTargetDragEvent evt) {
log(out, "FileDrop: dropActionChanged event."); log(out, "FileDrop: dropActionChanged event.");
// Is this an acceptable drag event? // Is this an acceptable drag event?
if (isDragOk(out, evt)) { // evt.acceptDrag( if (isDragOk(out, evt)) { // evt.acceptDrag(
// java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE // DnDConstants.ACTION_COPY_OR_MOVE
// ); // );
evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY); evt.acceptDrag(DnDConstants.ACTION_COPY);
log(out, "FileDrop: event accepted."); log(out, "FileDrop: event accepted.");
} // end if: drag ok } // end if: drag ok
else { else {
@ -431,7 +444,7 @@ public class FileDrop {
boolean support; boolean support;
try { try {
final Class arbitraryDndClass = Class final Class arbitraryDndClass = Class
.forName("java.awt.dnd.DnDConstants"); .forName("DnDConstants");
support = true; support = true;
} // end try } // end try
catch (final Exception e) { catch (final Exception e) {
@ -457,7 +470,7 @@ public class FileDrop {
continue; continue;
} }
final java.io.File file = new java.io.File( final File file = new File(
new java.net.URI(line)); new java.net.URI(line));
list.add(file); list.add(file);
} catch (final Exception ex) { } catch (final Exception ex) {
@ -465,7 +478,7 @@ public class FileDrop {
} }
} }
return (java.io.File[]) list.toArray(new File[0]); return (File[]) list.toArray(new File[0]);
} catch (final IOException ex) { } catch (final IOException ex) {
log(out, "FileDrop: IOException"); log(out, "FileDrop: IOException");
} }
@ -474,10 +487,10 @@ public class FileDrop {
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
private void makeDropTarget(final java.io.PrintStream out, private void makeDropTarget(final PrintStream out,
final java.awt.Component c, final boolean recursive) { final Component c, final boolean recursive) {
// Make drop target // Make drop target
final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget(); final DropTarget dt = new DropTarget();
try { try {
dt.addDropTargetListener(dropListener); dt.addDropTargetListener(dropListener);
} // end try } // end try
@ -492,29 +505,29 @@ public class FileDrop {
// end hierarchyChanged // end hierarchyChanged
c.addHierarchyListener(evt -> { c.addHierarchyListener(evt -> {
log(out, "FileDrop: Hierarchy changed."); log(out, "FileDrop: Hierarchy changed.");
final java.awt.Component parent = c.getParent(); final Component parent = c.getParent();
if (parent == null) { if (parent == null) {
c.setDropTarget(null); c.setDropTarget(null);
log(out, "FileDrop: Drop target cleared from component."); log(out, "FileDrop: Drop target cleared from component.");
} // end if: null parent } // end if: null parent
else { else {
new java.awt.dnd.DropTarget(c, dropListener); new DropTarget(c, dropListener);
log(out, "FileDrop: Drop target added to component."); log(out, "FileDrop: Drop target added to component.");
} // end else: parent not null } // end else: parent not null
}); // end hierarchy listener }); // end hierarchy listener
if (c.getParent() != null) { if (c.getParent() != null) {
new java.awt.dnd.DropTarget(c, dropListener); new DropTarget(c, dropListener);
} }
if (recursive && (c instanceof java.awt.Container)) { if (recursive && (c instanceof Container)) {
// Get the container // Get the container
final java.awt.Container cont = (java.awt.Container) c; final Container cont = (Container) c;
// Get it's components // Get its components
final java.awt.Component[] comps = cont.getComponents(); final Component[] comps = cont.getComponents();
// Set it's components as listeners also // Set its components as listeners also
for (java.awt.Component comp : comps) { for (Component comp : comps) {
makeDropTarget(out, comp, true); makeDropTarget(out, comp, true);
} }
} // end if: recursively set components as listener } // end if: recursively set components as listener
@ -523,12 +536,12 @@ public class FileDrop {
/** /**
* Determine if the dragged data is a file list. * Determine if the dragged data is a file list.
*/ */
private boolean isDragOk(final java.io.PrintStream out, private boolean isDragOk(final PrintStream out,
final java.awt.dnd.DropTargetDragEvent evt) { final DropTargetDragEvent evt) {
boolean ok = false; boolean ok = false;
// Get data flavors being dragged // Get data flavors being dragged
final java.awt.datatransfer.DataFlavor[] flavors = evt final DataFlavor[] flavors = evt
.getCurrentDataFlavors(); .getCurrentDataFlavors();
// See if any of the flavors are a file list // See if any of the flavors are a file list
@ -539,7 +552,7 @@ public class FileDrop {
// Is the flavor a file list? // Is the flavor a file list?
final DataFlavor curFlavor = flavors[i]; final DataFlavor curFlavor = flavors[i];
if (curFlavor if (curFlavor
.equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor) .equals(DataFlavor.javaFileListFlavor)
|| curFlavor.isRepresentationClassReader()) { || curFlavor.isRepresentationClassReader()) {
ok = true; ok = true;
} }
@ -564,7 +577,7 @@ public class FileDrop {
/** /**
* Outputs <tt>message</tt> to <tt>out</tt> if it's not null. * Outputs <tt>message</tt> to <tt>out</tt> if it's not null.
*/ */
private static void log(final java.io.PrintStream out, final String message) { // Log private static void log(final PrintStream out, final String message) { // Log
// message // message
// if // if
// requested // requested
@ -578,12 +591,12 @@ public class FileDrop {
* the all children. You should call this if you add and remove components * the all children. You should call this if you add and remove components
* after you've set up the drag-and-drop. This will recursively unregister * after you've set up the drag-and-drop. This will recursively unregister
* all components contained within <var>c</var> if <var>c</var> is a * all components contained within <var>c</var> if <var>c</var> is a
* {@link java.awt.Container}. * {@link Container}.
* *
* @param c The component to unregister as a drop target * @param c The component to unregister as a drop target
* @since 1.0 * @since 1.0
*/ */
public static boolean remove(final java.awt.Component c) { public static boolean remove(final Component c) {
return remove(null, c, true); return remove(null, c, true);
} // end remove } // end remove
@ -592,24 +605,24 @@ public class FileDrop {
* the all children. You should call this if you add and remove components * the all children. You should call this if you add and remove components
* after you've set up the drag-and-drop. * after you've set up the drag-and-drop.
* *
* @param out Optional {@link java.io.PrintStream} for logging drag and drop * @param out Optional {@link PrintStream} for logging drag and drop
* messages * messages
* @param c The component to unregister * @param c The component to unregister
* @param recursive Recursively unregister components within a container * @param recursive Recursively unregister components within a container
* @since 1.0 * @since 1.0
*/ */
public static boolean remove(final java.io.PrintStream out, public static boolean remove(final PrintStream out,
final java.awt.Component c, final boolean recursive) { // Make sure final Component c, final boolean recursive) { // Make sure
// we // we
// support // support
// dnd. //
if (supportsDnD()) { if (supportsDnD()) {
log(out, "FileDrop: Removing drag-and-drop hooks."); log(out, "FileDrop: Removing drag-and-drop hooks.");
c.setDropTarget(null); c.setDropTarget(null);
if (recursive && (c instanceof java.awt.Container)) { if (recursive && (c instanceof Container)) {
final java.awt.Component[] comps = ((java.awt.Container) c) final Component[] comps = ((Container) c)
.getComponents(); .getComponents();
for (java.awt.Component comp : comps) { for (Component comp : comps) {
remove(out, comp, true); remove(out, comp, true);
} }
return true; return true;
@ -628,7 +641,7 @@ public class FileDrop {
* example your class declaration may begin like this: <code><pre> * example your class declaration may begin like this: <code><pre>
* public class MyClass implements FileDrop.Listener * public class MyClass implements FileDrop.Listener
* ... * ...
* public void filesDropped( java.io.File[] files ) * public void filesDropped( File[] files )
* { * {
* ... * ...
* } // end filesDropped * } // end filesDropped
@ -645,7 +658,7 @@ public class FileDrop {
* @param files An array of <tt>File</tt>s that were dropped. * @param files An array of <tt>File</tt>s that were dropped.
* @since 1.0 * @since 1.0
*/ */
void filesDropped(java.io.File[] files); void filesDropped(File[] files);
} // end inner-interface Listener } // end inner-interface Listener
@ -668,17 +681,17 @@ public class FileDrop {
public static class Event extends java.util.EventObject { public static class Event extends java.util.EventObject {
private static final long serialVersionUID = -2175361562828864378L; private static final long serialVersionUID = -2175361562828864378L;
private final java.io.File[] files; private final File[] files;
/** /**
* Constructs an {@link Event} with the array of files that were dropped * Constructs an {@link Event} with the array of files that were dropped
* and the {@link FileDrop} that initiated the event. * and the {@link FileDrop} that initiated the event.
* *
* @param files The array of files that were dropped * @param files The array of files that were dropped
* @source The event source * @param source The event source
* @since 1.1 * @since 1.1
*/ */
public Event(final java.io.File[] files, final Object source) { public Event(final File[] files, final Object source) {
super(source); super(source);
this.files = files; this.files = files;
} // end constructor } // end constructor
@ -690,7 +703,7 @@ public class FileDrop {
* @return array of files that were dropped * @return array of files that were dropped
* @since 1.1 * @since 1.1
*/ */
public java.io.File[] getFiles() { public File[] getFiles() {
return files; return files;
} // end getFiles } // end getFiles
@ -701,7 +714,7 @@ public class FileDrop {
/** /**
* At last an easy way to encapsulate your custom objects for dragging and * At last an easy way to encapsulate your custom objects for dragging and
* dropping in your Java programs! When you need to create a * dropping in your Java programs! When you need to create a
* {@link java.awt.datatransfer.Transferable} object, use this class to wrap * {@link Transferable} object, use this class to wrap
* your object. For example: * your object. For example:
* <p> * <p>
* <pre> * <pre>
@ -732,10 +745,10 @@ public class FileDrop {
* </code> * </code>
* </pre> * </pre>
* <p> * <p>
* The {@link java.awt.datatransfer.DataFlavor} associated with * The {@link DataFlavor} associated with
* {@link TransferableObject} has the representation class * {@link TransferableObject} has the representation class
* <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type * <tt>net.iharder.TransferableObject.class</tt> and MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>. This data * <tt>application/x-net.iharder.TransferableObject</tt>. This data
* flavor is accessible via the static {@link #DATA_FLAVOR} property. * flavor is accessible via the static {@link #DATA_FLAVOR} property.
* <p> * <p>
* <p> * <p>
@ -748,44 +761,44 @@ public class FileDrop {
* @version 1.2 * @version 1.2
*/ */
public static class TransferableObject implements public static class TransferableObject implements
java.awt.datatransfer.Transferable { Transferable {
/** /**
* The MIME type for {@link #DATA_FLAVOR} is * The MIME type for {@link #DATA_FLAVOR} is
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>. * <tt>application/x-net.iharder.TransferableObject</tt>.
* *
* @since 1.1 * @since 1.1
*/ */
public final static String MIME_TYPE = "application/x-net.iharder.dnd.TransferableObject"; public final static String MIME_TYPE = "application/x-net.iharder.TransferableObject";
/** /**
* The default {@link java.awt.datatransfer.DataFlavor} for * The default {@link DataFlavor} for
* {@link TransferableObject} has the representation class * {@link TransferableObject} has the representation class
* <tt>net.iharder.dnd.TransferableObject.class</tt> and the MIME type * <tt>net.iharder.TransferableObject.class</tt> and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>. * <tt>application/x-net.iharder.TransferableObject</tt>.
* *
* @since 1.1 * @since 1.1
*/ */
public final static java.awt.datatransfer.DataFlavor DATA_FLAVOR = new java.awt.datatransfer.DataFlavor( public final static DataFlavor DATA_FLAVOR = new DataFlavor(
FileDrop.TransferableObject.class, MIME_TYPE); FileDrop.TransferableObject.class, MIME_TYPE);
private Fetcher fetcher; private Fetcher fetcher;
private Object data; private Object data;
private java.awt.datatransfer.DataFlavor customFlavor; private DataFlavor customFlavor;
/** /**
* Creates a new {@link TransferableObject} that wraps <var>data</var>. * Creates a new {@link TransferableObject} that wraps <var>data</var>.
* Along with the {@link #DATA_FLAVOR} associated with this class, this * Along with the {@link #DATA_FLAVOR} associated with this class, this
* creates a custom data flavor with a representation class determined * creates a custom data flavor with a representation class determined
* from <code>data.getClass()</code> and the MIME type * from <code>data.getClass()</code> and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>. * <tt>application/x-net.iharder.TransferableObject</tt>.
* *
* @param data The data to transfer * @param data The data to transfer
* @since 1.1 * @since 1.1
*/ */
public TransferableObject(final Object data) { public TransferableObject(final Object data) {
this.data = data; this.data = data;
this.customFlavor = new java.awt.datatransfer.DataFlavor( this.customFlavor = new DataFlavor(
data.getClass(), MIME_TYPE); data.getClass(), MIME_TYPE);
} // end constructor } // end constructor
@ -808,7 +821,7 @@ public class FileDrop {
* {@link #DATA_FLAVOR} associated with this class, this creates a * {@link #DATA_FLAVOR} associated with this class, this creates a
* custom data flavor with a representation class <var>dataClass</var> * custom data flavor with a representation class <var>dataClass</var>
* and the MIME type * and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>. * <tt>application/x-net.iharder.TransferableObject</tt>.
* *
* @param dataClass The {@link java.lang.Class} to use in the custom data * @param dataClass The {@link java.lang.Class} to use in the custom data
* flavor * flavor
@ -818,12 +831,12 @@ public class FileDrop {
*/ */
public TransferableObject(final Class dataClass, final Fetcher fetcher) { public TransferableObject(final Class dataClass, final Fetcher fetcher) {
this.fetcher = fetcher; this.fetcher = fetcher;
this.customFlavor = new java.awt.datatransfer.DataFlavor(dataClass, this.customFlavor = new DataFlavor(dataClass,
MIME_TYPE); MIME_TYPE);
} // end constructor } // end constructor
/** /**
* Returns the custom {@link java.awt.datatransfer.DataFlavor} * Returns the custom {@link DataFlavor}
* associated with the encapsulated object or <tt>null</tt> if the * associated with the encapsulated object or <tt>null</tt> if the
* {@link Fetcher} constructor was used without passing a * {@link Fetcher} constructor was used without passing a
* {@link java.lang.Class}. * {@link java.lang.Class}.
@ -831,7 +844,7 @@ public class FileDrop {
* @return The custom data flavor for the encapsulated object * @return The custom data flavor for the encapsulated object
* @since 1.1 * @since 1.1
*/ */
public java.awt.datatransfer.DataFlavor getCustomDataFlavor() { public DataFlavor getCustomDataFlavor() {
return customFlavor; return customFlavor;
} // end getCustomDataFlavor } // end getCustomDataFlavor
@ -842,22 +855,22 @@ public class FileDrop {
* data flavor, if one was created in the constructors, second the * data flavor, if one was created in the constructors, second the
* default {@link #DATA_FLAVOR} associated with * default {@link #DATA_FLAVOR} associated with
* {@link TransferableObject}, and third the * {@link TransferableObject}, and third the
* java.awt.datatransfer.DataFlavor.stringFlavor. * DataFlavor.stringFlavor.
* *
* @return An array of supported data flavors * @return An array of supported data flavors
* @since 1.1 * @since 1.1
*/ */
@Override @Override
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() { public DataFlavor[] getTransferDataFlavors() {
if (customFlavor != null) if (customFlavor != null)
return new java.awt.datatransfer.DataFlavor[]{customFlavor, return new DataFlavor[]{customFlavor,
DATA_FLAVOR, DATA_FLAVOR,
java.awt.datatransfer.DataFlavor.stringFlavor}; // end DataFlavor.stringFlavor}; // end
// flavors // flavors
// array // array
else else
return new java.awt.datatransfer.DataFlavor[]{DATA_FLAVOR, return new DataFlavor[]{DATA_FLAVOR,
java.awt.datatransfer.DataFlavor.stringFlavor}; // end DataFlavor.stringFlavor}; // end
// flavors // flavors
// array // array
} // end getTransferDataFlavors } // end getTransferDataFlavors
@ -875,19 +888,19 @@ public class FileDrop {
*/ */
@Override @Override
public Object getTransferData( public Object getTransferData(
final java.awt.datatransfer.DataFlavor flavor) final DataFlavor flavor)
throws java.awt.datatransfer.UnsupportedFlavorException { throws UnsupportedFlavorException {
// Native object // Native object
if (flavor.equals(DATA_FLAVOR)) if (flavor.equals(DATA_FLAVOR))
return fetcher == null ? data : fetcher.getObject(); return fetcher == null ? data : fetcher.getObject();
// String // String
if (flavor.equals(java.awt.datatransfer.DataFlavor.stringFlavor)) if (flavor.equals(DataFlavor.stringFlavor))
return fetcher == null ? data.toString() : fetcher.getObject() return fetcher == null ? data.toString() : fetcher.getObject()
.toString(); .toString();
// We can't do anything else // We can't do anything else
throw new java.awt.datatransfer.UnsupportedFlavorException(flavor); throw new UnsupportedFlavorException(flavor);
} // end getTransferData } // end getTransferData
/** /**
@ -901,7 +914,7 @@ public class FileDrop {
*/ */
@Override @Override
public boolean isDataFlavorSupported( public boolean isDataFlavorSupported(
final java.awt.datatransfer.DataFlavor flavor) { final DataFlavor flavor) {
// Native object // Native object
if (flavor.equals(DATA_FLAVOR)) if (flavor.equals(DATA_FLAVOR))
return true; return true;

View File

@ -54,7 +54,7 @@ import static the.bytecode.club.bytecodeviewer.Constants.*;
@Deprecated @Deprecated
public class JarUtils public class JarUtils
{ {
public static Object LOCK = new Object(); public static final Object LOCK = new Object();
/** /**
* Loads the classes and resources from the input jar file * Loads the classes and resources from the input jar file
@ -67,41 +67,41 @@ public class JarUtils
ResourceContainer container = new ResourceContainer(jarFile); ResourceContainer container = new ResourceContainer(jarFile);
LinkedHashMap<String, byte[]> files = new LinkedHashMap<>(); LinkedHashMap<String, byte[]> files = new LinkedHashMap<>();
ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile)); try (FileInputStream fis = new FileInputStream(jarFile);
ZipEntry entry; ZipInputStream jis = new ZipInputStream(fis)) {
while ((entry = jis.getNextEntry()) != null) { ZipEntry entry;
try { while ((entry = jis.getNextEntry()) != null) {
final String name = entry.getName(); try {
final byte[] bytes = MiscUtils.getBytes(jis); final String name = entry.getName();
if (!name.endsWith(".class")) { final byte[] bytes = MiscUtils.getBytes(jis);
if (!entry.isDirectory()) if (!name.endsWith(".class")) {
files.put(name, bytes);
} else {
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
{
try {
final ClassNode cn = getNode(bytes);
container.resourceClasses.put(FilenameUtils.removeExtension(name), cn);
} catch (Exception e) {
System.err.println("Skipping: " + name);
e.printStackTrace();
}
} else {
if (!entry.isDirectory()) if (!entry.isDirectory())
files.put(name, bytes); files.put(name, bytes);
//System.out.println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring."); } else {
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) {
try {
final ClassNode cn = getNode(bytes);
container.resourceClasses.put(FilenameUtils.removeExtension(name), cn);
} catch (Exception e) {
System.err.println("Skipping: " + name);
e.printStackTrace();
}
} else {
if (!entry.isDirectory())
files.put(name, bytes);
//System.out.println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring.");
}
} }
}
} catch (java.io.EOFException | ZipException e) { } catch (java.io.EOFException | ZipException e) {
//ignore cause apache unzip //ignore cause apache unzip
} catch (Exception e) { } catch (Exception e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} finally { } finally {
jis.closeEntry(); jis.closeEntry();
}
} }
} }
jis.close();
container.resourceFiles = files; container.resourceFiles = files;
BytecodeViewer.addResourceContainer(container); BytecodeViewer.addResourceContainer(container);
} }
@ -158,33 +158,34 @@ public class JarUtils
public static ArrayList<ClassNode> loadClasses(final File jarFile) throws IOException public static ArrayList<ClassNode> loadClasses(final File jarFile) throws IOException
{ {
ArrayList<ClassNode> classes = new ArrayList<>(); ArrayList<ClassNode> classes = new ArrayList<>();
ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile)); try (FileInputStream fis = new FileInputStream(jarFile);
ZipEntry entry; ZipInputStream jis = new ZipInputStream(fis)) {
while ((entry = jis.getNextEntry()) != null) { ZipEntry entry;
try { while ((entry = jis.getNextEntry()) != null) {
final String name = entry.getName(); try {
if (name.endsWith(".class")) { final String name = entry.getName();
byte[] bytes = MiscUtils.getBytes(jis); if (name.endsWith(".class")) {
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) byte[] bytes = MiscUtils.getBytes(jis);
{ if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) {
try { try {
final ClassNode cn = getNode(bytes); final ClassNode cn = getNode(bytes);
classes.add(cn); classes.add(cn);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
}
} else {
System.out.println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring.");
} }
} else {
System.out.println(jarFile + ">" + name + ": Header does not start with CAFEBABE, ignoring.");
} }
}
} catch (Exception e) { } catch (Exception e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} finally { } finally {
jis.closeEntry(); jis.closeEntry();
}
} }
} }
jis.close();
return classes; return classes;
} }
@ -200,24 +201,24 @@ public class JarUtils
LinkedHashMap<String, byte[]> files = new LinkedHashMap<>(); LinkedHashMap<String, byte[]> files = new LinkedHashMap<>();
ZipInputStream jis = new ZipInputStream(new FileInputStream(zipFile)); try (ZipInputStream jis = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry entry; ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) { while ((entry = jis.getNextEntry()) != null) {
try { try {
final String name = entry.getName(); final String name = entry.getName();
if (!name.endsWith(".class") && !name.endsWith(".dex")) { if (!name.endsWith(".class") && !name.endsWith(".dex")) {
if (!entry.isDirectory()) if (!entry.isDirectory())
files.put(name, MiscUtils.getBytes(jis)); files.put(name, MiscUtils.getBytes(jis));
jis.closeEntry();
}
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry(); jis.closeEntry();
} }
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
} }
} }
jis.close();
return files; return files;
} }
@ -246,9 +247,8 @@ public class JarUtils
*/ */
public static void saveAsJar(ArrayList<ClassNode> nodeList, String path, public static void saveAsJar(ArrayList<ClassNode> nodeList, String path,
String manifest) { String manifest) {
try { try (FileOutputStream fos = new FileOutputStream(path);
JarOutputStream out = new JarOutputStream( JarOutputStream out = new JarOutputStream(fos)) {
new FileOutputStream(path));
for (ClassNode cn : nodeList) { for (ClassNode cn : nodeList) {
ClassWriter cw = new ClassWriter(0); ClassWriter cw = new ClassWriter(0);
cn.accept(cw); cn.accept(cw);
@ -262,7 +262,7 @@ public class JarUtils
out.write((manifest.trim() + "\r\n\r\n").getBytes()); out.write((manifest.trim() + "\r\n\r\n").getBytes());
out.closeEntry(); out.closeEntry();
for (ResourceContainer container : BytecodeViewer.resourceContainers) for (ResourceContainer container : BytecodeViewer.resourceContainers) {
for (Entry<String, byte[]> entry : container.resourceFiles.entrySet()) { for (Entry<String, byte[]> entry : container.resourceFiles.entrySet()) {
String filename = entry.getKey(); String filename = entry.getKey();
if (!filename.startsWith("META-INF")) { if (!filename.startsWith("META-INF")) {
@ -271,8 +271,7 @@ public class JarUtils
out.closeEntry(); out.closeEntry();
} }
} }
}
out.close();
} catch (IOException e) { } catch (IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }
@ -289,9 +288,9 @@ public class JarUtils
//TODO figure out why is this synchronized and if it's actually needed (probably not) //TODO figure out why is this synchronized and if it's actually needed (probably not)
synchronized (LOCK) synchronized (LOCK)
{ {
try try (FileOutputStream fos = new FileOutputStream(path);
JarOutputStream out = new JarOutputStream(fos))
{ {
JarOutputStream out = new JarOutputStream(new FileOutputStream(path));
ArrayList<String> noDupe = new ArrayList<>(); ArrayList<String> noDupe = new ArrayList<>();
for (ClassNode cn : nodeList) for (ClassNode cn : nodeList)
{ {
@ -308,9 +307,7 @@ public class JarUtils
out.closeEntry(); out.closeEntry();
} }
} }
noDupe.clear(); noDupe.clear();
out.close();
} }
catch (IOException e) catch (IOException e)
{ {
@ -349,8 +346,8 @@ public class JarUtils
* @param path the exact jar output path * @param path the exact jar output path
*/ */
public static void saveAsJar(ArrayList<ClassNode> nodeList, String path) { public static void saveAsJar(ArrayList<ClassNode> nodeList, String path) {
try { try (FileOutputStream fos = new FileOutputStream(path);
JarOutputStream out = new JarOutputStream(new FileOutputStream(path)); JarOutputStream out = new JarOutputStream(fos)) {
ArrayList<String> noDupe = new ArrayList<>(); ArrayList<String> noDupe = new ArrayList<>();
for (ClassNode cn : nodeList) { for (ClassNode cn : nodeList) {
ClassWriter cw = new ClassWriter(0); ClassWriter cw = new ClassWriter(0);
@ -366,7 +363,7 @@ public class JarUtils
} }
} }
for (ResourceContainer container : BytecodeViewer.resourceContainers) for (ResourceContainer container : BytecodeViewer.resourceContainers) {
for (Entry<String, byte[]> entry : container.resourceFiles.entrySet()) { for (Entry<String, byte[]> entry : container.resourceFiles.entrySet()) {
String filename = entry.getKey(); String filename = entry.getKey();
if (!filename.startsWith("META-INF")) { if (!filename.startsWith("META-INF")) {
@ -378,9 +375,9 @@ public class JarUtils
} }
} }
} }
}
noDupe.clear(); noDupe.clear();
out.close();
} catch (IOException e) { } catch (IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }

View File

@ -85,22 +85,23 @@ public class MiscUtils
public static void printProcess(Process process) throws Exception { public static void printProcess(Process process) throws Exception {
//Read out dir output //Read out dir output
InputStream is = process.getInputStream(); try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr)) {
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
System.out.println(line); System.out.println(line);
}
} }
br.close();
is = process.getErrorStream(); try (InputStream is = process.getErrorStream();
isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr)) {
while ((line = br.readLine()) != null) { String line;
System.out.println(line); while ((line = br.readLine()) != null) {
System.out.println(line);
}
} }
br.close();
} }
/** /**
@ -212,8 +213,8 @@ public class MiscUtils
public static BufferedImage loadImage(BufferedImage defaultImage, byte[] contents) public static BufferedImage loadImage(BufferedImage defaultImage, byte[] contents)
{ {
try { try (ByteArrayInputStream bais = new ByteArrayInputStream(contents)) {
return ImageIO.read(new ByteArrayInputStream(contents)); return ImageIO.read(bais);
} catch (IOException e) { } catch (IOException e) {
BytecodeViewer.handleException(e); BytecodeViewer.handleException(e);
} }
@ -285,15 +286,15 @@ public class MiscUtils
*/ */
public static byte[] getBytes(final InputStream is) throws IOException public static byte[] getBytes(final InputStream is) throws IOException
{ {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int a; int a;
while ((a = is.read(buffer)) != -1) while ((a = is.read(buffer)) != -1)
baos.write(buffer, 0, a); baos.write(buffer, 0, a);
baos.close(); return baos.toByteArray();
return baos.toByteArray(); }
} }
public static File[] listFiles(File file) { public static File[] listFiles(File file) {

View File

@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
* Convert the various newline conventions to the local platform's newline convention. * Convert the various newline conventions to the local platform's newline convention.
* *
* This stream can be used with the Message.writeTo method to * This stream can be used with the Message.writeTo method to
* generate a message that uses the local plaform's line terminator * generate a message that uses the local platform's line terminator
* for the purpose of (e.g.) saving the message to a local file. * for the purpose of (e.g.) saving the message to a local file.
*/ */
public class NewlineOutputStream extends FilterOutputStream { public class NewlineOutputStream extends FilterOutputStream {

View File

@ -44,101 +44,80 @@ public final class ZipUtils {
*/ */
public static void unzipFilesToPath(String jarPath, String destinationDir) throws IOException { public static void unzipFilesToPath(String jarPath, String destinationDir) throws IOException {
File file = new File(jarPath); File file = new File(jarPath);
JarFile jar = new JarFile(file); try (JarFile jar = new JarFile(file)) {
// fist get all directories, // fist get all directories,
// then make those directory on the destination Path // then make those directory on the destination Path
/*for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) { /*for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = (JarEntry) enums.nextElement(); JarEntry entry = (JarEntry) enums.nextElement();
String fileName = destinationDir + File.separator + entry.getName(); String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName); File f = new File(fileName);
if (fileName.endsWith("/")) { if (fileName.endsWith("/")) {
f.mkdirs(); f.mkdirs();
}
}*/
//now create all files
for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = enums.nextElement();
String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName);
File parent = f.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!fileName.endsWith("/")) {
InputStream is = jar.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(f);
// write contents of 'is' to 'fos'
while (is.available() > 0) {
fos.write(is.read());
} }
fos.close(); }*/
is.close();
//now create all files
for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = enums.nextElement();
String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName);
File parent = f.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!fileName.endsWith("/")) {
try (InputStream is = jar.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(f)) {
// write contents of 'is' to 'fos'
while (is.available() > 0) {
fos.write(is.read());
}
}
}
} }
} }
try {
jar.close();
} catch (Exception ignored) {
}
} }
public static void zipFile(File inputFile, File outputZip) { public static void zipFile(File inputFile, File outputZip) {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
try { try (FileOutputStream fos = new FileOutputStream(outputZip);
FileOutputStream fos = new FileOutputStream(outputZip); ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(inputFile.getName()); ZipEntry ze = new ZipEntry(inputFile.getName());
zos.putNextEntry(ze); zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(inputFile); try (FileInputStream in = new FileInputStream(inputFile)) {
int len;
int len; while ((len = in.read(buffer)) > 0) {
while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len);
zos.write(buffer, 0, len); }
} }
in.close();
zos.closeEntry(); zos.closeEntry();
zos.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception { public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception {
ZipOutputStream zip; try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
FileOutputStream fileWriter; ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZip("", srcFolder, zip, ignore);
fileWriter = new FileOutputStream(destZipFile); zip.flush();
zip = new ZipOutputStream(fileWriter); }
addFolderToZip("", srcFolder, zip, ignore);
zip.flush();
zip.close();
} }
public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception { public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip; try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
FileOutputStream fileWriter; ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZipAPKTool("", srcFolder, zip);
fileWriter = new FileOutputStream(destZipFile); zip.flush();
zip = new ZipOutputStream(fileWriter); }
addFolderToZipAPKTool("", srcFolder, zip);
zip.flush();
zip.close();
} }
public static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String ignore) public static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String ignore)
@ -150,17 +129,17 @@ public final class ZipUtils {
} else { } else {
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int len; int len;
FileInputStream in = new FileInputStream(srcFile); try (FileInputStream in = new FileInputStream(srcFile)) {
ZipEntry entry; ZipEntry entry;
if (ignore == null) if (ignore == null)
entry = new ZipEntry(path + "/" + folder.getName()); entry = new ZipEntry(path + "/" + folder.getName());
else else
entry = new ZipEntry(path.replace(ignore, "BCV_Krakatau") + "/" + folder.getName()); entry = new ZipEntry(path.replace(ignore, "BCV_Krakatau") + "/" + folder.getName());
zip.putNextEntry(entry); zip.putNextEntry(entry);
while ((len = in.read(buf)) > 0) { while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len); zip.write(buf, 0, len);
}
} }
in.close();
} }
} }
@ -183,16 +162,16 @@ public final class ZipUtils {
} else { } else {
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int len; int len;
FileInputStream in = new FileInputStream(srcFile); try (FileInputStream in = new FileInputStream(srcFile)) {
ZipEntry entry; ZipEntry entry;
entry = new ZipEntry(path + "/" + folder.getName()); entry = new ZipEntry(path + "/" + folder.getName());
zip.putNextEntry(entry); zip.putNextEntry(entry);
while ((len = in.read(buf)) > 0) { while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len); zip.write(buf, 0, len);
}
} }
in.close();
} }
} }