diff options
author | Paulo Casanova <pasc@google.com> | 2017-01-04 10:01:35 +0000 |
---|---|---|
committer | Paulo Casanova <pasc@google.com> | 2017-01-04 10:01:35 +0000 |
commit | 1349abb9d4506275c0eb5aa6ef9f757c51e9de97 (patch) | |
tree | 0a2d5a3962cbb2238ea489dc83168f8407ab9358 /src | |
parent | ba150accda722df57396f79c0fb70df9fe9673db (diff) | |
download | apkzlib-1349abb9d4506275c0eb5aa6ef9f757c51e9de97.tar.gz |
Standardize apkzfile.
Standardize field names and some minor comment issues.
Test: No tests needed
Change-Id: Ia2fd816d913239f73640656069ba9ae82e09f08a
Diffstat (limited to 'src')
39 files changed, 1038 insertions, 940 deletions
diff --git a/src/main/java/com/android/apkzlib/sign/ManifestGenerationExtension.java b/src/main/java/com/android/apkzlib/sign/ManifestGenerationExtension.java index a8f9b98..33c47c6 100644 --- a/src/main/java/com/android/apkzlib/sign/ManifestGenerationExtension.java +++ b/src/main/java/com/android/apkzlib/sign/ManifestGenerationExtension.java @@ -65,25 +65,25 @@ public class ManifestGenerationExtension { * Who should be reported as the manifest builder. */ @Nonnull - private final String mBuiltBy; + private final String builtBy; /** * Who should be reported as the manifest creator. */ @Nonnull - private final String mCreatedBy; + private final String createdBy; /** * The file this extension is attached to. {@code null} if not yet registered. */ @Nullable - private ZFile mZFile; + private ZFile zFile; /** * The zip file's manifest. */ @Nonnull - private final Manifest mManifest; + private final Manifest manifest; /** * Byte representation of the manifest. There is no guarantee that two writes of the java's @@ -99,22 +99,22 @@ public class ManifestGenerationExtension { * receive the same byte array. */ @Nonnull - private CachedSupplier<byte[]> mManifestBytes; + private CachedSupplier<byte[]> manifestBytes; /** - * Has the current manifest been changed and not yet flushed? If {@link #mDirty} is - * {@code true}, then {@link #mManifestBytes} should not be valid. This means that - * marking the manifest as dirty should also invalidate {@link #mManifestBytes}. To avoid - * breaking the invariant, instead of setting {@link #mDirty}, {@link #markDirty()} should + * Has the current manifest been changed and not yet flushed? If {@link #dirty} is + * {@code true}, then {@link #manifestBytes} should not be valid. This means that + * marking the manifest as dirty should also invalidate {@link #manifestBytes}. To avoid + * breaking the invariant, instead of setting {@link #dirty}, {@link #markDirty()} should * be called. */ - private boolean mDirty; + private boolean dirty; /** * The extension to register with the {@link ZFile}. {@code null} if not registered. */ @Nullable - private ZFileExtension mExtension; + private ZFileExtension extension; /** * Creates a new extension. This will not register the extension with the provided @@ -124,14 +124,14 @@ public class ManifestGenerationExtension { * @param createdBy who created the manifest? */ public ManifestGenerationExtension(@Nonnull String builtBy, @Nonnull String createdBy) { - mBuiltBy = builtBy; - mCreatedBy = createdBy; - mManifest = new Manifest(); - mDirty = false; - mManifestBytes = new CachedSupplier<>(() -> { + this.builtBy = builtBy; + this.createdBy = createdBy; + manifest = new Manifest(); + dirty = false; + manifestBytes = new CachedSupplier<>(() -> { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); try { - mManifest.write(outBytes); + manifest.write(outBytes); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -145,8 +145,8 @@ public class ManifestGenerationExtension { * read and/or written. */ private void markDirty() { - mDirty = true; - mManifestBytes.reset(); + dirty = true; + manifestBytes.reset(); } /** @@ -156,12 +156,12 @@ public class ManifestGenerationExtension { * @throws IOException failed to analyze the zip */ public void register(@Nonnull ZFile zFile) throws IOException { - Preconditions.checkState(mExtension == null, "register() has already been invoked."); - mZFile = zFile; + Preconditions.checkState(extension == null, "register() has already been invoked."); + this.zFile = zFile; rebuildManifest(); - mExtension = new ZFileExtension() { + extension = new ZFileExtension() { @Nullable @Override public IOExceptionRunnable beforeUpdate() { @@ -169,16 +169,16 @@ public class ManifestGenerationExtension { } }; - mZFile.addZFileExtension(mExtension); + this.zFile.addZFileExtension(extension); } /** * Rebuilds the zip file's manifest, if it needs changes. */ private void rebuildManifest() throws IOException { - Verify.verifyNotNull(mZFile, "mZFile == null"); + Verify.verifyNotNull(zFile, "zFile == null"); - StoredEntry manifestEntry = mZFile.get(MANIFEST_NAME); + StoredEntry manifestEntry = zFile.get(MANIFEST_NAME); if (manifestEntry != null) { /* @@ -186,13 +186,13 @@ public class ManifestGenerationExtension { * because writing the manifest may not generate the same byte sequence, which may * trigger an unnecessary re-sign of the jar. */ - mManifest.clear(); + manifest.clear(); byte[] manifestBytes = manifestEntry.read(); - mManifest.read(new ByteArrayInputStream(manifestBytes)); - mManifestBytes.precomputed(manifestBytes); + manifest.read(new ByteArrayInputStream(manifestBytes)); + this.manifestBytes.precomputed(manifestBytes); } - Attributes mainAttributes = mManifest.getMainAttributes(); + Attributes mainAttributes = manifest.getMainAttributes(); String currentVersion = mainAttributes.getValue(ManifestAttributes.MANIFEST_VERSION); if (currentVersion == null) { setMainAttribute( @@ -207,8 +207,8 @@ public class ManifestGenerationExtension { /* * We "blindly" override all other main attributes. */ - setMainAttribute(ManifestAttributes.BUILT_BY, mBuiltBy); - setMainAttribute(ManifestAttributes.CREATED_BY, mCreatedBy); + setMainAttribute(ManifestAttributes.BUILT_BY, builtBy); + setMainAttribute(ManifestAttributes.CREATED_BY, createdBy); } /** @@ -218,7 +218,7 @@ public class ManifestGenerationExtension { * @param value the value */ private void setMainAttribute(@Nonnull String attribute, @Nonnull String value) { - Attributes mainAttributes = mManifest.getMainAttributes(); + Attributes mainAttributes = manifest.getMainAttributes(); String current = mainAttributes.getValue(attribute); if (!value.equals(current)) { mainAttributes.putValue(attribute, value); @@ -232,13 +232,13 @@ public class ManifestGenerationExtension { * @throws IOException failed to update the manifest */ private void updateManifest() throws IOException { - Verify.verifyNotNull(mZFile, "mZFile == null"); + Verify.verifyNotNull(zFile, "zFile == null"); - if (!mDirty) { + if (!dirty) { return; } - mZFile.add(MANIFEST_NAME, new ByteArrayInputStream(mManifestBytes.get())); - mDirty = false; + zFile.add(MANIFEST_NAME, new ByteArrayInputStream(manifestBytes.get())); + dirty = false; } } diff --git a/src/main/java/com/android/apkzlib/sign/SigningExtension.java b/src/main/java/com/android/apkzlib/sign/SigningExtension.java index 2673bed..2685aa1 100644 --- a/src/main/java/com/android/apkzlib/sign/SigningExtension.java +++ b/src/main/java/com/android/apkzlib/sign/SigningExtension.java @@ -76,60 +76,60 @@ public class SigningExtension { /** * Minimum API Level on which this APK is supposed to run. */ - private final int mMinSdkVersion; + private final int minSdkVersion; /** * Whether JAR signing (aka v1 signing) is enabled. */ - private final boolean mV1SigningEnabled; + private final boolean v1SigningEnabled; /** * Whether APK Signature Scheme v2 sining (aka v2 signing) is enabled. */ - private final boolean mV2SigningEnabled; + private final boolean v2SigningEnabled; /** * Certificate of the signer, to be embedded into the APK's signature. */ @Nonnull - private final X509Certificate mCertificate; + private final X509Certificate certificate; /** * APK signer which performs most of the heavy lifting. */ @Nonnull - private final ApkSignerEngine mSigner; + private final ApkSignerEngine signer; /** - * Names of APK entries which have been processed by {@link #mSigner}. + * Names of APK entries which have been processed by {@link #signer}. */ - private final Set<String> mSignerProcessedOutputEntryNames = new HashSet<>(); + private final Set<String> signerProcessedOutputEntryNames = new HashSet<>(); /** * Cached contents of the most recently output APK Signing Block or {@code null} if the block * hasn't yet been output. */ @Nullable - private byte[] mCachedApkSigningBlock; + private byte[] cachedApkSigningBlock; /** * {@code true} if signatures may need to be output, {@code false} if there's no need to output * signatures. This is used in an optimization where we don't modify the APK if it's already * signed and if no JAR entries have been added to or removed from the file. */ - private boolean mDirty; + private boolean dirty; /** * The extension registered with the {@link ZFile}. {@code null} if not registered. */ @Nullable - private ZFileExtension mExtension; + private ZFileExtension extension; /** * The file this extension is attached to. {@code null} if not yet registered. */ @Nullable - private ZFile mZFile; + private ZFile zFile; public SigningExtension( int minSdkVersion, @@ -140,24 +140,24 @@ public class SigningExtension { DefaultApkSignerEngine.SignerConfig signerConfig = new DefaultApkSignerEngine.SignerConfig.Builder( "CERT", privateKey, ImmutableList.of(certificate)).build(); - mSigner = + signer = new DefaultApkSignerEngine.Builder(ImmutableList.of(signerConfig), minSdkVersion) .setOtherSignersSignaturesPreserved(false) .setV1SigningEnabled(v1SigningEnabled) .setV2SigningEnabled(v2SigningEnabled) .setCreatedBy("1.0 (Android)") .build(); - mMinSdkVersion = minSdkVersion; - mV1SigningEnabled = v1SigningEnabled; - mV2SigningEnabled = v2SigningEnabled; - mCertificate = certificate; + this.minSdkVersion = minSdkVersion; + this.v1SigningEnabled = v1SigningEnabled; + this.v2SigningEnabled = v2SigningEnabled; + this.certificate = certificate; } public void register(@Nonnull ZFile zFile) throws NoSuchAlgorithmException, IOException { - Preconditions.checkState(mExtension == null, "register() already invoked"); - mZFile = zFile; - mDirty = !isCurrentSignatureAsRequested(); - mExtension = new ZFileExtension() { + Preconditions.checkState(extension == null, "register() already invoked"); + this.zFile = zFile; + dirty = !isCurrentSignatureAsRequested(); + extension = new ZFileExtension() { @Override public IOExceptionRunnable added( @Nonnull StoredEntry entry, @Nullable StoredEntry replaced) { @@ -185,7 +185,7 @@ public class SigningExtension { onOutputClosed(); } }; - mZFile.addZFileExtension(mExtension); + this.zFile.addZFileExtension(extension); } /** @@ -196,8 +196,8 @@ public class SigningExtension { ApkVerifier.Result result; try { result = - new ApkVerifier.Builder(new ZFileDataSource(mZFile)) - .setMinCheckedPlatformVersion(mMinSdkVersion) + new ApkVerifier.Builder(new ZFileDataSource(zFile)) + .setMinCheckedPlatformVersion(minSdkVersion) .build() .verify(); } catch (ApkFormatException e) { @@ -210,8 +210,8 @@ public class SigningExtension { return false; } - if ((result.isVerifiedUsingV1Scheme() != mV1SigningEnabled) - || (result.isVerifiedUsingV2Scheme() != mV2SigningEnabled)) { + if ((result.isVerifiedUsingV1Scheme() != v1SigningEnabled) + || (result.isVerifiedUsingV2Scheme() != v2SigningEnabled)) { // APK isn't signed with exactly the schemes we want it to be signed return false; } @@ -225,7 +225,7 @@ public class SigningExtension { byte[] expectedEncodedCert; byte[] actualEncodedCert; try { - expectedEncodedCert = mCertificate.getEncoded(); + expectedEncodedCert = certificate.getEncoded(); actualEncodedCert = verifiedSignerCerts.get(0).getEncoded(); } catch (CertificateEncodingException e) { // Failed to encode signing certificates @@ -250,8 +250,8 @@ public class SigningExtension { return; } ApkSignerEngine.InspectJarEntryRequest inspectEntryRequest = - mSigner.outputJarEntry(entryName); - mSignerProcessedOutputEntryNames.add(entryName); + signer.outputJarEntry(entryName); + signerProcessedOutputEntryNames.add(entryName); if (inspectEntryRequest != null) { byte[] entryContents = entry.read(); inspectEntryRequest.getDataSink().consume(entryContents, 0, entryContents.length); @@ -261,23 +261,23 @@ public class SigningExtension { private void onZipEntryRemovedFromOutput(@Nonnull String entryName) { setDirty(); - mSigner.outputJarEntryRemoved(entryName); - mSignerProcessedOutputEntryNames.remove(entryName); + signer.outputJarEntryRemoved(entryName); + signerProcessedOutputEntryNames.remove(entryName); } private void onOutputZipReadyForUpdate() throws IOException { - if (!mDirty) { + if (!dirty) { return; } // Notify signer engine about ZIP entries that have appeared in the output without the // engine knowing. Also identify ZIP entries which disappeared from the output without the // engine knowing. - Set<String> unprocessedRemovedEntryNames = new HashSet<>(mSignerProcessedOutputEntryNames); - for (StoredEntry entry : mZFile.entries()) { + Set<String> unprocessedRemovedEntryNames = new HashSet<>(signerProcessedOutputEntryNames); + for (StoredEntry entry : zFile.entries()) { String entryName = entry.getCentralDirectoryHeader().getName(); unprocessedRemovedEntryNames.remove(entryName); - if (!mSignerProcessedOutputEntryNames.contains(entryName)) { + if (!signerProcessedOutputEntryNames.contains(entryName)) { // Signer engine is not yet aware that this entry is in the output onZipEntryOutput(entry); } @@ -292,7 +292,7 @@ public class SigningExtension { // Check whether we need to output additional JAR entries which comprise the v1 signature ApkSignerEngine.OutputJarSignatureRequest addV1SignatureRequest; try { - addV1SignatureRequest = mSigner.outputJarEntries(); + addV1SignatureRequest = signer.outputJarEntries(); } catch (Exception e) { throw new IOException("Failed to generate v1 signature", e); } @@ -324,36 +324,36 @@ public class SigningExtension { for (ApkSignerEngine.OutputJarSignatureRequest.JarEntry entry : v1SignatureEntries) { String name = entry.getName(); byte[] data = entry.getData(); - mZFile.add(name, new ByteArrayInputStream(data)); + zFile.add(name, new ByteArrayInputStream(data)); } addV1SignatureRequest.done(); } private void onOutputZipEntriesWritten() throws IOException { - if (!mDirty) { + if (!dirty) { return; } // Check whether we should output an APK Signing Block which contains v2 signatures byte[] apkSigningBlock; - byte[] centralDirBytes = mZFile.getCentralDirectoryBytes(); - byte[] eocdBytes = mZFile.getEocdBytes(); + byte[] centralDirBytes = zFile.getCentralDirectoryBytes(); + byte[] eocdBytes = zFile.getEocdBytes(); ApkSignerEngine.OutputApkSigningBlockRequest addV2SignatureRequest; // This event may arrive a second time -- after we write out the APK Signing Block. Thus, we // cache the block to speed things up. The cached block is invalidated by any changes to the // file (as reported to this extension). - if (mCachedApkSigningBlock != null) { - apkSigningBlock = mCachedApkSigningBlock; + if (cachedApkSigningBlock != null) { + apkSigningBlock = cachedApkSigningBlock; addV2SignatureRequest = null; } else { DataSource centralDir = DataSources.asDataSource(ByteBuffer.wrap(centralDirBytes)); DataSource eocd = DataSources.asDataSource(ByteBuffer.wrap(eocdBytes)); long zipEntriesSizeBytes = - mZFile.getCentralDirectoryOffset() - mZFile.getExtraDirectoryOffset(); - DataSource zipEntries = new ZFileDataSource(mZFile, 0, zipEntriesSizeBytes); + zFile.getCentralDirectoryOffset() - zFile.getExtraDirectoryOffset(); + DataSource zipEntries = new ZFileDataSource(zFile, 0, zipEntriesSizeBytes); try { - addV2SignatureRequest = mSigner.outputZipSections(zipEntries, centralDir, eocd); + addV2SignatureRequest = signer.outputZipSections(zipEntries, centralDir, eocd); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | ApkFormatException | IOException e) { throw new IOException("Failed to generate v2 signature", e); @@ -361,16 +361,16 @@ public class SigningExtension { apkSigningBlock = (addV2SignatureRequest != null) ? addV2SignatureRequest.getApkSigningBlock() : new byte[0]; - mCachedApkSigningBlock = apkSigningBlock; + cachedApkSigningBlock = apkSigningBlock; } // Insert the APK Signing Block into the output right before the ZIP Central Directory and // accordingly update the start offset of ZIP Central Directory in ZIP End of Central // Directory. - mZFile.directWrite( - mZFile.getCentralDirectoryOffset() - mZFile.getExtraDirectoryOffset(), + zFile.directWrite( + zFile.getCentralDirectoryOffset() - zFile.getExtraDirectoryOffset(), apkSigningBlock); - mZFile.setExtraDirectoryOffset(apkSigningBlock.length); + zFile.setExtraDirectoryOffset(apkSigningBlock.length); if (addV2SignatureRequest != null) { addV2SignatureRequest.done(); @@ -378,15 +378,15 @@ public class SigningExtension { } private void onOutputClosed() { - if (!mDirty) { + if (!dirty) { return; } - mSigner.outputDone(); - mDirty = false; + signer.outputDone(); + dirty = false; } private void setDirty() { - mDirty = true; - mCachedApkSigningBlock = null; + dirty = true; + cachedApkSigningBlock = null; } }
\ No newline at end of file diff --git a/src/main/java/com/android/apkzlib/sign/ZFileDataSource.java b/src/main/java/com/android/apkzlib/sign/ZFileDataSource.java index c42db12..049cf35 100644 --- a/src/main/java/com/android/apkzlib/sign/ZFileDataSource.java +++ b/src/main/java/com/android/apkzlib/sign/ZFileDataSource.java @@ -33,19 +33,19 @@ class ZFileDataSource implements DataSource { private static final int MAX_READ_CHUNK_SIZE = 65536; @Nonnull - private final ZFile mFile; + private final ZFile file; /** * Offset (in bytes) relative to the start of file where the region visible in this data source * starts. */ - private final long mOffset; + private final long offset; /** * Size (in bytes) of the file region visible in this data source or {@code -1} if the whole * file is visible in this data source and thus its size may change if the file's size changes. */ - private final long mSize; + private final long size; /** * Constructs a new {@code ZFileDataSource} based on the data contained in the file. Changes to @@ -53,9 +53,9 @@ class ZFileDataSource implements DataSource { * source. */ public ZFileDataSource(@Nonnull ZFile file) { - mFile = file; - mOffset = 0; - mSize = -1; + this.file = file; + offset = 0; + size = -1; } /** @@ -66,23 +66,23 @@ class ZFileDataSource implements DataSource { public ZFileDataSource(@Nonnull ZFile file, long offset, long size) { Preconditions.checkArgument(offset >= 0, "offset < 0"); Preconditions.checkArgument(size >= 0, "size < 0"); - mFile = file; - mOffset = offset; - mSize = size; + this.file = file; + this.offset = offset; + this.size = size; } @Override public long size() { - if (mSize == -1) { + if (size == -1) { // Data source size is the current size of the file try { - return mFile.directSize(); + return file.directSize(); } catch (IOException e) { return 0; } } else { // Data source size is fixed - return mSize; + return size; } } @@ -94,7 +94,7 @@ class ZFileDataSource implements DataSource { return this; } - return new ZFileDataSource(mFile, mOffset + offset, size); + return new ZFileDataSource(file, this.offset + offset, size); } @Override @@ -105,12 +105,12 @@ class ZFileDataSource implements DataSource { return; } - long chunkOffsetInFile = mOffset + offset; + long chunkOffsetInFile = this.offset + offset; long remaining = size; byte[] buf = new byte[(int) Math.min(remaining, MAX_READ_CHUNK_SIZE)]; while (remaining > 0) { int chunkSize = (int) Math.min(remaining, buf.length); - int readSize = mFile.directRead(chunkOffsetInFile, buf, 0, chunkSize); + int readSize = file.directRead(chunkOffsetInFile, buf, 0, chunkSize); if (readSize == -1) { throw new EOFException("Premature EOF"); } @@ -132,7 +132,7 @@ class ZFileDataSource implements DataSource { int prevLimit = dest.limit(); try { - mFile.directFullyRead(mOffset + offset, dest); + file.directFullyRead(this.offset + offset, dest); } finally { dest.limit(prevLimit); } diff --git a/src/main/java/com/android/apkzlib/utils/CachedFileContents.java b/src/main/java/com/android/apkzlib/utils/CachedFileContents.java index f649692..0f5b933 100644 --- a/src/main/java/com/android/apkzlib/utils/CachedFileContents.java +++ b/src/main/java/com/android/apkzlib/utils/CachedFileContents.java @@ -53,29 +53,29 @@ public class CachedFileContents<T> { * The file. */ @Nonnull - private File mFile; + private File file; /** * Time when last closed (time when {@link #closed(Object)} was invoked). */ - private long mLastClosed; + private long lastClosed; /** * Size of the file when last closed. */ - private long mSize; + private long size; /** * Hash of the file when closed. {@code null} if hashing failed for some reason. */ @Nullable - private HashCode mHash; + private HashCode hash; /** * Cached data associated with the file. */ @Nullable - private T mCache; + private T cache; /** * Creates a new contents. When the file is written, {@link #closed(Object)} should be invoked @@ -84,7 +84,7 @@ public class CachedFileContents<T> { * @param file the file */ public CachedFileContents(@Nonnull File file) { - mFile = file; + this.file = file; } /** @@ -96,10 +96,10 @@ public class CachedFileContents<T> { * @param cache an optional cache to save */ public void closed(@Nullable T cache) { - mCache = cache; - mLastClosed = mFile.lastModified(); - mSize = mFile.length(); - mHash = hashFile(); + this.cache = cache; + lastClosed = file.lastModified(); + size = file.length(); + hash = hashFile(); } /** @@ -112,24 +112,24 @@ public class CachedFileContents<T> { public boolean isValid() { boolean valid = true; - if (!mFile.exists()) { + if (!file.exists()) { valid = false; } - if (valid && mFile.lastModified() != mLastClosed) { + if (valid && file.lastModified() != lastClosed) { valid = false; } - if (valid && mFile.length() != mSize) { + if (valid && file.length() != size) { valid = false; } - if (valid && !Objects.equal(mHash, hashFile())) { + if (valid && !Objects.equal(hash, hashFile())) { valid = false; } if (!valid) { - mCache = null; + cache = null; } return valid; @@ -144,7 +144,7 @@ public class CachedFileContents<T> { */ @Nullable public T getCache() { - return mCache; + return cache; } /** @@ -155,7 +155,7 @@ public class CachedFileContents<T> { @Nullable private HashCode hashFile() { try { - return Files.hash(mFile, Hashing.crc32()); + return Files.hash(file, Hashing.crc32()); } catch (IOException e) { return null; } @@ -169,6 +169,6 @@ public class CachedFileContents<T> { */ @Nonnull public File getFile() { - return mFile; + return file; } } diff --git a/src/main/java/com/android/apkzlib/utils/package-info.java b/src/main/java/com/android/apkzlib/utils/package-info.java new file mode 100644 index 0000000..2f17b60 --- /dev/null +++ b/src/main/java/com/android/apkzlib/utils/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Utilities to work with {@code apkzlib}. + */ +package com.android.apkzlib.utils;
\ No newline at end of file diff --git a/src/main/java/com/android/apkzlib/zfile/ApkCreator.java b/src/main/java/com/android/apkzlib/zfile/ApkCreator.java index d39891d..d602202 100644 --- a/src/main/java/com/android/apkzlib/zfile/ApkCreator.java +++ b/src/main/java/com/android/apkzlib/zfile/ApkCreator.java @@ -31,9 +31,9 @@ public interface ApkCreator extends Closeable { /** * Copies the content of a Jar/Zip archive into the receiver archive. - * <p> - * An optional {@link ZipEntryFilter} allows to selectively choose which files - * to copy over. + * + * <p>An optional predicate allows to selectively choose which files to copy over and an + * option function allows renaming the files as they are copied. * * @param zip the zip to copy data from * @param transform an optional transform to apply to file names before copying them @@ -42,8 +42,11 @@ public interface ApkCreator extends Closeable { * predicate applies after transformation * @throws IOException I/O error */ - void writeZip(@Nonnull File zip, @Nullable Function<String, String> transform, - @Nullable Predicate<String> isIgnored) throws IOException; + void writeZip( + @Nonnull File zip, + @Nullable Function<String, String> transform, + @Nullable Predicate<String> isIgnored) + throws IOException; /** * Writes a new {@link File} into the archive. If a file already existed with the given diff --git a/src/main/java/com/android/apkzlib/zfile/ApkCreatorFactory.java b/src/main/java/com/android/apkzlib/zfile/ApkCreatorFactory.java index 822fc74..503eaf1 100644 --- a/src/main/java/com/android/apkzlib/zfile/ApkCreatorFactory.java +++ b/src/main/java/com/android/apkzlib/zfile/ApkCreatorFactory.java @@ -49,53 +49,59 @@ public interface ApkCreatorFactory { * the APK may be updated instead of created). */ @Nonnull - private final File mApkPath; + private final File apkPath; /** * Key used to sign the APK. May be {@code null}. */ @Nullable - private final PrivateKey mKey; + private final PrivateKey key; /** - * Certificate used to sign the APK. Is {@code null} if and only if {@link #mKey} is + * Certificate used to sign the APK. Is {@code null} if and only if {@link #key} is * {@code null}. */ @Nullable - private final X509Certificate mCertificate; + private final X509Certificate certificate; /** * Whether signing the APK with JAR Signing Scheme (aka v1 signing) is enabled. */ - private final boolean mV1SigningEnabled; + private final boolean v1SigningEnabled; /** * Whether signing the APK with APK Signature Scheme v2 (aka v2 signing) is enabled. */ - private final boolean mV2SigningEnabled; + private final boolean v2SigningEnabled; /** * Built-by information for the APK, if any. */ @Nullable - private final String mBuiltBy; + private final String builtBy; /** * Created-by information for the APK, if any. */ @Nullable - private final String mCreatedBy; + private final String createdBy; /** * Minimum SDk version that will run the APK. */ - private final int mMinSdkVersion; + private final int minSdkVersion; + /** + * How should native libraries be packaged? + */ @Nonnull - private final NativeLibrariesPackagingMode mNativeLibrariesPackagingMode; + private final NativeLibrariesPackagingMode nativeLibrariesPackagingMode; + /** + * Predicate identifying paths that should not be compressed. + */ @Nonnull - private final Predicate<String> mNoCompressPredicate; + private final Predicate<String> noCompressPredicate; /** * @@ -132,16 +138,16 @@ public interface ApkCreatorFactory { "(key == null) != (certificate == null)"); Preconditions.checkArgument(minSdkVersion >= 0, "minSdkVersion < 0"); - mApkPath = apkPath; - mKey = key; - mCertificate = certificate; - mV1SigningEnabled = v1SigningEnabled; - mV2SigningEnabled = v2SigningEnabled; - mBuiltBy = builtBy; - mCreatedBy = createdBy; - mMinSdkVersion = minSdkVersion; - mNativeLibrariesPackagingMode = checkNotNull(nativeLibrariesPackagingMode); - mNoCompressPredicate = checkNotNull(noCompressPredicate); + this.apkPath = apkPath; + this.key = key; + this.certificate = certificate; + this.v1SigningEnabled = v1SigningEnabled; + this.v2SigningEnabled = v2SigningEnabled; + this.builtBy = builtBy; + this.createdBy = createdBy; + this.minSdkVersion = minSdkVersion; + this.nativeLibrariesPackagingMode = checkNotNull(nativeLibrariesPackagingMode); + this.noCompressPredicate = checkNotNull(noCompressPredicate); } /** @@ -152,7 +158,7 @@ public interface ApkCreatorFactory { */ @Nonnull public File getApkPath() { - return mApkPath; + return apkPath; } /** @@ -162,7 +168,7 @@ public interface ApkCreatorFactory { */ @Nullable public PrivateKey getPrivateKey() { - return mKey; + return key; } /** @@ -173,7 +179,7 @@ public interface ApkCreatorFactory { */ @Nullable public X509Certificate getCertificate() { - return mCertificate; + return certificate; } /** @@ -181,7 +187,7 @@ public interface ApkCreatorFactory { * scheme). */ public boolean isV1SigningEnabled() { - return mV1SigningEnabled; + return v1SigningEnabled; } /** @@ -189,7 +195,7 @@ public interface ApkCreatorFactory { * scheme). */ public boolean isV2SigningEnabled() { - return mV2SigningEnabled; + return v2SigningEnabled; } /** @@ -199,7 +205,7 @@ public interface ApkCreatorFactory { */ @Nullable public String getBuiltBy() { - return mBuiltBy; + return builtBy; } /** @@ -209,7 +215,7 @@ public interface ApkCreatorFactory { */ @Nullable public String getCreatedBy() { - return mCreatedBy; + return createdBy; } /** @@ -218,7 +224,7 @@ public interface ApkCreatorFactory { * @return the minimum SDK version */ public int getMinSdkVersion() { - return mMinSdkVersion; + return minSdkVersion; } /** @@ -226,7 +232,7 @@ public interface ApkCreatorFactory { */ @Nonnull public NativeLibrariesPackagingMode getNativeLibrariesPackagingMode() { - return mNativeLibrariesPackagingMode; + return nativeLibrariesPackagingMode; } /** @@ -234,7 +240,7 @@ public interface ApkCreatorFactory { */ @Nonnull public Predicate<String> getNoCompressPredicate() { - return mNoCompressPredicate; + return noCompressPredicate; } } } diff --git a/src/main/java/com/android/apkzlib/zfile/ApkZFileCreator.java b/src/main/java/com/android/apkzlib/zfile/ApkZFileCreator.java index 69289f7..b96901c 100644 --- a/src/main/java/com/android/apkzlib/zfile/ApkZFileCreator.java +++ b/src/main/java/com/android/apkzlib/zfile/ApkZFileCreator.java @@ -51,18 +51,18 @@ class ApkZFileCreator implements ApkCreator { * The zip file. */ @Nonnull - private final ZFile mZip; + private final ZFile zip; /** * Has the zip file been closed? */ - private boolean mClosed; + private boolean closed; /** * Predicate defining which files should not be compressed. */ @Nonnull - private final Predicate<String> mNoCompressPredicate; + private final Predicate<String> noCompressPredicate; /** * Creates a new creator. @@ -78,10 +78,10 @@ class ApkZFileCreator implements ApkCreator { switch (creationData.getNativeLibrariesPackagingMode()) { case COMPRESSED: - mNoCompressPredicate = creationData.getNoCompressPredicate(); + noCompressPredicate = creationData.getNoCompressPredicate(); break; case UNCOMPRESSED_AND_ALIGNED: - mNoCompressPredicate = + noCompressPredicate = creationData.getNoCompressPredicate().or( name -> name.endsWith(NATIVE_LIBRARIES_SUFFIX)); options.setAlignmentRule( @@ -91,7 +91,7 @@ class ApkZFileCreator implements ApkCreator { throw new AssertionError(); } - mZip = ZFiles.apk( + zip = ZFiles.apk( creationData.getApkPath(), options, creationData.getPrivateKey(), @@ -101,13 +101,13 @@ class ApkZFileCreator implements ApkCreator { creationData.getBuiltBy(), creationData.getCreatedBy(), creationData.getMinSdkVersion()); - mClosed = false; + closed = false; } @Override public void writeZip(@Nonnull File zip, @Nullable Function<String, String> transform, @Nullable Predicate<String> isIgnored) throws IOException { - Preconditions.checkState(!mClosed, "mClosed == true"); + Preconditions.checkState(!closed, "closed == true"); Preconditions.checkArgument(zip.isFile(), "!zip.isFile()"); Closer closer = Closer.create(); @@ -121,7 +121,7 @@ class ApkZFileCreator implements ApkCreator { predicate = isIgnored; } - mZip.mergeFrom(toMerge, predicate); + this.zip.mergeFrom(toMerge, predicate); } catch (Throwable t) { throw closer.rethrow(t); } finally { @@ -131,14 +131,14 @@ class ApkZFileCreator implements ApkCreator { @Override public void writeFile(@Nonnull File inputFile, @Nonnull String apkPath) throws IOException { - Preconditions.checkState(!mClosed, "mClosed == true"); + Preconditions.checkState(!closed, "closed == true"); - boolean mayCompress = !mNoCompressPredicate.test(apkPath); + boolean mayCompress = !noCompressPredicate.test(apkPath); Closer closer = Closer.create(); try { FileInputStream inputFileStream = closer.register(new FileInputStream(inputFile)); - mZip.add(apkPath, inputFileStream, mayCompress); + zip.add(apkPath, inputFileStream, mayCompress); } catch (IOException e) { throw closer.rethrow(e, IOException.class); } catch (Throwable t) { @@ -150,9 +150,9 @@ class ApkZFileCreator implements ApkCreator { @Override public void deleteFile(@Nonnull String apkPath) throws IOException { - Preconditions.checkState(!mClosed, "mClosed == true"); + Preconditions.checkState(!closed, "closed == true"); - StoredEntry entry = mZip.get(apkPath); + StoredEntry entry = zip.get(apkPath); if (entry != null) { entry.delete(); } @@ -160,11 +160,11 @@ class ApkZFileCreator implements ApkCreator { @Override public void close() throws IOException { - if (mClosed) { + if (closed) { return; } - mZip.close(); - mClosed = true; + zip.close(); + closed = true; } } diff --git a/src/main/java/com/android/apkzlib/zfile/ApkZFileCreatorFactory.java b/src/main/java/com/android/apkzlib/zfile/ApkZFileCreatorFactory.java index 5f05b28..2e4c7c9 100644 --- a/src/main/java/com/android/apkzlib/zfile/ApkZFileCreatorFactory.java +++ b/src/main/java/com/android/apkzlib/zfile/ApkZFileCreatorFactory.java @@ -30,7 +30,7 @@ public class ApkZFileCreatorFactory implements ApkCreatorFactory { * Options for the {@link ZFileOptions} to use in all APKs. */ @Nonnull - private final ZFileOptions mOptions; + private final ZFileOptions options; /** * Creates a new factory. @@ -38,7 +38,7 @@ public class ApkZFileCreatorFactory implements ApkCreatorFactory { * @param options the options to use for all instances created */ public ApkZFileCreatorFactory(@Nonnull ZFileOptions options) { - mOptions = options; + this.options = options; } @@ -46,7 +46,7 @@ public class ApkZFileCreatorFactory implements ApkCreatorFactory { @Nonnull public ApkCreator make(@Nonnull CreationData creationData) { try { - return new ApkZFileCreator(creationData, mOptions); + return new ApkZFileCreator(creationData, options); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/src/main/java/com/android/apkzlib/zfile/package-info.java b/src/main/java/com/android/apkzlib/zfile/package-info.java new file mode 100644 index 0000000..0c5ab6d --- /dev/null +++ b/src/main/java/com/android/apkzlib/zfile/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The {@code zfile} package contains + */ +package com.android.apkzlib.zfile;
\ No newline at end of file diff --git a/src/main/java/com/android/apkzlib/zip/AlignmentRule.java b/src/main/java/com/android/apkzlib/zip/AlignmentRule.java index bb5b0e5..4ee6963 100644 --- a/src/main/java/com/android/apkzlib/zip/AlignmentRule.java +++ b/src/main/java/com/android/apkzlib/zip/AlignmentRule.java @@ -37,5 +37,3 @@ public interface AlignmentRule { */ int alignment(@Nonnull String path); } - - diff --git a/src/main/java/com/android/apkzlib/zip/CentralDirectory.java b/src/main/java/com/android/apkzlib/zip/CentralDirectory.java index e088298..7f06df7 100644 --- a/src/main/java/com/android/apkzlib/zip/CentralDirectory.java +++ b/src/main/java/com/android/apkzlib/zip/CentralDirectory.java @@ -175,19 +175,19 @@ class CentralDirectory { * Contains all entries in the directory mapped from their names. */ @Nonnull - private final Map<String, StoredEntry> mEntries; + private final Map<String, StoredEntry> entries; /** * The file where this directory belongs to. */ @Nonnull - private final ZFile mFile; + private final ZFile file; /** * Supplier that provides a byte representation of the central directory. */ @Nonnull - private final CachedSupplier<byte[]> mBytesSupplier; + private final CachedSupplier<byte[]> bytesSupplier; /** * Creates a new, empty, central directory, for a given zip file. @@ -195,9 +195,9 @@ class CentralDirectory { * @param file the file */ CentralDirectory(@Nonnull ZFile file) { - mEntries = Maps.newHashMap(); - mFile = file; - mBytesSupplier = new CachedSupplier<>(this::computeByteRepresentation); + entries = Maps.newHashMap(); + this.file = file; + bytesSupplier = new CachedSupplier<>(this::computeByteRepresentation); } /** @@ -253,16 +253,16 @@ class CentralDirectory { for (StoredEntry entry : entries) { CentralDirectoryHeader cdr = entry.getCentralDirectoryHeader(); Preconditions.checkArgument( - !directory.mEntries.containsKey(cdr.getName()), + !directory.entries.containsKey(cdr.getName()), "Duplicate filename"); - directory.mEntries.put(cdr.getName(), entry); + directory.entries.put(cdr.getName(), entry); } return directory; } /** - * Reads the next entry from the central directory and adds it to {@link #mEntries}. + * Reads the next entry from the central directory and adds it to {@link #entries}. * * @param bytes the central directory's data, positioned starting at the beginning of the next * entry to read; when finished, the buffer's position will be at the first byte after the @@ -293,7 +293,7 @@ class CentralDirectory { long lastModTime; long lastModDate; - if (mFile.areTimestampsIgnored()) { + if (this.file.areTimestampsIgnored()) { lastModTime = 0; lastModDate = 0; F_LAST_MOD_TIME.skip(bytes); @@ -364,16 +364,16 @@ class CentralDirectory { StoredEntry entry; try { - entry = new StoredEntry(centralDirectoryHeader, mFile, null); + entry = new StoredEntry(centralDirectoryHeader, this.file, null); } catch (IOException e) { throw new IOException("Failed to read stored entry '" + fileName + "'.", e); } - if (mEntries.containsKey(fileName)) { + if (entries.containsKey(fileName)) { throw new IOException("File file contains duplicate file '" + fileName + "'."); } - mEntries.put(fileName, entry); + entries.put(fileName, entry); } /** @@ -383,7 +383,7 @@ class CentralDirectory { */ @Nonnull Map<String, StoredEntry> getEntries() { - return ImmutableMap.copyOf(mEntries); + return ImmutableMap.copyOf(entries); } /** @@ -393,7 +393,7 @@ class CentralDirectory { * @throws IOException failed to write the byte array */ byte[] toBytes() throws IOException { - return mBytesSupplier.get(); + return bytesSupplier.get(); } /** @@ -404,15 +404,15 @@ class CentralDirectory { */ private byte[] computeByteRepresentation() { - List<StoredEntry> sorted = Lists.newArrayList(mEntries.values()); + List<StoredEntry> sorted = Lists.newArrayList(entries.values()); sorted.sort(StoredEntry.COMPARE_BY_NAME); - CentralDirectoryHeader[] cdhs = new CentralDirectoryHeader[mEntries.size()]; + CentralDirectoryHeader[] cdhs = new CentralDirectoryHeader[entries.size()]; CentralDirectoryHeaderCompressInfo[] compressInfos = - new CentralDirectoryHeaderCompressInfo[mEntries.size()]; - byte[][] encodedFileNames = new byte[mEntries.size()][]; - byte[][] extraFields = new byte[mEntries.size()][]; - byte[][] comments = new byte[mEntries.size()][]; + new CentralDirectoryHeaderCompressInfo[entries.size()]; + byte[][] encodedFileNames = new byte[entries.size()][]; + byte[][] extraFields = new byte[entries.size()][]; + byte[][] comments = new byte[entries.size()][]; try { /* @@ -435,14 +435,14 @@ class CentralDirectory { ByteBuffer out = ByteBuffer.allocate(total); - for (idx = 0; idx < mEntries.size(); idx++) { + for (idx = 0; idx < entries.size(); idx++) { F_SIGNATURE.write(out); F_MADE_BY.write(out, cdhs[idx].getMadeBy()); F_VERSION_EXTRACT.write(out, compressInfos[idx].getVersionExtract()); F_GP_BIT.write(out, cdhs[idx].getGpBit().getValue()); F_METHOD.write(out, compressInfos[idx].getMethod().methodCode); - if (mFile.areTimestampsIgnored()) { + if (file.areTimestampsIgnored()) { F_LAST_MOD_TIME.write(out, 0); F_LAST_MOD_DATE.write(out, 0); } else { diff --git a/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeader.java b/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeader.java index b5b5226..7e7e50b 100644 --- a/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeader.java +++ b/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeader.java @@ -45,84 +45,84 @@ public class CentralDirectoryHeader implements Cloneable { * Name of the file. */ @Nonnull - private String mName; + private String name; /** * CRC32 of the data. 0 if not yet computed. */ - private long mCrc32; + private long crc32; /** * Size of the file uncompressed. 0 if the file has no data. */ - private long mUncompressedSize; + private long uncompressedSize; /** * Code of the program that made the zip. We actually don't care about this. */ - private long mMadeBy; + private long madeBy; /** * General-purpose bit flag. */ @Nonnull - private GPFlags mGpBit; + private GPFlags gpBit; /** * Last modification time in MS-DOS format (see {@link MsDosDateTimeUtils#packTime(long)}). */ - private long mLastModTime; + private long lastModTime; /** * Last modification time in MS-DOS format (see {@link MsDosDateTimeUtils#packDate(long)}). */ - private long mLastModDate; + private long lastModDate; /** * Extra data field contents. This field follows a specific structure according to the * specification. */ @Nonnull - private ExtraField mExtraField; + private ExtraField extraField; /** * File comment. */ @Nonnull - private byte[] mComment; + private byte[] comment; /** * File internal attributes. */ - private long mInternalAttributes; + private long internalAttributes; /** * File external attributes. */ - private long mExternalAttributes; + private long externalAttributes; /** * Offset in the file where the data is located. This will be -1 if the header corresponds to * a new file that is not yet written in the zip and, therefore, has no written data. */ - private long mOffset; + private long offset; /** * Encoded file name. */ - private byte[] mEncodedFileName; + private byte[] encodedFileName; /** * Compress information that may not have been computed yet due to lazy compression. */ @Nonnull - private Future<CentralDirectoryHeaderCompressInfo> mCompressInfo; + private Future<CentralDirectoryHeaderCompressInfo> compressInfo; /** * The file this header belongs to. */ @Nonnull - private final ZFile mFile; + private final ZFile file; /** * Creates data for a file. @@ -139,26 +139,26 @@ public class CentralDirectoryHeader implements Cloneable { @Nonnull Future<CentralDirectoryHeaderCompressInfo> compressInfo, @Nonnull GPFlags flags, @Nonnull ZFile zFile) { - mName = name; - mUncompressedSize = uncompressedSize; - mCrc32 = 0; + this.name = name; + this.uncompressedSize = uncompressedSize; + crc32 = 0; /* * Set sensible defaults for the rest. */ - mMadeBy = DEFAULT_VERSION_MADE_BY; - - mGpBit = flags; - mLastModTime = MsDosDateTimeUtils.packCurrentTime(); - mLastModDate = MsDosDateTimeUtils.packCurrentDate(); - mExtraField = new ExtraField(); - mComment = new byte[0]; - mInternalAttributes = 0; - mExternalAttributes = 0; - mOffset = -1; - mEncodedFileName = EncodeUtils.encode(name, mGpBit); - mCompressInfo = compressInfo; - mFile = zFile; + madeBy = DEFAULT_VERSION_MADE_BY; + + gpBit = flags; + lastModTime = MsDosDateTimeUtils.packCurrentTime(); + lastModDate = MsDosDateTimeUtils.packCurrentDate(); + extraField = new ExtraField(); + comment = new byte[0]; + internalAttributes = 0; + externalAttributes = 0; + offset = -1; + encodedFileName = EncodeUtils.encode(name, gpBit); + this.compressInfo = compressInfo; + file = zFile; } /** @@ -168,7 +168,7 @@ public class CentralDirectoryHeader implements Cloneable { */ @Nonnull public String getName() { - return mName; + return name; } /** @@ -177,7 +177,7 @@ public class CentralDirectoryHeader implements Cloneable { * @return the size of the file */ public long getUncompressedSize() { - return mUncompressedSize; + return uncompressedSize; } /** @@ -186,7 +186,7 @@ public class CentralDirectoryHeader implements Cloneable { * @return the CRC32, 0 if not yet computed */ public long getCrc32() { - return mCrc32; + return crc32; } /** @@ -195,7 +195,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param crc32 the CRC 32 */ void setCrc32(long crc32) { - mCrc32 = crc32; + this.crc32 = crc32; } /** @@ -204,7 +204,7 @@ public class CentralDirectoryHeader implements Cloneable { * @return the code */ public long getMadeBy() { - return mMadeBy; + return madeBy; } /** @@ -213,7 +213,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param madeBy the code */ void setMadeBy(long madeBy) { - mMadeBy = madeBy; + this.madeBy = madeBy; } /** @@ -223,7 +223,7 @@ public class CentralDirectoryHeader implements Cloneable { */ @Nonnull public GPFlags getGpBit() { - return mGpBit; + return gpBit; } /** @@ -233,7 +233,7 @@ public class CentralDirectoryHeader implements Cloneable { * {@link MsDosDateTimeUtils#packTime(long)}) */ public long getLastModTime() { - return mLastModTime; + return lastModTime; } /** @@ -243,7 +243,7 @@ public class CentralDirectoryHeader implements Cloneable { * {@link MsDosDateTimeUtils#packTime(long)}) */ void setLastModTime(long lastModTime) { - mLastModTime = lastModTime; + this.lastModTime = lastModTime; } /** @@ -253,7 +253,7 @@ public class CentralDirectoryHeader implements Cloneable { * {@link MsDosDateTimeUtils#packDate(long)}) */ public long getLastModDate() { - return mLastModDate; + return lastModDate; } /** @@ -263,7 +263,7 @@ public class CentralDirectoryHeader implements Cloneable { * {@link MsDosDateTimeUtils#packDate(long)}) */ void setLastModDate(long lastModDate) { - mLastModDate = lastModDate; + this.lastModDate = lastModDate; } /** @@ -273,7 +273,7 @@ public class CentralDirectoryHeader implements Cloneable { */ @Nonnull public ExtraField getExtraField() { - return mExtraField; + return extraField; } /** @@ -283,7 +283,7 @@ public class CentralDirectoryHeader implements Cloneable { */ public void setExtraField(@Nonnull ExtraField extraField) { setExtraFieldNoNotify(extraField); - mFile.centralDirectoryChanged(); + file.centralDirectoryChanged(); } /** @@ -293,7 +293,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param extraField the data to set */ void setExtraFieldNoNotify(@Nonnull ExtraField extraField) { - mExtraField = extraField; + this.extraField = extraField; } /** @@ -303,7 +303,7 @@ public class CentralDirectoryHeader implements Cloneable { */ @Nonnull public byte[] getComment() { - return mComment; + return comment; } /** @@ -312,7 +312,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param comment the comment */ void setComment(@Nonnull byte[] comment) { - mComment = comment; + this.comment = comment; } /** @@ -321,7 +321,7 @@ public class CentralDirectoryHeader implements Cloneable { * @return the entry's internal attributes */ public long getInternalAttributes() { - return mInternalAttributes; + return internalAttributes; } /** @@ -330,7 +330,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param internalAttributes the entry's internal attributes */ void setInternalAttributes(long internalAttributes) { - mInternalAttributes = internalAttributes; + this.internalAttributes = internalAttributes; } /** @@ -339,7 +339,7 @@ public class CentralDirectoryHeader implements Cloneable { * @return the entry's external attributes */ public long getExternalAttributes() { - return mExternalAttributes; + return externalAttributes; } /** @@ -348,7 +348,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param externalAttributes the entry's external attributes */ void setExternalAttributes(long externalAttributes) { - mExternalAttributes = externalAttributes; + this.externalAttributes = externalAttributes; } /** @@ -358,7 +358,7 @@ public class CentralDirectoryHeader implements Cloneable { * is stored in memory */ public long getOffset() { - return mOffset; + return offset; } /** @@ -367,7 +367,7 @@ public class CentralDirectoryHeader implements Cloneable { * @param offset the offset or {@code -1} if the file is new and has no data in the zip yet */ void setOffset(long offset) { - mOffset = offset; + this.offset = offset; } /** @@ -376,7 +376,7 @@ public class CentralDirectoryHeader implements Cloneable { * @return the encoded file name */ public byte[] getEncodedFileName() { - return mEncodedFileName; + return encodedFileName; } /** @@ -387,15 +387,15 @@ public class CentralDirectoryHeader implements Cloneable { * We actually create a new set of flags. Since the only information we care about is the * UTF-8 encoding, we'll just create a brand new object. */ - mGpBit = GPFlags.make(mGpBit.isUtf8FileName()); + gpBit = GPFlags.make(gpBit.isUtf8FileName()); } @Override protected CentralDirectoryHeader clone() throws CloneNotSupportedException { CentralDirectoryHeader cdr = (CentralDirectoryHeader) super.clone(); - cdr.mExtraField = mExtraField; - cdr.mComment = Arrays.copyOf(mComment, mComment.length); - cdr.mEncodedFileName = Arrays.copyOf(mEncodedFileName, mEncodedFileName.length); + cdr.extraField = extraField; + cdr.comment = Arrays.copyOf(comment, comment.length); + cdr.encodedFileName = Arrays.copyOf(encodedFileName, encodedFileName.length); return cdr; } @@ -406,7 +406,7 @@ public class CentralDirectoryHeader implements Cloneable { */ @Nonnull public Future<CentralDirectoryHeaderCompressInfo> getCompressionInfo() { - return mCompressInfo; + return compressInfo; } /** diff --git a/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeaderCompressInfo.java b/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeaderCompressInfo.java index 305f120..7c3ad63 100644 --- a/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeaderCompressInfo.java +++ b/src/main/java/com/android/apkzlib/zip/CentralDirectoryHeaderCompressInfo.java @@ -43,12 +43,12 @@ public class CentralDirectoryHeaderCompressInfo { /** * Size of the file compressed. 0 if the file has no data. */ - private final long mCompressedSize; + private final long compressedSize; /** * Version needed to extract the zip. */ - private final long mVersionExtract; + private final long versionExtract; /** * Creates new compression information for the central directory header. @@ -63,8 +63,8 @@ public class CentralDirectoryHeaderCompressInfo { long compressedSize, long versionToExtract) { mMethod = method; - mCompressedSize = compressedSize; - mVersionExtract = versionToExtract; + this.compressedSize = compressedSize; + versionExtract = versionToExtract; } /** @@ -77,15 +77,15 @@ public class CentralDirectoryHeaderCompressInfo { public CentralDirectoryHeaderCompressInfo(@Nonnull CentralDirectoryHeader header, @Nonnull CompressionMethod method, long compressedSize) { mMethod = method; - mCompressedSize = compressedSize; + this.compressedSize = compressedSize; if (header.getName().endsWith("/") || method == CompressionMethod.DEFLATE) { /* * Directories and compressed files only in version 2.0. */ - mVersionExtract = VERSION_WITH_DIRECTORIES_AND_DEFLATE; + versionExtract = VERSION_WITH_DIRECTORIES_AND_DEFLATE; } else { - mVersionExtract = VERSION_WITH_STORE_FILES_ONLY; + versionExtract = VERSION_WITH_STORE_FILES_ONLY; } } @@ -95,7 +95,7 @@ public class CentralDirectoryHeaderCompressInfo { * @return the compressed data size */ public long getCompressedSize() { - return mCompressedSize; + return compressedSize; } /** @@ -114,6 +114,6 @@ public class CentralDirectoryHeaderCompressInfo { * @return the minimum version */ public long getVersionExtract() { - return mVersionExtract; + return versionExtract; } } diff --git a/src/main/java/com/android/apkzlib/zip/CompressionResult.java b/src/main/java/com/android/apkzlib/zip/CompressionResult.java index f051f1e..34f5d72 100644 --- a/src/main/java/com/android/apkzlib/zip/CompressionResult.java +++ b/src/main/java/com/android/apkzlib/zip/CompressionResult.java @@ -28,52 +28,56 @@ public class CompressionResult { * The compression method used. */ @Nonnull - private final CompressionMethod mCompressionMethod; + private final CompressionMethod compressionMethod; /** * The resulting data. */ @Nonnull - private final CloseableByteSource mSource; + private final CloseableByteSource source; /** - * Size of the compressed source. Kept because {@code mSource.size()} can throw + * Size of the compressed source. Kept because {@code source.size()} can throw * {@code IOException}. */ private final long mSize; /** * Creates a new compression result. + * * @param source the data source * @param method the compression method */ public CompressionResult(@Nonnull CloseableByteSource source, @Nonnull CompressionMethod method, long size) { - mCompressionMethod = method; - mSource = source; + compressionMethod = method; + this.source = source; mSize = size; } /** * Obtains the compression method. + * * @return the compression method */ @Nonnull public CompressionMethod getCompressionMethod() { - return mCompressionMethod; + return compressionMethod; } /** * Obtains the compressed data. + * * @return the data, the resulting array should not be modified */ @Nonnull public CloseableByteSource getSource() { - return mSource; + return source; } /** * Obtains the size of the compression result. + * * @return the size */ public long getSize() { diff --git a/src/main/java/com/android/apkzlib/zip/Compressor.java b/src/main/java/com/android/apkzlib/zip/Compressor.java index 9cec463..a94242e 100644 --- a/src/main/java/com/android/apkzlib/zip/Compressor.java +++ b/src/main/java/com/android/apkzlib/zip/Compressor.java @@ -29,6 +29,7 @@ public interface Compressor { /** * Compresses an entry source. + * * @param source the source to compress * @return a future that will eventually contain the compression result */ diff --git a/src/main/java/com/android/apkzlib/zip/Eocd.java b/src/main/java/com/android/apkzlib/zip/Eocd.java index 47cbf5a..36a0a6e 100644 --- a/src/main/java/com/android/apkzlib/zip/Eocd.java +++ b/src/main/java/com/android/apkzlib/zip/Eocd.java @@ -89,29 +89,29 @@ class Eocd { /** * Number of entries in the central directory. */ - private final int mTotalRecords; + private final int totalRecords; /** * Offset from the beginning of the archive where the Central Directory is located. */ - private final long mDirectoryOffset; + private final long directoryOffset; /** * Number of bytes of the Central Directory. */ - private final long mDirectorySize; + private final long directorySize; /** * Contents of the EOCD comment. */ @Nonnull - private final byte[] mComment; + private final byte[] comment; /** * Supplier of the byte representation of the EOCD. */ @Nonnull - private final CachedSupplier<byte[]> mByteSupplier; + private final CachedSupplier<byte[]> byteSupplier; /** * Creates a new EOCD, reading it from a byte source. This method will parse the byte source @@ -145,18 +145,18 @@ class Eocd { Verify.verify(totalRecords1 <= Integer.MAX_VALUE); - mTotalRecords = Ints.checkedCast(totalRecords1); - mDirectorySize = directorySize; - mDirectoryOffset = directoryOffset; + totalRecords = Ints.checkedCast(totalRecords1); + this.directorySize = directorySize; + this.directoryOffset = directoryOffset; if (bytes.remaining() < commentSize) { throw new IOException("Corrupt EOCD record: not enough data for comment (comment " + "size is " + commentSize + ")."); } - mComment = new byte[commentSize]; - bytes.get(mComment); - mByteSupplier = new CachedSupplier<>(this::computeByteRepresentation); + comment = new byte[commentSize]; + bytes.get(comment); + byteSupplier = new CachedSupplier<>(this::computeByteRepresentation); } /** @@ -173,11 +173,11 @@ class Eocd { Preconditions.checkArgument(directoryOffset >= 0, "directoryOffset < 0"); Preconditions.checkArgument(directorySize >= 0, "directorySize < 0"); - mTotalRecords = totalRecords; - mDirectoryOffset = directoryOffset; - mDirectorySize = directorySize; - mComment = new byte[0]; - mByteSupplier = new CachedSupplier<byte[]>(this::computeByteRepresentation); + this.totalRecords = totalRecords; + this.directoryOffset = directoryOffset; + this.directorySize = directorySize; + comment = new byte[0]; + byteSupplier = new CachedSupplier<byte[]>(this::computeByteRepresentation); } /** @@ -186,7 +186,7 @@ class Eocd { * @return the number of records */ int getTotalRecords() { - return mTotalRecords; + return totalRecords; } /** @@ -196,7 +196,7 @@ class Eocd { * @return the offset where the Central Directory is located */ long getDirectoryOffset() { - return mDirectoryOffset; + return directoryOffset; } /** @@ -205,7 +205,7 @@ class Eocd { * @return the number of bytes that make up the Central Directory */ long getDirectorySize() { - return mDirectorySize; + return directorySize; } /** @@ -214,7 +214,7 @@ class Eocd { * @return the size, in bytes, of the EOCD */ long getEocdSize() { - return F_COMMENT_SIZE.endOffset() + mComment.length; + return F_COMMENT_SIZE.endOffset() + comment.length; } /** @@ -225,7 +225,7 @@ class Eocd { */ @Nonnull byte[] toBytes() throws IOException { - return mByteSupplier.get(); + return byteSupplier.get(); } /** @@ -236,18 +236,18 @@ class Eocd { */ @Nonnull private byte[] computeByteRepresentation() { - ByteBuffer out = ByteBuffer.allocate(F_COMMENT_SIZE.endOffset() + mComment.length); + ByteBuffer out = ByteBuffer.allocate(F_COMMENT_SIZE.endOffset() + comment.length); try { F_SIGNATURE.write(out); F_NUMBER_OF_DISK.write(out); F_DISK_CD_START.write(out); - F_RECORDS_DISK.write(out, mTotalRecords); - F_RECORDS_TOTAL.write(out, mTotalRecords); - F_CD_SIZE.write(out, mDirectorySize); - F_CD_OFFSET.write(out, mDirectoryOffset); - F_COMMENT_SIZE.write(out, mComment.length); - out.put(mComment); + F_RECORDS_DISK.write(out, totalRecords); + F_RECORDS_TOTAL.write(out, totalRecords); + F_CD_SIZE.write(out, directorySize); + F_CD_OFFSET.write(out, directoryOffset); + F_COMMENT_SIZE.write(out, comment.length); + out.put(comment); return out.array(); } catch (IOException e) { diff --git a/src/main/java/com/android/apkzlib/zip/ExtraField.java b/src/main/java/com/android/apkzlib/zip/ExtraField.java index 113ef64..4e11519 100644 --- a/src/main/java/com/android/apkzlib/zip/ExtraField.java +++ b/src/main/java/com/android/apkzlib/zip/ExtraField.java @@ -55,11 +55,11 @@ public class ExtraField { static final int ALIGNMENT_ZIP_EXTRA_DATA_FIELD_HEADER_ID = 0xd935; /** - * The field's raw data, if it is known. Either this variable or {@link #mSegments} must be + * The field's raw data, if it is known. Either this variable or {@link #segments} must be * non-{@code null}. */ @Nullable - private final byte[] mRawData; + private final byte[] rawData; /** * The list of field's segments. Will be populated if the extra field is created based on a @@ -67,7 +67,7 @@ public class ExtraField { * on the raw bytes. */ @Nullable - private ImmutableList<Segment> mSegments; + private ImmutableList<Segment> segments; /** * Creates an extra field based on existing raw data. @@ -75,16 +75,16 @@ public class ExtraField { * @param rawData the raw data; will not be parsed unless needed */ public ExtraField(@Nonnull byte[] rawData) { - mRawData = rawData; - mSegments = null; + this.rawData = rawData; + segments = null; } /** * Creates a new extra field with no segments. */ public ExtraField() { - mRawData = null; - mSegments = ImmutableList.of(); + rawData = null; + segments = ImmutableList.of(); } /** @@ -93,8 +93,8 @@ public class ExtraField { * @param segments the segments */ public ExtraField(@Nonnull ImmutableList<Segment> segments) { - mRawData = null; - mSegments = segments; + rawData = null; + this.segments = segments; } /** @@ -104,12 +104,12 @@ public class ExtraField { * @throws IOException failed to parse the extra field */ public ImmutableList<Segment> getSegments() throws IOException { - if (mSegments == null) { + if (segments == null) { parseSegments(); } - Preconditions.checkNotNull(mSegments); - return mSegments; + Preconditions.checkNotNull(segments); + return segments; } /** @@ -135,16 +135,16 @@ public class ExtraField { } /** - * Parses the raw data and generates all segments in {@link #mSegments}. + * Parses the raw data and generates all segments in {@link #segments}. * * @throws IOException failed to parse the data */ private void parseSegments() throws IOException { - Preconditions.checkNotNull(mRawData); - Preconditions.checkState(mSegments == null); + Preconditions.checkNotNull(rawData); + Preconditions.checkState(segments == null); List<Segment> segments = new ArrayList<>(); - ByteBuffer buffer = ByteBuffer.wrap(mRawData); + ByteBuffer buffer = ByteBuffer.wrap(rawData); while (buffer.remaining() > 0) { int headerId = LittleEndianUtils.readUnsigned2Le(buffer); @@ -165,7 +165,7 @@ public class ExtraField { segments.add(seg); } - mSegments = ImmutableList.copyOf(segments); + this.segments = ImmutableList.copyOf(segments); } /** @@ -174,12 +174,12 @@ public class ExtraField { * @return the size */ public int size() { - if (mRawData != null) { - return mRawData.length; + if (rawData != null) { + return rawData.length; } else { - Preconditions.checkNotNull(mSegments); + Preconditions.checkNotNull(segments); int sz = 0; - for (Segment s : mSegments) { + for (Segment s : segments) { sz += s.size(); } @@ -195,11 +195,11 @@ public class ExtraField { * @throws IOException failed to write the extra fields */ public void write(@Nonnull ByteBuffer out) throws IOException { - if (mRawData != null) { - out.put(mRawData); + if (rawData != null) { + out.put(rawData); } else { - Preconditions.checkNotNull(mSegments); - for (Segment s : mSegments) { + Preconditions.checkNotNull(segments); + for (Segment s : segments) { s.write(out); } } @@ -277,13 +277,13 @@ public class ExtraField { /** * Header ID. */ - private final int mHeaderId; + private final int headerId; /** * Data in the segment. */ @Nonnull - private final byte[] mData; + private final byte[] data; /** * Creates a new raw data segment. @@ -292,25 +292,25 @@ public class ExtraField { * @param data the segment data */ RawDataSegment(int headerId, @Nonnull byte[] data) { - mHeaderId = headerId; - mData = data; + this.headerId = headerId; + this.data = data; } @Override public int getHeaderId() { - return mHeaderId; + return headerId; } @Override public void write(@Nonnull ByteBuffer out) throws IOException { - LittleEndianUtils.writeUnsigned2Le(out, mHeaderId); - LittleEndianUtils.writeUnsigned2Le(out, mData.length); - out.put(mData); + LittleEndianUtils.writeUnsigned2Le(out, headerId); + LittleEndianUtils.writeUnsigned2Le(out, data.length); + out.put(data); } @Override public int size() { - return 4 + mData.length; + return 4 + data.length; } } @@ -326,12 +326,12 @@ public class ExtraField { /** * The alignment value. */ - private int mAlignment; + private int alignment; /** * How many bytes of padding are in this segment? */ - private int mPadding; + private int padding; /** * Creates a new alignment segment. @@ -347,8 +347,8 @@ public class ExtraField { * We have 6 bytes of fixed data: header ID (2 bytes), data size (2 bytes), alignment * value (2 bytes). */ - mAlignment = alignment; - mPadding = totalSize - 6; + this.alignment = alignment; + padding = totalSize - 6; } /** @@ -362,25 +362,25 @@ public class ExtraField { Preconditions.checkArgument(headerId == ALIGNMENT_ZIP_EXTRA_DATA_FIELD_HEADER_ID); ByteBuffer dataBuffer = ByteBuffer.wrap(data); - mAlignment = LittleEndianUtils.readUnsigned2Le(dataBuffer); - if (mAlignment <= 0) { - throw new IOException("Invalid alignment in alignment field: " + mAlignment); + alignment = LittleEndianUtils.readUnsigned2Le(dataBuffer); + if (alignment <= 0) { + throw new IOException("Invalid alignment in alignment field: " + alignment); } - mPadding = data.length - 2; + padding = data.length - 2; } @Override public void write(@Nonnull ByteBuffer out) throws IOException { LittleEndianUtils.writeUnsigned2Le(out, ALIGNMENT_ZIP_EXTRA_DATA_FIELD_HEADER_ID); - LittleEndianUtils.writeUnsigned2Le(out, mPadding + 2); - LittleEndianUtils.writeUnsigned2Le(out, mAlignment); - out.put(new byte[mPadding]); + LittleEndianUtils.writeUnsigned2Le(out, padding + 2); + LittleEndianUtils.writeUnsigned2Le(out, alignment); + out.put(new byte[padding]); } @Override public int size() { - return mPadding + 6; + return padding + 6; } @Override diff --git a/src/main/java/com/android/apkzlib/zip/FileUseMap.java b/src/main/java/com/android/apkzlib/zip/FileUseMap.java index 2070aad..a72a956 100644 --- a/src/main/java/com/android/apkzlib/zip/FileUseMap.java +++ b/src/main/java/com/android/apkzlib/zip/FileUseMap.java @@ -50,24 +50,24 @@ import javax.annotation.Nullable; class FileUseMap { /** * Size of the file according to the map. This should always match the last entry in - * {@code #mMap}. + * {@code #map}. */ - private long mSize; + private long size; /** - * Tree with all intervals ordered by position. Contains coverage from 0 up to {@link #mSize}. - * If {@link #mSize} is zero then this set is empty. This is the only situation in which the map + * Tree with all intervals ordered by position. Contains coverage from 0 up to {@link #size}. + * If {@link #size} is zero then this set is empty. This is the only situation in which the map * will be empty. */ @Nonnull - private TreeSet<FileUseMapEntry<?>> mMap; + private TreeSet<FileUseMapEntry<?>> map; /** - * Tree with all free blocks ordered by size. This is essentially a view over {@link #mMap} + * Tree with all free blocks ordered by size. This is essentially a view over {@link #map} * containing only the free blocks, but in a different order. */ @Nonnull - private TreeSet<FileUseMapEntry<?>> mFree; + private TreeSet<FileUseMapEntry<?>> free; /** * If defined, defines the minimum size for a free entry. @@ -84,9 +84,9 @@ class FileUseMap { Preconditions.checkArgument(size >= 0, "size < 0"); Preconditions.checkArgument(minFreeSize >= 0, "minFreeSize < 0"); - mSize = size; - mMap = new TreeSet<>(FileUseMapEntry.COMPARE_BY_START); - mFree = new TreeSet<>(FileUseMapEntry.COMPARE_BY_SIZE); + this.size = size; + map = new TreeSet<>(FileUseMapEntry.COMPARE_BY_START); + free = new TreeSet<>(FileUseMapEntry.COMPARE_BY_SIZE); mMinFreeSize = minFreeSize; if (size > 0) { @@ -100,10 +100,10 @@ class FileUseMap { * @param entry the entry to add */ private void internalAdd(@Nonnull FileUseMapEntry<?> entry) { - mMap.add(entry); + map.add(entry); if (entry.isFree()) { - mFree.add(entry); + free.add(entry); } } @@ -113,11 +113,11 @@ class FileUseMap { * @param entry the entry to remove */ private void internalRemove(@Nonnull FileUseMapEntry<?> entry) { - boolean wasRemoved = mMap.remove(entry); - Preconditions.checkState(wasRemoved, "entry not in mMap"); + boolean wasRemoved = map.remove(entry); + Preconditions.checkState(wasRemoved, "entry not in map"); if (entry.isFree()) { - mFree.remove(entry); + free.remove(entry); } } @@ -129,8 +129,8 @@ class FileUseMap { * @param entry the entry to add */ private void add(@Nonnull FileUseMapEntry<?> entry) { - Preconditions.checkArgument(entry.getStart() < mSize, "entry.getStart() >= mSize"); - Preconditions.checkArgument(entry.getEnd() <= mSize, "entry.getEnd() > mSize"); + Preconditions.checkArgument(entry.getStart() < size, "entry.getStart() >= size"); + Preconditions.checkArgument(entry.getEnd() <= size, "entry.getEnd() > size"); Preconditions.checkArgument(!entry.isFree(), "entry.isFree()"); FileUseMapEntry<?> container = findContainer(entry); @@ -150,7 +150,7 @@ class FileUseMap { * @param entry the entry */ void remove(@Nonnull FileUseMapEntry<?> entry) { - Preconditions.checkState(mMap.contains(entry), "!mMap.contains(entry)"); + Preconditions.checkState(map.contains(entry), "!map.contains(entry)"); Preconditions.checkArgument(!entry.isFree(), "entry.isFree()"); internalRemove(entry); @@ -191,7 +191,7 @@ class FileUseMap { */ @Nonnull private FileUseMapEntry<?> findContainer(@Nonnull FileUseMapEntry<?> entry) { - FileUseMapEntry container = mMap.floor(entry); + FileUseMapEntry container = map.floor(entry); Verify.verifyNotNull(container); Verify.verify(container.getStart() <= entry.getStart()); Verify.verify(container.getEnd() >= entry.getEnd()); @@ -203,7 +203,7 @@ class FileUseMap { * Splits a container to add an entry, adding new free entries before and after the provided * entry if needed. * - * @param container the container entry, a free entry that is in {@link #mMap} that that + * @param container the container entry, a free entry that is in {@link #map} that that * encloses {@code entry} * @param entry the entry that will be used to split {@code container} * @return a set of non-overlapping entries that completely covers {@code container} and that @@ -252,7 +252,7 @@ class FileUseMap { /* * See if we have a previous entry to merge with this one. */ - prevToMerge = mMap.floor(FileUseMapEntry.makeFree(start - 1, start)); + prevToMerge = map.floor(FileUseMapEntry.makeFree(start - 1, start)); Verify.verifyNotNull(prevToMerge); if (!prevToMerge.isFree()) { prevToMerge = null; @@ -261,11 +261,11 @@ class FileUseMap { FileUseMapEntry<?> nextToMerge = null; long end = entry.getEnd(); - if (end < mSize) { + if (end < size) { /* * See if we have a next entry to merge with this one. */ - nextToMerge = mMap.ceiling(FileUseMapEntry.makeFree(end, end + 1)); + nextToMerge = map.ceiling(FileUseMapEntry.makeFree(end, end + 1)); Verify.verifyNotNull(nextToMerge); if (!nextToMerge.isFree()) { nextToMerge = null; @@ -296,18 +296,18 @@ class FileUseMap { * Truncates map removing the top entry if it is free and reducing the map's size. */ void truncate() { - if (mSize == 0) { + if (size == 0) { return; } /* * Find the last entry. */ - FileUseMapEntry<?> last = mMap.last(); + FileUseMapEntry<?> last = map.last(); Verify.verifyNotNull(last, "last == null"); if (last.isFree()) { internalRemove(last); - mSize = last.getStart(); + size = last.getStart(); } } @@ -317,7 +317,7 @@ class FileUseMap { * @return the size */ long size() { - return mSize; + return size; } /** @@ -326,7 +326,7 @@ class FileUseMap { * @return the size of the file discounting the last block if it is empty */ long usedSize() { - if (mSize == 0) { + if (size == 0) { return 0; } @@ -334,13 +334,13 @@ class FileUseMap { * Find the last entry to see if it is an empty entry. If it is, we need to remove its size * from the returned value. */ - FileUseMapEntry<?> last = mMap.last(); + FileUseMapEntry<?> last = map.last(); Verify.verifyNotNull(last, "last == null"); if (last.isFree()) { return last.getStart(); } else { - Verify.verify(last.getEnd() == mSize); - return mSize; + Verify.verify(last.getEnd() == size); + return size; } } @@ -351,16 +351,16 @@ class FileUseMap { * @param size the new size of the map that cannot be smaller that the current size */ void extend(long size) { - Preconditions.checkArgument(size >= mSize, "size < mSize"); + Preconditions.checkArgument(size >= this.size, "size < size"); - if (mSize == size) { + if (this.size == size) { return; } - FileUseMapEntry<?> newBlock = FileUseMapEntry.makeFree(mSize, size); + FileUseMapEntry<?> newBlock = FileUseMapEntry.makeFree(this.size, size); internalAdd(newBlock); - mSize = size; + this.size = size; coalesce(newBlock); } @@ -389,10 +389,10 @@ class FileUseMap { switch (alg) { case BEST_FIT: - matches = mFree.tailSet(minimumSizedEntry); + matches = free.tailSet(minimumSizedEntry); break; case FIRST_FIT: - matches = mMap; + matches = map; break; default: throw new AssertionError(); @@ -445,7 +445,7 @@ class FileUseMap { */ long emptySpaceLeft = curr.getSize() - (size + extraSize); if (emptySpaceLeft > 0 && emptySpaceLeft < mMinFreeSize) { - FileUseMapEntry<?> next = mMap.higher(curr); + FileUseMapEntry<?> next = map.higher(curr); if (next != null && !next.isFree()) { continue; } @@ -473,9 +473,9 @@ class FileUseMap { /* * If no entry that could hold size is found, get the first free byte. */ - long firstFree = mSize; - if (best == null && !mMap.isEmpty()) { - FileUseMapEntry<?> last = mMap.last(); + long firstFree = this.size; + if (best == null && !map.isEmpty()) { + FileUseMapEntry<?> last = map.last(); if (last.isFree()) { firstFree = last.getStart(); } @@ -515,8 +515,8 @@ class FileUseMap { List<FileUseMapEntry<?>> getFreeAreas() { List<FileUseMapEntry<?>> freeAreas = Lists.newArrayList(); - for (FileUseMapEntry<?> area : mMap) { - if (area.isFree() && area.getEnd() != mSize) { + for (FileUseMapEntry<?> area : map) { + if (area.isFree() && area.getEnd() != size) { freeAreas.add(area); } } @@ -535,13 +535,13 @@ class FileUseMap { FileUseMapEntry<?> before(@Nonnull FileUseMapEntry<?> entry) { Preconditions.checkNotNull(entry, "entry == null"); - return mMap.lower(entry); + return map.lower(entry); } @Override public String toString() { StringJoiner j = new StringJoiner(", "); - mMap.stream() + map.stream() .map(e -> e.getStart() + " - " + e.getEnd() + ": " + e.getStore()) .forEach(j::add); return "FileUseMap[" + j.toString() + "]"; diff --git a/src/main/java/com/android/apkzlib/zip/FileUseMapEntry.java b/src/main/java/com/android/apkzlib/zip/FileUseMapEntry.java index bc68a89..3e5aaba 100644 --- a/src/main/java/com/android/apkzlib/zip/FileUseMapEntry.java +++ b/src/main/java/com/android/apkzlib/zip/FileUseMapEntry.java @@ -50,18 +50,18 @@ class FileUseMapEntry<T> { /** * The first byte in the entry. */ - private final long mStart; + private final long start; /** * The first byte no longer in the entry. */ - private final long mEnd; + private final long end; /** * The stored data. If {@code null} then this entry represents a free entry. */ @Nullable - private final T mStore; + private final T store; /** * Creates a new map entry. @@ -74,9 +74,9 @@ class FileUseMapEntry<T> { Preconditions.checkArgument(start >= 0, "start < 0"); Preconditions.checkArgument(end > start, "end <= start"); - mStart = start; - mEnd = end; - mStore = store; + this.start = start; + this.end = end; + this.store = store; } /** @@ -111,7 +111,7 @@ class FileUseMapEntry<T> { * is empty and contains no data) */ long getStart() { - return mStart; + return start; } /** @@ -120,7 +120,7 @@ class FileUseMapEntry<T> { * @return the first byte no longer in the entry */ long getEnd() { - return mEnd; + return end; } /** @@ -129,7 +129,7 @@ class FileUseMapEntry<T> { * @return the number of bytes contained in the entry */ long getSize() { - return mEnd - mStart; + return end - start; } /** @@ -138,7 +138,7 @@ class FileUseMapEntry<T> { * @return is this entry free? */ boolean isFree() { - return mStore == null; + return store == null; } /** @@ -148,15 +148,15 @@ class FileUseMapEntry<T> { */ @Nullable T getStore() { - return mStore; + return store; } @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("start", mStart) - .add("end", mEnd) - .add("store", mStore) + .add("start", start) + .add("end", end) + .add("store", store) .toString(); } } diff --git a/src/main/java/com/android/apkzlib/zip/GPFlags.java b/src/main/java/com/android/apkzlib/zip/GPFlags.java index 356eb70..fc27c5d 100644 --- a/src/main/java/com/android/apkzlib/zip/GPFlags.java +++ b/src/main/java/com/android/apkzlib/zip/GPFlags.java @@ -67,20 +67,21 @@ class GPFlags { */ private static final int BIT_UNUSED = (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 14) | (1 << 15); + /** * Bit flag value. */ - private final long mValue; + private final long value; /** * Has the CRC computation beeen deferred? */ - private boolean mDeferredCrc; + private boolean deferredCrc; /** * Is the file name encoded in UTF-8? */ - private boolean mUtf8FileName; + private boolean utf8FileName; /** * Creates a new flags object. @@ -88,10 +89,10 @@ class GPFlags { * @param value the value of the bit mask */ private GPFlags(long value) { - mValue = value; + this.value = value; - mDeferredCrc = ((value & BIT_DEFERRED_CRC) != 0); - mUtf8FileName = ((value & BIT_EFS) != 0); + deferredCrc = ((value & BIT_DEFERRED_CRC) != 0); + utf8FileName = ((value & BIT_EFS) != 0); } /** @@ -100,7 +101,7 @@ class GPFlags { * @return the value of the bit mask */ public long getValue() { - return mValue; + return value; } /** @@ -109,7 +110,7 @@ class GPFlags { * @return is the CRC computation deferred? */ public boolean isDeferredCrc() { - return mDeferredCrc; + return deferredCrc; } /** @@ -118,7 +119,7 @@ class GPFlags { * @return is the file name encoded in UTF-8? */ public boolean isUtf8FileName() { - return mUtf8FileName; + return utf8FileName; } /** diff --git a/src/main/java/com/android/apkzlib/zip/InflaterByteSource.java b/src/main/java/com/android/apkzlib/zip/InflaterByteSource.java index cd1cd36..974d4ac 100644 --- a/src/main/java/com/android/apkzlib/zip/InflaterByteSource.java +++ b/src/main/java/com/android/apkzlib/zip/InflaterByteSource.java @@ -35,14 +35,14 @@ public class InflaterByteSource extends CloseableByteSource { * The stream factory for the deflated data. */ @Nonnull - private final CloseableByteSource mDeflatedSource; + private final CloseableByteSource deflatedSource; /** * Creates a new source. * @param byteSource the factory for deflated data */ public InflaterByteSource(@Nonnull CloseableByteSource byteSource) { - mDeflatedSource = byteSource; + deflatedSource = byteSource; } @Override @@ -53,12 +53,12 @@ public class InflaterByteSource extends CloseableByteSource { * "Oh, I need an extra dummy byte to allow for some... err... optimizations..." */ ByteArrayInputStream hackByte = new ByteArrayInputStream(new byte[] { 0 }); - return new InflaterInputStream(new SequenceInputStream(mDeflatedSource.openStream(), + return new InflaterInputStream(new SequenceInputStream(deflatedSource.openStream(), hackByte), new Inflater(true)); } @Override public void innerClose() throws IOException { - mDeflatedSource.close(); + deflatedSource.close(); } } diff --git a/src/main/java/com/android/apkzlib/zip/LazyDelegateByteSource.java b/src/main/java/com/android/apkzlib/zip/LazyDelegateByteSource.java index ebabad7..bdd3e4c 100644 --- a/src/main/java/com/android/apkzlib/zip/LazyDelegateByteSource.java +++ b/src/main/java/com/android/apkzlib/zip/LazyDelegateByteSource.java @@ -42,14 +42,14 @@ public class LazyDelegateByteSource extends CloseableByteSource { * Byte source where we delegate operations to. */ @Nonnull - private final ListenableFuture<CloseableByteSource> mDelegate; + private final ListenableFuture<CloseableByteSource> delegate; /** * Creates a new byte source that delegates operations to the provided source. * @param delegate the source that will receive all operations */ public LazyDelegateByteSource(@Nonnull ListenableFuture<CloseableByteSource> delegate) { - mDelegate = delegate; + this.delegate = delegate; } /** @@ -58,7 +58,7 @@ public class LazyDelegateByteSource extends CloseableByteSource { */ @Nonnull public ListenableFuture<CloseableByteSource> getDelegate() { - return mDelegate; + return delegate; } /** @@ -69,7 +69,7 @@ public class LazyDelegateByteSource extends CloseableByteSource { @Nonnull private CloseableByteSource get() throws IOException { try { - CloseableByteSource r = mDelegate.get(); + CloseableByteSource r = delegate.get(); if (r == null) { throw new IOException("Delegate byte source computation resulted in null."); } diff --git a/src/main/java/com/android/apkzlib/zip/ProcessedAndRawByteSources.java b/src/main/java/com/android/apkzlib/zip/ProcessedAndRawByteSources.java index acea3df..86c6382 100644 --- a/src/main/java/com/android/apkzlib/zip/ProcessedAndRawByteSources.java +++ b/src/main/java/com/android/apkzlib/zip/ProcessedAndRawByteSources.java @@ -34,50 +34,53 @@ public class ProcessedAndRawByteSources implements Closeable { * The processed byte source. */ @Nonnull - private final CloseableByteSource mProcessedSource; + private final CloseableByteSource processedSource; /** * The processed raw source. */ @Nonnull - private final CloseableByteSource mRawSource; + private final CloseableByteSource rawSource; /** * Creates a new container. + * * @param processedSource the processed source * @param rawSource the raw source */ public ProcessedAndRawByteSources(@Nonnull CloseableByteSource processedSource, @Nonnull CloseableByteSource rawSource) { - mProcessedSource = processedSource; - mRawSource = rawSource; + this.processedSource = processedSource; + this.rawSource = rawSource; } /** * Obtains a byte source that read the processed contents of the entry. + * * @return a byte source */ @Nonnull public CloseableByteSource getProcessedByteSource() { - return mProcessedSource; + return processedSource; } /** * Obtains a byte source that reads the raw contents of an entry. This is the data that is * ultimately stored in the file and, in the case of compressed files, is the same data in the * source returned by {@link #getProcessedByteSource()}. + * * @return a byte source */ @Nonnull public CloseableByteSource getRawByteSource() { - return mRawSource; + return rawSource; } @Override public void close() throws IOException { Closer closer = Closer.create(); - closer.register(mProcessedSource); - closer.register(mRawSource); + closer.register(processedSource); + closer.register(rawSource); closer.close(); } } diff --git a/src/main/java/com/android/apkzlib/zip/StoredEntry.java b/src/main/java/com/android/apkzlib/zip/StoredEntry.java index 10289ca..aec3daf 100644 --- a/src/main/java/com/android/apkzlib/zip/StoredEntry.java +++ b/src/main/java/com/android/apkzlib/zip/StoredEntry.java @@ -154,43 +154,43 @@ public class StoredEntry { * Type of entry. */ @Nonnull - private StoredEntryType mType; + private StoredEntryType type; /** * The central directory header with information about the file. */ @Nonnull - private CentralDirectoryHeader mCdh; + private CentralDirectoryHeader cdh; /** * The file this entry is associated with */ @Nonnull - private ZFile mFile; + private ZFile file; /** * Has this entry been deleted? */ - private boolean mDeleted; + private boolean deleted; /** * Extra field specified in the local directory. */ @Nonnull - private ExtraField mLocalExtra; + private ExtraField localExtra; /** * Type of data descriptor associated with the entry. */ @Nonnull - private DataDescriptorType mDataDescriptorType; + private DataDescriptorType dataDescriptorType; /** * Source for this entry's data. If this entry is a directory, this source has to have zero * size. */ @Nonnull - private ProcessedAndRawByteSources mSource; + private ProcessedAndRawByteSources source; /** * Creates a new stored entry. @@ -204,16 +204,16 @@ public class StoredEntry { */ StoredEntry(@Nonnull CentralDirectoryHeader header, @Nonnull ZFile file, @Nullable ProcessedAndRawByteSources source) throws IOException { - mCdh = header; - mFile = file; - mDeleted = false; + cdh = header; + this.file = file; + deleted = false; if (header.getOffset() >= 0) { /* * This will be overwritten during readLocalHeader. However, IJ complains if we don't - * assign a value to mLocalExtra because of the @Nonnull annotation. + * assign a value to localExtra because of the @Nonnull annotation. */ - mLocalExtra = new ExtraField(); + localExtra = new ExtraField(); readLocalHeader(); @@ -225,16 +225,16 @@ public class StoredEntry { * the file from the zip when needed. The assignment is not really needed, but we * would get a warning because of the @NotNull otherwise. */ - mSource = createSourceFromZip(mCdh.getOffset()); + this.source = createSourceFromZip(cdh.getOffset()); } else { /* * There is no local extra data for new files. */ - mLocalExtra = new ExtraField(); + localExtra = new ExtraField(); Preconditions.checkNotNull(source, "Source was not defined, but contents are not " + "on file."); - mSource = source; + this.source = source; } /* @@ -242,31 +242,31 @@ public class StoredEntry { * This seems to be respected by all zip utilities although I could not find there anywhere * in the specification. */ - if (mCdh.getName().endsWith(Character.toString(ZFile.SEPARATOR))) { - mType = StoredEntryType.DIRECTORY; - Verify.verify(mSource.getProcessedByteSource().isEmpty(), + if (cdh.getName().endsWith(Character.toString(ZFile.SEPARATOR))) { + type = StoredEntryType.DIRECTORY; + Verify.verify(this.source.getProcessedByteSource().isEmpty(), "Directory source is not empty."); - Verify.verify(mCdh.getCrc32() == 0, "Directory has CRC32 = %s.", mCdh.getCrc32()); - Verify.verify(mCdh.getUncompressedSize() == 0, "Directory has uncompressed size = %s.", - mCdh.getUncompressedSize()); + Verify.verify(cdh.getCrc32() == 0, "Directory has CRC32 = %s.", cdh.getCrc32()); + Verify.verify(cdh.getUncompressedSize() == 0, "Directory has uncompressed size = %s.", + cdh.getUncompressedSize()); /* * Some clever (OMG!) tools, like jar will actually try to compress the directory * contents and generate a 2 byte compressed data. Of course, the uncompressed size is * zero and we're just wasting space. */ - long compressedSize = mCdh.getCompressionInfoWithWait().getCompressedSize(); + long compressedSize = cdh.getCompressionInfoWithWait().getCompressedSize(); Verify.verify(compressedSize == 0 || compressedSize == 2, "Directory has compressed size = %s.", compressedSize); } else { - mType = StoredEntryType.FILE; + type = StoredEntryType.FILE; } /* * By default we assume there is no data descriptor unless the CRC is marked as deferred * in the header's GP Bit. */ - mDataDescriptorType = DataDescriptorType.NO_DATA_DESCRIPTOR; + dataDescriptorType = DataDescriptorType.NO_DATA_DESCRIPTOR; if (header.getGpBit().isDeferredCrc()) { /* * If the deferred CRC bit exists, then we have an extra descriptor field. This extra @@ -289,8 +289,8 @@ public class StoredEntry { * @return the local header size in bytes */ public int getLocalHeaderSize() { - Preconditions.checkState(!mDeleted, "mDeleted"); - return FIXED_LOCAL_FILE_HEADER_SIZE + mCdh.getEncodedFileName().length + mLocalExtra.size(); + Preconditions.checkState(!deleted, "deleted"); + return FIXED_LOCAL_FILE_HEADER_SIZE + cdh.getEncodedFileName().length + localExtra.size(); } /** @@ -301,9 +301,9 @@ public class StoredEntry { * @throws IOException failed to get compression information */ long getInFileSize() throws IOException { - Preconditions.checkState(!mDeleted, "mDeleted"); - return mCdh.getCompressionInfoWithWait().getCompressedSize() + getLocalHeaderSize() - + mDataDescriptorType.size; + Preconditions.checkState(!deleted, "deleted"); + return cdh.getCompressionInfoWithWait().getCompressedSize() + getLocalHeaderSize() + + dataDescriptorType.size; } /** @@ -314,7 +314,7 @@ public class StoredEntry { */ @Nonnull public InputStream open() throws IOException { - return mSource.getProcessedByteSource().openStream(); + return source.getProcessedByteSource().openStream(); } /** @@ -337,8 +337,8 @@ public class StoredEntry { */ @Nonnull public StoredEntryType getType() { - Preconditions.checkState(!mDeleted, "mDeleted"); - return mType; + Preconditions.checkState(!deleted, "deleted"); + return type; } /** @@ -360,17 +360,17 @@ public class StoredEntry { * @throws IOException failed to delete the entry */ void delete(boolean notify) throws IOException { - Preconditions.checkState(!mDeleted, "mDeleted"); - mFile.delete(this, notify); - mDeleted = true; - mSource.close(); + Preconditions.checkState(!deleted, "deleted"); + file.delete(this, notify); + deleted = true; + source.close(); } /** * Returns {@code true} if this entry has been deleted/replaced. */ public boolean isDeleted() { - return mDeleted; + return deleted; } /** @@ -380,7 +380,7 @@ public class StoredEntry { */ @Nonnull public CentralDirectoryHeader getCentralDirectoryHeader() { - return mCdh; + return cdh; } /** @@ -388,35 +388,35 @@ public class StoredEntry { * Header provided in the constructor. This method should only be called if the entry already * exists on disk; new entries do not have local headers. * <p> - * This method will define the {@link #mLocalExtra} field that is only defined in the + * This method will define the {@link #localExtra} field that is only defined in the * local descriptor. * * @throws IOException failed to read the local header */ private void readLocalHeader() throws IOException { byte[] localHeader = new byte[FIXED_LOCAL_FILE_HEADER_SIZE]; - mFile.directFullyRead(mCdh.getOffset(), localHeader); + file.directFullyRead(cdh.getOffset(), localHeader); - CentralDirectoryHeaderCompressInfo compressInfo = mCdh.getCompressionInfoWithWait(); + CentralDirectoryHeaderCompressInfo compressInfo = cdh.getCompressionInfoWithWait(); ByteBuffer bytes = ByteBuffer.wrap(localHeader); F_LOCAL_SIGNATURE.verify(bytes); - if (mFile.getSkipVersionToExtractValidation()) { + if (file.getSkipVersionToExtractValidation()) { F_VERSION_EXTRACT.skip(bytes); } else { F_VERSION_EXTRACT.verify(bytes, compressInfo.getVersionExtract()); } - F_GP_BIT.verify(bytes, mCdh.getGpBit().getValue()); + F_GP_BIT.verify(bytes, cdh.getGpBit().getValue()); F_METHOD.verify(bytes, compressInfo.getMethod().methodCode); - if (mFile.areTimestampsIgnored()) { + if (file.areTimestampsIgnored()) { F_LAST_MOD_TIME.skip(bytes); F_LAST_MOD_DATE.skip(bytes); } else { - F_LAST_MOD_TIME.verify(bytes, mCdh.getLastModTime()); - F_LAST_MOD_DATE.verify(bytes, mCdh.getLastModDate()); + F_LAST_MOD_TIME.verify(bytes, cdh.getLastModTime()); + F_LAST_MOD_DATE.verify(bytes, cdh.getLastModDate()); } /* @@ -424,32 +424,32 @@ public class StoredEntry { * File Header must be ignored and their actual values must be read from the Data * Descriptor following the contents of this entry. See readDataDescriptorRecord(). */ - if (mCdh.getGpBit().isDeferredCrc()) { + if (cdh.getGpBit().isDeferredCrc()) { F_CRC32.skip(bytes); F_COMPRESSED_SIZE.skip(bytes); F_UNCOMPRESSED_SIZE.skip(bytes); } else { - F_CRC32.verify(bytes, mCdh.getCrc32()); + F_CRC32.verify(bytes, cdh.getCrc32()); F_COMPRESSED_SIZE.verify(bytes, compressInfo.getCompressedSize()); - F_UNCOMPRESSED_SIZE.verify(bytes, mCdh.getUncompressedSize()); + F_UNCOMPRESSED_SIZE.verify(bytes, cdh.getUncompressedSize()); } - F_FILE_NAME_LENGTH.verify(bytes, mCdh.getEncodedFileName().length); + F_FILE_NAME_LENGTH.verify(bytes, cdh.getEncodedFileName().length); long extraLength = F_EXTRA_LENGTH.read(bytes); - long fileNameStart = mCdh.getOffset() + F_EXTRA_LENGTH.endOffset(); - byte[] fileNameData = new byte[mCdh.getEncodedFileName().length]; - mFile.directFullyRead(fileNameStart, fileNameData); + long fileNameStart = cdh.getOffset() + F_EXTRA_LENGTH.endOffset(); + byte[] fileNameData = new byte[cdh.getEncodedFileName().length]; + file.directFullyRead(fileNameStart, fileNameData); - String fileName = EncodeUtils.decode(fileNameData, mCdh.getGpBit()); - if (!fileName.equals(mCdh.getName())) { - throw new IOException("Central directory reports file as being named '" + mCdh.getName() + String fileName = EncodeUtils.decode(fileNameData, cdh.getGpBit()); + if (!fileName.equals(cdh.getName())) { + throw new IOException("Central directory reports file as being named '" + cdh.getName() + "' but local header reports file being named '" + fileName + "'."); } - long localExtraStart = fileNameStart + mCdh.getEncodedFileName().length; + long localExtraStart = fileNameStart + cdh.getEncodedFileName().length; byte[] localExtraRaw = new byte[Ints.checkedCast(extraLength)]; - mFile.directFullyRead(localExtraStart, localExtraRaw); - mLocalExtra = new ExtraField(localExtraRaw); + file.directFullyRead(localExtraStart, localExtraRaw); + localExtra = new ExtraField(localExtraRaw); } /** @@ -457,18 +457,18 @@ public class StoredEntry { * that a data descriptor does exist. It will read the data descriptor and check that the data * described there matches the data provided in the Central Directory. * <p> - * This method will set the {@link #mDataDescriptorType} field to the appropriate type of + * This method will set the {@link #dataDescriptorType} field to the appropriate type of * data descriptor record. * * @throws IOException failed to read the data descriptor record */ private void readDataDescriptorRecord() throws IOException { - CentralDirectoryHeaderCompressInfo compressInfo = mCdh.getCompressionInfoWithWait(); + CentralDirectoryHeaderCompressInfo compressInfo = cdh.getCompressionInfoWithWait(); - long ddStart = mCdh.getOffset() + FIXED_LOCAL_FILE_HEADER_SIZE - + mCdh.getName().length() + mLocalExtra.size() + compressInfo.getCompressedSize(); + long ddStart = cdh.getOffset() + FIXED_LOCAL_FILE_HEADER_SIZE + + cdh.getName().length() + localExtra.size() + compressInfo.getCompressedSize(); byte ddData[] = new byte[DataDescriptorType.DATA_DESCRIPTOR_WITH_SIGNATURE.size]; - mFile.directFullyRead(ddStart, ddData); + file.directFullyRead(ddStart, ddData); ByteBuffer ddBytes = ByteBuffer.wrap(ddData); @@ -476,9 +476,9 @@ public class StoredEntry { int cpos = ddBytes.position(); long sig = signatureField.read(ddBytes); if (sig == DATA_DESC_SIGNATURE) { - mDataDescriptorType = DataDescriptorType.DATA_DESCRIPTOR_WITH_SIGNATURE; + dataDescriptorType = DataDescriptorType.DATA_DESCRIPTOR_WITH_SIGNATURE; } else { - mDataDescriptorType = DataDescriptorType.DATA_DESCRIPTOR_WITHOUT_SIGNATURE; + dataDescriptorType = DataDescriptorType.DATA_DESCRIPTOR_WITHOUT_SIGNATURE; ddBytes.position(cpos); } @@ -487,10 +487,10 @@ public class StoredEntry { ZipField.F4 uncompressedField = new ZipField.F4(compressedField.endOffset(), "Uncompressed size"); - if (!mFile.getSkipDataDescriptorVerification()) { - crc32Field.verify(ddBytes, mCdh.getCrc32()); + if (!file.getSkipDataDescriptorVerification()) { + crc32Field.verify(ddBytes, cdh.getCrc32()); compressedField.verify(ddBytes, compressInfo.getCompressedSize()); - uncompressedField.verify(ddBytes, mCdh.getUncompressedSize()); + uncompressedField.verify(ddBytes, cdh.getUncompressedSize()); } } @@ -508,7 +508,7 @@ public class StoredEntry { final CentralDirectoryHeaderCompressInfo compressInfo; try { - compressInfo = mCdh.getCompressionInfoWithWait(); + compressInfo = cdh.getCompressionInfoWithWait(); } catch (IOException e) { throw new RuntimeException("IOException should never occur here because compression " + "information should be immediately available if reading from zip.", e); @@ -526,13 +526,13 @@ public class StoredEntry { @Nonnull @Override public InputStream openStream() throws IOException { - Preconditions.checkState(!mDeleted, "mDeleted"); + Preconditions.checkState(!deleted, "deleted"); long dataStart = zipOffset + getLocalHeaderSize(); long dataEnd = dataStart + compressInfo.getCompressedSize(); - mFile.openReadOnly(); - return mFile.directOpen(dataStart, dataEnd); + file.openReadOnly(); + return file.directOpen(dataStart, dataEnd); } @Override @@ -559,7 +559,7 @@ public class StoredEntry { @Nonnull CloseableByteSource rawContents) { CentralDirectoryHeaderCompressInfo compressInfo; try { - compressInfo = mCdh.getCompressionInfoWithWait(); + compressInfo = cdh.getCompressionInfoWithWait(); } catch (IOException e) { throw new RuntimeException("IOException should never occur here because compression " + "information should be immediately available if creating from raw " @@ -582,7 +582,7 @@ public class StoredEntry { } /** - * Replaces {@link #mSource} with one that reads file data from the zip file. + * Replaces {@link #source} with one that reads file data from the zip file. * * @param zipFileOffset the offset in the zip file where data is written; must be non-negative * @throws IOException failed to replace the source @@ -590,14 +590,14 @@ public class StoredEntry { void replaceSourceFromZip(long zipFileOffset) throws IOException { Preconditions.checkArgument(zipFileOffset >= 0, "zipFileOffset < 0"); - ProcessedAndRawByteSources oldSource = mSource; - mSource = createSourceFromZip(zipFileOffset); - mCdh.setOffset(zipFileOffset); + ProcessedAndRawByteSources oldSource = source; + source = createSourceFromZip(zipFileOffset); + cdh.setOffset(zipFileOffset); oldSource.close(); } /** - * Loads all data in memory and replaces {@link #mSource} with one that contains all the data + * Loads all data in memory and replaces {@link #source} with one that contains all the data * in memory. * * <p>If the entry's contents are already in memory, this call does nothing. @@ -605,7 +605,7 @@ public class StoredEntry { * @throws IOException failed to replace the source */ void loadSourceIntoMemory() throws IOException { - if (mCdh.getOffset() == -1) { + if (cdh.getOffset() == -1) { /* * No offset in the CDR means data has not been written to disk which, in turn, * means data is already loaded into memory. @@ -613,11 +613,11 @@ public class StoredEntry { return; } - ProcessedAndRawByteSources oldSource = mSource; + ProcessedAndRawByteSources oldSource = source; byte[] rawContents = oldSource.getRawByteSource().read(); - mSource = createSourcesFromRawContents(new CloseableDelegateByteSource( + source = createSourcesFromRawContents(new CloseableDelegateByteSource( ByteSource.wrap(rawContents), rawContents.length)); - mCdh.setOffset(-1); + cdh.setOffset(-1); oldSource.close(); } @@ -629,7 +629,7 @@ public class StoredEntry { */ @Nonnull ProcessedAndRawByteSources getSource() { - return mSource; + return source; } /** @@ -639,7 +639,7 @@ public class StoredEntry { */ @Nonnull public DataDescriptorType getDataDescriptorType() { - return mDataDescriptorType; + return dataDescriptorType; } /** @@ -651,35 +651,35 @@ public class StoredEntry { @Nonnull byte[] toHeaderData() throws IOException { - byte[] encodedFileName = mCdh.getEncodedFileName(); + byte[] encodedFileName = cdh.getEncodedFileName(); ByteBuffer out = ByteBuffer.allocate( - F_EXTRA_LENGTH.endOffset() + encodedFileName.length + mLocalExtra.size()); + F_EXTRA_LENGTH.endOffset() + encodedFileName.length + localExtra.size()); - CentralDirectoryHeaderCompressInfo compressInfo = mCdh.getCompressionInfoWithWait(); + CentralDirectoryHeaderCompressInfo compressInfo = cdh.getCompressionInfoWithWait(); F_LOCAL_SIGNATURE.write(out); F_VERSION_EXTRACT.write(out, compressInfo.getVersionExtract()); - F_GP_BIT.write(out, mCdh.getGpBit().getValue()); + F_GP_BIT.write(out, cdh.getGpBit().getValue()); F_METHOD.write(out, compressInfo.getMethod().methodCode); - if (mFile.areTimestampsIgnored()) { + if (file.areTimestampsIgnored()) { F_LAST_MOD_TIME.write(out, 0); F_LAST_MOD_DATE.write(out, 0); } else { - F_LAST_MOD_TIME.write(out, mCdh.getLastModTime()); - F_LAST_MOD_DATE.write(out, mCdh.getLastModDate()); + F_LAST_MOD_TIME.write(out, cdh.getLastModTime()); + F_LAST_MOD_DATE.write(out, cdh.getLastModDate()); } - F_CRC32.write(out, mCdh.getCrc32()); + F_CRC32.write(out, cdh.getCrc32()); F_COMPRESSED_SIZE.write(out, compressInfo.getCompressedSize()); - F_UNCOMPRESSED_SIZE.write(out, mCdh.getUncompressedSize()); - F_FILE_NAME_LENGTH.write(out, mCdh.getEncodedFileName().length); - F_EXTRA_LENGTH.write(out, mLocalExtra.size()); + F_UNCOMPRESSED_SIZE.write(out, cdh.getUncompressedSize()); + F_FILE_NAME_LENGTH.write(out, cdh.getEncodedFileName().length); + F_EXTRA_LENGTH.write(out, localExtra.size()); - out.put(mCdh.getEncodedFileName()); - mLocalExtra.write(out); + out.put(cdh.getEncodedFileName()); + localExtra.write(out); return out.array(); } @@ -697,9 +697,9 @@ public class StoredEntry { * file */ public boolean realign() throws IOException { - Preconditions.checkState(!mDeleted, "Entry has been deleted."); + Preconditions.checkState(!deleted, "Entry has been deleted."); - return mFile.realign(this); + return file.realign(this); } /** @@ -709,7 +709,7 @@ public class StoredEntry { */ @Nonnull public ExtraField getLocalExtra() { - return mLocalExtra; + return localExtra; } /** @@ -720,7 +720,7 @@ public class StoredEntry { */ public void setLocalExtra(@Nonnull ExtraField localExtra) throws IOException { boolean resized = setLocalExtraNoNotify(localExtra); - mFile.localHeaderChanged(this, resized); + file.localHeaderChanged(this, resized); } /** @@ -748,13 +748,13 @@ public class StoredEntry { */ loadSourceIntoMemory(); - if (mLocalExtra.size() != localExtra.size()) { + if (this.localExtra.size() != localExtra.size()) { sizeChanged = true; } else { sizeChanged = false; } - mLocalExtra = localExtra; + this.localExtra = localExtra; return sizeChanged; } } diff --git a/src/main/java/com/android/apkzlib/zip/ZFile.java b/src/main/java/com/android/apkzlib/zip/ZFile.java index 9fd1ef1..f677d91 100644 --- a/src/main/java/com/android/apkzlib/zip/ZFile.java +++ b/src/main/java/com/android/apkzlib/zip/ZFile.java @@ -234,28 +234,28 @@ public class ZFile implements Closeable { * File zip file. */ @Nonnull - private final File mFile; + private final File file; /** * The random access file used to access the zip file. This will be {@code null} if and only - * if {@link #mState} is {@link ZipFileState#CLOSED}. + * if {@link #state} is {@link ZipFileState#CLOSED}. */ @Nullable - private RandomAccessFile mRaf; + private RandomAccessFile raf; /** * The map containing the in-memory contents of the zip file. It keeps track of which parts of * the zip file are used and which are not. */ @Nonnull - private final FileUseMap mMap; + private final FileUseMap map; /** * The EOCD entry. Will be {@code null} if there is no EOCD (because the zip is new) or the * one that exists on disk is no longer valid (because the zip has been changed). */ @Nullable - private FileUseMapEntry<Eocd> mEocdEntry; + private FileUseMapEntry<Eocd> eocdEntry; /** * The Central Directory entry. Will be {@code null} if there is no Central Directory (because @@ -263,42 +263,42 @@ public class ZFile implements Closeable { * has been changed). */ @Nullable - private FileUseMapEntry<CentralDirectory> mDirectoryEntry; + private FileUseMapEntry<CentralDirectory> directoryEntry; /** * All entries in the zip file. It includes in-memory changes and may not reflect what is * written on disk. Only entries that have been compressed are in this list. */ @Nonnull - private final Map<String, FileUseMapEntry<StoredEntry>> mEntries; + private final Map<String, FileUseMapEntry<StoredEntry>> entries; /** * Entries added to the zip file, but that are not yet compressed. When compression is done, - * these entries are eventually moved to {@link #mEntries}. mUncompressedEntries is a list + * these entries are eventually moved to {@link #entries}. uncompressedEntries is a list * because entries need to be kept in the order by which they were added. It allows adding * multiple files with the same name and getting the right notifications on which files replaced * which. * * <p>Files are placed in this list in {@link #add(StoredEntry)} method. This method will - * keep files here temporarily and move then to {@link #mEntries} when the data is + * keep files here temporarily and move then to {@link #entries} when the data is * available. * - * <p>Moving files out of this list to {@link #mEntries} is done by + * <p>Moving files out of this list to {@link #entries} is done by * {@link #processAllReadyEntries()}. */ @Nonnull - private final List<StoredEntry> mUncompressedEntries; + private final List<StoredEntry> uncompressedEntries; /** * Current state of the zip file. */ @Nonnull - private ZipFileState mState; + private ZipFileState state; /** * Are the in-memory changes that have not been written to the zip file? */ - private boolean mDirty; + private boolean dirty; /** * Non-{@code null} only if the file is currently closed. Used to detect if the zip is @@ -306,78 +306,78 @@ public class ZFile implements Closeable { * be {@code null} even if it is closed. */ @Nullable - private CachedFileContents<Object> mClosedControl; + private CachedFileContents<Object> closedControl; /** * The alignment rule. */ @Nonnull - private final AlignmentRule mAlignmentRule; + private final AlignmentRule alignmentRule; /** * Extensions registered with the file. */ @Nonnull - private final List<ZFileExtension> mExtensions; + private final List<ZFileExtension> extensions; /** * When notifying extensions, extensions may request that some runnables are executed. This * list collects all runnables by the order they were requested. Together with - * {@link #mIsNotifying}, it is used to avoid reordering notifications. + * {@link #isNotifying}, it is used to avoid reordering notifications. */ @Nonnull - private final List<IOExceptionRunnable> mToRun; + private final List<IOExceptionRunnable> toRun; /** * {@code true} when {@link #notify(com.android.apkzlib.utils.IOExceptionFunction)} is notifying extensions. Used * to avoid reordering notifications. */ - private boolean mIsNotifying; + private boolean isNotifying; /** * An extra offset for the central directory location. {@code 0} if the central directory * should be written in its standard location. */ - private long mExtraDirectoryOffset; + private long extraDirectoryOffset; /** * Should all timestamps be zeroed when reading / writing the zip? */ - private boolean mNoTimestamps; + private boolean noTimestamps; /** * Compressor to use. */ @Nonnull - private Compressor mCompressor; + private Compressor compressor; /** * Byte tracker to use. */ @Nonnull - private final ByteTracker mTracker; + private final ByteTracker tracker; /** * Use the zip entry's "extra field" field to cover empty space in the zip file? */ - private boolean mCoverEmptySpaceUsingExtraField; + private boolean coverEmptySpaceUsingExtraField; /** * Should files be automatically sorted when updating? */ - private boolean mAutoSortFiles; + private boolean autoSortFiles; /** * Should data descriptor verification be skipped? See * {@link ZFileOptions#getSkipDataDescriptorValidation()}. */ - private boolean mSkipDataDescriptorVerification; + private boolean skipDataDescriptorVerification; /** * Should the "version to extract" field validation be skipped? See * {@link ZFileOptions#getSkipZipVersionToExtractValidation()}. */ - private boolean mSkipVersionToExtractValidation; + private boolean skipVersionToExtractValidation; /** @@ -404,49 +404,49 @@ public class ZFile implements Closeable { * @throws IOException some file exists but could not be read */ public ZFile(@Nonnull File file, @Nonnull ZFileOptions options) throws IOException { - mFile = file; - mMap = new FileUseMap( + this.file = file; + map = new FileUseMap( 0, options.getCoverEmptySpaceUsingExtraField() ? MINIMUM_EXTRA_FIELD_SIZE : 0); - mDirty = false; - mClosedControl = null; - mAlignmentRule = options.getAlignmentRule(); - mExtensions = Lists.newArrayList(); - mToRun = Lists.newArrayList(); - mNoTimestamps = options.getNoTimestamps(); - mTracker = options.getTracker(); - mCompressor = options.getCompressor(); - mCoverEmptySpaceUsingExtraField = options.getCoverEmptySpaceUsingExtraField(); - mAutoSortFiles = options.getAutoSortFiles(); - mSkipDataDescriptorVerification = options.getSkipDataDescriptorValidation(); - mSkipVersionToExtractValidation = options.getSkipZipVersionToExtractValidation(); + dirty = false; + closedControl = null; + alignmentRule = options.getAlignmentRule(); + extensions = Lists.newArrayList(); + toRun = Lists.newArrayList(); + noTimestamps = options.getNoTimestamps(); + tracker = options.getTracker(); + compressor = options.getCompressor(); + coverEmptySpaceUsingExtraField = options.getCoverEmptySpaceUsingExtraField(); + autoSortFiles = options.getAutoSortFiles(); + skipDataDescriptorVerification = options.getSkipDataDescriptorValidation(); + skipVersionToExtractValidation = options.getSkipZipVersionToExtractValidation(); /* * These two values will be overwritten by openReadOnly() below if the file exists. */ - mState = ZipFileState.CLOSED; - mRaf = null; + state = ZipFileState.CLOSED; + raf = null; if (file.exists()) { openReadOnly(); } else { - mDirty = true; + dirty = true; } - mEntries = Maps.newHashMap(); - mUncompressedEntries = Lists.newArrayList(); - mExtraDirectoryOffset = 0; + entries = Maps.newHashMap(); + uncompressedEntries = Lists.newArrayList(); + extraDirectoryOffset = 0; try { - if (mState != ZipFileState.CLOSED) { - long rafSize = mRaf.length(); + if (state != ZipFileState.CLOSED) { + long rafSize = raf.length(); if (rafSize > Integer.MAX_VALUE) { throw new IOException("File exceeds size limit of " + Integer.MAX_VALUE + "."); } - mMap.extend(Ints.checkedCast(rafSize)); + map.extend(Ints.checkedCast(rafSize)); readData(); notify(ZFileExtension::open); @@ -466,7 +466,7 @@ public class ZFile implements Closeable { public Set<StoredEntry> entries() { Map<String, StoredEntry> entries = Maps.newHashMap(); - for (FileUseMapEntry<StoredEntry> mapEntry : mEntries.values()) { + for (FileUseMapEntry<StoredEntry> mapEntry : this.entries.values()) { StoredEntry entry = mapEntry.getStore(); assert entry != null; entries.put(entry.getCentralDirectoryHeader().getName(), entry); @@ -476,7 +476,7 @@ public class ZFile implements Closeable { * mUncompressed may override mEntriesReady as we may not have yet processed all * entries. */ - for (StoredEntry uncompressed : mUncompressedEntries) { + for (StoredEntry uncompressed : uncompressedEntries) { entries.put(uncompressed.getCentralDirectoryHeader().getName(), uncompressed); } @@ -493,15 +493,15 @@ public class ZFile implements Closeable { public StoredEntry get(@Nonnull String path) { /* * The latest entries are the last ones in uncompressed and they may eventually override - * files in mEntries. + * files in entries. */ - for (StoredEntry stillUncompressed : Lists.reverse(mUncompressedEntries)) { + for (StoredEntry stillUncompressed : Lists.reverse(uncompressedEntries)) { if (stillUncompressed.getCentralDirectoryHeader().getName().equals(path)) { return stillUncompressed; } } - FileUseMapEntry<StoredEntry> found = mEntries.get(path); + FileUseMapEntry<StoredEntry> found = entries.get(path); if (found == null) { return null; } @@ -516,8 +516,8 @@ public class ZFile implements Closeable { * @throws IOException failed to read the zip file */ private void readData() throws IOException { - Preconditions.checkState(mState != ZipFileState.CLOSED, "mState == ZipFileState.CLOSED"); - Preconditions.checkState(mRaf != null, "mRaf == null"); + Preconditions.checkState(state != ZipFileState.CLOSED, "state == ZipFileState.CLOSED"); + Preconditions.checkState(raf != null, "raf == null"); readEocd(); readCentralDirectory(); @@ -528,8 +528,8 @@ public class ZFile implements Closeable { long entryEndOffset; long directoryStartOffset; - if (mDirectoryEntry != null) { - CentralDirectory directory = mDirectoryEntry.getStore(); + if (directoryEntry != null) { + CentralDirectory directory = directoryEntry.getStore(); assert directory != null; entryEndOffset = 0; @@ -551,23 +551,23 @@ public class ZFile implements Closeable { * file. */ - FileUseMapEntry<StoredEntry> mapEntry = mMap.add(start, end, entry); - mEntries.put(entry.getCentralDirectoryHeader().getName(), mapEntry); + FileUseMapEntry<StoredEntry> mapEntry = map.add(start, end, entry); + entries.put(entry.getCentralDirectoryHeader().getName(), mapEntry); if (end > entryEndOffset) { entryEndOffset = end; } } - directoryStartOffset = mDirectoryEntry.getStart(); + directoryStartOffset = directoryEntry.getStart(); } else { /* * No directory means an empty zip file. Use the start of the EOCD to compute * an existing offset. */ - Verify.verifyNotNull(mEocdEntry); - assert mEocdEntry != null; - directoryStartOffset = mEocdEntry.getStart(); + Verify.verifyNotNull(eocdEntry); + assert eocdEntry != null; + directoryStartOffset = eocdEntry.getStart(); entryEndOffset = 0; } @@ -577,25 +577,25 @@ public class ZFile implements Closeable { } /** - * Finds the EOCD marker and reads it. It will populate the {@link #mEocdEntry} variable. + * Finds the EOCD marker and reads it. It will populate the {@link #eocdEntry} variable. * * @throws IOException failed to read the EOCD */ private void readEocd() throws IOException { - Preconditions.checkState(mState != ZipFileState.CLOSED, "mState == ZipFileState.CLOSED"); - Preconditions.checkState(mRaf != null, "mRaf == null"); + Preconditions.checkState(state != ZipFileState.CLOSED, "state == ZipFileState.CLOSED"); + Preconditions.checkState(raf != null, "raf == null"); /* * Read the last part of the zip into memory. If we don't find the EOCD signature by then, * the file is corrupt. */ int lastToRead = LAST_BYTES_TO_READ; - if (lastToRead > mRaf.length()) { - lastToRead = Ints.checkedCast(mRaf.length()); + if (lastToRead > raf.length()) { + lastToRead = Ints.checkedCast(raf.length()); } byte[] last = new byte[lastToRead]; - directFullyRead(mRaf.length() - lastToRead, last); + directFullyRead(raf.length() - lastToRead, last); byte[] eocdSignature = new byte[] { 0x06, 0x05, 0x4b, 0x50 }; @@ -633,14 +633,14 @@ public class ZFile implements Closeable { try { eocd = new Eocd(eocdBytes); - eocdStart = Ints.checkedCast(mRaf.length() - lastToRead + foundEocdSignature); + eocdStart = Ints.checkedCast(raf.length() - lastToRead + foundEocdSignature); /* * Make sure the EOCD takes the whole file up to the end. */ - if (eocdStart + eocd.getEocdSize() != mRaf.length()) { + if (eocdStart + eocd.getEocdSize() != raf.length()) { throw new IOException("EOCD starts at " + eocdStart + " and has " - + eocd.getEocdSize() + " bytes, but file ends at " + mRaf.length() + + eocd.getEocdSize() + " bytes, but file ends at " + raf.length() + "."); } } catch (IOException e) { @@ -677,35 +677,35 @@ public class ZFile implements Closeable { } } - mEocdEntry = mMap.add(eocdStart, eocdStart + eocd.getEocdSize(), eocd); + eocdEntry = map.add(eocdStart, eocdStart + eocd.getEocdSize(), eocd); } /** - * Reads the zip's central directory and populates the {@link #mDirectoryEntry} variable. This + * Reads the zip's central directory and populates the {@link #directoryEntry} variable. This * method can only be called after the EOCD has been read. If the central directory is empty - * (if there are no files on the zip archive), then {@link #mDirectoryEntry} will be set to + * (if there are no files on the zip archive), then {@link #directoryEntry} will be set to * {@code null}. * * @throws IOException failed to read the central directory */ private void readCentralDirectory() throws IOException { - Preconditions.checkNotNull(mEocdEntry, "mEocdEntry == null"); - Preconditions.checkNotNull(mEocdEntry.getStore(), "mEocdEntry.getStore() == null"); - Preconditions.checkState(mState != ZipFileState.CLOSED, "mState == ZipFileState.CLOSED"); - Preconditions.checkState(mRaf != null, "mRaf == null"); - Preconditions.checkState(mDirectoryEntry == null, "mDirectoryEntry != null"); + Preconditions.checkNotNull(eocdEntry, "eocdEntry == null"); + Preconditions.checkNotNull(eocdEntry.getStore(), "eocdEntry.getStore() == null"); + Preconditions.checkState(state != ZipFileState.CLOSED, "state == ZipFileState.CLOSED"); + Preconditions.checkState(raf != null, "raf == null"); + Preconditions.checkState(directoryEntry == null, "directoryEntry != null"); - Eocd eocd = mEocdEntry.getStore(); + Eocd eocd = eocdEntry.getStore(); long dirSize = eocd.getDirectorySize(); if (dirSize > Integer.MAX_VALUE) { throw new IOException("Cannot read central directory with size " + dirSize + "."); } - if (eocd.getDirectoryOffset() + dirSize != mEocdEntry.getStart()) { + if (eocd.getDirectoryOffset() + dirSize != eocdEntry.getStart()) { throw new IOException("Central directory is stored in [" + eocd.getDirectoryOffset() + " - " + (eocd.getDirectoryOffset() + dirSize) + "] and EOCD starts at " - + mEocdEntry.getStart() + "."); + + eocdEntry.getStart() + "."); } byte[] directoryData = new byte[Ints.checkedCast(dirSize)]; @@ -717,7 +717,7 @@ public class ZFile implements Closeable { eocd.getTotalRecords(), this); if (eocd.getDirectorySize() > 0) { - mDirectoryEntry = mMap.add(eocd.getDirectoryOffset(), eocd.getDirectoryOffset() + directoryEntry = map.add(eocd.getDirectoryOffset(), eocd.getDirectoryOffset() + eocd.getDirectorySize(), directory); } } @@ -736,11 +736,11 @@ public class ZFile implements Closeable { */ @Nonnull public InputStream directOpen(final long start, final long end) throws IOException { - Preconditions.checkState(mState != ZipFileState.CLOSED, "mState == ZipFileState.CLOSED"); - Preconditions.checkState(mRaf != null, "mRaf == null"); + Preconditions.checkState(state != ZipFileState.CLOSED, "state == ZipFileState.CLOSED"); + Preconditions.checkState(raf != null, "raf == null"); Preconditions.checkArgument(start >= 0, "start < 0"); Preconditions.checkArgument(end >= start, "end < start"); - Preconditions.checkArgument(end <= mRaf.length(), "end > mRaf.length()"); + Preconditions.checkArgument(end <= raf.length(), "end > raf.length()"); return new InputStream() { private long mCurr = start; @@ -801,14 +801,14 @@ public class ZFile implements Closeable { */ void delete(@Nonnull final StoredEntry entry, boolean notify) throws IOException { String path = entry.getCentralDirectoryHeader().getName(); - FileUseMapEntry<StoredEntry> mapEntry = mEntries.get(path); + FileUseMapEntry<StoredEntry> mapEntry = entries.get(path); Preconditions.checkNotNull(mapEntry, "mapEntry == null"); Preconditions.checkArgument(entry == mapEntry.getStore(), "entry != mapEntry.getStore()"); - mDirty = true; + dirty = true; - mMap.remove(mapEntry); - mEntries.remove(path); + map.remove(mapEntry); + entries.remove(path); if (notify) { notify(ext -> ext.removed(entry)); @@ -836,7 +836,7 @@ public class ZFile implements Closeable { processAllReadyEntriesWithWait(); - if (!mDirty) { + if (!dirty) { return; } @@ -847,7 +847,7 @@ public class ZFile implements Closeable { * empty spaces or sort. If we sort, we don't need to repack as sorting forces the * zip file to be as compact as possible. */ - if (mAutoSortFiles) { + if (autoSortFiles) { sortZipContents(); } else { packIfNecessary(); @@ -858,22 +858,22 @@ public class ZFile implements Closeable { * will have to be rewritten. */ deleteDirectoryAndEocd(); - mMap.truncate(); + map.truncate(); /* * If we need to use the extra field to cover empty spaces, we do the processing here. */ - if (mCoverEmptySpaceUsingExtraField) { + if (coverEmptySpaceUsingExtraField) { /* We will go over all files in the zip and check whether there is empty space before * them. If there is, then we will move the entry to the beginning of the empty space * (covering it) and extend the extra field with the size of the empty space. */ - for (FileUseMapEntry<StoredEntry> entry : new HashSet<>(mEntries.values())) { + for (FileUseMapEntry<StoredEntry> entry : new HashSet<>(entries.values())) { StoredEntry storedEntry = entry.getStore(); assert storedEntry != null; - FileUseMapEntry<?> before = mMap.before(entry); + FileUseMapEntry<?> before = map.before(entry); if (before == null || !before.isFree()) { continue; } @@ -899,8 +899,8 @@ public class ZFile implements Closeable { * Remove the entry. */ String name = storedEntry.getCentralDirectoryHeader().getName(); - mMap.remove(entry); - Verify.verify(entry == mEntries.remove(name)); + map.remove(entry); + Verify.verify(entry == entries.remove(name)); /* * Make a list will all existing segments in the entry's extra field, but remove @@ -927,7 +927,7 @@ public class ZFile implements Closeable { storedEntry.setLocalExtraNoNotify( new ExtraField(ImmutableList.copyOf(extraFieldSegments))); - mEntries.put(name, mMap.add(newStart, newStart + newSize, storedEntry)); + entries.put(name, map.add(newStart, newStart + newSize, storedEntry)); /* * Reset the offset to force the file to be rewritten. @@ -949,7 +949,7 @@ public class ZFile implements Closeable { TreeMap<FileUseMapEntry<?>, StoredEntry> toWriteToStore = new TreeMap<>(FileUseMapEntry.COMPARE_BY_START); - for (FileUseMapEntry<StoredEntry> entry : mEntries.values()) { + for (FileUseMapEntry<StoredEntry> entry : entries.values()) { StoredEntry entryStore = entry.getStore(); assert entryStore != null; if (entryStore.getCentralDirectoryHeader().getOffset() == -1) { @@ -960,7 +960,7 @@ public class ZFile implements Closeable { /* * Add all free entries to the set. */ - for(FileUseMapEntry<?> freeArea : mMap.getFreeAreas()) { + for(FileUseMapEntry<?> freeArea : map.getFreeAreas()) { toWriteToStore.put(freeArea, null); } @@ -983,7 +983,7 @@ public class ZFile implements Closeable { computeCentralDirectory(); computeEocd(); - hasCentralDirectory = (mDirectoryEntry != null); + hasCentralDirectory = (directoryEntry != null); notify(ext -> { ext.entriesWritten(); @@ -994,15 +994,15 @@ public class ZFile implements Closeable { throw new IOException("Extensions keep resetting the central directory. This is " + "probably a bug."); } - } while (hasCentralDirectory && mDirectoryEntry == null); + } while (hasCentralDirectory && directoryEntry == null); appendCentralDirectory(); appendEocd(); - Verify.verifyNotNull(mRaf); - mRaf.setLength(mMap.size()); + Verify.verifyNotNull(raf); + raf.setLength(map.size()); - mDirty = false; + dirty = false; notify(ext -> { ext.updated(); @@ -1012,7 +1012,7 @@ public class ZFile implements Closeable { /** * Reorganizes the zip so that there are no gaps between files bigger than - * {@link #MAX_LOCAL_EXTRA_FIELD_CONTENTS_SIZE} if {@link #mCoverEmptySpaceUsingExtraField} + * {@link #MAX_LOCAL_EXTRA_FIELD_CONTENTS_SIZE} if {@link #coverEmptySpaceUsingExtraField} * is set to {@code true}. * * <p>Essentially, this makes sure we can cover any empty space with the extra field, given @@ -1022,19 +1022,19 @@ public class ZFile implements Closeable { * @throws IOException failed to repack */ private void packIfNecessary() throws IOException { - if (!mCoverEmptySpaceUsingExtraField) { + if (!coverEmptySpaceUsingExtraField) { return; } SortedSet<FileUseMapEntry<StoredEntry>> entriesByLocation = new TreeSet<>(FileUseMapEntry.COMPARE_BY_START); - entriesByLocation.addAll(mEntries.values()); + entriesByLocation.addAll(entries.values()); for (FileUseMapEntry<StoredEntry> entry : entriesByLocation) { StoredEntry storedEntry = entry.getStore(); assert storedEntry != null; - FileUseMapEntry<?> before = mMap.before(entry); + FileUseMapEntry<?> before = map.before(entry); if (before == null || !before.isFree()) { continue; } @@ -1063,17 +1063,17 @@ public class ZFile implements Closeable { private void reAdd(@Nonnull StoredEntry entry, @Nonnull PositionHint positionHint) throws IOException { String name = entry.getCentralDirectoryHeader().getName(); - FileUseMapEntry<StoredEntry> mapEntry = mEntries.get(name); + FileUseMapEntry<StoredEntry> mapEntry = entries.get(name); Preconditions.checkNotNull(mapEntry); Preconditions.checkState(mapEntry.getStore() == entry); entry.loadSourceIntoMemory(); - mMap.remove(mapEntry); - mEntries.remove(name); + map.remove(mapEntry); + entries.remove(name); FileUseMapEntry<StoredEntry> positioned = positionInFile(entry, positionHint); - mEntries.put(name, positioned); - mDirty = true; + entries.put(name, positioned); + dirty = true; } /** @@ -1085,7 +1085,7 @@ public class ZFile implements Closeable { * @throws IOException failed to load the entry into memory */ void localHeaderChanged(@Nonnull StoredEntry entry, boolean resized) throws IOException { - mDirty = true; + dirty = true; if (resized) { reAdd(entry, PositionHint.ANYWHERE); @@ -1096,7 +1096,7 @@ public class ZFile implements Closeable { * Invoked when the central directory has changed and needs to be rewritten. */ void centralDirectoryChanged() { - mDirty = true; + dirty = true; deleteDirectoryAndEocd(); } @@ -1105,7 +1105,7 @@ public class ZFile implements Closeable { */ @Override public void close() throws IOException { - // We need to make sure to release mRaf, otherwise we end up locking the file on + // We need to make sure to release raf, otherwise we end up locking the file on // Windows. Use try-with-resources to handle exception suppressing. try (Closeable ignored = this::innerClose) { update(); @@ -1122,14 +1122,14 @@ public class ZFile implements Closeable { * as well as allowing the zip file to be truncated if files have been removed. */ private void deleteDirectoryAndEocd() { - if (mDirectoryEntry != null) { - mMap.remove(mDirectoryEntry); - mDirectoryEntry = null; + if (directoryEntry != null) { + map.remove(directoryEntry); + directoryEntry = null; } - if (mEocdEntry != null) { - mMap.remove(mEocdEntry); - mEocdEntry = null; + if (eocdEntry != null) { + map.remove(eocdEntry); + eocdEntry = null; } } @@ -1146,8 +1146,8 @@ public class ZFile implements Closeable { Preconditions.checkArgument(entry.getDataDescriptorType() == DataDescriptorType. NO_DATA_DESCRIPTOR, "Cannot write entries with a data " + "descriptor."); - Preconditions.checkNotNull(mRaf, "mRaf == null"); - Preconditions.checkState(mState == ZipFileState.OPEN_RW, "mState != ZipFileState.OPEN_RW"); + Preconditions.checkNotNull(raf, "raf == null"); + Preconditions.checkState(state == ZipFileState.OPEN_RW, "state != ZipFileState.OPEN_RW"); /* * Place the cursor and write the local header. @@ -1183,19 +1183,19 @@ public class ZFile implements Closeable { /** * Computes the central directory. The central directory must not have been computed yet. When - * this method finishes, the central directory has been computed {@link #mDirectoryEntry}, - * unless the directory is empty in which case {@link #mDirectoryEntry} + * this method finishes, the central directory has been computed {@link #directoryEntry}, + * unless the directory is empty in which case {@link #directoryEntry} * is left as {@code null}. Nothing is written to disk as a result of this method's invocation. * * @throws IOException failed to append the central directory */ private void computeCentralDirectory() throws IOException { - Preconditions.checkState(mState == ZipFileState.OPEN_RW, "mState != ZipFileState.OPEN_RW"); - Preconditions.checkNotNull(mRaf, "mRaf == null"); - Preconditions.checkState(mDirectoryEntry == null, "mDirectoryEntry == null"); + Preconditions.checkState(state == ZipFileState.OPEN_RW, "state != ZipFileState.OPEN_RW"); + Preconditions.checkNotNull(raf, "raf == null"); + Preconditions.checkState(directoryEntry == null, "directoryEntry == null"); Set<StoredEntry> newStored = Sets.newHashSet(); - for (FileUseMapEntry<StoredEntry> mapEntry : mEntries.values()) { + for (FileUseMapEntry<StoredEntry> mapEntry : entries.values()) { newStored.add(mapEntry.getStore()); } @@ -1203,47 +1203,47 @@ public class ZFile implements Closeable { * Make sure we truncate the map before computing the central directory's location since * the central directory is the last part of the file. */ - mMap.truncate(); + map.truncate(); CentralDirectory newDirectory = CentralDirectory.makeFromEntries(newStored, this); byte[] newDirectoryBytes = newDirectory.toBytes(); - long directoryOffset = mMap.size() + mExtraDirectoryOffset; + long directoryOffset = map.size() + extraDirectoryOffset; - mMap.extend(directoryOffset + newDirectoryBytes.length); + map.extend(directoryOffset + newDirectoryBytes.length); if (newDirectoryBytes.length > 0) { - mDirectoryEntry = mMap.add(directoryOffset, directoryOffset + newDirectoryBytes.length, + directoryEntry = map.add(directoryOffset, directoryOffset + newDirectoryBytes.length, newDirectory); } } /** - * Writes the central directory to the end of the zip file. {@link #mDirectoryEntry} may be + * Writes the central directory to the end of the zip file. {@link #directoryEntry} may be * {@code null} only if there are no files in the archive. * * @throws IOException failed to append the central directory */ private void appendCentralDirectory() throws IOException { - Preconditions.checkState(mState == ZipFileState.OPEN_RW, "mState != ZipFileState.OPEN_RW"); - Preconditions.checkNotNull(mRaf, "mRaf == null"); + Preconditions.checkState(state == ZipFileState.OPEN_RW, "state != ZipFileState.OPEN_RW"); + Preconditions.checkNotNull(raf, "raf == null"); - if (mEntries.isEmpty()) { - Preconditions.checkState(mDirectoryEntry == null, "mDirectoryEntry != null"); + if (entries.isEmpty()) { + Preconditions.checkState(directoryEntry == null, "directoryEntry != null"); return; } - Preconditions.checkNotNull(mDirectoryEntry, "mDirectoryEntry != null"); + Preconditions.checkNotNull(directoryEntry, "directoryEntry != null"); - CentralDirectory newDirectory = mDirectoryEntry.getStore(); + CentralDirectory newDirectory = directoryEntry.getStore(); Preconditions.checkNotNull(newDirectory, "newDirectory != null"); byte[] newDirectoryBytes = newDirectory.toBytes(); - long directoryOffset = mDirectoryEntry.getStart(); + long directoryOffset = directoryEntry.getStart(); /* * It is fine to seek beyond the end of file. Seeking beyond the end of file will not extend * the file. Even if we do not have any directory data to write, the extend() call below - * will force the file to be extended leaving exactly mExtraDirectoryOffset bytes empty at + * will force the file to be extended leaving exactly extraDirectoryOffset bytes empty at * the beginning. */ directWrite(directoryOffset, newDirectoryBytes); @@ -1259,77 +1259,77 @@ public class ZFile implements Closeable { */ @Nonnull public byte[] getCentralDirectoryBytes() throws IOException { - if (mEntries.isEmpty()) { - Preconditions.checkState(mDirectoryEntry == null, "mDirectoryEntry != null"); + if (entries.isEmpty()) { + Preconditions.checkState(directoryEntry == null, "directoryEntry != null"); return new byte[0]; } - Preconditions.checkNotNull(mDirectoryEntry, "mDirectoryEntry == null"); + Preconditions.checkNotNull(directoryEntry, "directoryEntry == null"); - CentralDirectory cd = mDirectoryEntry.getStore(); + CentralDirectory cd = directoryEntry.getStore(); Preconditions.checkNotNull(cd, "cd == null"); return cd.toBytes(); } /** - * Computes the EOCD. This creates a new {@link #mEocdEntry}. The - * central directory must already be written. If {@link #mDirectoryEntry} is {@code null}, then + * Computes the EOCD. This creates a new {@link #eocdEntry}. The + * central directory must already be written. If {@link #directoryEntry} is {@code null}, then * the zip file must not have any entries. * * @throws IOException failed to write the EOCD */ private void computeEocd() throws IOException { - Preconditions.checkState(mState == ZipFileState.OPEN_RW, "mState != ZipFileState.OPEN_RW"); - Preconditions.checkNotNull(mRaf, "mRaf == null"); - if (mDirectoryEntry == null) { - Preconditions.checkState(mEntries.isEmpty(), - "mDirectoryEntry == null && !mEntries.isEmpty()"); + Preconditions.checkState(state == ZipFileState.OPEN_RW, "state != ZipFileState.OPEN_RW"); + Preconditions.checkNotNull(raf, "raf == null"); + if (directoryEntry == null) { + Preconditions.checkState(entries.isEmpty(), + "directoryEntry == null && !entries.isEmpty()"); } long dirStart; long dirSize = 0; - if (mDirectoryEntry != null) { - CentralDirectory directory = mDirectoryEntry.getStore(); + if (directoryEntry != null) { + CentralDirectory directory = directoryEntry.getStore(); assert directory != null; - dirStart = mDirectoryEntry.getStart(); - dirSize = mDirectoryEntry.getSize(); - Verify.verify(directory.getEntries().size() == mEntries.size()); + dirStart = directoryEntry.getStart(); + dirSize = directoryEntry.getSize(); + Verify.verify(directory.getEntries().size() == entries.size()); } else { /* * If we do not have a directory, then we must leave any requested offset empty. */ - dirStart = mExtraDirectoryOffset; + dirStart = extraDirectoryOffset; } - Eocd eocd = new Eocd(mEntries.size(), dirStart, dirSize); + Eocd eocd = new Eocd(entries.size(), dirStart, dirSize); byte[] eocdBytes = eocd.toBytes(); - long eocdOffset = mMap.size(); + long eocdOffset = map.size(); - mMap.extend(eocdOffset + eocdBytes.length); + map.extend(eocdOffset + eocdBytes.length); - mEocdEntry = mMap.add(eocdOffset, eocdOffset + eocdBytes.length, eocd); + eocdEntry = map.add(eocdOffset, eocdOffset + eocdBytes.length, eocd); } /** - * Writes the EOCD to the end of the zip file. This creates a new {@link #mEocdEntry}. The - * central directory must already be written. If {@link #mDirectoryEntry} is {@code null}, then + * Writes the EOCD to the end of the zip file. This creates a new {@link #eocdEntry}. The + * central directory must already be written. If {@link #directoryEntry} is {@code null}, then * the zip file must not have any entries. * * @throws IOException failed to write the EOCD */ private void appendEocd() throws IOException { - Preconditions.checkState(mState == ZipFileState.OPEN_RW, "mState != ZipFileState.OPEN_RW"); - Preconditions.checkNotNull(mRaf, "mRaf == null"); - Preconditions.checkNotNull(mEocdEntry, "mEocdEntry == null"); + Preconditions.checkState(state == ZipFileState.OPEN_RW, "state != ZipFileState.OPEN_RW"); + Preconditions.checkNotNull(raf, "raf == null"); + Preconditions.checkNotNull(eocdEntry, "eocdEntry == null"); - Eocd eocd = mEocdEntry.getStore(); + Eocd eocd = eocdEntry.getStore(); Preconditions.checkNotNull(eocd, "eocd == null"); byte[] eocdBytes = eocd.toBytes(); - long eocdOffset = mEocdEntry.getStart(); + long eocdOffset = eocdEntry.getStart(); directWrite(eocdOffset, eocdBytes); } @@ -1343,9 +1343,9 @@ public class ZFile implements Closeable { */ @Nonnull public byte[] getEocdBytes() throws IOException { - Preconditions.checkNotNull(mEocdEntry, "mEocdEntry == null"); + Preconditions.checkNotNull(eocdEntry, "eocdEntry == null"); - Eocd eocd = mEocdEntry.getStore(); + Eocd eocd = eocdEntry.getStore(); Preconditions.checkNotNull(eocd, "eocd == null"); return eocd.toBytes(); } @@ -1356,20 +1356,20 @@ public class ZFile implements Closeable { * @throws IOException failed to close the file */ private void innerClose() throws IOException { - if (mState == ZipFileState.CLOSED) { + if (state == ZipFileState.CLOSED) { return; } - Verify.verifyNotNull(mRaf, "mRaf == null"); + Verify.verifyNotNull(raf, "raf == null"); - mRaf.close(); - mRaf = null; - mState = ZipFileState.CLOSED; - if (mClosedControl == null) { - mClosedControl = new CachedFileContents<>(mFile); + raf.close(); + raf = null; + state = ZipFileState.CLOSED; + if (closedControl == null) { + closedControl = new CachedFileContents<>(file); } - mClosedControl.closed(null); + closedControl.closed(null); } /** @@ -1380,28 +1380,28 @@ public class ZFile implements Closeable { * @throws IOException failed to open the file */ public void openReadOnly() throws IOException { - if (mState != ZipFileState.CLOSED) { + if (state != ZipFileState.CLOSED) { return; } - mState = ZipFileState.OPEN_RO; - mRaf = new RandomAccessFile(mFile, "r"); + state = ZipFileState.OPEN_RO; + raf = new RandomAccessFile(file, "r"); } /** * Opens (or reopens) the zip file as read-write. This method will ensure that - * {@link #mRaf} is not null and open for writing. + * {@link #raf} is not null and open for writing. * * @throws IOException failed to open the file, failed to close it or the file was closed and * has been modified outside the control of this object */ private void reopenRw() throws IOException { - if (mState == ZipFileState.OPEN_RW) { + if (state == ZipFileState.OPEN_RW) { return; } boolean wasClosed; - if (mState == ZipFileState.OPEN_RO) { + if (state == ZipFileState.OPEN_RO) { /* * ReadAccessFile does not have a way to reopen as RW so we have to close it and * open it again. @@ -1412,16 +1412,16 @@ public class ZFile implements Closeable { wasClosed = true; } - Verify.verify(mState == ZipFileState.CLOSED, "mState != ZpiFileState.CLOSED"); - Verify.verify(mRaf == null, "mRaf != null"); + Verify.verify(state == ZipFileState.CLOSED, "state != ZpiFileState.CLOSED"); + Verify.verify(raf == null, "raf != null"); - if (mClosedControl != null && !mClosedControl.isValid()) { - throw new IOException("File '" + mFile.getAbsolutePath() + "' has been modified " + if (closedControl != null && !closedControl.isValid()) { + throw new IOException("File '" + file.getAbsolutePath() + "' has been modified " + "by an external application."); } - mRaf = new RandomAccessFile(mFile, "rw"); - mState = ZipFileState.OPEN_RW; + raf = new RandomAccessFile(file, "rw"); + state = ZipFileState.OPEN_RW; if (wasClosed) { notify(ZFileExtension::open); @@ -1457,7 +1457,7 @@ public class ZFile implements Closeable { @Nonnull InputStream stream, boolean mayCompress) throws IOException { - CloseableByteSource source = mTracker.fromStream(stream); + CloseableByteSource source = tracker.fromStream(stream); long crc32 = source.hash(Hashing.crc32()).padToLong(); boolean encodeWithUtf8 = !EncodeUtils.canAsciiEncode(name); @@ -1505,7 +1505,7 @@ public class ZFile implements Closeable { @Nonnull CentralDirectoryHeader newFileData) throws IOException { if (mayCompress) { - ListenableFuture<CompressionResult> result = mCompressor.compress(source); + ListenableFuture<CompressionResult> result = compressor.compress(source); Futures.addCallback(result, new FutureCallback<CompressionResult>() { @Override public void onSuccess(CompressionResult result) { @@ -1560,25 +1560,25 @@ public class ZFile implements Closeable { /** * Adds a {@link StoredEntry} to the zip. The entry is not immediately added to - * {@link #mEntries} because data may not yet be available. Instead, it is placed under - * {@link #mUncompressedEntries} and later moved to {@link #processAllReadyEntries()} when + * {@link #entries} because data may not yet be available. Instead, it is placed under + * {@link #uncompressedEntries} and later moved to {@link #processAllReadyEntries()} when * done. * * <p>This method invokes {@link #processAllReadyEntries()} to move the entry if it has already * been computed so, if there is no delay in compression, and no more files are in waiting - * queue, then the entry is added to {@link #mEntries} immediately. + * queue, then the entry is added to {@link #entries} immediately. * * @param newEntry the entry to add * @throws IOException failed to process this entry (or a previous one whose future only * completed now) */ private void add(@Nonnull final StoredEntry newEntry) throws IOException { - mUncompressedEntries.add(newEntry); + uncompressedEntries.add(newEntry); processAllReadyEntries(); } /** - * Moves all ready entries from {@link #mUncompressedEntries} to {@link #mEntries}. It will + * Moves all ready entries from {@link #uncompressedEntries} to {@link #entries}. It will * stop as soon as entry whose future has not been completed is found. * * @throws IOException the exception reported in the future computation, if any, or failed @@ -1588,15 +1588,15 @@ public class ZFile implements Closeable { /* * Many things can happen during addToEntries(). Because addToEntries() fires * notifications to extensions, other files can be added, removed, etc. Ee are *not* - * guaranteed that new stuff does not get into mUncompressedEntries: add() will still work + * guaranteed that new stuff does not get into uncompressedEntries: add() will still work * and will add new entries in there. * * However -- important -- processReadyEntries() may be invoked during addToEntries() * because of the extension mechanism. This means that stuff *can* be removed from - * mUncompressedEntries and moved to mEntries during addToEntries(). + * uncompressedEntries and moved to entries during addToEntries(). */ - while (!mUncompressedEntries.isEmpty()) { - StoredEntry next = mUncompressedEntries.get(0); + while (!uncompressedEntries.isEmpty()) { + StoredEntry next = uncompressedEntries.get(0); CentralDirectoryHeader cdh = next.getCentralDirectoryHeader(); Future<CentralDirectoryHeaderCompressInfo> compressionInfo = cdh.getCompressionInfo(); if (!compressionInfo.isDone()) { @@ -1606,7 +1606,7 @@ public class ZFile implements Closeable { return; } - mUncompressedEntries.remove(0); + uncompressedEntries.remove(0); try { compressionInfo.get(); @@ -1622,19 +1622,19 @@ public class ZFile implements Closeable { } /** - * Waits until {@link #mUncompressedEntries} is empty. + * Waits until {@link #uncompressedEntries} is empty. * * @throws IOException the exception reported in the future computation, if any, or failed * to add a file to the archive */ private void processAllReadyEntriesWithWait() throws IOException { processAllReadyEntries(); - while (!mUncompressedEntries.isEmpty()) { + while (!uncompressedEntries.isEmpty()) { /* * Wait for the first future to complete and then try again. Keep looping until we're * done. */ - StoredEntry first = mUncompressedEntries.get(0); + StoredEntry first = uncompressedEntries.get(0); CentralDirectoryHeader cdh = first.getCentralDirectoryHeader(); cdh.getCompressionInfoWithWait(); @@ -1643,8 +1643,8 @@ public class ZFile implements Closeable { } /** - * Adds a new file to {@link #mEntries}. This is actually added to the zip and its space - * allocated in the {@link #mMap}. + * Adds a new file to {@link #entries}. This is actually added to the zip and its space + * allocated in the {@link #map}. * * @param newEntry the new entry to add * @throws IOException failed to add the file @@ -1659,7 +1659,7 @@ public class ZFile implements Closeable { * StoredEntry.delete() will call {@link ZFile#delete(StoredEntry, boolean)} to perform * data structure cleanup. */ - FileUseMapEntry<StoredEntry> toReplace = mEntries.get( + FileUseMapEntry<StoredEntry> toReplace = entries.get( newEntry.getCentralDirectoryHeader().getName()); final StoredEntry replaceStore; if (toReplace != null) { @@ -1672,9 +1672,9 @@ public class ZFile implements Closeable { FileUseMapEntry<StoredEntry> fileUseMapEntry = positionInFile(newEntry, PositionHint.ANYWHERE); - mEntries.put(newEntry.getCentralDirectoryHeader().getName(), fileUseMapEntry); + entries.put(newEntry.getCentralDirectoryHeader().getName(), fileUseMapEntry); - mDirty = true; + dirty = true; notify(ext -> ext.added(newEntry, replaceStore)); } @@ -1716,13 +1716,13 @@ public class ZFile implements Closeable { throw new AssertionError(); } - long newOffset = mMap.locateFree(size, localHeaderSize, alignment, algorithm); + long newOffset = map.locateFree(size, localHeaderSize, alignment, algorithm); long newEnd = newOffset + entry.getInFileSize(); - if (newEnd > mMap.size()) { - mMap.extend(newEnd); + if (newEnd > map.size()) { + map.extend(newEnd); } - return mMap.add(newOffset, newEnd, entry); + return map.add(newOffset, newEnd, entry); } /** @@ -1741,7 +1741,7 @@ public class ZFile implements Closeable { if (isCompressed) { return AlignmentRule.NO_ALIGNMENT; } else { - return mAlignmentRule.alignment(cdh.getName()); + return alignmentRule.alignment(cdh.getName()); } } @@ -1768,7 +1768,7 @@ public class ZFile implements Closeable { boolean replaceCurrent = true; String path = fromEntry.getCentralDirectoryHeader().getName(); - FileUseMapEntry<StoredEntry> currentEntry = mEntries.get(path); + FileUseMapEntry<StoredEntry> currentEntry = entries.get(path); if (currentEntry != null) { long fromSize = fromEntry.getCentralDirectoryHeader().getUncompressedSize(); @@ -1826,7 +1826,7 @@ public class ZFile implements Closeable { * Build the new source and wrap it around an inflater source if data came from * a compressed source. */ - CloseableByteSource rawContents = mTracker.fromSource(fromSource.getRawByteSource()); + CloseableByteSource rawContents = tracker.fromSource(fromSource.getRawByteSource()); CloseableByteSource processedContents; if (fromCompressInfo.getMethod() == CompressionMethod.DEFLATE) { //noinspection IOResourceOpenedButNotSafelyClosed @@ -1852,7 +1852,7 @@ public class ZFile implements Closeable { * or {@link #close()} are invoked. */ public void touch() { - mDirty = true; + dirty = true; } /** @@ -1900,7 +1900,7 @@ public class ZFile implements Closeable { */ boolean realign(@Nonnull StoredEntry entry) throws IOException { FileUseMapEntry<StoredEntry> mapEntry = - mEntries.get(entry.getCentralDirectoryHeader().getName()); + entries.get(entry.getCentralDirectoryHeader().getName()); Verify.verify(entry == mapEntry.getStore()); long currentDataOffset = mapEntry.getStart() + entry.getLocalHeaderSize(); @@ -1918,21 +1918,21 @@ public class ZFile implements Closeable { * File is not aligned but it is not written. We do not really need to do much other * than find another place in the map. */ - mMap.remove(mapEntry); + map.remove(mapEntry); long newStart = - mMap.locateFree( + map.locateFree( mapEntry.getSize(), entry.getLocalHeaderSize(), expectedAlignment, FileUseMap.PositionAlgorithm.BEST_FIT); - mapEntry = mMap.add(newStart, newStart + entry.getInFileSize(), entry); - mEntries.put(entry.getCentralDirectoryHeader().getName(), mapEntry); + mapEntry = map.add(newStart, newStart + entry.getInFileSize(), entry); + entries.put(entry.getCentralDirectoryHeader().getName(), mapEntry); /* * Just for safety. We're modifying the in-memory structures but the file should * already be marked as dirty. */ - Verify.verify(mDirty); + Verify.verify(dirty); return false; @@ -1964,7 +1964,7 @@ public class ZFile implements Closeable { clonedCdh.setOffset(-1); clonedCdh.resetDeferredCrc(); - CloseableByteSource rawContents = mTracker.fromSource(source.getRawByteSource()); + CloseableByteSource rawContents = tracker.fromSource(source.getRawByteSource()); CloseableByteSource processedContents; if (compressInfo.getMethod() == CompressionMethod.DEFLATE) { @@ -1991,7 +1991,7 @@ public class ZFile implements Closeable { * @param extension the listener to add */ public void addZFileExtension(@Nonnull ZFileExtension extension) { - mExtensions.add(extension); + extensions.add(extension); } /** @@ -2000,7 +2000,7 @@ public class ZFile implements Closeable { * @param extension the listener to remove */ public void removeZFileExtension(@Nonnull ZFileExtension extension) { - mExtensions.remove(extension); + extensions.remove(extension); } /** @@ -2012,23 +2012,23 @@ public class ZFile implements Closeable { */ private void notify(@Nonnull IOExceptionFunction<ZFileExtension, IOExceptionRunnable> function) throws IOException { - for (ZFileExtension fl : Lists.newArrayList(mExtensions)) { + for (ZFileExtension fl : Lists.newArrayList(extensions)) { IOExceptionRunnable r = function.apply(fl); if (r != null) { - mToRun.add(r); + toRun.add(r); } } - if (!mIsNotifying) { - mIsNotifying = true; + if (!isNotifying) { + isNotifying = true; try { - while (!mToRun.isEmpty()) { - IOExceptionRunnable r = mToRun.remove(0); + while (!toRun.isEmpty()) { + IOExceptionRunnable r = toRun.remove(0); r.run(); } } finally { - mIsNotifying = false; + isNotifying = false; } } } @@ -2058,10 +2058,10 @@ public class ZFile implements Closeable { Preconditions.checkArgument(start + count <= data.length, "start + count > data.length"); reopenRw(); - assert mRaf != null; + assert raf != null; - mRaf.seek(offset); - mRaf.write(data, start, count); + raf.seek(offset); + raf.write(data, start, count); } /** @@ -2084,11 +2084,11 @@ public class ZFile implements Closeable { /* * Only force a reopen if the file is closed. */ - if (mRaf == null) { + if (raf == null) { reopenRw(); - assert mRaf != null; + assert raf != null; } - return mRaf.length(); + return raf.length(); } /** @@ -2132,13 +2132,13 @@ public class ZFile implements Closeable { /* * Only force a reopen if the file is closed. */ - if (mRaf == null) { + if (raf == null) { reopenRw(); - assert mRaf != null; + assert raf != null; } - mRaf.seek(offset); - return mRaf.getChannel().read(dest); + raf.seek(offset); + return raf.getChannel().read(dest); } /** @@ -2182,12 +2182,12 @@ public class ZFile implements Closeable { /* * Only force a reopen if the file is closed. */ - if (mRaf == null) { + if (raf == null) { reopenRw(); - assert mRaf != null; + assert raf != null; } - FileChannel fileChannel = mRaf.getChannel(); + FileChannel fileChannel = raf.getChannel(); while (dest.hasRemaining()) { fileChannel.position(offset); int chunkSize = fileChannel.read(dest); @@ -2267,22 +2267,22 @@ public class ZFile implements Closeable { * includes any extra offset for the central directory */ public long getCentralDirectoryOffset() { - if (mDirectoryEntry != null) { - return mDirectoryEntry.getStart(); + if (directoryEntry != null) { + return directoryEntry.getStart(); } /* * If there are no entries, the central directory is written at the start of the file. */ - if (mEntries.isEmpty()) { - return mExtraDirectoryOffset; + if (entries.isEmpty()) { + return extraDirectoryOffset; } /* * The Central Directory is written after all entries. This will be at the end of the file * if the */ - return mMap.usedSize() + mExtraDirectoryOffset; + return map.usedSize() + extraDirectoryOffset; } /** @@ -2293,11 +2293,11 @@ public class ZFile implements Closeable { * been computed */ public long getCentralDirectorySize() { - if (mDirectoryEntry != null) { - return mDirectoryEntry.getSize(); + if (directoryEntry != null) { + return directoryEntry.getSize(); } - if (mEntries.isEmpty()) { + if (entries.isEmpty()) { return 0; } @@ -2310,11 +2310,11 @@ public class ZFile implements Closeable { * @return the offset of the EOCD or {@code -1} if none exists yet */ public long getEocdOffset() { - if (mEocdEntry == null) { + if (eocdEntry == null) { return -1; } - return mEocdEntry.getStart(); + return eocdEntry.getStart(); } /** @@ -2323,11 +2323,11 @@ public class ZFile implements Closeable { * @return the size of the EOCD of {@code -1} it none exists yet */ public long getEocdSize() { - if (mEocdEntry == null) { + if (eocdEntry == null) { return -1; } - return mEocdEntry.getSize(); + return eocdEntry.getSize(); } /** @@ -2340,10 +2340,10 @@ public class ZFile implements Closeable { public void setExtraDirectoryOffset(long offset) { Preconditions.checkArgument(offset >= 0, "offset < 0"); - if (mExtraDirectoryOffset != offset) { - mExtraDirectoryOffset = offset; + if (extraDirectoryOffset != offset) { + extraDirectoryOffset = offset; deleteDirectoryAndEocd(); - mDirty = true; + dirty = true; } } @@ -2353,7 +2353,7 @@ public class ZFile implements Closeable { * @return the offset or {@code 0} if no offset is set */ public long getExtraDirectoryOffset() { - return mExtraDirectoryOffset; + return extraDirectoryOffset; } /** @@ -2362,7 +2362,7 @@ public class ZFile implements Closeable { * @return are the timestamps being ignored? */ public boolean areTimestampsIgnored() { - return mNoTimestamps; + return noTimestamps; } /** @@ -2379,27 +2379,27 @@ public class ZFile implements Closeable { processAllReadyEntriesWithWait(); - Verify.verify(mUncompressedEntries.isEmpty()); + Verify.verify(uncompressedEntries.isEmpty()); SortedSet<StoredEntry> sortedEntries = Sets.newTreeSet(StoredEntry.COMPARE_BY_NAME); - for (FileUseMapEntry<StoredEntry> fmEntry : mEntries.values()) { + for (FileUseMapEntry<StoredEntry> fmEntry : entries.values()) { StoredEntry entry = fmEntry.getStore(); Preconditions.checkNotNull(entry); sortedEntries.add(entry); entry.loadSourceIntoMemory(); - mMap.remove(fmEntry); + map.remove(fmEntry); } - mEntries.clear(); + entries.clear(); for (StoredEntry entry : sortedEntries) { String name = entry.getCentralDirectoryHeader().getName(); FileUseMapEntry<StoredEntry> positioned = positionInFile(entry, PositionHint.LOWEST_OFFSET); - mEntries.put(name, positioned); + entries.put(name, positioned); } - mDirty = true; + dirty = true; } /** @@ -2410,7 +2410,7 @@ public class ZFile implements Closeable { */ @Nonnull public File getFile() { - return mFile; + return file; } /** @@ -2419,7 +2419,7 @@ public class ZFile implements Closeable { * @return should it be skipped? */ boolean getSkipDataDescriptorVerification() { - return mSkipDataDescriptorVerification; + return skipDataDescriptorVerification; } /** @@ -2428,7 +2428,7 @@ public class ZFile implements Closeable { * @return should it be skipped? */ boolean getSkipVersionToExtractValidation() { - return mSkipVersionToExtractValidation; + return skipVersionToExtractValidation; } /** diff --git a/src/main/java/com/android/apkzlib/zip/ZFileOptions.java b/src/main/java/com/android/apkzlib/zip/ZFileOptions.java index 39da52a..49e57e6 100644 --- a/src/main/java/com/android/apkzlib/zip/ZFileOptions.java +++ b/src/main/java/com/android/apkzlib/zip/ZFileOptions.java @@ -30,57 +30,57 @@ public class ZFileOptions { * The byte tracker. */ @Nonnull - private ByteTracker mTracker; + private ByteTracker tracker; /** * The compressor to use. */ @Nonnull - private Compressor mCompressor; + private Compressor compressor; /** * Should timestamps be zeroed? */ - private boolean mNoTimestamps; + private boolean noTimestamps; /** * The alignment rule to use. */ @Nonnull - private AlignmentRule mAlignmentRule; + private AlignmentRule alignmentRule; /** * Should the extra field be used to cover empty space? */ - private boolean mCoverEmptySpaceUsingExtraField; + private boolean coverEmptySpaceUsingExtraField; /** * Should files be automatically sorted before update? */ - private boolean mAutoSortFiles; + private boolean autoSortFiles; /** * Should validation of the data descriptors of entries be skipped? See * {@link #getSkipDataDescriptorValidation()} */ - private boolean mSkipDataDescriptionValidation; + private boolean skipDataDescriptionValidation; /** * Should validation of minimum zip version to extract be performed? */ - private boolean mSkipZipVersionToExtractValidation; + private boolean skipZipVersionToExtractValidation; /** * Creates a new options object. All options are set to their defaults. */ public ZFileOptions() { - mTracker = new ByteTracker(); - mCompressor = + tracker = new ByteTracker(); + compressor = new DeflateExecutionCompressor( Runnable::run, - mTracker, + tracker, Deflater.DEFAULT_COMPRESSION); - mAlignmentRule = AlignmentRules.compose(); + alignmentRule = AlignmentRules.compose(); } /** @@ -90,7 +90,7 @@ public class ZFileOptions { */ @Nonnull public ByteTracker getTracker() { - return mTracker; + return tracker; } /** @@ -100,7 +100,7 @@ public class ZFileOptions { */ @Nonnull public Compressor getCompressor() { - return mCompressor; + return compressor; } /** @@ -109,7 +109,7 @@ public class ZFileOptions { * @param compressor the compressor */ public void setCompressor(@Nonnull Compressor compressor) { - mCompressor = compressor; + this.compressor = compressor; } /** @@ -118,7 +118,7 @@ public class ZFileOptions { * @return should timestamps be zeroed? */ public boolean getNoTimestamps() { - return mNoTimestamps; + return noTimestamps; } /** @@ -127,7 +127,7 @@ public class ZFileOptions { * @param noTimestamps should timestamps be zeroed? */ public void setNoTimestamps(boolean noTimestamps) { - mNoTimestamps = noTimestamps; + this.noTimestamps = noTimestamps; } /** @@ -137,7 +137,7 @@ public class ZFileOptions { */ @Nonnull public AlignmentRule getAlignmentRule() { - return mAlignmentRule; + return alignmentRule; } /** @@ -146,7 +146,7 @@ public class ZFileOptions { * @param alignmentRule the alignment rule */ public void setAlignmentRule(@Nonnull AlignmentRule alignmentRule) { - mAlignmentRule = alignmentRule; + this.alignmentRule = alignmentRule; } /** @@ -156,7 +156,7 @@ public class ZFileOptions { * @return should the extra field be used to cover empty spaces? */ public boolean getCoverEmptySpaceUsingExtraField() { - return mCoverEmptySpaceUsingExtraField; + return coverEmptySpaceUsingExtraField; } /** @@ -166,7 +166,7 @@ public class ZFileOptions { * @param coverEmptySpaceUsingExtraField should the extra field be used to cover empty spaces? */ public void setCoverEmptySpaceUsingExtraField(boolean coverEmptySpaceUsingExtraField) { - mCoverEmptySpaceUsingExtraField = coverEmptySpaceUsingExtraField; + this.coverEmptySpaceUsingExtraField = coverEmptySpaceUsingExtraField; } /** @@ -176,7 +176,7 @@ public class ZFileOptions { * @return should the file be automatically sorted? */ public boolean getAutoSortFiles() { - return mAutoSortFiles; + return autoSortFiles; } /** @@ -186,7 +186,7 @@ public class ZFileOptions { * @param autoSortFiles should the file be automatically sorted? */ public void setAutoSortFiles(boolean autoSortFiles) { - mAutoSortFiles = autoSortFiles; + this.autoSortFiles = autoSortFiles; } /** @@ -198,7 +198,7 @@ public class ZFileOptions { * @return should data descriptors be validated? */ public boolean getSkipDataDescriptorValidation() { - return mSkipDataDescriptionValidation; + return skipDataDescriptionValidation; } /** @@ -208,7 +208,7 @@ public class ZFileOptions { * @param skip should validation be skipped? */ public void setSkipDataDescriptionValidation(boolean skip) { - mSkipDataDescriptionValidation = skip; + skipDataDescriptionValidation = skip; } /** @@ -218,7 +218,7 @@ public class ZFileOptions { * @return should the "zip version to extract" field be ignored? */ public boolean getSkipZipVersionToExtractValidation() { - return mSkipZipVersionToExtractValidation; + return skipZipVersionToExtractValidation; } /** @@ -228,6 +228,6 @@ public class ZFileOptions { * @param skip should the "zip version to extract" field be ignored? */ public void setSkipZipVersionToExtractValidation(boolean skip) { - mSkipZipVersionToExtractValidation = skip; + skipZipVersionToExtractValidation = skip; } } diff --git a/src/main/java/com/android/apkzlib/zip/ZipField.java b/src/main/java/com/android/apkzlib/zip/ZipField.java index db6bb0b..135c720 100644 --- a/src/main/java/com/android/apkzlib/zip/ZipField.java +++ b/src/main/java/com/android/apkzlib/zip/ZipField.java @@ -58,29 +58,29 @@ abstract class ZipField { * Field name. Used for providing (more) useful error messages. */ @Nonnull - private final String mName; + private final String name; /** * Offset of the file in the record. */ - protected final int mOffset; + protected final int offset; /** * Size of the field. Only 2 or 4 allowed. */ - private final int mSize; + private final int size; /** * If a fixed value exists for the field, then this attribute will contain that value. */ @Nullable - private final Long mExpected; + private final Long expected; /** * All invariants that this field must verify. */ @Nonnull - private Set<ZipFieldInvariant> mInvariants; + private Set<ZipFieldInvariant> invariants; /** * Creates a new field that does not contain a fixed value. @@ -94,11 +94,11 @@ abstract class ZipField { Preconditions.checkArgument(offset >= 0, "offset >= 0"); Preconditions.checkArgument(size == 2 || size == 4, "size != 2 && size != 4"); - mName = name; - mOffset = offset; - mSize = size; - mExpected = null; - mInvariants = Sets.newHashSet(invariants); + this.name = name; + this.offset = offset; + this.size = size; + expected = null; + this.invariants = Sets.newHashSet(invariants); } /** @@ -113,11 +113,11 @@ abstract class ZipField { Preconditions.checkArgument(offset >= 0, "offset >= 0"); Preconditions.checkArgument(size == 2 || size == 4, "size != 2 && size != 4"); - mName = name; - mOffset = offset; - mSize = size; - mExpected = expected; - mInvariants = Sets.newHashSet(); + this.name = name; + this.offset = offset; + this.size = size; + this.expected = expected; + invariants = Sets.newHashSet(); } /** @@ -128,9 +128,9 @@ abstract class ZipField { * @throws IOException the invariants are not verified */ private void checkVerifiesInvariants(long value) throws IOException { - for (ZipFieldInvariant invariant : mInvariants) { + for (ZipFieldInvariant invariant : invariants) { if (!invariant.isValid(value)) { - throw new IOException("Value " + value + " of field " + mName + " is invalid " + throw new IOException("Value " + value + " of field " + name + " is invalid " + "(fails '" + invariant.getName() + "')."); } } @@ -144,12 +144,12 @@ abstract class ZipField { * @throws IOException failed to advance the buffer */ void skip(@Nonnull ByteBuffer bytes) throws IOException { - if (bytes.remaining() < mSize) { - throw new IOException("Cannot skip field " + mName + " because only " + if (bytes.remaining() < size) { + throw new IOException("Cannot skip field " + name + " because only " + bytes.remaining() + " remain in the buffer."); } - bytes.position(bytes.position() + mSize); + bytes.position(bytes.position() + size); } /** @@ -161,15 +161,15 @@ abstract class ZipField { * @throws IOException failed to read the field */ long read(@Nonnull ByteBuffer bytes) throws IOException { - if (bytes.remaining() < mSize) { - throw new IOException("Cannot skip field " + mName + " because only " + if (bytes.remaining() < size) { + throw new IOException("Cannot skip field " + name + " because only " + bytes.remaining() + " remain in the buffer."); } bytes.order(ByteOrder.LITTLE_ENDIAN); long r; - if (mSize == 2) { + if (size == 2) { r = LittleEndianUtils.readUnsigned2Le(bytes); } else { r = LittleEndianUtils.readUnsigned4Le(bytes); @@ -188,8 +188,8 @@ abstract class ZipField { * @throws IOException failed to read the field or the field does not have the expected value */ void verify(@Nonnull ByteBuffer bytes) throws IOException { - Preconditions.checkState(mExpected != null, "mExpected == null"); - verify(bytes, mExpected); + Preconditions.checkState(expected != null, "expected == null"); + verify(bytes, expected); } /** @@ -205,7 +205,7 @@ abstract class ZipField { checkVerifiesInvariants(expected); long r = read(bytes); if (r != expected) { - throw new IOException("Incorrect value for field '" + mName + "': value is " + + throw new IOException("Incorrect value for field '" + name + "': value is " + r + " but " + expected + " expected."); } } @@ -223,11 +223,11 @@ abstract class ZipField { Preconditions.checkArgument(value >= 0, "value (%s) < 0", value); - if (mSize == 2) { + if (size == 2) { Preconditions.checkArgument(value <= 0x0000ffff, "value (%s) > 0x0000ffff", value); LittleEndianUtils.writeUnsigned2Le(output, Ints.checkedCast(value)); } else { - Verify.verify(mSize == 4); + Verify.verify(size == 4); Preconditions.checkArgument(value <= 0x00000000ffffffffL, "value (%s) > 0x00000000ffffffffL", value); LittleEndianUtils.writeUnsigned4Le(output, value); @@ -242,8 +242,8 @@ abstract class ZipField { * @throws IOException failed to write the value in the stream */ void write(@Nonnull ByteBuffer output) throws IOException { - Preconditions.checkState(mExpected != null, "mExpected == null"); - write(output, mExpected); + Preconditions.checkState(expected != null, "expected == null"); + write(output, expected); } /** @@ -252,7 +252,7 @@ abstract class ZipField { * @return the start offset */ int offset() { - return mOffset; + return offset; } /** @@ -262,7 +262,7 @@ abstract class ZipField { * @return the end offset */ int endOffset() { - return mOffset + mSize; + return offset + size; } /** diff --git a/src/main/java/com/android/apkzlib/zip/ZipFieldInvariantMaxValue.java b/src/main/java/com/android/apkzlib/zip/ZipFieldInvariantMaxValue.java index 0b2203e..5905e1a 100644 --- a/src/main/java/com/android/apkzlib/zip/ZipFieldInvariantMaxValue.java +++ b/src/main/java/com/android/apkzlib/zip/ZipFieldInvariantMaxValue.java @@ -24,7 +24,7 @@ class ZipFieldInvariantMaxValue implements ZipFieldInvariant { /** * The maximum value allowed. */ - private long mMax; + private long max; /** * Creates a new invariant. @@ -32,16 +32,16 @@ class ZipFieldInvariantMaxValue implements ZipFieldInvariant { * @param max the maximum value allowed for the field */ ZipFieldInvariantMaxValue(int max) { - mMax = max; + this.max = max; } @Override public boolean isValid(long value) { - return value <= mMax; + return value <= max; } @Override public String getName() { - return "Maximum value " + mMax; + return "Maximum value " + max; } } diff --git a/src/main/java/com/android/apkzlib/zip/compress/BestAndDefaultDeflateExecutorCompressor.java b/src/main/java/com/android/apkzlib/zip/compress/BestAndDefaultDeflateExecutorCompressor.java index 20ef477..8948a1c 100644 --- a/src/main/java/com/android/apkzlib/zip/compress/BestAndDefaultDeflateExecutorCompressor.java +++ b/src/main/java/com/android/apkzlib/zip/compress/BestAndDefaultDeflateExecutorCompressor.java @@ -34,19 +34,19 @@ public class BestAndDefaultDeflateExecutorCompressor extends ExecutorCompressor * Deflater using the default compression level. */ @Nonnull - private final DeflateExecutionCompressor mDefaultDeflater; + private final DeflateExecutionCompressor defaultDeflater; /** * Deflater using the best compression level. */ @Nonnull - private final DeflateExecutionCompressor mBestDeflater; + private final DeflateExecutionCompressor bestDeflater; /** * Minimum best compression size / default compression size ratio needed to pick the default * compression size. */ - private final double mMinRatio; + private final double minRatio; /** * Creates a new compressor. @@ -65,22 +65,22 @@ public class BestAndDefaultDeflateExecutorCompressor extends ExecutorCompressor Preconditions.checkArgument(minRatio >= 0.0, "minRatio < 0.0"); Preconditions.checkArgument(minRatio <= 1.0, "minRatio > 1.0"); - mDefaultDeflater = new DeflateExecutionCompressor(executor, tracker, - Deflater.DEFAULT_COMPRESSION); - mBestDeflater = new DeflateExecutionCompressor(executor, tracker, - Deflater.BEST_COMPRESSION); - mMinRatio = minRatio; + defaultDeflater = + new DeflateExecutionCompressor(executor, tracker, Deflater.DEFAULT_COMPRESSION); + bestDeflater = + new DeflateExecutionCompressor(executor, tracker, Deflater.BEST_COMPRESSION); + this.minRatio = minRatio; } @Nonnull @Override protected CompressionResult immediateCompress(@Nonnull CloseableByteSource source) throws Exception { - CompressionResult defaultResult = mDefaultDeflater.immediateCompress(source); - CompressionResult bestResult = mBestDeflater.immediateCompress(source); + CompressionResult defaultResult = defaultDeflater.immediateCompress(source); + CompressionResult bestResult = bestDeflater.immediateCompress(source); double sizeRatio = bestResult.getSize() / (double) defaultResult.getSize(); - if (sizeRatio >= mMinRatio) { + if (sizeRatio >= minRatio) { return defaultResult; } else { return bestResult; diff --git a/src/main/java/com/android/apkzlib/zip/compress/DeflateExecutionCompressor.java b/src/main/java/com/android/apkzlib/zip/compress/DeflateExecutionCompressor.java index b7e87f4..309e356 100644 --- a/src/main/java/com/android/apkzlib/zip/compress/DeflateExecutionCompressor.java +++ b/src/main/java/com/android/apkzlib/zip/compress/DeflateExecutionCompressor.java @@ -35,13 +35,13 @@ public class DeflateExecutionCompressor extends ExecutorCompressor { /** * Deflate compression level. */ - private final int mLevel; + private final int level; /** * Byte tracker to use to create byte sources. */ @Nonnull - private final ByteTracker mTracker; + private final ByteTracker tracker; /** * Creates a new compressor. @@ -50,12 +50,14 @@ public class DeflateExecutionCompressor extends ExecutorCompressor { * @param tracker the byte tracker to use to keep track of memory usage * @param level the compression level */ - public DeflateExecutionCompressor(@Nonnull Executor executor, @Nonnull ByteTracker tracker, + public DeflateExecutionCompressor( + @Nonnull Executor executor, + @Nonnull ByteTracker tracker, int level) { super(executor); - mLevel = level; - mTracker = tracker; + this.level = level; + this.tracker = tracker; } @Nonnull @@ -63,13 +65,13 @@ public class DeflateExecutionCompressor extends ExecutorCompressor { protected CompressionResult immediateCompress(@Nonnull CloseableByteSource source) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); - Deflater deflater = new Deflater(mLevel, true); + Deflater deflater = new Deflater(level, true); try (DeflaterOutputStream dos = new DeflaterOutputStream(output, deflater)) { dos.write(source.read()); } - CloseableByteSource result = mTracker.fromStream(output); + CloseableByteSource result = tracker.fromStream(output); if (result.size() >= source.size()) { return new CompressionResult(source, CompressionMethod.STORE, source.size()); } else { diff --git a/src/main/java/com/android/apkzlib/zip/compress/ExecutorCompressor.java b/src/main/java/com/android/apkzlib/zip/compress/ExecutorCompressor.java index b136558..96ad281 100644 --- a/src/main/java/com/android/apkzlib/zip/compress/ExecutorCompressor.java +++ b/src/main/java/com/android/apkzlib/zip/compress/ExecutorCompressor.java @@ -34,14 +34,14 @@ public abstract class ExecutorCompressor implements Compressor { * The executor that does the work. */ @Nonnull - private final Executor mExecutor; + private final Executor executor; /** * Compressor that delegates execution into the given executor. * @param executor the executor that will do the compress */ public ExecutorCompressor(@Nonnull Executor executor) { - mExecutor = executor; + this.executor = executor; } @Nonnull @@ -49,7 +49,7 @@ public abstract class ExecutorCompressor implements Compressor { public ListenableFuture<CompressionResult> compress( @Nonnull final CloseableByteSource source) { final SettableFuture<CompressionResult> future = SettableFuture.create(); - mExecutor.execute(() -> { + executor.execute(() -> { try { future.set(immediateCompress(source)); } catch (Exception e) { diff --git a/src/main/java/com/android/apkzlib/zip/compress/package-info.java b/src/main/java/com/android/apkzlib/zip/compress/package-info.java new file mode 100644 index 0000000..e2fcbd6 --- /dev/null +++ b/src/main/java/com/android/apkzlib/zip/compress/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Compressors to use with the {@code zip} package. + */ +package com.android.apkzlib.zip.compress;
\ No newline at end of file diff --git a/src/main/java/com/android/apkzlib/zip/utils/ByteTracker.java b/src/main/java/com/android/apkzlib/zip/utils/ByteTracker.java index 6bad5f7..88ed939 100644 --- a/src/main/java/com/android/apkzlib/zip/utils/ByteTracker.java +++ b/src/main/java/com/android/apkzlib/zip/utils/ByteTracker.java @@ -23,20 +23,24 @@ import java.io.IOException; import java.io.InputStream; import javax.annotation.Nonnull; +/** + * Keeps track of used bytes allowing gauging memory usage. + */ public class ByteTracker { /** * Number of bytes currently in use. */ - private long mBytesUsed; + private long bytesUsed; /** * Maximum number of bytes used. */ - private long mMaxBytesUsed; + private long maxBytesUsed; /** * Creates a new byte source by fully reading an input stream. + * * @param stream the input stream * @return a byte source containing the cached data from the given stream * @throws IOException failed to read the stream @@ -55,11 +59,13 @@ public class ByteTracker { /** * Creates a new byte source by snapshotting the provided stream. + * * @param stream the stream with the data * @return a byte source containing the cached data from the given stream * @throws IOException failed to read the stream */ - public CloseableDelegateByteSource fromStream(@Nonnull ByteArrayOutputStream stream) throws IOException { + public CloseableDelegateByteSource fromStream(@Nonnull ByteArrayOutputStream stream) + throws IOException { byte[] data = stream.toByteArray(); updateUsage(data.length); return new CloseableDelegateByteSource(ByteSource.wrap(data), data.length) { @@ -73,6 +79,7 @@ public class ByteTracker { /** * Creates a new byte source from another byte source. + * * @param source the byte source to copy data from * @return the tracked byte source * @throws IOException failed to read data from the byte source @@ -83,28 +90,31 @@ public class ByteTracker { /** * Updates the memory used by this tracker. + * * @param delta the number of bytes to add or remove, if negative */ private synchronized void updateUsage(long delta) { - mBytesUsed += delta; - if (mMaxBytesUsed < mBytesUsed) { - mMaxBytesUsed = mBytesUsed; + bytesUsed += delta; + if (maxBytesUsed < bytesUsed) { + maxBytesUsed = bytesUsed; } } /** * Obtains the number of bytes currently used. + * * @return the number of bytes */ public synchronized long getBytesUsed() { - return mBytesUsed; + return bytesUsed; } /** * Obtains the maximum number of bytes ever used by this tracker. + * * @return the number of bytes */ public synchronized long getMaxBytesUsed() { - return mMaxBytesUsed; + return maxBytesUsed; } } diff --git a/src/main/java/com/android/apkzlib/zip/utils/CloseableByteSource.java b/src/main/java/com/android/apkzlib/zip/utils/CloseableByteSource.java index 8638a48..1479a03 100644 --- a/src/main/java/com/android/apkzlib/zip/utils/CloseableByteSource.java +++ b/src/main/java/com/android/apkzlib/zip/utils/CloseableByteSource.java @@ -32,31 +32,32 @@ public abstract class CloseableByteSource extends ByteSource implements Closeabl /** * Has the source been closed? */ - private boolean mClosed; + private boolean closed; /** * Creates a new byte source. */ public CloseableByteSource() { - mClosed = false; + closed = false; } @Override public final synchronized void close() throws IOException { - if (mClosed) { + if (closed) { return; } try { innerClose(); } finally { - mClosed = true; + closed = true; } } /** * Closes the by source. This method is only invoked once, even if {@link #close()} is - * called multiple times + * called multiple times. + * * @throws IOException failed to close */ protected abstract void innerClose() throws IOException; diff --git a/src/main/java/com/android/apkzlib/zip/utils/CloseableDelegateByteSource.java b/src/main/java/com/android/apkzlib/zip/utils/CloseableDelegateByteSource.java index 83873a3..aebb29a 100644 --- a/src/main/java/com/android/apkzlib/zip/utils/CloseableDelegateByteSource.java +++ b/src/main/java/com/android/apkzlib/zip/utils/CloseableDelegateByteSource.java @@ -38,11 +38,11 @@ public class CloseableDelegateByteSource extends CloseableByteSource { * The byte source we delegate all operations to. {@code null} if disposed. */ @Nullable - private ByteSource mInner; + private ByteSource inner; /** - * Size of the byte source. This is the same as {@code mInner.size()} (when {@code mInner} - * is not {@code null}), but we keep it separate to avoid calling {@code mInner.size()} + * Size of the byte source. This is the same as {@code inner.size()} (when {@code inner} + * is not {@code null}), but we keep it separate to avoid calling {@code inner.size()} * because it might throw {@code IOException}. */ private final long mSize; @@ -54,7 +54,7 @@ public class CloseableDelegateByteSource extends CloseableByteSource { * @param size the size of the source */ public CloseableDelegateByteSource(@Nonnull ByteSource inner, long size) { - mInner = inner; + this.inner = inner; mSize = size; } @@ -66,11 +66,11 @@ public class CloseableDelegateByteSource extends CloseableByteSource { */ @Nonnull private synchronized ByteSource get() { - if (mInner == null) { + if (inner == null) { throw new ByteSourceDisposedException(); } - return mInner; + return inner; } /** @@ -78,11 +78,11 @@ public class CloseableDelegateByteSource extends CloseableByteSource { */ @Override protected synchronized void innerClose() throws IOException { - if (mInner == null) { + if (inner == null) { return; } - mInner = null; + inner = null; } /** diff --git a/src/main/java/com/android/apkzlib/zip/utils/LittleEndianUtils.java b/src/main/java/com/android/apkzlib/zip/utils/LittleEndianUtils.java index c0f3588..c257d39 100644 --- a/src/main/java/com/android/apkzlib/zip/utils/LittleEndianUtils.java +++ b/src/main/java/com/android/apkzlib/zip/utils/LittleEndianUtils.java @@ -73,8 +73,10 @@ public class LittleEndianUtils { Preconditions.checkNotNull(bytes, "bytes == null"); if (bytes.remaining() < 2) { - throw new EOFException("Not enough data: 2 bytes expected, " + bytes.remaining() - + " available."); + throw new EOFException( + "Not enough data: 2 bytes expected, " + + bytes.remaining() + + " available."); } byte b0 = bytes.get(); @@ -97,8 +99,10 @@ public class LittleEndianUtils { throws IOException { Preconditions.checkNotNull(output, "output == null"); Preconditions.checkArgument(value >= 0, "value (%s) < 0", value); - Preconditions.checkArgument(value <= 0x00000000ffffffffL, - "value (%s) > 0x00000000ffffffffL", value); + Preconditions.checkArgument( + value <= 0x00000000ffffffffL, + "value (%s) > 0x00000000ffffffffL", + value); output.put((byte) (value & 0xff)); output.put((byte) ((value >> 8) & 0xff)); diff --git a/src/main/java/com/android/apkzlib/zip/utils/MsDosDateTimeUtils.java b/src/main/java/com/android/apkzlib/zip/utils/MsDosDateTimeUtils.java index 62fa11e..2b9f365 100644 --- a/src/main/java/com/android/apkzlib/zip/utils/MsDosDateTimeUtils.java +++ b/src/main/java/com/android/apkzlib/zip/utils/MsDosDateTimeUtils.java @@ -33,6 +33,7 @@ public class MsDosDateTimeUtils { /** * Packs java time value into an MS-DOS time value. + * * @param time the time value * @return the MS-DOS packed time */ @@ -57,6 +58,7 @@ public class MsDosDateTimeUtils { /** * Packs the current time value into an MS-DOS time value. + * * @return the MS-DOS packed time */ public static int packCurrentTime() { @@ -65,6 +67,7 @@ public class MsDosDateTimeUtils { /** * Packs java time value into an MS-DOS date value. + * * @param time the time value * @return the MS-DOS packed date */ @@ -99,6 +102,7 @@ public class MsDosDateTimeUtils { /** * Packs the current time value into an MS-DOS date value. + * * @return the MS-DOS packed date */ public static int packCurrentDate() { diff --git a/src/main/java/com/android/apkzlib/zip/utils/RandomAccessFileUtils.java b/src/main/java/com/android/apkzlib/zip/utils/RandomAccessFileUtils.java index 73166fd..3bfb55c 100644 --- a/src/main/java/com/android/apkzlib/zip/utils/RandomAccessFileUtils.java +++ b/src/main/java/com/android/apkzlib/zip/utils/RandomAccessFileUtils.java @@ -23,12 +23,9 @@ import javax.annotation.Nonnull; /** * Utility class with utility methods for random access files. */ -public class RandomAccessFileUtils { - /** - * Utility class: no constructor. - */ - private RandomAccessFileUtils() { - } +public final class RandomAccessFileUtils { + + private RandomAccessFileUtils() {} /** * Reads from an random access file until the provided array is filled. Data is read from the @@ -36,7 +33,7 @@ public class RandomAccessFileUtils { * * @param raf the file to read data from * @param data the array that will receive the data - * @throws IOException + * @throws IOException failed to read the data */ public static void fullyRead(@Nonnull RandomAccessFile raf, @Nonnull byte[] data) throws IOException { @@ -51,8 +48,12 @@ public class RandomAccessFileUtils { } if (p < data.length) { - throw new IOException("Failed to read " + data.length + " bytes from file. Only " - + p + " bytes could be read."); + throw new IOException( + "Failed to read " + + data.length + + " bytes from file. Only " + + p + + " bytes could be read."); } } } |