Merge pull request #336 from ThexXTURBOXx/fixes

Fix most leaks
This commit is contained in:
Konloch 2021-07-26 21:19:55 -07:00 committed by GitHub
commit 9b61352c01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
37 changed files with 650 additions and 716 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -260,12 +260,9 @@ public class UpdateCheck implements Runnable
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."
+ nl + nl + "Expect this to take several minutes.");
InputStream is = new URL(url).openConnection().getInputStream();
FileOutputStream fos = new FileOutputStream(saveTo);
try
{
try (InputStream is = new URL(url).openConnection().getInputStream();
FileOutputStream fos = new FileOutputStream(saveTo)) {
byte[] buffer = new byte[8192];
int len;
int downloaded = 0;
@ -286,14 +283,6 @@ public class UpdateCheck implements Runnable
} else
flag = false;
}
} finally {
try {
if (is != null)
is.close();
} finally {
fos.flush();
fos.close();
}
}
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 {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1)
byteArrayOut.write(buffer, 0, bytesRead);
byteArrayOut.close();
return byteArrayOut.toByteArray();
try (ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1)
byteArrayOut.write(buffer, 0, bytesRead);
return byteArrayOut.toByteArray();
}
}
protected ClassNode create(byte[] b) {
@ -92,13 +92,15 @@ public class ExternalLibrary extends ExternalResource<JarContents<ClassNode>> {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
byte[] bytes = read(jar.getInputStream(entry));
if (entry.getName().endsWith(".class")) {
ClassNode cn = create(bytes);
contents.getClassContents().add(cn);
} else {
JarResource resource = new JarResource(entry.getName(), bytes);
contents.getResourceContents().add(resource);
try (InputStream is = jar.getInputStream(entry)) {
byte[] bytes = read(is);
if (entry.getName().endsWith(".class")) {
ClassNode cn = create(bytes);
contents.getClassContents().add(cn);
} else {
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();
//Read out dir output
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();
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);
}
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
log.append(nl).append(line);
br.close();
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);
}
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);
if (!clazz.exists())

View file

@ -84,28 +84,25 @@ public class KrakatauAssembler extends InternalCompiler
BytecodeViewer.createdProcesses.add(process);
//Read out dir output
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();
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);
}
log.append(nl).append(nl).append(TranslatedStrings.ERROR2).append(nl).append(nl);
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
log.append(nl).append(line);
br.close();
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);
}
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);
byte[] b = FileUtils.readFileToByteArray(Objects.requireNonNull(

View file

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

View file

@ -1,6 +1,5 @@
package the.bytecode.club.bytecodeviewer.decompilers.impl;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
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(MiscUtils.getUniqueName(fileStart, ".class") + ".class");
try {
final FileOutputStream fos = new FileOutputStream(tempClass);
try (FileOutputStream fos = new FileOutputStream(tempClass)) {
fos.write(b);
fos.close();
} catch (final IOException e) {
BytecodeViewer.handleException(e);
}
@ -319,15 +314,12 @@ public class CFRDecompiler extends InternalDecompiler
}
@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();
Deque<File> queue = new LinkedList<>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
try {
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
try (OutputStream out = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(out)) {
while (!queue.isEmpty()) {
directory = queue.pop();
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.StringWriter;
import me.konloch.kontainer.io.DiskReader;
import org.apache.commons.lang3.ArrayUtils;
import org.objectweb.asm.tree.ClassNode;
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.decompilers.InternalDecompiler;
import the.bytecode.club.bytecodeviewer.translation.TranslatedStrings;
@ -72,10 +70,8 @@ public class FernFlowerDecompiler extends InternalDecompiler
final File tempClass = new File(start + ".class");
String exception = "";
try {
final FileOutputStream fos = new FileOutputStream(tempClass);
try (FileOutputStream fos = new FileOutputStream(tempClass)) {
fos.write(b);
fos.close();
} catch (final IOException e) {
StringWriter exceptionWriter = new StringWriter();
e.printStackTrace(new PrintWriter(exceptionWriter));

View file

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

View file

@ -72,10 +72,8 @@ public class JDGUIDecompiler extends InternalDecompiler
}
}
try {
final FileOutputStream fos = new FileOutputStream(tempClass);
try (FileOutputStream fos = new FileOutputStream(tempClass)) {
fos.write(b);
fos.close();
} catch (final IOException e) {
BytecodeViewer.handleException(e);
}
@ -101,16 +99,14 @@ public class JDGUIDecompiler extends InternalDecompiler
//PrintStream ps = new PrintStream("test.html");
//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();
decompiler.decompile(loader, printer, internalPath, preferences.getPreferences());
String decompiledSource;
decompiledSource = DiskReader.loadAsString(tempJava.getAbsolutePath());
try (PrintStream ps = new PrintStream(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) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));

View file

@ -112,28 +112,31 @@ public class KrakatauDecompiler extends InternalDecompiler
Process process = pb.start();
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);
String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
//Read out dir output
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);
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
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();
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();
//if the motherfucker failed this'll fail, aka wont set.
@ -196,26 +199,28 @@ public class KrakatauDecompiler extends InternalDecompiler
Process process = pb.start();
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);
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);
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
//Read out dir output
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);
}
}
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();
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();
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);
String line;
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
//Read out dir output
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);
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
log.append(nl).append(line);
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();
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();
//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");
} catch (Exception e) {
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");
try {
final FileOutputStream fos = new FileOutputStream(tempClass);
try (FileOutputStream fos = new FileOutputStream(tempClass)) {
fos.write(b);
fos.close();
} catch (final IOException e) {
BytecodeViewer.handleException(e);
}
@ -185,11 +181,12 @@ public class ProcyonDecompiler extends InternalDecompiler
|| ((resolvedType = type.resolve()) == null)) {
throw new Exception("Unable to resolve type.");
}
Writer writer = new OutputStreamWriter(out);
settings.getLanguage().decompileType(resolvedType,
new PlainTextOutput(writer),
decompilationOptions);
writer.flush();
try (Writer writer = new OutputStreamWriter(out)) {
settings.getLanguage().decompileType(resolvedType,
new PlainTextOutput(writer),
decompilationOptions);
writer.flush();
}
} finally {
out.closeEntry();
}
@ -201,16 +198,11 @@ public class ProcyonDecompiler extends InternalDecompiler
continue;
history.add(etn);
out.putNextEntry(etn);
try {
InputStream in = jfile.getInputStream(entry);
try (InputStream in = jfile.getInputStream(entry)) {
if (in != null) {
try {
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
out.write(data, 0, count);
}
} finally {
in.close();
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
out.write(data, 0, count);
}
}
} finally {
@ -239,7 +231,7 @@ public class ProcyonDecompiler extends InternalDecompiler
_typeLoaders.add(new InputTypeLoader());
}
public final List<ITypeLoader> getTypeLoaders() {
public List<ITypeLoader> getTypeLoaders() {
return _typeLoaders;
}

View file

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

View file

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

View file

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

View file

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

View file

@ -1,10 +1,12 @@
package the.bytecode.club.bytecodeviewer.decompilers.jdgui;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream;
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 NEWLINE = "\n";
@ -227,4 +229,10 @@ public class PlainTextPrinter implements Printer {
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;
import java.io.InputStream;
import java.util.Scanner;
import the.bytecode.club.bytecodeviewer.bootloader.InitialBootScreen;
import the.bytecode.club.bytecodeviewer.Configuration;
@ -41,11 +43,15 @@ public class HTMLPane extends JEditorPane
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)
{
if (text == null)
return null;
HTMLPane pane = new HTMLPane();
text = text.replace("{fatJar}", String.valueOf(FAT_JAR));
@ -67,12 +73,13 @@ public class HTMLPane extends JEditorPane
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");
String string = s.hasNext() ? s.next() : "";
is.close();
s.close();
return string;
if (is == null)
return null;
try (InputStream stream = is;
Scanner s = new Scanner(stream).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : "";
}
}
}

View file

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

View file

@ -1,5 +1,7 @@
package the.bytecode.club.bytecodeviewer.gui.components;
import java.io.Closeable;
import java.io.IOException;
import javax.swing.*;
import java.io.OutputStream;
import java.io.PrintStream;
@ -26,7 +28,7 @@ import java.io.PrintStream;
* @author Konloch
* @since 6/21/2021
*/
public class JTextAreaOutputStream extends OutputStream
public class JTextAreaOutputStream extends OutputStream implements Closeable
{
private StringBuilder sb = new StringBuilder();
private final JTextArea textArea;
@ -61,4 +63,10 @@ public class JTextAreaOutputStream extends OutputStream
{
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;
import com.github.weisj.darklaf.extensions.rsyntaxarea.DarklafRSyntaxTheme;
import java.io.InputStream;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
import the.bytecode.club.bytecodeviewer.Configuration;
@ -72,14 +73,19 @@ public enum RSTATheme
switch(this)
{
case THEME_MATCH:
if(Configuration.lafTheme == LAFTheme.SYSTEM) //on system theme force default theme
Theme.load(Constants.class.getResourceAsStream(DEFAULT.file)).apply(area);
else
if (Configuration.lafTheme == LAFTheme.SYSTEM) {
//on system theme force default theme
try (InputStream is = Constants.class.getResourceAsStream(DEFAULT.file)) {
Theme.load(is).apply(area);
}
} else
new DarklafRSyntaxTheme().apply(area);
break;
default:
Theme.load(Constants.class.getResourceAsStream(file)).apply(area);
try (InputStream is = Constants.class.getResourceAsStream(file)) {
Theme.load(is).apply(area);
}
break;
}
} catch (Throwable ignored) {

View file

@ -74,43 +74,40 @@ public class CompiledJavaPluginLaunchStrategy implements PluginLaunchStrategy {
private static Set<LoadedNodeData> loadData(File jarFile) throws Throwable
{
ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile));
ZipEntry entry;
try (FileInputStream fis = new FileInputStream(jarFile);
ZipInputStream jis = new ZipInputStream(fis)) {
ZipEntry entry;
Set<LoadedNodeData> set = new HashSet<>();
Set<LoadedNodeData> set = new HashSet<>();
while ((entry = jis.getNextEntry()) != null)
{
try
{
String name = entry.getName();
if (name.endsWith(".class"))
{
byte[] bytes = MiscUtils.getBytes(jis);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
{
try {
ClassReader cr = new ClassReader(bytes);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
LoadedNodeData data = new LoadedNodeData(bytes, cn);
set.add(data);
} catch (Exception e) {
e.printStackTrace();
while ((entry = jis.getNextEntry()) != null) {
try {
String name = entry.getName();
if (name.endsWith(".class")) {
byte[] bytes = MiscUtils.getBytes(jis);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) {
try {
ClassReader cr = new ClassReader(bytes);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
LoadedNodeData data = new LoadedNodeData(bytes, cn);
set.add(data);
} catch (Exception e) {
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) {
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 {

View file

@ -1,5 +1,6 @@
package the.bytecode.club.bytecodeviewer.resources;
import java.io.InputStream;
import the.bytecode.club.bytecodeviewer.BytecodeViewer;
import the.bytecode.club.bytecodeviewer.Configuration;
import the.bytecode.club.bytecodeviewer.SettingsSerializer;
@ -368,7 +369,7 @@ public class ExternalResources
//check for matching text
if(readProcess(p).toLowerCase().contains(matchingText))
onMatch.run();
} catch (Exception e) { } //ignore
} catch (Exception ignored) { } //ignore
}
/**
@ -376,16 +377,18 @@ public class ExternalResources
*/
public String readProcess(Process process) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
builder.append(System.getProperty("line.separator"));
try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr)) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
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.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@ -111,7 +112,11 @@ public class IconResources
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) {
@ -127,9 +132,9 @@ public class IconResources
try {
imageByte = Base64.decodeBase64(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
try (ByteArrayInputStream bis = new ByteArrayInputStream(imageByte)) {
image = ImageIO.read(bis);
}
} catch (Exception e) {
BytecodeViewer.handleException(e);
}

View file

@ -56,7 +56,9 @@ public class ResourceContainerImporter
*/
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
{
ZipInputStream jis = new ZipInputStream(new FileInputStream(container.file));
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null)
{
final String name = entry.getName();
//skip directories
if(entry.isDirectory())
continue;
addUnknownFile(name, jis, classesOnly);
jis.closeEntry();
try (ZipInputStream jis = new ZipInputStream(new FileInputStream(container.file))) {
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
final String name = entry.getName();
//skip directories
if (entry.isDirectory())
continue;
addUnknownFile(name, jis, classesOnly);
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
{
final String name = file.getName();
byte[] bytes = MiscUtils.getBytes(new FileInputStream(file));
ResourceContainer container = new ResourceContainer(file);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
{
final ClassNode cn = JarUtils.getNode(bytes);
container.resourceClasses.put(FilenameUtils.removeExtension(name), cn);
container.resourceClassBytes.put(name, bytes);
try (FileInputStream fis = new FileInputStream(file)) {
byte[] bytes = MiscUtils.getBytes(fis);
ResourceContainer container = new ResourceContainer(file);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
{
final ClassNode cn = JarUtils.getNode(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;
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.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.File;
import java.io.IOException;
import java.io.PrintStream;
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 *
@ -29,8 +42,8 @@ import java.io.Reader;
/**
* 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
* <tt>javax.swing.JComponent</tt>s will indicate the drop event with a changed
* a Java program. Any <tt>Component</tt> can be dropped onto, but only
* <tt>JComponent</tt>s will indicate the drop event with a changed
* border.
*
* 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();
* new FileDrop( myPanel, new FileDrop.Listener()
* { public void filesDropped( java.io.File[] files )
* { public void filesDropped( File[] files )
* {
* // handle file drop
* ...
@ -47,7 +60,7 @@ import java.io.Reader;
* }); // end FileDrop.Listener
*
* 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.
*
* 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"})
public class FileDrop {
private transient javax.swing.border.Border normalBorder;
private transient java.awt.dnd.DropTargetListener dropListener;
private transient Border normalBorder;
private transient DropTargetListener dropListener;
/**
* Discover if the running JVM is modern enough to have drag and drop.
@ -76,12 +89,12 @@ public class FileDrop {
private static Boolean supportsDnD;
// 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);
/**
* 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
* container will change borders.
*
@ -89,10 +102,10 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @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
c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), // Drag border
true, // Recursive
listener);
@ -100,7 +113,7 @@ public class FileDrop {
/**
* 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
* parent will change borders.
*
@ -109,11 +122,11 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(final java.awt.Component c, final boolean recursive,
public FileDrop(final Component c, final boolean recursive,
final Listener listener) {
this(null, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), // Drag border
recursive, // Recursive
listener);
@ -131,11 +144,11 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @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) {
this(out, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), false, // Recursive
listener);
} // end constructor
@ -143,7 +156,7 @@ public class FileDrop {
/**
* Constructor with a default border, debugging optionally turned on and the
* 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
* Debugging turned on, more status messages will be displayed to
* <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>.
* @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) {
this(out, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2,
BorderFactory.createMatteBorder(2, 2, 2, 2,
defaultBorderColor), // Drag border
recursive, // Recursive
listener);
@ -174,8 +187,8 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(final java.awt.Component c,
final javax.swing.border.Border dragBorder, final Listener listener) {
public FileDrop(final Component c,
final Border dragBorder, final Listener listener) {
this(null, // Logging stream
c, // Drop target
dragBorder, // Drag border
@ -185,7 +198,7 @@ public class FileDrop {
/**
* 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
* the parent will change borders.
*
@ -195,8 +208,8 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(final java.awt.Component c,
final javax.swing.border.Border dragBorder,
public FileDrop(final Component c,
final Border dragBorder,
final boolean recursive, final Listener listener) {
this(null, c, dragBorder, recursive, listener);
} // end constructor
@ -214,8 +227,8 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(final java.io.PrintStream out, final java.awt.Component c,
final javax.swing.border.Border dragBorder, final Listener listener) {
public FileDrop(final PrintStream out, final Component c,
final Border dragBorder, final Listener listener) {
this(out, // Logging stream
c, // Drop target
dragBorder, // Drag border
@ -237,21 +250,21 @@ public class FileDrop {
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(final java.io.PrintStream out, final java.awt.Component c,
final javax.swing.border.Border dragBorder,
public FileDrop(final PrintStream out, final Component c,
final Border dragBorder,
final boolean recursive, final Listener listener) {
if (supportsDnD()) { // Make a drop listener
dropListener = new java.awt.dnd.DropTargetListener() {
dropListener = new DropTargetListener() {
@Override
public void dragEnter(final java.awt.dnd.DropTargetDragEvent evt) {
public void dragEnter(final DropTargetDragEvent evt) {
log(out, "FileDrop: dragEnter event.");
// Is this an acceptable drag event?
if (isDragOk(out, evt)) {
// If it's a Swing component, set its border
if (c instanceof javax.swing.JComponent) {
final javax.swing.JComponent jc = (javax.swing.JComponent) c;
if (c instanceof JComponent) {
final JComponent jc = (JComponent) c;
normalBorder = jc.getBorder();
log(out, "FileDrop: normal border saved.");
jc.setBorder(dragBorder);
@ -260,8 +273,8 @@ public class FileDrop {
// Acknowledge that it's okay to enter
// evt.acceptDrag(
// java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY);
// DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag(DnDConstants.ACTION_COPY);
log(out, "FileDrop: event accepted.");
} // end if: drag ok
else { // Reject the drag event
@ -271,7 +284,7 @@ public class FileDrop {
} // end dragEnter
@Override
public void dragOver(final java.awt.dnd.DropTargetDragEvent evt) { // This
public void dragOver(final DropTargetDragEvent evt) { // This
// is
// called
// continually
@ -288,28 +301,28 @@ public class FileDrop {
} // end dragOver
@Override
public void drop(final java.awt.dnd.DropTargetDropEvent evt) {
public void drop(final DropTargetDropEvent evt) {
log(out, "FileDrop: drop event.");
try { // Get whatever was dropped
final java.awt.datatransfer.Transferable tr = evt
final Transferable tr = evt
.getTransferable();
// Is it a file list?
if (tr.isDataFlavorSupported(java.awt.datatransfer.DataFlavor.javaFileListFlavor)) {
if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
// Say we'll take it.
// evt.acceptDrop (
// java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
// DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop(DnDConstants.ACTION_COPY);
log(out, "FileDrop: file list accepted.");
// Get a useful list
final java.util.List fileList = (java.util.List) tr
.getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
.getTransferData(DataFlavor.javaFileListFlavor);
final java.util.Iterator iterator = fileList
.iterator();
// Convert list to array
final java.io.File[] filesTemp = new java.io.File[fileList
final File[] filesTemp = new File[fileList
.size()];
fileList.toArray(filesTemp);
@ -334,9 +347,9 @@ public class FileDrop {
if (flavor.isRepresentationClassReader()) {
// Say we'll take it.
// 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.");
final Reader reader = flavor
@ -367,12 +380,12 @@ public class FileDrop {
// (KDE/Gnome) support added.
} // end else: not a file list
} // end try
catch (final java.io.IOException io) {
catch (final IOException io) {
log(out, "FileDrop: IOException - abort:");
BytecodeViewer.handleException(io);
evt.rejectDrop();
} // end catch IOException
catch (final java.awt.datatransfer.UnsupportedFlavorException ufe) {
catch (final UnsupportedFlavorException ufe) {
log(out,
"FileDrop: UnsupportedFlavorException - abort:");
BytecodeViewer.handleException(
@ -381,8 +394,8 @@ public class FileDrop {
} // end catch: UnsupportedFlavorException
finally {
// If it's a Swing component, reset its border
if (c instanceof javax.swing.JComponent) {
final javax.swing.JComponent jc = (javax.swing.JComponent) c;
if (c instanceof JComponent) {
final JComponent jc = (JComponent) c;
jc.setBorder(normalBorder);
log(out, "FileDrop: normal border restored.");
} // end if: JComponent
@ -390,11 +403,11 @@ public class FileDrop {
} // end drop
@Override
public void dragExit(final java.awt.dnd.DropTargetEvent evt) {
public void dragExit(final DropTargetEvent evt) {
log(out, "FileDrop: dragExit event.");
// If it's a Swing component, reset its border
if (c instanceof javax.swing.JComponent) {
final javax.swing.JComponent jc = (javax.swing.JComponent) c;
if (c instanceof JComponent) {
final JComponent jc = (JComponent) c;
jc.setBorder(normalBorder);
log(out, "FileDrop: normal border restored.");
} // end if: JComponent
@ -402,13 +415,13 @@ public class FileDrop {
@Override
public void dropActionChanged(
final java.awt.dnd.DropTargetDragEvent evt) {
final DropTargetDragEvent evt) {
log(out, "FileDrop: dropActionChanged event.");
// Is this an acceptable drag event?
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.");
} // end if: drag ok
else {
@ -431,7 +444,7 @@ public class FileDrop {
boolean support;
try {
final Class arbitraryDndClass = Class
.forName("java.awt.dnd.DnDConstants");
.forName("DnDConstants");
support = true;
} // end try
catch (final Exception e) {
@ -457,7 +470,7 @@ public class FileDrop {
continue;
}
final java.io.File file = new java.io.File(
final File file = new File(
new java.net.URI(line));
list.add(file);
} 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) {
log(out, "FileDrop: IOException");
}
@ -474,10 +487,10 @@ public class FileDrop {
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
private void makeDropTarget(final java.io.PrintStream out,
final java.awt.Component c, final boolean recursive) {
private void makeDropTarget(final PrintStream out,
final Component c, final boolean recursive) {
// Make drop target
final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget();
final DropTarget dt = new DropTarget();
try {
dt.addDropTargetListener(dropListener);
} // end try
@ -492,29 +505,29 @@ public class FileDrop {
// end hierarchyChanged
c.addHierarchyListener(evt -> {
log(out, "FileDrop: Hierarchy changed.");
final java.awt.Component parent = c.getParent();
final Component parent = c.getParent();
if (parent == null) {
c.setDropTarget(null);
log(out, "FileDrop: Drop target cleared from component.");
} // end if: null parent
else {
new java.awt.dnd.DropTarget(c, dropListener);
new DropTarget(c, dropListener);
log(out, "FileDrop: Drop target added to component.");
} // end else: parent not null
}); // end hierarchy listener
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
final java.awt.Container cont = (java.awt.Container) c;
final Container cont = (Container) c;
// Get it's components
final java.awt.Component[] comps = cont.getComponents();
// Get its components
final Component[] comps = cont.getComponents();
// Set it's components as listeners also
for (java.awt.Component comp : comps) {
// Set its components as listeners also
for (Component comp : comps) {
makeDropTarget(out, comp, true);
}
} // end if: recursively set components as listener
@ -523,12 +536,12 @@ public class FileDrop {
/**
* Determine if the dragged data is a file list.
*/
private boolean isDragOk(final java.io.PrintStream out,
final java.awt.dnd.DropTargetDragEvent evt) {
private boolean isDragOk(final PrintStream out,
final DropTargetDragEvent evt) {
boolean ok = false;
// Get data flavors being dragged
final java.awt.datatransfer.DataFlavor[] flavors = evt
final DataFlavor[] flavors = evt
.getCurrentDataFlavors();
// See if any of the flavors are a file list
@ -539,7 +552,7 @@ public class FileDrop {
// Is the flavor a file list?
final DataFlavor curFlavor = flavors[i];
if (curFlavor
.equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor)
.equals(DataFlavor.javaFileListFlavor)
|| curFlavor.isRepresentationClassReader()) {
ok = true;
}
@ -564,7 +577,7 @@ public class FileDrop {
/**
* 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
// if
// requested
@ -578,12 +591,12 @@ public class FileDrop {
* 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
* 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
* @since 1.0
*/
public static boolean remove(final java.awt.Component c) {
public static boolean remove(final Component c) {
return remove(null, c, true);
} // end remove
@ -592,24 +605,24 @@ public class FileDrop {
* the all children. You should call this if you add and remove components
* 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
* @param c The component to unregister
* @param recursive Recursively unregister components within a container
* @since 1.0
*/
public static boolean remove(final java.io.PrintStream out,
final java.awt.Component c, final boolean recursive) { // Make sure
public static boolean remove(final PrintStream out,
final Component c, final boolean recursive) { // Make sure
// we
// support
// dnd.
//
if (supportsDnD()) {
log(out, "FileDrop: Removing drag-and-drop hooks.");
c.setDropTarget(null);
if (recursive && (c instanceof java.awt.Container)) {
final java.awt.Component[] comps = ((java.awt.Container) c)
if (recursive && (c instanceof Container)) {
final Component[] comps = ((Container) c)
.getComponents();
for (java.awt.Component comp : comps) {
for (Component comp : comps) {
remove(out, comp, true);
}
return true;
@ -628,7 +641,7 @@ public class FileDrop {
* example your class declaration may begin like this: <code><pre>
* public class MyClass implements FileDrop.Listener
* ...
* public void filesDropped( java.io.File[] files )
* public void filesDropped( File[] files )
* {
* ...
* } // end filesDropped
@ -645,7 +658,7 @@ public class FileDrop {
* @param files An array of <tt>File</tt>s that were dropped.
* @since 1.0
*/
void filesDropped(java.io.File[] files);
void filesDropped(File[] files);
} // end inner-interface Listener
@ -668,17 +681,17 @@ public class FileDrop {
public static class Event extends java.util.EventObject {
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
* and the {@link FileDrop} that initiated the event.
*
* @param files The array of files that were dropped
* @source The event source
* @param source The event source
* @since 1.1
*/
public Event(final java.io.File[] files, final Object source) {
public Event(final File[] files, final Object source) {
super(source);
this.files = files;
} // end constructor
@ -690,7 +703,7 @@ public class FileDrop {
* @return array of files that were dropped
* @since 1.1
*/
public java.io.File[] getFiles() {
public File[] getFiles() {
return files;
} // end getFiles
@ -701,7 +714,7 @@ public class FileDrop {
/**
* At last an easy way to encapsulate your custom objects for dragging and
* 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:
* <p>
* <pre>
@ -732,10 +745,10 @@ public class FileDrop {
* </code>
* </pre>
* <p>
* The {@link java.awt.datatransfer.DataFlavor} associated with
* The {@link DataFlavor} associated with
* {@link TransferableObject} has the representation class
* <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>. This data
* <tt>net.iharder.TransferableObject.class</tt> and MIME type
* <tt>application/x-net.iharder.TransferableObject</tt>. This data
* flavor is accessible via the static {@link #DATA_FLAVOR} property.
* <p>
* <p>
@ -748,44 +761,44 @@ public class FileDrop {
* @version 1.2
*/
public static class TransferableObject implements
java.awt.datatransfer.Transferable {
Transferable {
/**
* 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
*/
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
* <tt>net.iharder.dnd.TransferableObject.class</tt> and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
* <tt>net.iharder.TransferableObject.class</tt> and the MIME type
* <tt>application/x-net.iharder.TransferableObject</tt>.
*
* @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);
private Fetcher fetcher;
private Object data;
private java.awt.datatransfer.DataFlavor customFlavor;
private DataFlavor customFlavor;
/**
* Creates a new {@link TransferableObject} that wraps <var>data</var>.
* Along with the {@link #DATA_FLAVOR} associated with this class, this
* creates a custom data flavor with a representation class determined
* 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
* @since 1.1
*/
public TransferableObject(final Object data) {
this.data = data;
this.customFlavor = new java.awt.datatransfer.DataFlavor(
this.customFlavor = new DataFlavor(
data.getClass(), MIME_TYPE);
} // end constructor
@ -808,7 +821,7 @@ public class FileDrop {
* {@link #DATA_FLAVOR} associated with this class, this creates a
* custom data flavor with a representation class <var>dataClass</var>
* 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
* flavor
@ -818,12 +831,12 @@ public class FileDrop {
*/
public TransferableObject(final Class dataClass, final Fetcher fetcher) {
this.fetcher = fetcher;
this.customFlavor = new java.awt.datatransfer.DataFlavor(dataClass,
this.customFlavor = new DataFlavor(dataClass,
MIME_TYPE);
} // 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
* {@link Fetcher} constructor was used without passing a
* {@link java.lang.Class}.
@ -831,7 +844,7 @@ public class FileDrop {
* @return The custom data flavor for the encapsulated object
* @since 1.1
*/
public java.awt.datatransfer.DataFlavor getCustomDataFlavor() {
public DataFlavor getCustomDataFlavor() {
return customFlavor;
} // end getCustomDataFlavor
@ -842,22 +855,22 @@ public class FileDrop {
* data flavor, if one was created in the constructors, second the
* default {@link #DATA_FLAVOR} associated with
* {@link TransferableObject}, and third the
* java.awt.datatransfer.DataFlavor.stringFlavor.
* DataFlavor.stringFlavor.
*
* @return An array of supported data flavors
* @since 1.1
*/
@Override
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() {
public DataFlavor[] getTransferDataFlavors() {
if (customFlavor != null)
return new java.awt.datatransfer.DataFlavor[]{customFlavor,
return new DataFlavor[]{customFlavor,
DATA_FLAVOR,
java.awt.datatransfer.DataFlavor.stringFlavor}; // end
DataFlavor.stringFlavor}; // end
// flavors
// array
else
return new java.awt.datatransfer.DataFlavor[]{DATA_FLAVOR,
java.awt.datatransfer.DataFlavor.stringFlavor}; // end
return new DataFlavor[]{DATA_FLAVOR,
DataFlavor.stringFlavor}; // end
// flavors
// array
} // end getTransferDataFlavors
@ -875,19 +888,19 @@ public class FileDrop {
*/
@Override
public Object getTransferData(
final java.awt.datatransfer.DataFlavor flavor)
throws java.awt.datatransfer.UnsupportedFlavorException {
final DataFlavor flavor)
throws UnsupportedFlavorException {
// Native object
if (flavor.equals(DATA_FLAVOR))
return fetcher == null ? data : fetcher.getObject();
// String
if (flavor.equals(java.awt.datatransfer.DataFlavor.stringFlavor))
if (flavor.equals(DataFlavor.stringFlavor))
return fetcher == null ? data.toString() : fetcher.getObject()
.toString();
// We can't do anything else
throw new java.awt.datatransfer.UnsupportedFlavorException(flavor);
throw new UnsupportedFlavorException(flavor);
} // end getTransferData
/**
@ -901,7 +914,7 @@ public class FileDrop {
*/
@Override
public boolean isDataFlavorSupported(
final java.awt.datatransfer.DataFlavor flavor) {
final DataFlavor flavor) {
// Native object
if (flavor.equals(DATA_FLAVOR))
return true;

View file

@ -54,7 +54,7 @@ import static the.bytecode.club.bytecodeviewer.Constants.*;
@Deprecated
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
@ -67,41 +67,41 @@ public class JarUtils
ResourceContainer container = new ResourceContainer(jarFile);
LinkedHashMap<String, byte[]> files = new LinkedHashMap<>();
ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile));
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
try {
final String name = entry.getName();
final byte[] bytes = MiscUtils.getBytes(jis);
if (!name.endsWith(".class")) {
if (!entry.isDirectory())
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 {
try (FileInputStream fis = new FileInputStream(jarFile);
ZipInputStream jis = new ZipInputStream(fis)) {
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
try {
final String name = entry.getName();
final byte[] bytes = MiscUtils.getBytes(jis);
if (!name.endsWith(".class")) {
if (!entry.isDirectory())
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) {
//ignore cause apache unzip
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
} catch (java.io.EOFException | ZipException e) {
//ignore cause apache unzip
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
}
}
}
jis.close();
container.resourceFiles = files;
BytecodeViewer.addResourceContainer(container);
}
@ -158,33 +158,34 @@ public class JarUtils
public static ArrayList<ClassNode> loadClasses(final File jarFile) throws IOException
{
ArrayList<ClassNode> classes = new ArrayList<>();
ZipInputStream jis = new ZipInputStream(new FileInputStream(jarFile));
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
try {
final String name = entry.getName();
if (name.endsWith(".class")) {
byte[] bytes = MiscUtils.getBytes(jis);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe"))
{
try {
final ClassNode cn = getNode(bytes);
classes.add(cn);
} catch (Exception e) {
e.printStackTrace();
try (FileInputStream fis = new FileInputStream(jarFile);
ZipInputStream jis = new ZipInputStream(fis)) {
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
try {
final String name = entry.getName();
if (name.endsWith(".class")) {
byte[] bytes = MiscUtils.getBytes(jis);
if (MiscUtils.getFileHeaderMagicNumber(bytes).equalsIgnoreCase("cafebabe")) {
try {
final ClassNode cn = getNode(bytes);
classes.add(cn);
} catch (Exception e) {
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) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
}
}
}
jis.close();
return classes;
}
@ -200,24 +201,24 @@ public class JarUtils
LinkedHashMap<String, byte[]> files = new LinkedHashMap<>();
ZipInputStream jis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
try {
final String name = entry.getName();
if (!name.endsWith(".class") && !name.endsWith(".dex")) {
if (!entry.isDirectory())
files.put(name, MiscUtils.getBytes(jis));
try (ZipInputStream jis = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
try {
final String name = entry.getName();
if (!name.endsWith(".class") && !name.endsWith(".dex")) {
if (!entry.isDirectory())
files.put(name, MiscUtils.getBytes(jis));
jis.closeEntry();
}
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
}
} catch (Exception e) {
BytecodeViewer.handleException(e);
} finally {
jis.closeEntry();
}
}
jis.close();
return files;
}
@ -246,9 +247,8 @@ public class JarUtils
*/
public static void saveAsJar(ArrayList<ClassNode> nodeList, String path,
String manifest) {
try {
JarOutputStream out = new JarOutputStream(
new FileOutputStream(path));
try (FileOutputStream fos = new FileOutputStream(path);
JarOutputStream out = new JarOutputStream(fos)) {
for (ClassNode cn : nodeList) {
ClassWriter cw = new ClassWriter(0);
cn.accept(cw);
@ -262,7 +262,7 @@ public class JarUtils
out.write((manifest.trim() + "\r\n\r\n").getBytes());
out.closeEntry();
for (ResourceContainer container : BytecodeViewer.resourceContainers)
for (ResourceContainer container : BytecodeViewer.resourceContainers) {
for (Entry<String, byte[]> entry : container.resourceFiles.entrySet()) {
String filename = entry.getKey();
if (!filename.startsWith("META-INF")) {
@ -271,8 +271,7 @@ public class JarUtils
out.closeEntry();
}
}
out.close();
}
} catch (IOException 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)
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<>();
for (ClassNode cn : nodeList)
{
@ -308,9 +307,7 @@ public class JarUtils
out.closeEntry();
}
}
noDupe.clear();
out.close();
}
catch (IOException e)
{
@ -349,8 +346,8 @@ public class JarUtils
* @param path the exact jar output path
*/
public static void saveAsJar(ArrayList<ClassNode> nodeList, String path) {
try {
JarOutputStream out = new JarOutputStream(new FileOutputStream(path));
try (FileOutputStream fos = new FileOutputStream(path);
JarOutputStream out = new JarOutputStream(fos)) {
ArrayList<String> noDupe = new ArrayList<>();
for (ClassNode cn : nodeList) {
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()) {
String filename = entry.getKey();
if (!filename.startsWith("META-INF")) {
@ -378,9 +375,9 @@ public class JarUtils
}
}
}
}
noDupe.clear();
out.close();
} catch (IOException e) {
BytecodeViewer.handleException(e);
}

View file

@ -85,22 +85,23 @@ public class MiscUtils
public static void printProcess(Process process) throws Exception {
//Read out dir output
InputStream is = process.getInputStream();
try (InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
br.close();
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
System.out.println(line);
try (InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
String 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)
{
try {
return ImageIO.read(new ByteArrayInputStream(contents));
try (ByteArrayInputStream bais = new ByteArrayInputStream(contents)) {
return ImageIO.read(bais);
} catch (IOException e) {
BytecodeViewer.handleException(e);
}
@ -285,15 +286,15 @@ public class MiscUtils
*/
public static byte[] getBytes(final InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int a;
while ((a = is.read(buffer)) != -1)
baos.write(buffer, 0, a);
baos.close();
return baos.toByteArray();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int a;
while ((a = is.read(buffer)) != -1)
baos.write(buffer, 0, a);
return baos.toByteArray();
}
}
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.
*
* 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.
*/
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 {
File file = new File(jarPath);
JarFile jar = new JarFile(file);
try (JarFile jar = new JarFile(file)) {
// fist get all directories,
// then make those directory on the destination Path
/*for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = (JarEntry) enums.nextElement();
// fist get all directories,
// then make those directory on the destination Path
/*for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) {
JarEntry entry = (JarEntry) enums.nextElement();
String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName);
String fileName = destinationDir + File.separator + entry.getName();
File f = new File(fileName);
if (fileName.endsWith("/")) {
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());
if (fileName.endsWith("/")) {
f.mkdirs();
}
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) {
byte[] buffer = new byte[1024];
try {
FileOutputStream fos = new FileOutputStream(outputZip);
ZipOutputStream zos = new ZipOutputStream(fos);
try (FileOutputStream fos = new FileOutputStream(outputZip);
ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipEntry ze = new ZipEntry(inputFile.getName());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(inputFile);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
try (FileInputStream in = new FileInputStream(inputFile)) {
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
in.close();
zos.closeEntry();
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception {
ZipOutputStream zip;
FileOutputStream fileWriter;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip, ignore);
zip.flush();
zip.close();
try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZip("", srcFolder, zip, ignore);
zip.flush();
}
}
public static void zipFolderAPKTool(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip;
FileOutputStream fileWriter;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZipAPKTool("", srcFolder, zip);
zip.flush();
zip.close();
try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZipAPKTool("", srcFolder, zip);
zip.flush();
}
}
public static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String ignore)
@ -150,17 +129,17 @@ public final class ZipUtils {
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
ZipEntry entry;
if (ignore == null)
entry = new ZipEntry(path + "/" + folder.getName());
else
entry = new ZipEntry(path.replace(ignore, "BCV_Krakatau") + "/" + folder.getName());
zip.putNextEntry(entry);
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
try (FileInputStream in = new FileInputStream(srcFile)) {
ZipEntry entry;
if (ignore == null)
entry = new ZipEntry(path + "/" + folder.getName());
else
entry = new ZipEntry(path.replace(ignore, "BCV_Krakatau") + "/" + folder.getName());
zip.putNextEntry(entry);
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
in.close();
}
}
@ -183,16 +162,16 @@ public final class ZipUtils {
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
ZipEntry entry;
try (FileInputStream in = new FileInputStream(srcFile)) {
ZipEntry entry;
entry = new ZipEntry(path + "/" + folder.getName());
zip.putNextEntry(entry);
entry = new ZipEntry(path + "/" + folder.getName());
zip.putNextEntry(entry);
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
in.close();
}
}