refactor: Replace to nio & apply CS inspection skips (#3055)

This commit is contained in:
sv99 2023-05-13 13:12:22 +03:00 committed by GitHub
parent 8d222d7f58
commit 48b71b34b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 60 additions and 26 deletions

View File

@ -41,6 +41,7 @@ import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;
@ -98,6 +99,7 @@ public class Androlib {
smaliDir = new File(outDir, SMALI_DIRNAME + "_" + filename.substring(0, filename.indexOf(".")));
}
OS.rmdir(smaliDir);
//noinspection ResultOfMethodCallIgnored
smaliDir.mkdirs();
LOGGER.info("Baksmaling " + filename + "...");
DexFile dexFile = SmaliDecoder.decode(apkFile, smaliDir, filename, bakDeb, apiLevel);
@ -236,6 +238,7 @@ public class Androlib {
LOGGER.info("Copying original files...");
File originalDir = new File(outDir, "original");
if (!originalDir.exists()) {
//noinspection ResultOfMethodCallIgnored
originalDir.mkdirs();
}
@ -313,6 +316,7 @@ public class Androlib {
outFile = new File(appDir, "dist" + File.separator + (outFileName == null ? "out.apk" : outFileName));
}
//noinspection ResultOfMethodCallIgnored
new File(appDir, APK_DIRNAME).mkdirs();
File manifest = new File(appDir, "AndroidManifest.xml");
File manifestOriginal = new File(appDir, "AndroidManifest.xml.orig");
@ -353,6 +357,7 @@ public class Androlib {
if (manifest.isFile() && manifest.exists()) {
try {
if (manifestOriginal.exists()) {
//noinspection ResultOfMethodCallIgnored
manifestOriginal.delete();
}
FileUtils.copyFile(manifest, manifestOriginal);
@ -412,7 +417,7 @@ public class Androlib {
if (buildOptions.forceBuildAll || isModified(working, stored)) {
LOGGER.info("Copying " + appDir.toString() + " " + filename + " file...");
try {
BrutIO.copyAndClose(new FileInputStream(working), new FileOutputStream(stored));
BrutIO.copyAndClose(Files.newInputStream(working.toPath()), Files.newOutputStream(stored.toPath()));
return true;
} catch (IOException ex) {
throw new AndrolibException(ex);
@ -433,6 +438,7 @@ public class Androlib {
}
if (buildOptions.forceBuildAll || isModified(smaliDir, dex)) {
LOGGER.info("Smaling " + folder + " folder into " + filename + "...");
//noinspection ResultOfMethodCallIgnored
dex.delete();
SmaliBuilder.build(smaliDir, dex, buildOptions.forceApi > 0 ? buildOptions.forceApi : mMinSdkVersion);
}
@ -503,6 +509,7 @@ public class Androlib {
File netSecConfOrig = new File(appDir, "res/xml/network_security_config.xml");
if (netSecConfOrig.exists()) {
LOGGER.info("Replacing existing network_security_config.xml!");
//noinspection ResultOfMethodCallIgnored
netSecConfOrig.delete();
}
ResXmlPatcher.modNetworkSecurityConfig(netSecConfOrig);
@ -511,7 +518,9 @@ public class Androlib {
}
File apkFile = File.createTempFile("APKTOOL", null);
//noinspection ResultOfMethodCallIgnored
apkFile.delete();
//noinspection ResultOfMethodCallIgnored
resourceFile.delete();
File ninePatch = new File(appDir, "9patch");
@ -539,6 +548,7 @@ public class Androlib {
}
// delete tmpDir
//noinspection ResultOfMethodCallIgnored
apkFile.delete();
}
return true;
@ -576,6 +586,7 @@ public class Androlib {
LOGGER.info("Building AndroidManifest.xml...");
File apkFile = File.createTempFile("APKTOOL", null);
//noinspection ResultOfMethodCallIgnored
apkFile.delete();
File ninePatch = new File(appDir, "9patch");
@ -590,6 +601,7 @@ public class Androlib {
Directory tmpDir = new ExtFile(apkFile).getDirectory();
tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES);
//noinspection ResultOfMethodCallIgnored
apkFile.delete();
}
return true;
@ -668,7 +680,7 @@ public class Androlib {
try (
ZipFile inputFile = new ZipFile(tempFile);
ZipOutputStream actualOutput = new ZipOutputStream(new FileOutputStream(outFile))
ZipOutputStream actualOutput = new ZipOutputStream(Files.newOutputStream(outFile.toPath()))
) {
copyExistingFiles(inputFile, actualOutput);
copyUnknownFiles(appDir, actualOutput, files);
@ -677,6 +689,7 @@ public class Androlib {
}
// Remove our temporary file.
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
@ -726,7 +739,7 @@ public class Androlib {
newEntry.setMethod(ZipEntry.STORED);
newEntry.setSize(inputFile.length());
newEntry.setCompressedSize(-1);
BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(inputFile));
BufferedInputStream unknownFile = new BufferedInputStream(Files.newInputStream(inputFile.toPath()));
CRC32 crc = BrutIO.calculateCrc(unknownFile);
newEntry.setCrc(crc.getValue());
unknownFile.close();
@ -743,10 +756,12 @@ public class Androlib {
public void buildApk(File appDir, File outApk) throws AndrolibException {
LOGGER.info("Building apk file...");
if (outApk.exists()) {
//noinspection ResultOfMethodCallIgnored
outApk.delete();
} else {
File outDir = outApk.getParentFile();
if (outDir != null && !outDir.exists()) {
//noinspection ResultOfMethodCallIgnored
outDir.mkdirs();
}
}

View File

@ -28,6 +28,7 @@ import com.android.tools.smali.smali.smaliTreeWalker;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
public class SmaliMod {
public static boolean assembleSmaliFile(File smaliFile, DexBuilder dexBuilder, int apiLevel, boolean verboseErrors,
@ -36,7 +37,7 @@ public class SmaliMod {
CommonTokenStream tokens;
smaliFlexLexer lexer;
InputStream is = new FileInputStream(smaliFile);
InputStream is = Files.newInputStream(smaliFile.toPath());
InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
lexer = new smaliFlexLexer(reader, apiLevel);

View File

@ -37,6 +37,7 @@ import org.apache.commons.io.IOUtils;
import org.xmlpull.v1.XmlSerializer;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Logger;
import java.util.zip.CRC32;
@ -185,7 +186,7 @@ final public class AndrolibResources {
attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next());
Directory inApk, in = null, out;
Directory inApk, out;
try {
inApk = apkFile.getDirectory();
out = new FileDirectory(outDir);
@ -433,7 +434,8 @@ final public class AndrolibResources {
if (buildOptions.doNotCompress != null && !customAapt) {
// Use custom -e option to avoid limits on commandline length.
// Can only be used when custom aapt binary is not used.
String extensionsFilePath = createDoNotCompressExtensionsFile(buildOptions).getAbsolutePath();
String extensionsFilePath =
Objects.requireNonNull(createDoNotCompressExtensionsFile(buildOptions)).getAbsolutePath();
cmd.add("-e");
cmd.add(extensionsFilePath);
} else if (buildOptions.doNotCompress != null) {
@ -555,7 +557,8 @@ final public class AndrolibResources {
if (buildOptions.doNotCompress != null && !customAapt) {
// Use custom -e option to avoid limits on commandline length.
// Can only be used when custom aapt binary is not used.
String extensionsFilePath = createDoNotCompressExtensionsFile(buildOptions).getAbsolutePath();
String extensionsFilePath =
Objects.requireNonNull(createDoNotCompressExtensionsFile(buildOptions)).getAbsolutePath();
cmd.add("-e");
cmd.add(extensionsFilePath);
} else if (buildOptions.doNotCompress != null) {
@ -801,7 +804,7 @@ final public class AndrolibResources {
if (id == 1) {
try (InputStream in = getAndroidFrameworkResourcesAsStream();
OutputStream out = new FileOutputStream(apk)) {
OutputStream out = Files.newOutputStream(apk.toPath())) {
IOUtils.copy(in, out);
return apk;
} catch (IOException ex) {
@ -822,12 +825,13 @@ final public class AndrolibResources {
LOGGER.warning("Can't empty framework directory, no file found at: " + apk.getAbsolutePath());
} else {
try {
if (apk.exists() && dir.listFiles().length > 1 && ! buildOptions.forceDeleteFramework) {
if (apk.exists() && Objects.requireNonNull(dir.listFiles()).length > 1 && ! buildOptions.forceDeleteFramework) {
LOGGER.warning("More than default framework detected. Please run command with `--force` parameter to wipe framework directory.");
} else {
for (File file : dir.listFiles()) {
for (File file : Objects.requireNonNull(dir.listFiles())) {
if (file.isFile() && file.getName().endsWith(".apk")) {
LOGGER.info("Removing " + file.getName() + " framework file...");
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
@ -879,7 +883,7 @@ final public class AndrolibResources {
+ (tag == null ? "" : '-' + tag)
+ ".apk");
out = new ZipOutputStream(new FileOutputStream(outFile));
out = new ZipOutputStream(Files.newOutputStream(outFile.toPath()));
out.setMethod(ZipOutputStream.STORED);
CRC32 crc = new CRC32();
crc.update(data);
@ -919,8 +923,9 @@ final public class AndrolibResources {
public void publicizeResources(File arscFile) throws AndrolibException {
byte[] data = new byte[(int) arscFile.length()];
try(InputStream in = new FileInputStream(arscFile);
OutputStream out = new FileOutputStream(arscFile)) {
try(InputStream in = Files.newInputStream(arscFile.toPath());
OutputStream out = Files.newOutputStream(arscFile.toPath())) {
//noinspection ResultOfMethodCallIgnored
in.read(data);
publicizeResources(data);
out.write(data);
@ -1034,7 +1039,7 @@ final public class AndrolibResources {
public BuildOptions buildOptions;
public Map<String, String> mResFileMapping = new HashMap();
public Map<String, String> mResFileMapping = new HashMap<>();
// TODO: dirty static hack. I have to refactor decoding mechanisms.
public static boolean sKeepBroken = false;

View File

@ -168,7 +168,7 @@ public final class ResXmlPatcher {
* build, thus preventing the application from installing. This is from a bug/error
* in AOSP where public resources cannot be part of an authorities attribute within
* a provider tag.
*
* <p>
* This finds any reference and replaces it with the literal value found in the
* res/values/strings.xml file.
*

View File

@ -25,9 +25,9 @@ import com.android.tools.smali.dexlib2.Opcodes;
import com.android.tools.smali.dexlib2.writer.builder.DexBuilder;
import com.android.tools.smali.dexlib2.writer.io.FileDataStore;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.logging.Logger;
public class SmaliBuilder {
@ -63,7 +63,7 @@ public class SmaliBuilder {
private void buildFile(String fileName, DexBuilder dexBuilder)
throws AndrolibException, IOException {
File inFile = new File(mSmaliDir, fileName);
InputStream inStream = new FileInputStream(inFile);
InputStream inStream = Files.newInputStream(inFile.toPath());
if (fileName.endsWith(".smali")) {
try {

View File

@ -80,7 +80,7 @@ public class SmaliDecoder {
dexEntry = container.getEntry(mDexFile);
}
// Double check the passed param exists
// Double-check the passed param exists
if (dexEntry == null) {
dexEntry = container.getEntry(container.getDexEntryNames().get(0));
}

View File

@ -22,6 +22,7 @@ import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Objects;
/**
* Implementation of XmlSerializer interface from XmlPull V1 API. This
@ -106,7 +107,7 @@ public class MXSerializer implements XmlSerializer {
private final boolean checkNamesInterned = false;
private void checkInterning(String name) {
if (namesInterned && name != name.intern()) {
if (namesInterned && !Objects.equals(name, name.intern())) {
throw new IllegalArgumentException("all names passed as arguments must be interned"
+ "when NAMES INTERNED feature is enabled");
}

View File

@ -127,7 +127,7 @@ public abstract class TestUtils {
public static byte[] readHeaderOfFile(File file, int size) throws IOException {
byte[] buffer = new byte[size];
InputStream inputStream = new FileInputStream(file);
InputStream inputStream = Files.newInputStream(file.toPath());
if (inputStream.read(buffer) != buffer.length) {
throw new IOException("File size too small for buffer length: " + size);
}

View File

@ -90,6 +90,7 @@ public class DirUtil {
} else {
String cleanedFilename = BrutIO.sanitizeUnknownFile(out, fileName);
File outFile = new File(out, cleanedFilename);
//noinspection ResultOfMethodCallIgnored
outFile.getParentFile().mkdirs();
BrutIO.copyAndClose(in.getFileInput(fileName), Files.newOutputStream(outFile.toPath()));
}

View File

@ -59,6 +59,7 @@ public class FileDirectory extends AbstractDirectory {
@Override
protected AbstractDirectory createDirLocal(String name) throws DirectoryException {
File dir = new File(generatePath(name));
//noinspection ResultOfMethodCallIgnored
dir.mkdir();
return new FileDirectory(dir);
}
@ -93,6 +94,7 @@ public class FileDirectory extends AbstractDirectory {
@Override
protected void removeFileLocal(String name) {
//noinspection ResultOfMethodCallIgnored
new File(generatePath(name)).delete();
}

View File

@ -22,6 +22,7 @@ import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.file.Files;
import java.util.Collection;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
@ -39,7 +40,7 @@ public class ZipUtils {
throws BrutException, IOException {
mDoNotCompress = doNotCompress;
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zip));
ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zip.toPath()));
zipFolders(folder, zipOutputStream);
// We manually set the assets because we need to retain the folder structure
@ -67,7 +68,7 @@ public class ZipUtils {
if (mDoNotCompress != null && (mDoNotCompress.contains(extension) || mDoNotCompress.contains(zipEntry.getName()))) {
zipEntry.setMethod(ZipEntry.STORED);
zipEntry.setSize(file.length());
BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(file));
BufferedInputStream unknownFile = new BufferedInputStream(Files.newInputStream(file.toPath()));
CRC32 crc = BrutIO.calculateCrc(unknownFile);
zipEntry.setCrc(crc.getValue());
unknownFile.close();

View File

@ -67,6 +67,7 @@ public class AaptManager {
if (! aaptPath.isEmpty()) {
File aaptFile = new File(aaptPath);
if (aaptFile.canRead() && aaptFile.exists()) {
//noinspection ResultOfMethodCallIgnored
aaptFile.setExecutable(true);
return aaptFile.getPath();
} else {
@ -101,6 +102,7 @@ public class AaptManager {
if (!aapt.isFile()) {
throw new BrutException("Could not identify aapt binary as executable.");
}
//noinspection ResultOfMethodCallIgnored
aapt.setExecutable(true);
List<String> cmd = new ArrayList<>();

View File

@ -20,6 +20,7 @@ import brut.common.BrutException;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
@ -51,7 +52,7 @@ public abstract class Jar {
File fileOut = File.createTempFile(tmpPrefix, suffix + ".tmp");
fileOut.deleteOnExit();
OutputStream out = new FileOutputStream(fileOut);
OutputStream out = Files.newOutputStream(fileOut.toPath());
IOUtils.copy(in, out);
in.close();
out.close();

View File

@ -20,6 +20,7 @@ import brut.common.BrutException;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -43,15 +44,18 @@ public class OS {
if (file.isDirectory()) {
rmdir(file);
} else {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
//noinspection ResultOfMethodCallIgnored
dir.delete();
}
public static void rmfile(String file) {
File del = new File(file);
del.delete();
//noinspection ResultOfMethodCallIgnored
del.delete();
}
public static void rmdir(String dir) throws BrutException {
@ -59,6 +63,7 @@ public class OS {
}
public static void cpdir(File src, File dest) throws BrutException {
//noinspection ResultOfMethodCallIgnored
dest.mkdirs();
File[] files = src.listFiles();
if (files == null) {
@ -72,8 +77,8 @@ public class OS {
continue;
}
try {
try (InputStream in = new FileInputStream(file)) {
try (OutputStream out = new FileOutputStream(destFile)) {
try (InputStream in = Files.newInputStream(file.toPath())) {
try (OutputStream out = Files.newOutputStream(destFile.toPath())) {
IOUtils.copy(in, out);
}
}