diff --git a/.gitignore b/.gitignore
index 9b16e7ca24..dc2f0774d7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,4 @@ build
.gradle
*.apk
app/manifest-merger-release-report.txt
+*~*
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000000..c3b207f108
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "app/otr4j"]
+ path = app/otr4j
+ url = https://github.com/otr4j/otr4j.git
diff --git a/LICENSE b/LICENSE
index 855e555ac4..4e9382270b 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,62 +1,94 @@
-Copyright (c) 2013, Redsolution LTD.
+Copyright (c) 2015, Redsolution Inc.
All rights reserved.
-Project is distributed under "GNU General Public License, Version 3" (see assets/LICENSE-GPLv3.txt).
+Project is distributed under GNU General Public License, Version 3 (see app/src/main/assets/LICENSE-GPLv3.txt).
-Note about restrictions:
+Following files as well as translations in app/src/main/res/values* are distributed under Creative Commons Attribution Non-Commercial Share Alike license:
-Following files are distributed under "Creative Commons Attribution Non-Commercial No Derivatives":
-res/drawable*/ic_connect.png
-res/drawable*/ic_disconnect.png
-res/drawable*/ic_information.png
-res/drawable*/ic_launcher.png
-res/drawable*/ic_stat_*.png
-res/drawable*/title_logo.9.png
+app/src/main/res/drawable/about_backdrop.jpg
+app/src/main/res/drawable*/chat_background.png
+app/src/main/res/drawable/contact_shadow.jpg
+app/src/main/res/drawable*/drawer_*.jpg
+app/src/main/res/drawable*/ic_avatar_*.png
+app/src/main/res/drawable*/ic_client_*.png
+app/src/main/res/drawable*/ic_offline_shadow_24dp.png
+app/src/main/res/drawable*/ic_scroll_indicator_circle_*.png
+app/src/main/res/drawable*/ic_stat_offline.png
+app/src/main/res/drawable*/ic_stat_cnline.png
+app/src/main/res/drawable*/ic_status_*.png
+app/src/main/res/drawable*/message_*.9.png
-Following files are part of The Android Open Source Project licensed under the Apache License, Version 2.0 (the "License") (see assets/LICENSE-Apache2.txt):
-res/drawable/notify_panel_notification_icon_bg_tile.xml
-res/layout/info_preference.xml
-res/layout/preference.xml
-res/layout/progress_preference.xml
-res/drawable*/emo_im_*.png
-res/drawable*/ic_menu_*.png
+Following files are part of official icon set from Google and distributed under Creative Common Attribution 4.0 International License (CC-BY 4.0):
-The rest of graphic in res/drawable* as well as translations in res/values* are distributed under "Creative Commons Attribution Non-Commercial Share Alike".
+app/src/main/res/drawable*/ic_add_white_24dp.png
+app/src/main/res/drawable*/ic_arrow_left_white_24dp.png
+app/src/main/res/drawable*/ic_button_send_*_24dp.png
+app/src/main/res/drawable*/ic_chat_white_24dp.png
+app/src/main/res/drawable*/ic_clear_all_white_24dp.png
+app/src/main/res/drawable*/ic_clear_white_24dp.png
+app/src/main/res/drawable*/ic_exit_grey600_24dp.png
+app/src/main/res/drawable*/ic_expander_indicator_down_black_24dp.png
+app/src/main/res/drawable*/ic_expander_indicator_right_black_24dp.png
+app/src/main/res/drawable*/ic_group_add_white_24dp.png
+app/src/main/res/drawable*/ic_hangouts_grey600_24dp.png
+app/src/main/res/drawable*/ic_help_circle_grey600_24dp.png
+app/src/main/res/drawable*/ic_list_white_24dp.png
+app/src/main/res/drawable*/ic_message_delivered_18dp.png
+app/src/main/res/drawable*/ic_message_has_error_18dp.png
+app/src/main/res/drawable*/ic_message_not_sent_18dp.png
+app/src/main/res/drawable*/ic_person_add_white_24dp.png
+app/src/main/res/drawable*/ic_search_white_24dp.png
+app/src/main/res/drawable*/ic_security_*_24dp.png
+app/src/main/res/drawable*/ic_settings_grey600_24dp.png
+app/src/main/res/drawable*/ic_show_offline_*.png
+app/src/main/res/drawable*/ic_stat_add_circle.png
+app/src/main/res/drawable*/ic_stat_chat.png
+app/src/main/res/drawable*/ic_stat_error.png
+app/src/main/res/drawable*/ic_stat_help.png
+app/src/main/res/drawable*/ic_stat_play_circle_fill.png
+app/src/main/res/drawable*/ic_vcard_address_24dp.png
+app/src/main/res/drawable*/ic_vcard_birthday_24dp.png
+app/src/main/res/drawable*/ic_vcard_contact_info_24dp.png
+app/src/main/res/drawable*/ic_vcard_email_24dp.png
+app/src/main/res/drawable*/ic_vcard_job_title_24dp.png
+app/src/main/res/drawable*/ic_vcard_notes_24dp.png
+app/src/main/res/drawable*/ic_vcard_phone_24dp.png
+app/src/main/res/drawable*/ic_vcard_web_24dp.png
-Also following components are in use (see the source code or official sites for license details):
+XMPP logo is licensed under a slightly modified MIT license (http://xmpp.org/about-xmpp/xsf/xsf-ipr-policy/#legal):
+app/src/main/res/drawable*/ic_vcard_xmpp_24dp.png
-ZXing
-src/com/google/zxing/*
-Apache License, Version 2.0 (the "License").
+The Jabber logo is licensed under the Creative Commons Attribution License
+app/src/main/res/drawable*/ic_vcard_jabber_24dp.png
+
+Xabber, Redsolution logo are trademarks of Redsolution Inc., and are licensed under Creative Commons Attribution-NoDerivs license:
+app/src/main/res/drawable*/ic_connect.png
+app/src/main/res/drawable*/ic_disconnect.png
+app/src/main/res/drawable*/ic_launcher.png
+app/src/main/res/drawable*/redsolution_logo*.9.png
-JZLib
-src/com/jcraft/jzlib/*
-BSD license.
+Following file is part of The Android Open Source Project licensed under the Apache License, Version 2.0 (the "License") (see assets/LICENSE-Apache2.txt):
+app/src/main/res/layout/preference.xml
+
+Also source code of following components is included in repository (see the source code or official sites for license details):
Novel sasl client
-src/com/novell/sasl/*
+app/src/main/java/com/novell/sasl/*
The OpenLDAP Public License.
Measite Smack SASL
-src/de/measite/smack/*
+app/src/main/java/de/measite/smack/*
Apache License, Version 2.0 (the "License").
Apache Harmony
-src/org/apache/harmony/*
+app/src/main/java/org/apache/harmony/*
Apache License, Version 2.0 (the "License").
Apache Qpid
-src/org/apache/qpid/*
+app/src/main/java/org/apache/qpid/*
Apache License, Version 2.0 (the "License").
Smack
-src/org/jivesoftware/*
+app/src/main/java/org/jivesoftware/*
Apache License, Version 2.0 (the "License").
-DNS Java
-src/org/xbill/*
-BSD license.
-
-OTR4J
-libs/otr4j.jar
-GNU Lesser General Public License, Version 3.
diff --git a/README.rst b/README.rst
index 88e27359c6..3c3276e8e1 100644
--- a/README.rst
+++ b/README.rst
@@ -4,6 +4,19 @@ Xabber - XMPP client for Android
Open source Jabber (XMPP) client with multi-account support, clean and simple interface.
Being both free (as in freedom!) and ad-free, Xabber is designed to be the best Jabber client for Android.
+Build instrustions
+==================
+
+Xabber uses Gradle build system. The only specific thing is git submodule for otr4j library. To make it work use following commands:
+
+ ::
+
+ git submodule init
+
+ git submodule update
+
+And otr4j would be cloned to your local repository.
+
Supported protocols
===================
@@ -27,12 +40,19 @@ Supported protocols
* XEP-0059: Result Set Management
* XEP-0136: Message Archiving
* XEP-0224: Attention
+* XEP-0077: In-Band Registration
Translations
============
-We use webtranslateit.com as our translation system.
-All related resources are automatically generated from files got with webtranslateit.com.
-If you want to update any translation please email us to info[at]xabber.com and specify all the translation languages you want to edit.
-Then we'll send an invitation to our project on webtranslateit.com.
-Please don't create pull requests with translation fixes as any changes will be overwritten with the next update from webtranslateit.com.
+
+
+We use crowdin.com as our translation system.
+All related resources are automatically generated from files got with crowdin.com.
+If you want to update any translation go to Xabber page https://crowdin.com/project/xabber and request to join our translation team
+Please don't create pull requests with translation fixes as any changes will be overwritten with the next update from crowdin.com.
+
+Wiki
+====
+
+Visit our wiki pages for additional information: https://github.com/redsolution/xabber-android/wiki
diff --git a/app/build.gradle b/app/build.gradle
index 1aff0155a4..b963ee9010 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -1,23 +1,55 @@
apply plugin: 'com.android.application'
android {
- compileSdkVersion 9
- buildToolsVersion "21.1.2"
+ compileSdkVersion 22
+ buildToolsVersion "22.0.1"
defaultConfig {
- applicationId "com.xabber.androiddev"
- minSdkVersion 3
- targetSdkVersion 9
+ minSdkVersion 14
+ targetSdkVersion 22
+ versionCode 200
+ versionName '1.0.28'
}
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_7
+ targetCompatibility JavaVersion.VERSION_1_7
+ }
+
+ lintOptions {
+ // problems with generated "applicationId" string resource
+ disable 'MissingTranslation'
+ }
+
+ productFlavors {
+
+ dev {
+ applicationId "com.xabber.androiddev"
+ resValue 'string', 'application_package', applicationId
}
+
+ beta {
+ applicationId "com.xabber.android.beta"
+ resValue 'string', 'application_package', applicationId
+ }
+
}
}
+repositories {
+ mavenCentral()
+}
+
dependencies {
- compile files('libs/otr4j.jar')
+ compile 'com.android.support:design:22.2.0'
+ compile 'com.android.support:appcompat-v7:22.2.0'
+ compile 'com.android.support:support-v13:22.2.0'
+ compile 'com.github.ksoichiro:android-observablescrollview:1.5.0'
+ compile 'de.hdodenhof:circleimageview:1.2.2'
+ compile 'com.melnykov:floatingactionbutton:1.2.0'
+ compile 'dnsjava:dnsjava:2.1.7'
+ compile 'com.github.bumptech.glide:glide:3.6.0'
+ compile 'com.google.zxing:android-integration:3.1.0'
+ compile 'com.jcraft:jzlib:1.0.7'
+ compile project('otr4j')
}
diff --git a/app/libs/otr4j.jar b/app/libs/otr4j.jar
deleted file mode 100644
index 76a2b51ab5..0000000000
Binary files a/app/libs/otr4j.jar and /dev/null differ
diff --git a/app/otr4j b/app/otr4j
new file mode 160000
index 0000000000..0ced840950
--- /dev/null
+++ b/app/otr4j
@@ -0,0 +1 @@
+Subproject commit 0ced840950b4db1a403ea085b642a7028b1ef03d
diff --git a/app/src/beta/res/values/application_title.xml b/app/src/beta/res/values/application_title.xml
new file mode 100644
index 0000000000..2adc250af3
--- /dev/null
+++ b/app/src/beta/res/values/application_title.xml
@@ -0,0 +1,18 @@
+
+
+ Xabber
+ Xabber Beta
+ Xabber
+
diff --git a/app/src/dev/res/values/application_title.xml b/app/src/dev/res/values/application_title.xml
new file mode 100644
index 0000000000..47e7a80832
--- /dev/null
+++ b/app/src/dev/res/values/application_title.xml
@@ -0,0 +1,18 @@
+
+
+ Xabber
+ Xabber Dev
+ Xabber
+
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8f25d2e340..8f9babc534 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -13,20 +13,28 @@
along with this program. If not, see http://www.gnu.org/licenses/.
-->
+ package="com.xabber.android">
+
+
+
+
+
+
+
+
+
+
+
+
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/application_title_full"
+ android:theme="@style/Theme">
@@ -63,90 +71,155 @@
+ android:parentActivityName="com.xabber.android.ui.preferences.PreferenceEditor"
+ android:theme="@style/ThemeDark"
+ >
+
+
+
+
+ android:parentActivityName="com.xabber.android.ui.preferences.PreferenceEditor"
+ >
+
+
+
-
+ android:parentActivityName="com.xabber.android.ui.preferences.AccountList"
+ >
+
+
+
+ android:label="@string/occupant_list"
+ android:parentActivityName="com.xabber.android.ui.ChatViewer"
+ >
+
+
+
+
+
+
+
+
+
+ android:name="com.xabber.android.ui.GroupEditor"
+ android:parentActivityName="com.xabber.android.ui.ContactViewer"
+ >
+
+
+
+ android:label="@string/contact_add"
+ android:parentActivityName="com.xabber.android.ui.preferences.AccountList"
+ >
+
+
+
+ android:label="@string/account_add"
+ android:parentActivityName="com.xabber.android.ui.preferences.AccountList"
+ >
+
+
+
+ android:parentActivityName="com.xabber.android.ui.ContactList"
+ >
+
+
+
+ android:label="@string/status_editor"
+ android:parentActivityName="com.xabber.android.ui.ContactList"
+ >
+
+
+
+ android:parentActivityName="com.xabber.android.ui.ContactList"
+ >
+
+
+
+
+
+ android:parentActivityName="com.xabber.android.ui.ChatViewer"
+ >
+
+
+
+
+
+
+
+
@@ -155,19 +228,51 @@
+
+
+
+
+
+
+ android:parentActivityName="com.xabber.android.ui.ChatViewer"
+ >
+
+
+
+
+ android:parentActivityName="com.xabber.android.ui.ChatViewer"
+ >
+
+
+
+
+
+
+
+
+ android:name="com.xabber.android.ui.preferences.PhraseList"
+ android:parentActivityName="com.xabber.android.ui.preferences.NotificationsSettings">
+
+
+
+ android:name="com.xabber.android.ui.preferences.PhraseEditor"
+ android:parentActivityName="com.xabber.android.ui.preferences.PhraseList">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/app/src/main/java/com/google/zxing/integration/android/IntentIntegrator.java b/app/src/main/java/com/google/zxing/integration/android/IntentIntegrator.java
deleted file mode 100644
index cd4327784c..0000000000
--- a/app/src/main/java/com/google/zxing/integration/android/IntentIntegrator.java
+++ /dev/null
@@ -1,415 +0,0 @@
-/*
- * Copyright 2009 ZXing authors
- *
- * 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.
- */
-
-package com.google.zxing.integration.android;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.ActivityNotFoundException;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.net.Uri;
-import android.os.Bundle;
-import android.util.Log;
-
-/**
- *
A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple
- * way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the
- * project's source code.
- *
- *
Initiating a barcode scan
- *
- *
To integrate, create an instance of {@code IntentIntegrator} and call {@link #initiateScan()} and wait
- * for the result in your app.
- *
- *
It does require that the Barcode Scanner (or work-alike) application is installed. The
- * {@link #initiateScan()} method will prompt the user to download the application, if needed.
- *
- *
There are a few steps to using this integration. First, your {@link Activity} must implement
- * the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:
- *
- *
{@code
- * public void onActivityResult(int requestCode, int resultCode, Intent intent) {
- * IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
- * if (scanResult != null) {
- * // handle scan result
- * }
- * // else continue with any other code you need in the method
- * ...
- * }
- * }
- *
- *
This is where you will handle a scan result.
- *
- *
Second, just call this in response to a user action somewhere to begin the scan process:
Note that {@link #initiateScan()} returns an {@link AlertDialog} which is non-null if the
- * user was prompted to download the application. This lets the calling app potentially manage the dialog.
- * In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()}
- * method.
- *
- *
You can use {@link #setTitle(String)} to customize the title of this download prompt dialog (or, use
- * {@link #setTitleByID(int)} to set the title by string resource ID.) Likewise, the prompt message, and
- * yes/no button labels can be changed.
- *
- *
Finally, you can use {@link #addExtra(String, Object)} to add more parameters to the Intent used
- * to invoke the scanner. This can be used to set additional options not directly exposed by this
- * simplified API.
- *
- *
By default, this will only allow applications that are known to respond to this intent correctly
- * do so. The apps that are allowed to response can be set with {@link #setTargetApplications(Collection)}.
- * For example, set to {@link #TARGET_BARCODE_SCANNER_ONLY} to only target the Barcode Scanner app itself.
- *
- *
Sharing text via barcode
- *
- *
To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(CharSequence)}.
- *
- *
Some code, particularly download integration, was contributed from the Anobiit application.
- *
- *
Enabling experimental barcode formats
- *
- *
Some formats are not enabled by default even when scanning with {@link #ALL_CODE_TYPES}, such as
- * {@link com.google.zxing.BarcodeFormat#PDF_417}. Use {@link #initiateScan(java.util.Collection)} with
- * a collection containing the names of formats to scan for explicitly, like "PDF_417", to use such
- * formats.
- *
- * @author Sean Owen
- * @author Fred Lin
- * @author Isaac Potoczny-Jones
- * @author Brad Drehmer
- * @author gcstang
- */
-public class IntentIntegrator {
-
- public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
- private static final String TAG = IntentIntegrator.class.getSimpleName();
-
- public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
- public static final String DEFAULT_MESSAGE =
- "This application requires Barcode Scanner. Would you like to install it?";
- public static final String DEFAULT_YES = "Yes";
- public static final String DEFAULT_NO = "No";
-
- public static final String BS_PACKAGE = "com.google.zxing.client.android";
- private static final String BSPLUS_PACKAGE = "com.srowen.bs.android";
-
- // supported barcode formats
- public static final Collection PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
- public static final Collection ONE_D_CODE_TYPES =
- list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
- "ITF", "RSS_14", "RSS_EXPANDED");
- public static final Collection QR_CODE_TYPES = Collections.singleton("QR_CODE");
- public static final Collection DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
-
- public static final Collection ALL_CODE_TYPES = null;
-
- public static final Collection TARGET_BARCODE_SCANNER_ONLY = Collections.singleton(BS_PACKAGE);
- public static final Collection TARGET_ALL_KNOWN = list(
- BS_PACKAGE, // Barcode Scanner
- BSPLUS_PACKAGE, // Barcode Scanner+
- BSPLUS_PACKAGE + ".simple" // Barcode Scanner+ Simple
- // What else supports this intent?
- );
-
- private final Activity activity;
- private String title;
- private String message;
- private String buttonYes;
- private String buttonNo;
- private Collection targetApplications;
- private final Map moreExtras;
-
- public IntentIntegrator(Activity activity) {
- this.activity = activity;
- title = DEFAULT_TITLE;
- message = DEFAULT_MESSAGE;
- buttonYes = DEFAULT_YES;
- buttonNo = DEFAULT_NO;
- targetApplications = TARGET_ALL_KNOWN;
- moreExtras = new HashMap(3);
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public void setTitleByID(int titleID) {
- title = activity.getString(titleID);
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public void setMessageByID(int messageID) {
- message = activity.getString(messageID);
- }
-
- public String getButtonYes() {
- return buttonYes;
- }
-
- public void setButtonYes(String buttonYes) {
- this.buttonYes = buttonYes;
- }
-
- public void setButtonYesByID(int buttonYesID) {
- buttonYes = activity.getString(buttonYesID);
- }
-
- public String getButtonNo() {
- return buttonNo;
- }
-
- public void setButtonNo(String buttonNo) {
- this.buttonNo = buttonNo;
- }
-
- public void setButtonNoByID(int buttonNoID) {
- buttonNo = activity.getString(buttonNoID);
- }
-
- public Collection getTargetApplications() {
- return targetApplications;
- }
-
- public void setTargetApplications(Collection targetApplications) {
- this.targetApplications = targetApplications;
- }
-
- public void setSingleTargetApplication(String targetApplication) {
- this.targetApplications = Collections.singleton(targetApplication);
- }
-
- public Map getMoreExtras() {
- return moreExtras;
- }
-
- public void addExtra(String key, Object value) {
- moreExtras.put(key, value);
- }
-
- /**
- * Initiates a scan for all known barcode types.
- */
- public AlertDialog initiateScan() {
- return initiateScan(ALL_CODE_TYPES);
- }
-
- /**
- * Initiates a scan only for a certain set of barcode types, given as strings corresponding
- * to their names in ZXing's {@code BarcodeFormat} class like "UPC_A". You can supply constants
- * like {@link #PRODUCT_CODE_TYPES} for example.
- *
- * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
- * if a prompt was needed, or null otherwise
- */
- public AlertDialog initiateScan(Collection desiredBarcodeFormats) {
- Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
- intentScan.addCategory(Intent.CATEGORY_DEFAULT);
-
- // check which types of codes to scan for
- if (desiredBarcodeFormats != null) {
- // set the desired barcode types
- StringBuilder joinedByComma = new StringBuilder();
- for (String format : desiredBarcodeFormats) {
- if (joinedByComma.length() > 0) {
- joinedByComma.append(',');
- }
- joinedByComma.append(format);
- }
- intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
- }
-
- String targetAppPackage = findTargetAppPackage(intentScan);
- if (targetAppPackage == null) {
- return showDownloadDialog();
- }
-// intentScan.setPackage(targetAppPackage);
- intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
- attachMoreExtras(intentScan);
- startActivityForResult(intentScan, REQUEST_CODE);
- return null;
- }
-
- /**
- * Start an activity.
- * This method is defined to allow different methods of activity starting for
- * newer versions of Android and for compatibility library.
- *
- * @param intent Intent to start.
- * @param code Request code for the activity
- * @see android.app.Activity#startActivityForResult(Intent, int)
- * @see android.app.Fragment#startActivityForResult(Intent, int)
- */
- protected void startActivityForResult(Intent intent, int code) {
- activity.startActivityForResult(intent, code);
- }
-
- private String findTargetAppPackage(Intent intent) {
- PackageManager pm = activity.getPackageManager();
- List availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
- if (availableApps != null) {
- for (ResolveInfo availableApp : availableApps) {
- String packageName = availableApp.activityInfo.packageName;
- if (targetApplications.contains(packageName)) {
- return packageName;
- }
- }
- }
- return null;
- }
-
- private AlertDialog showDownloadDialog() {
- AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
- downloadDialog.setTitle(title);
- downloadDialog.setMessage(message);
- downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {
- Uri uri = Uri.parse("market://details?id=" + BS_PACKAGE);
- Intent intent = new Intent(Intent.ACTION_VIEW, uri);
- try {
- activity.startActivity(intent);
- } catch (ActivityNotFoundException anfe) {
- // Hmm, market is not installed
- Log.w(TAG, "Android Market is not installed; cannot install Barcode Scanner");
- }
- }
- });
- downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {}
- });
- return downloadDialog.show();
- }
-
-
- /**
- *
Call this from your {@link Activity}'s
- * {@link Activity#onActivityResult(int, int, Intent)} method.
- *
- * @return null if the event handled here was not related to this class, or
- * else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning,
- * the fields will be null.
- */
- public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
- if (requestCode == REQUEST_CODE) {
- if (resultCode == Activity.RESULT_OK) {
- String contents = intent.getStringExtra("SCAN_RESULT");
- String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
- byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
- int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
- Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
- String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
- return new IntentResult(contents,
- formatName,
- rawBytes,
- orientation,
- errorCorrectionLevel);
- }
- return new IntentResult();
- }
- return null;
- }
-
-
- /**
- * Defaults to type "TEXT_TYPE".
- * @see #shareText(CharSequence, CharSequence)
- */
- public AlertDialog shareText(CharSequence text) {
- return shareText(text, "TEXT_TYPE");
- }
-
- /**
- * Shares the given text by encoding it as a barcode, such that another user can
- * scan the text off the screen of the device.
- *
- * @param text the text string to encode as a barcode
- * @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
- * @return the {@link AlertDialog} that was shown to the user prompting them to download the app
- * if a prompt was needed, or null otherwise
- */
- public AlertDialog shareText(CharSequence text, CharSequence type) {
- Intent intent = new Intent();
- intent.addCategory(Intent.CATEGORY_DEFAULT);
- intent.setAction(BS_PACKAGE + ".ENCODE");
- intent.putExtra("ENCODE_TYPE", type);
- intent.putExtra("ENCODE_DATA", text);
- String targetAppPackage = findTargetAppPackage(intent);
- if (targetAppPackage == null) {
- return showDownloadDialog();
- }
-// intent.setPackage(targetAppPackage);
- intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
- attachMoreExtras(intent);
- activity.startActivity(intent);
- return null;
- }
-
- private static Collection list(String... values) {
- return Collections.unmodifiableCollection(Arrays.asList(values));
- }
-
- private void attachMoreExtras(Intent intent) {
- for (Map.Entry entry : moreExtras.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- // Kind of hacky
- if (value instanceof Integer) {
- intent.putExtra(key, (Integer) value);
- } else if (value instanceof Long) {
- intent.putExtra(key, (Long) value);
- } else if (value instanceof Boolean) {
- intent.putExtra(key, (Boolean) value);
- } else if (value instanceof Double) {
- intent.putExtra(key, (Double) value);
- } else if (value instanceof Float) {
- intent.putExtra(key, (Float) value);
- } else if (value instanceof Bundle) {
- intent.putExtra(key, (Bundle) value);
- } else {
- intent.putExtra(key, value.toString());
- }
- }
- }
-
-}
diff --git a/app/src/main/java/com/google/zxing/integration/android/IntentResult.java b/app/src/main/java/com/google/zxing/integration/android/IntentResult.java
deleted file mode 100644
index 2469af92c0..0000000000
--- a/app/src/main/java/com/google/zxing/integration/android/IntentResult.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright 2009 ZXing authors
- *
- * 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.
- */
-
-package com.google.zxing.integration.android;
-
-/**
- *
Encapsulates the result of a barcode scan invoked through {@link IntentIntegrator}.
- *
- * @author Sean Owen
- */
-public final class IntentResult {
-
- private final String contents;
- private final String formatName;
- private final byte[] rawBytes;
- private final Integer orientation;
- private final String errorCorrectionLevel;
-
- IntentResult() {
- this(null, null, null, null, null);
- }
-
- IntentResult(String contents,
- String formatName,
- byte[] rawBytes,
- Integer orientation,
- String errorCorrectionLevel) {
- this.contents = contents;
- this.formatName = formatName;
- this.rawBytes = rawBytes;
- this.orientation = orientation;
- this.errorCorrectionLevel = errorCorrectionLevel;
- }
-
- /**
- * @return raw content of barcode
- */
- public String getContents() {
- return contents;
- }
-
- /**
- * @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
- */
- public String getFormatName() {
- return formatName;
- }
-
- /**
- * @return raw bytes of the barcode content, if applicable, or null otherwise
- */
- public byte[] getRawBytes() {
- return rawBytes;
- }
-
- /**
- * @return rotation of the image, in degrees, which resulted in a successful scan. May be null.
- */
- public Integer getOrientation() {
- return orientation;
- }
-
- /**
- * @return name of the error correction level used in the barcode, if applicable
- */
- public String getErrorCorrectionLevel() {
- return errorCorrectionLevel;
- }
-
- @Override
- public String toString() {
- StringBuilder dialogText = new StringBuilder(100);
- dialogText.append("Format: ").append(formatName).append('\n');
- dialogText.append("Contents: ").append(contents).append('\n');
- int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
- dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
- dialogText.append("Orientation: ").append(orientation).append('\n');
- dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
- return dialogText.toString();
- }
-
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/Adler32.java b/app/src/main/java/com/jcraft/jzlib/Adler32.java
deleted file mode 100644
index d8b6ef8633..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/Adler32.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-final class Adler32{
-
- // largest prime smaller than 65536
- static final private int BASE=65521;
- // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
- static final private int NMAX=5552;
-
- long adler32(long adler, byte[] buf, int index, int len){
- if(buf == null){ return 1L; }
-
- long s1=adler&0xffff;
- long s2=(adler>>16)&0xffff;
- int k;
-
- while(len > 0) {
- k=len=16){
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- s1+=buf[index++]&0xff; s2+=s1;
- k-=16;
- }
- if(k!=0){
- do{
- s1+=buf[index++]&0xff; s2+=s1;
- }
- while(--k!=0);
- }
- s1%=BASE;
- s2%=BASE;
- }
- return (s2<<16)|s1;
- }
-
- /*
- private java.util.zip.Adler32 adler=new java.util.zip.Adler32();
- long adler32(long value, byte[] buf, int index, int len){
- if(value==1) {adler.reset();}
- if(buf==null) {adler.reset();}
- else{adler.update(buf, index, len);}
- return adler.getValue();
- }
- */
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/ChangeLog b/app/src/main/java/com/jcraft/jzlib/ChangeLog
deleted file mode 100644
index c828fae3ef..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/ChangeLog
+++ /dev/null
@@ -1,115 +0,0 @@
-ChangeLog of JZlib
-====================================================================
-Last modified: Thu Aug 18 16:16:06 UTC 2005
-
-
-Changes since version 1.0.6:
-- change: memory and performance optimizations in the inflate operation.
- Many thanks to Paul Wakefield at platx.org(http://www.platx.org), who
- suggested above improvements.
-- change: added the nowrap argument to Z{Input,Output}?Stream.
-
-
-Changes since version 1.0.5:
-- ZInputStream.read(byte[], int, int) method return sometimes zero
- instead of -1 at the end of stream.
-- ZOutputStream.end() method should not declare IOException.
-- It should be possible to call ZOutputStream.end() method more times
- (because you can call close() method and after it end() method in
- finally block).
-- ZOutputStream.finish() method should not ignore IOException from flush().
-Many thanks to Matej Kraus at seznam.cz , who pointed out above problems.
-
-
-Changes since version 1.0.4:
-- a minor bug fix in ZInputStream
-
-
-Changes since version 1.0.3:
-- fixed a bug in closing ZOutputStream.
- The inflating and deflating processes were not finished successfully.
-- added 'finish' and 'end' methods to ZOutputStream.java
-- added 'example/test_stream_deflate_inflate.java'
-
-
-Changes since version 1.0.2:
-- enabled pure Java implementation of adler32 and
- commented out the dependency on J2SE in Adler32.java for J2ME users.
-
-
-Changes since version 1.0.1:
-- fixed a bug in deflating some trivial data, for example,
- large data chunk filled with zero.
-- added 'version' method to JZlib class.
-
-
-Changes since version 1.0.0:
-- added ZInputStream and ZOutputStream classes.
-- fixed a typo in LICENSE.txt.
-
-
-Changes since version 0.0.9:
-- fixed a bug in setting a dictionary in the inflation process.
-- The license was changed to a BSD style license.
-- Z{Input,Output}Stream classes were deleted.
-
-
-Changes since version 0.0.8:
-- fixed a bug in handling a preset dictionary in the inflation process.
-
-
-Changes since version 0.0.7:
-- added methods to control the window size (the size of the history
- buffer) and to handle the no-wrap option (no zlib header or check),
- which is the undocumented functionality of zlib.
-
-
-Changes since version 0.0.6:
-- updated InfBlocks.java as zlib did to fix the vulnerability related to
- the 'double free'. Of course, JZlib is free from such a vulnerability
- like the 'double free', but JZlib had crashed with NullPointerException
- by a specially-crafted block of invalid deflated data.
-
-
-Changes since version 0.0.5:
-- added 'flush()' method to com.jcraft.jzlib.ZOutputStream.
-- fixed to take care when occurring the buffer overflow in
- com.jcraft.jzlib.ZOutputStream.
-Many thanks to Tim Bendfelt at cs.wisc.edu , who pointed out above problems.
-
-
-Changes since version 0.0.4:
-............................
-- fixed a bug in Adler32 class.
-- fixed a bug in ZInputStream class
-- modified ZInputStream to be extended from InputStream
- instead of FileInputStream.
-- modified ZOutputStream to be extended from OutputStream
- instead of FileOutputStream.
-- modified ZStream to be changeable wbits. Give wbits value to
- the method 'deflateInit' of ZStream.
-Many thanks to Bryan Keller, who reported bugs
-and made suggestions.
-
-
-Changes since version 0.0.3:
-............................
-- fixed a bug in the compression level 0.
-- modified to be compatible with JIKES's bug.
-- added Z[Input,Output]Stream written by Lapo Luchini.
-
-
-Changes since version 0.0.2:
-............................
-- fixed a critical bug, which had arisen in the deflating operation with
- NO_FLUSH and DEFAULT_COMPRESSION mode.
- Many thanks to Bryan Keller(keller@neomar.com), who reported this glitch.
-
-
-Changes since version 0.0.1:
-............................
-- fixed the bad compression ratio problem, which is reported from
- Martin Smith(martin@spamcop.net). The compression ratio was not so good
- compared with the compression ration of zlib. Now, this problem has been
- fixed and, I hope, that deflated files by JZlib and zlib are completely
- same bit by bit.
diff --git a/app/src/main/java/com/jcraft/jzlib/Deflate.java b/app/src/main/java/com/jcraft/jzlib/Deflate.java
deleted file mode 100644
index 99788020b0..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/Deflate.java
+++ /dev/null
@@ -1,1623 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-public
-final class Deflate{
-
- static final private int MAX_MEM_LEVEL=9;
-
- static final private int Z_DEFAULT_COMPRESSION=-1;
-
- static final private int MAX_WBITS=15; // 32K LZ77 window
- static final private int DEF_MEM_LEVEL=8;
-
- static class Config{
- int good_length; // reduce lazy search above this match length
- int max_lazy; // do not perform lazy search above this match length
- int nice_length; // quit search above this match length
- int max_chain;
- int func;
- Config(int good_length, int max_lazy,
- int nice_length, int max_chain, int func){
- this.good_length=good_length;
- this.max_lazy=max_lazy;
- this.nice_length=nice_length;
- this.max_chain=max_chain;
- this.func=func;
- }
- }
-
- static final private int STORED=0;
- static final private int FAST=1;
- static final private int SLOW=2;
- static final private Config[] config_table;
- static{
- config_table=new Config[10];
- // good lazy nice chain
- config_table[0]=new Config(0, 0, 0, 0, STORED);
- config_table[1]=new Config(4, 4, 8, 4, FAST);
- config_table[2]=new Config(4, 5, 16, 8, FAST);
- config_table[3]=new Config(4, 6, 32, 32, FAST);
-
- config_table[4]=new Config(4, 4, 16, 16, SLOW);
- config_table[5]=new Config(8, 16, 32, 32, SLOW);
- config_table[6]=new Config(8, 16, 128, 128, SLOW);
- config_table[7]=new Config(8, 32, 128, 256, SLOW);
- config_table[8]=new Config(32, 128, 258, 1024, SLOW);
- config_table[9]=new Config(32, 258, 258, 4096, SLOW);
- }
-
- static final private String[] z_errmsg = {
- "need dictionary", // Z_NEED_DICT 2
- "stream end", // Z_STREAM_END 1
- "", // Z_OK 0
- "file error", // Z_ERRNO (-1)
- "stream error", // Z_STREAM_ERROR (-2)
- "data error", // Z_DATA_ERROR (-3)
- "insufficient memory", // Z_MEM_ERROR (-4)
- "buffer error", // Z_BUF_ERROR (-5)
- "incompatible version",// Z_VERSION_ERROR (-6)
- ""
- };
-
- // block not completed, need more input or more output
- static final private int NeedMore=0;
-
- // block flush performed
- static final private int BlockDone=1;
-
- // finish started, need only more output at next deflate
- static final private int FinishStarted=2;
-
- // finish done, accept no more input or output
- static final private int FinishDone=3;
-
- // preset dictionary flag in zlib header
- static final private int PRESET_DICT=0x20;
-
- static final private int Z_FILTERED=1;
- static final private int Z_HUFFMAN_ONLY=2;
- static final private int Z_DEFAULT_STRATEGY=0;
-
- static final private int Z_NO_FLUSH=0;
- static final private int Z_PARTIAL_FLUSH=1;
- static final private int Z_SYNC_FLUSH=2;
- static final private int Z_FULL_FLUSH=3;
- static final private int Z_FINISH=4;
-
- static final private int Z_OK=0;
- static final private int Z_STREAM_END=1;
- static final private int Z_NEED_DICT=2;
- static final private int Z_ERRNO=-1;
- static final private int Z_STREAM_ERROR=-2;
- static final private int Z_DATA_ERROR=-3;
- static final private int Z_MEM_ERROR=-4;
- static final private int Z_BUF_ERROR=-5;
- static final private int Z_VERSION_ERROR=-6;
-
- static final private int INIT_STATE=42;
- static final private int BUSY_STATE=113;
- static final private int FINISH_STATE=666;
-
- // The deflate compression method
- static final private int Z_DEFLATED=8;
-
- static final private int STORED_BLOCK=0;
- static final private int STATIC_TREES=1;
- static final private int DYN_TREES=2;
-
- // The three kinds of block type
- static final private int Z_BINARY=0;
- static final private int Z_ASCII=1;
- static final private int Z_UNKNOWN=2;
-
- static final private int Buf_size=8*2;
-
- // repeat previous bit length 3-6 times (2 bits of repeat count)
- static final private int REP_3_6=16;
-
- // repeat a zero length 3-10 times (3 bits of repeat count)
- static final private int REPZ_3_10=17;
-
- // repeat a zero length 11-138 times (7 bits of repeat count)
- static final private int REPZ_11_138=18;
-
- static final private int MIN_MATCH=3;
- static final private int MAX_MATCH=258;
- static final private int MIN_LOOKAHEAD=(MAX_MATCH+MIN_MATCH+1);
-
- static final private int MAX_BITS=15;
- static final private int D_CODES=30;
- static final private int BL_CODES=19;
- static final private int LENGTH_CODES=29;
- static final private int LITERALS=256;
- static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
- static final private int HEAP_SIZE=(2*L_CODES+1);
-
- static final private int END_BLOCK=256;
-
- ZStream strm; // pointer back to this zlib stream
- int status; // as the name implies
- byte[] pending_buf; // output still pending
- int pending_buf_size; // size of pending_buf
- int pending_out; // next pending byte to output to the stream
- int pending; // nb of bytes in the pending buffer
- int noheader; // suppress zlib header and adler32
- byte data_type; // UNKNOWN, BINARY or ASCII
- byte method; // STORED (for zip only) or DEFLATED
- int last_flush; // value of flush param for previous deflate call
-
- int w_size; // LZ77 window size (32K by default)
- int w_bits; // log2(w_size) (8..16)
- int w_mask; // w_size - 1
-
- byte[] window;
- // Sliding window. Input bytes are read into the second half of the window,
- // and move to the first half later to keep a dictionary of at least wSize
- // bytes. With this organization, matches are limited to a distance of
- // wSize-MAX_MATCH bytes, but this ensures that IO is always
- // performed with a length multiple of the block size. Also, it limits
- // the window size to 64K, which is quite useful on MSDOS.
- // To do: use the user input buffer as sliding window.
-
- int window_size;
- // Actual size of window: 2*wSize, except when the user input buffer
- // is directly used as sliding window.
-
- short[] prev;
- // Link to older string with same hash index. To limit the size of this
- // array to 64K, this link is maintained only for the last 32K strings.
- // An index in this array is thus a window index modulo 32K.
-
- short[] head; // Heads of the hash chains or NIL.
-
- int ins_h; // hash index of string to be inserted
- int hash_size; // number of elements in hash table
- int hash_bits; // log2(hash_size)
- int hash_mask; // hash_size-1
-
- // Number of bits by which ins_h must be shifted at each input
- // step. It must be such that after MIN_MATCH steps, the oldest
- // byte no longer takes part in the hash key, that is:
- // hash_shift * MIN_MATCH >= hash_bits
- int hash_shift;
-
- // Window position at the beginning of the current output block. Gets
- // negative when the window is moved backwards.
-
- int block_start;
-
- int match_length; // length of best match
- int prev_match; // previous match
- int match_available; // set if previous match exists
- int strstart; // start of string to insert
- int match_start; // start of matching string
- int lookahead; // number of valid bytes ahead in window
-
- // Length of the best match at previous step. Matches not greater than this
- // are discarded. This is used in the lazy match evaluation.
- int prev_length;
-
- // To speed up deflation, hash chains are never searched beyond this
- // length. A higher limit improves compression ratio but degrades the speed.
- int max_chain_length;
-
- // Attempt to find a better match only when the current match is strictly
- // smaller than this value. This mechanism is used only for compression
- // levels >= 4.
- int max_lazy_match;
-
- // Insert new strings in the hash table only if the match length is not
- // greater than this length. This saves time but degrades compression.
- // max_insert_length is used only for compression levels <= 3.
-
- int level; // compression level (1..9)
- int strategy; // favor or force Huffman coding
-
- // Use a faster search when the previous match is longer than this
- int good_match;
-
- // Stop searching when current match exceeds this
- int nice_match;
-
- short[] dyn_ltree; // literal and length tree
- short[] dyn_dtree; // distance tree
- short[] bl_tree; // Huffman tree for bit lengths
-
- Tree l_desc=new Tree(); // desc for literal tree
- Tree d_desc=new Tree(); // desc for distance tree
- Tree bl_desc=new Tree(); // desc for bit length tree
-
- // number of codes at each bit length for an optimal tree
- short[] bl_count=new short[MAX_BITS+1];
-
- // heap used to build the Huffman trees
- int[] heap=new int[2*L_CODES+1];
-
- int heap_len; // number of elements in the heap
- int heap_max; // element of largest frequency
- // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
- // The same heap array is used to build all trees.
-
- // Depth of each subtree used as tie breaker for trees of equal frequency
- byte[] depth=new byte[2*L_CODES+1];
-
- int l_buf; // index for literals or lengths */
-
- // Size of match buffer for literals/lengths. There are 4 reasons for
- // limiting lit_bufsize to 64K:
- // - frequencies can be kept in 16 bit counters
- // - if compression is not successful for the first block, all input
- // data is still in the window so we can still emit a stored block even
- // when input comes from standard input. (This can also be done for
- // all blocks if lit_bufsize is not greater than 32K.)
- // - if compression is not successful for a file smaller than 64K, we can
- // even emit a stored file instead of a stored block (saving 5 bytes).
- // This is applicable only for zip (not gzip or zlib).
- // - creating new Huffman trees less frequently may not provide fast
- // adaptation to changes in the input data statistics. (Take for
- // example a binary file with poorly compressible code followed by
- // a highly compressible string table.) Smaller buffer sizes give
- // fast adaptation but have of course the overhead of transmitting
- // trees more frequently.
- // - I can't count above 4
- int lit_bufsize;
-
- int last_lit; // running index in l_buf
-
- // Buffer for distances. To simplify the code, d_buf and l_buf have
- // the same number of elements. To use different lengths, an extra flag
- // array would be necessary.
-
- int d_buf; // index of pendig_buf
-
- int opt_len; // bit length of current block with optimal trees
- int static_len; // bit length of current block with static trees
- int matches; // number of string matches in current block
- int last_eob_len; // bit length of EOB code for last block
-
- // Output buffer. bits are inserted starting at the bottom (least
- // significant bits).
- short bi_buf;
-
- // Number of valid bits in bi_buf. All bits above the last valid bit
- // are always zero.
- int bi_valid;
-
- Deflate(){
- dyn_ltree=new short[HEAP_SIZE*2];
- dyn_dtree=new short[(2*D_CODES+1)*2]; // distance tree
- bl_tree=new short[(2*BL_CODES+1)*2]; // Huffman tree for bit lengths
- }
-
- void lm_init() {
- window_size=2*w_size;
-
- head[hash_size-1]=0;
- for(int i=0; i= 3; max_blindex--) {
- if (bl_tree[Tree.bl_order[max_blindex]*2+1] != 0) break;
- }
- // Update opt_len to include the bit length tree and counts
- opt_len += 3*(max_blindex+1) + 5+5+4;
-
- return max_blindex;
- }
-
-
- // Send the header for a block using dynamic Huffman trees: the counts, the
- // lengths of the bit length codes, the literal tree and the distance tree.
- // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
- void send_all_trees(int lcodes, int dcodes, int blcodes){
- int rank; // index in bl_order
-
- send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
- send_bits(dcodes-1, 5);
- send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
- for (rank = 0; rank < blcodes; rank++) {
- send_bits(bl_tree[Tree.bl_order[rank]*2+1], 3);
- }
- send_tree(dyn_ltree, lcodes-1); // literal tree
- send_tree(dyn_dtree, dcodes-1); // distance tree
- }
-
- // Send a literal or distance tree in compressed form, using the codes in
- // bl_tree.
- void send_tree (short[] tree,// the tree to be sent
- int max_code // and its largest code of non zero frequency
- ){
- int n; // iterates over all tree elements
- int prevlen = -1; // last emitted length
- int curlen; // length of current code
- int nextlen = tree[0*2+1]; // length of next code
- int count = 0; // repeat count of the current code
- int max_count = 7; // max repeat count
- int min_count = 4; // min repeat count
-
- if (nextlen == 0){ max_count = 138; min_count = 3; }
-
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen; nextlen = tree[(n+1)*2+1];
- if(++count < max_count && curlen == nextlen) {
- continue;
- }
- else if(count < min_count) {
- do { send_code(curlen, bl_tree); } while (--count != 0);
- }
- else if(curlen != 0){
- if(curlen != prevlen){
- send_code(curlen, bl_tree); count--;
- }
- send_code(REP_3_6, bl_tree);
- send_bits(count-3, 2);
- }
- else if(count <= 10){
- send_code(REPZ_3_10, bl_tree);
- send_bits(count-3, 3);
- }
- else{
- send_code(REPZ_11_138, bl_tree);
- send_bits(count-11, 7);
- }
- count = 0; prevlen = curlen;
- if(nextlen == 0){
- max_count = 138; min_count = 3;
- }
- else if(curlen == nextlen){
- max_count = 6; min_count = 3;
- }
- else{
- max_count = 7; min_count = 4;
- }
- }
- }
-
- // Output a byte on the stream.
- // IN assertion: there is enough room in pending_buf.
- final void put_byte(byte[] p, int start, int len){
- System.arraycopy(p, start, pending_buf, pending, len);
- pending+=len;
- }
-
- final void put_byte(byte c){
- pending_buf[pending++]=c;
- }
- final void put_short(int w) {
- put_byte((byte)(w/*&0xff*/));
- put_byte((byte)(w>>>8));
- }
- final void putShortMSB(int b){
- put_byte((byte)(b>>8));
- put_byte((byte)(b/*&0xff*/));
- }
-
- final void send_code(int c, short[] tree){
- int c2=c*2;
- send_bits((tree[c2]&0xffff), (tree[c2+1]&0xffff));
- }
-
- void send_bits(int value, int length){
- int len = length;
- if (bi_valid > (int)Buf_size - len) {
- int val = value;
-// bi_buf |= (val << bi_valid);
- bi_buf |= ((val << bi_valid)&0xffff);
- put_short(bi_buf);
- bi_buf = (short)(val >>> (Buf_size - bi_valid));
- bi_valid += len - Buf_size;
- } else {
-// bi_buf |= (value) << bi_valid;
- bi_buf |= (((value) << bi_valid)&0xffff);
- bi_valid += len;
- }
- }
-
- // Send one empty static block to give enough lookahead for inflate.
- // This takes 10 bits, of which 7 may remain in the bit buffer.
- // The current inflate code requires 9 bits of lookahead. If the
- // last two codes for the previous block (real code plus EOB) were coded
- // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
- // the last real code. In this case we send two empty static blocks instead
- // of one. (There are no problems if the previous block is stored or fixed.)
- // To simplify the code, we assume the worst case of last real code encoded
- // on one bit only.
- void _tr_align(){
- send_bits(STATIC_TREES<<1, 3);
- send_code(END_BLOCK, StaticTree.static_ltree);
-
- bi_flush();
-
- // Of the 10 bits for the empty block, we have already sent
- // (10 - bi_valid) bits. The lookahead for the last real code (before
- // the EOB of the previous block) was thus at least one plus the length
- // of the EOB plus what we have just sent of the empty static block.
- if (1 + last_eob_len + 10 - bi_valid < 9) {
- send_bits(STATIC_TREES<<1, 3);
- send_code(END_BLOCK, StaticTree.static_ltree);
- bi_flush();
- }
- last_eob_len = 7;
- }
-
-
- // Save the match info and tally the frequency counts. Return true if
- // the current block must be flushed.
- boolean _tr_tally (int dist, // distance of matched string
- int lc // match length-MIN_MATCH or unmatched char (if dist==0)
- ){
-
- pending_buf[d_buf+last_lit*2] = (byte)(dist>>>8);
- pending_buf[d_buf+last_lit*2+1] = (byte)dist;
-
- pending_buf[l_buf+last_lit] = (byte)lc; last_lit++;
-
- if (dist == 0) {
- // lc is the unmatched char
- dyn_ltree[lc*2]++;
- }
- else {
- matches++;
- // Here, lc is the match length - MIN_MATCH
- dist--; // dist = match distance - 1
- dyn_ltree[(Tree._length_code[lc]+LITERALS+1)*2]++;
- dyn_dtree[Tree.d_code(dist)*2]++;
- }
-
- if ((last_lit & 0x1fff) == 0 && level > 2) {
- // Compute an upper bound for the compressed length
- int out_length = last_lit*8;
- int in_length = strstart - block_start;
- int dcode;
- for (dcode = 0; dcode < D_CODES; dcode++) {
- out_length += (int)dyn_dtree[dcode*2] *
- (5L+Tree.extra_dbits[dcode]);
- }
- out_length >>>= 3;
- if ((matches < (last_lit/2)) && out_length < in_length/2) return true;
- }
-
- return (last_lit == lit_bufsize-1);
- // We avoid equality with lit_bufsize because of wraparound at 64K
- // on 16 bit machines and because stored blocks are restricted to
- // 64K-1 bytes.
- }
-
- // Send the block data compressed using the given Huffman trees
- void compress_block(short[] ltree, short[] dtree){
- int dist; // distance of matched string
- int lc; // match length or unmatched char (if dist == 0)
- int lx = 0; // running index in l_buf
- int code; // the code to send
- int extra; // number of extra bits to send
-
- if (last_lit != 0){
- do{
- dist=((pending_buf[d_buf+lx*2]<<8)&0xff00)|
- (pending_buf[d_buf+lx*2+1]&0xff);
- lc=(pending_buf[l_buf+lx])&0xff; lx++;
-
- if(dist == 0){
- send_code(lc, ltree); // send a literal byte
- }
- else{
- // Here, lc is the match length - MIN_MATCH
- code = Tree._length_code[lc];
-
- send_code(code+LITERALS+1, ltree); // send the length code
- extra = Tree.extra_lbits[code];
- if(extra != 0){
- lc -= Tree.base_length[code];
- send_bits(lc, extra); // send the extra length bits
- }
- dist--; // dist is now the match distance - 1
- code = Tree.d_code(dist);
-
- send_code(code, dtree); // send the distance code
- extra = Tree.extra_dbits[code];
- if (extra != 0) {
- dist -= Tree.base_dist[code];
- send_bits(dist, extra); // send the extra distance bits
- }
- } // literal or match pair ?
-
- // Check that the overlay between pending_buf and d_buf+l_buf is ok:
- }
- while (lx < last_lit);
- }
-
- send_code(END_BLOCK, ltree);
- last_eob_len = ltree[END_BLOCK*2+1];
- }
-
- // Set the data type to ASCII or BINARY, using a crude approximation:
- // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
- // IN assertion: the fields freq of dyn_ltree are set and the total of all
- // frequencies does not exceed 64K (to fit in an int on 16 bit machines).
- void set_data_type(){
- int n = 0;
- int ascii_freq = 0;
- int bin_freq = 0;
- while(n<7){ bin_freq += dyn_ltree[n*2]; n++;}
- while(n<128){ ascii_freq += dyn_ltree[n*2]; n++;}
- while(n (ascii_freq >>> 2) ? Z_BINARY : Z_ASCII);
- }
-
- // Flush the bit buffer, keeping at most 7 bits in it.
- void bi_flush(){
- if (bi_valid == 16) {
- put_short(bi_buf);
- bi_buf=0;
- bi_valid=0;
- }
- else if (bi_valid >= 8) {
- put_byte((byte)bi_buf);
- bi_buf>>>=8;
- bi_valid-=8;
- }
- }
-
- // Flush the bit buffer and align the output on a byte boundary
- void bi_windup(){
- if (bi_valid > 8) {
- put_short(bi_buf);
- } else if (bi_valid > 0) {
- put_byte((byte)bi_buf);
- }
- bi_buf = 0;
- bi_valid = 0;
- }
-
- // Copy a stored block, storing first the length and its
- // one's complement if requested.
- void copy_block(int buf, // the input data
- int len, // its length
- boolean header // true if block header must be written
- ){
- int index=0;
- bi_windup(); // align on byte boundary
- last_eob_len = 8; // enough lookahead for inflate
-
- if (header) {
- put_short((short)len);
- put_short((short)~len);
- }
-
- // while(len--!=0) {
- // put_byte(window[buf+index]);
- // index++;
- // }
- put_byte(window, buf, len);
- }
-
- void flush_block_only(boolean eof){
- _tr_flush_block(block_start>=0 ? block_start : -1,
- strstart-block_start,
- eof);
- block_start=strstart;
- strm.flush_pending();
- }
-
- // Copy without compression as much as possible from the input stream, return
- // the current block state.
- // This function does not insert new strings in the dictionary since
- // uncompressible data is probably not useful. This function is used
- // only for the level=0 compression option.
- // NOTE: this function should be optimized to avoid extra copying from
- // window to pending_buf.
- int deflate_stored(int flush){
- // Stored blocks are limited to 0xffff bytes, pending_buf is limited
- // to pending_buf_size, and each stored block has a 5 byte header:
-
- int max_block_size = 0xffff;
- int max_start;
-
- if(max_block_size > pending_buf_size - 5) {
- max_block_size = pending_buf_size - 5;
- }
-
- // Copy as much as possible from input to output:
- while(true){
- // Fill the window as much as possible:
- if(lookahead<=1){
- fill_window();
- if(lookahead==0 && flush==Z_NO_FLUSH) return NeedMore;
- if(lookahead==0) break; // flush the current block
- }
-
- strstart+=lookahead;
- lookahead=0;
-
- // Emit a stored block if pending_buf will be full:
- max_start=block_start+max_block_size;
- if(strstart==0|| strstart>=max_start) {
- // strstart == 0 is possible when wraparound on 16-bit machine
- lookahead = (int)(strstart-max_start);
- strstart = (int)max_start;
-
- flush_block_only(false);
- if(strm.avail_out==0) return NeedMore;
-
- }
-
- // Flush if we may have to slide, otherwise block_start may become
- // negative and the data will be gone:
- if(strstart-block_start >= w_size-MIN_LOOKAHEAD) {
- flush_block_only(false);
- if(strm.avail_out==0) return NeedMore;
- }
- }
-
- flush_block_only(flush == Z_FINISH);
- if(strm.avail_out==0)
- return (flush == Z_FINISH) ? FinishStarted : NeedMore;
-
- return flush == Z_FINISH ? FinishDone : BlockDone;
- }
-
- // Send a stored block
- void _tr_stored_block(int buf, // input block
- int stored_len, // length of input block
- boolean eof // true if this is the last block for a file
- ){
- send_bits((STORED_BLOCK<<1)+(eof?1:0), 3); // send block type
- copy_block(buf, stored_len, true); // with header
- }
-
- // Determine the best encoding for the current block: dynamic trees, static
- // trees or store, and output the encoded block to the zip file.
- void _tr_flush_block(int buf, // input block, or NULL if too old
- int stored_len, // length of input block
- boolean eof // true if this is the last block for a file
- ) {
- int opt_lenb, static_lenb;// opt_len and static_len in bytes
- int max_blindex = 0; // index of last bit length code of non zero freq
-
- // Build the Huffman trees unless a stored block is forced
- if(level > 0) {
- // Check if the file is ascii or binary
- if(data_type == Z_UNKNOWN) set_data_type();
-
- // Construct the literal and distance trees
- l_desc.build_tree(this);
-
- d_desc.build_tree(this);
-
- // At this point, opt_len and static_len are the total bit lengths of
- // the compressed block data, excluding the tree representations.
-
- // Build the bit length tree for the above two trees, and get the index
- // in bl_order of the last bit length code to send.
- max_blindex=build_bl_tree();
-
- // Determine the best encoding. Compute first the block length in bytes
- opt_lenb=(opt_len+3+7)>>>3;
- static_lenb=(static_len+3+7)>>>3;
-
- if(static_lenb<=opt_lenb) opt_lenb=static_lenb;
- }
- else {
- opt_lenb=static_lenb=stored_len+5; // force a stored block
- }
-
- if(stored_len+4<=opt_lenb && buf != -1){
- // 4: two words for the lengths
- // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
- // Otherwise we can't have processed more than WSIZE input bytes since
- // the last block flush, because compression would have been
- // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
- // transform a block into a stored block.
- _tr_stored_block(buf, stored_len, eof);
- }
- else if(static_lenb == opt_lenb){
- send_bits((STATIC_TREES<<1)+(eof?1:0), 3);
- compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
- }
- else{
- send_bits((DYN_TREES<<1)+(eof?1:0), 3);
- send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
- compress_block(dyn_ltree, dyn_dtree);
- }
-
- // The above check is made mod 2^32, for files larger than 512 MB
- // and uLong implemented on 32 bits.
-
- init_block();
-
- if(eof){
- bi_windup();
- }
- }
-
- // Fill the window when the lookahead becomes insufficient.
- // Updates strstart and lookahead.
- //
- // IN assertion: lookahead < MIN_LOOKAHEAD
- // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
- // At least one byte has been read, or avail_in == 0; reads are
- // performed for at least two bytes (required for the zip translate_eol
- // option -- not supported here).
- void fill_window(){
- int n, m;
- int p;
- int more; // Amount of free space at the end of the window.
-
- do{
- more = (window_size-lookahead-strstart);
-
- // Deal with !@#$% 64K limit:
- if(more==0 && strstart==0 && lookahead==0){
- more = w_size;
- }
- else if(more==-1) {
- // Very unlikely, but possible on 16 bit machine if strstart == 0
- // and lookahead == 1 (input done one byte at time)
- more--;
-
- // If the window is almost full and there is insufficient lookahead,
- // move the upper half to the lower one to make room in the upper half.
- }
- else if(strstart >= w_size+ w_size-MIN_LOOKAHEAD) {
- System.arraycopy(window, w_size, window, 0, w_size);
- match_start-=w_size;
- strstart-=w_size; // we now have strstart >= MAX_DIST
- block_start-=w_size;
-
- // Slide the hash table (could be avoided with 32 bit values
- // at the expense of memory usage). We slide even when level == 0
- // to keep the hash table consistent if we switch back to level > 0
- // later. (Using level 0 permanently is not an optimal usage of
- // zlib, so we don't care about this pathological case.)
-
- n = hash_size;
- p=n;
- do {
- m = (head[--p]&0xffff);
- head[p]=(m>=w_size ? (short)(m-w_size) : 0);
- }
- while (--n != 0);
-
- n = w_size;
- p = n;
- do {
- m = (prev[--p]&0xffff);
- prev[p] = (m >= w_size ? (short)(m-w_size) : 0);
- // If n is not on any hash chain, prev[n] is garbage but
- // its value will never be used.
- }
- while (--n!=0);
- more += w_size;
- }
-
- if (strm.avail_in == 0) return;
-
- // If there was no sliding:
- // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
- // more == window_size - lookahead - strstart
- // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
- // => more >= window_size - 2*WSIZE + 2
- // In the BIG_MEM or MMAP case (not yet supported),
- // window_size == input_size + MIN_LOOKAHEAD &&
- // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
- // Otherwise, window_size == 2*WSIZE so more >= 2.
- // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
-
- n = strm.read_buf(window, strstart + lookahead, more);
- lookahead += n;
-
- // Initialize the hash value now that we have some input:
- if(lookahead >= MIN_MATCH) {
- ins_h = window[strstart]&0xff;
- ins_h=(((ins_h)<= MIN_MATCH){
- ins_h=(((ins_h)<=MIN_MATCH){
- // check_match(strstart, match_start, match_length);
-
- bflush=_tr_tally(strstart-match_start, match_length-MIN_MATCH);
-
- lookahead -= match_length;
-
- // Insert new strings in the hash table only if the match length
- // is not too large. This saves time but degrades compression.
- if(match_length <= max_lazy_match &&
- lookahead >= MIN_MATCH) {
- match_length--; // string at strstart already in hash table
- do{
- strstart++;
-
- ins_h=((ins_h<= MIN_MATCH) {
- ins_h=(((ins_h)< 4096))) {
-
- // If prev_match is also MIN_MATCH, match_start is garbage
- // but we will ignore the current match anyway.
- match_length = MIN_MATCH-1;
- }
- }
-
- // If there was a match at the previous step and the current
- // match is not better, output the previous match:
- if(prev_length >= MIN_MATCH && match_length <= prev_length) {
- int max_insert = strstart + lookahead - MIN_MATCH;
- // Do not insert strings in hash table beyond this.
-
- // check_match(strstart-1, prev_match, prev_length);
-
- bflush=_tr_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
-
- // Insert in hash table all strings up to the end of the match.
- // strstart-1 and strstart are already inserted. If there is not
- // enough lookahead, the last two strings are not inserted in
- // the hash table.
- lookahead -= prev_length-1;
- prev_length -= 2;
- do{
- if(++strstart <= max_insert) {
- ins_h=(((ins_h)<(w_size-MIN_LOOKAHEAD) ?
- strstart-(w_size-MIN_LOOKAHEAD) : 0;
- int nice_match=this.nice_match;
-
- // Stop when cur_match becomes <= limit. To simplify the code,
- // we prevent matches with the string of window index 0.
-
- int wmask = w_mask;
-
- int strend = strstart + MAX_MATCH;
- byte scan_end1 = window[scan+best_len-1];
- byte scan_end = window[scan+best_len];
-
- // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
- // It is easy to get rid of this optimization if necessary.
-
- // Do not waste too much time if we already have a good match:
- if (prev_length >= good_match) {
- chain_length >>= 2;
- }
-
- // Do not look for matches beyond the end of the input. This is necessary
- // to make deflate deterministic.
- if (nice_match > lookahead) nice_match = lookahead;
-
- do {
- match = cur_match;
-
- // Skip to next match if the match length cannot increase
- // or if the match length is less than 2:
- if (window[match+best_len] != scan_end ||
- window[match+best_len-1] != scan_end1 ||
- window[match] != window[scan] ||
- window[++match] != window[scan+1]) continue;
-
- // The check at best_len-1 can be removed because it will be made
- // again later. (This heuristic is not always a win.)
- // It is not necessary to compare scan[2] and match[2] since they
- // are always equal when the other bytes match, given that
- // the hash keys are equal and that HASH_BITS >= 8.
- scan += 2; match++;
-
- // We check for insufficient lookahead only every 8th comparison;
- // the 256th check will be made at strstart+258.
- do {
- } while (window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- window[++scan] == window[++match] &&
- scan < strend);
-
- len = MAX_MATCH - (int)(strend - scan);
- scan = strend - MAX_MATCH;
-
- if(len>best_len) {
- match_start = cur_match;
- best_len = len;
- if (len >= nice_match) break;
- scan_end1 = window[scan+best_len-1];
- scan_end = window[scan+best_len];
- }
-
- } while ((cur_match = (prev[cur_match & wmask]&0xffff)) > limit
- && --chain_length != 0);
-
- if (best_len <= lookahead) return best_len;
- return lookahead;
- }
-
- int deflateInit(ZStream strm, int level, int bits){
- return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL,
- Z_DEFAULT_STRATEGY);
- }
- int deflateInit(ZStream strm, int level){
- return deflateInit(strm, level, MAX_WBITS);
- }
- int deflateInit2(ZStream strm, int level, int method, int windowBits,
- int memLevel, int strategy){
- int noheader = 0;
- // byte[] my_version=ZLIB_VERSION;
-
- //
- // if (version == null || version[0] != my_version[0]
- // || stream_size != sizeof(z_stream)) {
- // return Z_VERSION_ERROR;
- // }
-
- strm.msg = null;
-
- if (level == Z_DEFAULT_COMPRESSION) level = 6;
-
- if (windowBits < 0) { // undocumented feature: suppress zlib header
- noheader = 1;
- windowBits = -windowBits;
- }
-
- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL ||
- method != Z_DEFLATED ||
- windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
- strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
- return Z_STREAM_ERROR;
- }
-
- strm.dstate = (Deflate)this;
-
- this.noheader = noheader;
- w_bits = windowBits;
- w_size = 1 << w_bits;
- w_mask = w_size - 1;
-
- hash_bits = memLevel + 7;
- hash_size = 1 << hash_bits;
- hash_mask = hash_size - 1;
- hash_shift = ((hash_bits+MIN_MATCH-1)/MIN_MATCH);
-
- window = new byte[w_size*2];
- prev = new short[w_size];
- head = new short[hash_size];
-
- lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
-
- // We overlay pending_buf and d_buf+l_buf. This works since the average
- // output size for (length,distance) codes is <= 24 bits.
- pending_buf = new byte[lit_bufsize*4];
- pending_buf_size = lit_bufsize*4;
-
- d_buf = lit_bufsize/2;
- l_buf = (1+2)*lit_bufsize;
-
- this.level = level;
-
-//System.out.println("level="+level);
-
- this.strategy = strategy;
- this.method = (byte)method;
-
- return deflateReset(strm);
- }
-
- int deflateReset(ZStream strm){
- strm.total_in = strm.total_out = 0;
- strm.msg = null; //
- strm.data_type = Z_UNKNOWN;
-
- pending = 0;
- pending_out = 0;
-
- if(noheader < 0) {
- noheader = 0; // was set to -1 by deflate(..., Z_FINISH);
- }
- status = (noheader!=0) ? BUSY_STATE : INIT_STATE;
- strm.adler=strm._adler.adler32(0, null, 0, 0);
-
- last_flush = Z_NO_FLUSH;
-
- tr_init();
- lm_init();
- return Z_OK;
- }
-
- int deflateEnd(){
- if(status!=INIT_STATE && status!=BUSY_STATE && status!=FINISH_STATE){
- return Z_STREAM_ERROR;
- }
- // Deallocate in reverse order of allocations:
- pending_buf=null;
- head=null;
- prev=null;
- window=null;
- // free
- // dstate=null;
- return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
- }
-
- int deflateParams(ZStream strm, int _level, int _strategy){
- int err=Z_OK;
-
- if(_level == Z_DEFAULT_COMPRESSION){
- _level = 6;
- }
- if(_level < 0 || _level > 9 ||
- _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
- return Z_STREAM_ERROR;
- }
-
- if(config_table[level].func!=config_table[_level].func &&
- strm.total_in != 0) {
- // Flush the last buffer:
- err = strm.deflate(Z_PARTIAL_FLUSH);
- }
-
- if(level != _level) {
- level = _level;
- max_lazy_match = config_table[level].max_lazy;
- good_match = config_table[level].good_length;
- nice_match = config_table[level].nice_length;
- max_chain_length = config_table[level].max_chain;
- }
- strategy = _strategy;
- return err;
- }
-
- int deflateSetDictionary (ZStream strm, byte[] dictionary, int dictLength){
- int length = dictLength;
- int index=0;
-
- if(dictionary == null || status != INIT_STATE)
- return Z_STREAM_ERROR;
-
- strm.adler=strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
-
- if(length < MIN_MATCH) return Z_OK;
- if(length > w_size-MIN_LOOKAHEAD){
- length = w_size-MIN_LOOKAHEAD;
- index=dictLength-length; // use the tail of the dictionary
- }
- System.arraycopy(dictionary, index, window, 0, length);
- strstart = length;
- block_start = length;
-
- // Insert all strings in the hash table (except for the last two bytes).
- // s->lookahead stays null, so s->ins_h will be recomputed at the next
- // call of fill_window.
-
- ins_h = window[0]&0xff;
- ins_h=(((ins_h)<Z_FINISH || flush<0){
- return Z_STREAM_ERROR;
- }
-
- if(strm.next_out == null ||
- (strm.next_in == null && strm.avail_in != 0) ||
- (status == FINISH_STATE && flush != Z_FINISH)) {
- strm.msg=z_errmsg[Z_NEED_DICT-(Z_STREAM_ERROR)];
- return Z_STREAM_ERROR;
- }
- if(strm.avail_out == 0){
- strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
- return Z_BUF_ERROR;
- }
-
- this.strm = strm; // just in case
- old_flush = last_flush;
- last_flush = flush;
-
- // Write the zlib header
- if(status == INIT_STATE) {
- int header = (Z_DEFLATED+((w_bits-8)<<4))<<8;
- int level_flags=((level-1)&0xff)>>1;
-
- if(level_flags>3) level_flags=3;
- header |= (level_flags<<6);
- if(strstart!=0) header |= PRESET_DICT;
- header+=31-(header % 31);
-
- status=BUSY_STATE;
- putShortMSB(header);
-
-
- // Save the adler32 of the preset dictionary:
- if(strstart!=0){
- putShortMSB((int)(strm.adler>>>16));
- putShortMSB((int)(strm.adler&0xffff));
- }
- strm.adler=strm._adler.adler32(0, null, 0, 0);
- }
-
- // Flush as much pending output as possible
- if(pending != 0) {
- strm.flush_pending();
- if(strm.avail_out == 0) {
- //System.out.println(" avail_out==0");
- // Since avail_out is 0, deflate will be called again with
- // more output space, but possibly with both pending and
- // avail_in equal to zero. There won't be anything to do,
- // but this is not an error situation so make sure we
- // return OK instead of BUF_ERROR at next call of deflate:
- last_flush = -1;
- return Z_OK;
- }
-
- // Make sure there is something to do and avoid duplicate consecutive
- // flushes. For repeated and useless calls with Z_FINISH, we keep
- // returning Z_STREAM_END instead of Z_BUFF_ERROR.
- }
- else if(strm.avail_in==0 && flush <= old_flush &&
- flush != Z_FINISH) {
- strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
- return Z_BUF_ERROR;
- }
-
- // User must not provide more input after the first FINISH:
- if(status == FINISH_STATE && strm.avail_in != 0) {
- strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
- return Z_BUF_ERROR;
- }
-
- // Start a new block or continue the current one.
- if(strm.avail_in!=0 || lookahead!=0 ||
- (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
- int bstate=-1;
- switch(config_table[level].func){
- case STORED:
- bstate = deflate_stored(flush);
- break;
- case FAST:
- bstate = deflate_fast(flush);
- break;
- case SLOW:
- bstate = deflate_slow(flush);
- break;
- default:
- }
-
- if (bstate==FinishStarted || bstate==FinishDone) {
- status = FINISH_STATE;
- }
- if (bstate==NeedMore || bstate==FinishStarted) {
- if(strm.avail_out == 0) {
- last_flush = -1; // avoid BUF_ERROR next call, see above
- }
- return Z_OK;
- // If flush != Z_NO_FLUSH && avail_out == 0, the next call
- // of deflate should use the same flush parameter to make sure
- // that the flush is complete. So we don't have to output an
- // empty block here, this will be done at next call. This also
- // ensures that for a very small output buffer, we emit at most
- // one empty block.
- }
-
- if (bstate==BlockDone) {
- if(flush == Z_PARTIAL_FLUSH) {
- _tr_align();
- }
- else { // FULL_FLUSH or SYNC_FLUSH
- _tr_stored_block(0, 0, false);
- // For a full flush, this empty block will be recognized
- // as a special marker by inflate_sync().
- if(flush == Z_FULL_FLUSH) {
- //state.head[s.hash_size-1]=0;
- for(int i=0; i>>16));
- putShortMSB((int)(strm.adler&0xffff));
- strm.flush_pending();
-
- // If avail_out is zero, the application will call deflate again
- // to flush the rest.
- noheader = -1; // write the trailer only once!
- return pending != 0 ? Z_OK : Z_STREAM_END;
- }
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/InfBlocks.java b/app/src/main/java/com/jcraft/jzlib/InfBlocks.java
deleted file mode 100644
index f6997fc6bd..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/InfBlocks.java
+++ /dev/null
@@ -1,614 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-final class InfBlocks{
- static final private int MANY=1440;
-
- // And'ing with mask[n] masks the lower n bits
- static final private int[] inflate_mask = {
- 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
- 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
- 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
- 0x00007fff, 0x0000ffff
- };
-
- // Table for deflate from PKZIP's appnote.txt.
- static final int[] border = { // Order of the bit length code lengths
- 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
- };
-
- static final private int Z_OK=0;
- static final private int Z_STREAM_END=1;
- static final private int Z_NEED_DICT=2;
- static final private int Z_ERRNO=-1;
- static final private int Z_STREAM_ERROR=-2;
- static final private int Z_DATA_ERROR=-3;
- static final private int Z_MEM_ERROR=-4;
- static final private int Z_BUF_ERROR=-5;
- static final private int Z_VERSION_ERROR=-6;
-
- static final private int TYPE=0; // get type bits (3, including end bit)
- static final private int LENS=1; // get lengths for stored
- static final private int STORED=2;// processing stored block
- static final private int TABLE=3; // get table lengths
- static final private int BTREE=4; // get bit lengths tree for a dynamic block
- static final private int DTREE=5; // get length, distance trees for a dynamic block
- static final private int CODES=6; // processing fixed or dynamic block
- static final private int DRY=7; // output remaining window bytes
- static final private int DONE=8; // finished last block, done
- static final private int BAD=9; // ot a data error--stuck here
-
- int mode; // current inflate_block mode
-
- int left; // if STORED, bytes left to copy
-
- int table; // table lengths (14 bits)
- int index; // index into blens (or border)
- int[] blens; // bit lengths of codes
- int[] bb=new int[1]; // bit length tree depth
- int[] tb=new int[1]; // bit length decoding tree
-
- InfCodes codes=new InfCodes(); // if CODES, current state
-
- int last; // true if this block is the last block
-
- // mode independent information
- int bitk; // bits in bit buffer
- int bitb; // bit buffer
- int[] hufts; // single malloc for tree space
- byte[] window; // sliding window
- int end; // one byte after sliding window
- int read; // window read pointer
- int write; // window write pointer
- Object checkfn; // check function
- long check; // check on output
-
- InfTree inftree=new InfTree();
-
- InfBlocks(ZStream z, Object checkfn, int w){
- hufts=new int[MANY*3];
- window=new byte[w];
- end=w;
- this.checkfn = checkfn;
- mode = TYPE;
- reset(z, null);
- }
-
- void reset(ZStream z, long[] c){
- if(c!=null) c[0]=check;
- if(mode==BTREE || mode==DTREE){
- }
- if(mode==CODES){
- codes.free(z);
- }
- mode=TYPE;
- bitk=0;
- bitb=0;
- read=write=0;
-
- if(checkfn != null)
- z.adler=check=z._adler.adler32(0L, null, 0, 0);
- }
-
- int proc(ZStream z, int r){
- int t; // temporary storage
- int b; // bit buffer
- int k; // bits in bit buffer
- int p; // input data pointer
- int n; // bytes available there
- int q; // output window write pointer
- int m; // bytes to end of window or read pointer
-
- // copy input/output information to locals (UPDATE macro restores)
- {p=z.next_in_index;n=z.avail_in;b=bitb;k=bitk;}
- {q=write;m=(int)(q>> 1){
- case 0: // stored
- {b>>>=(3);k-=(3);}
- t = k & 7; // go to byte boundary
-
- {b>>>=(t);k-=(t);}
- mode = LENS; // get length of stored block
- break;
- case 1: // fixed
- {
- int[] bl=new int[1];
- int[] bd=new int[1];
- int[][] tl=new int[1][];
- int[][] td=new int[1][];
-
- InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
- codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);
- }
-
- {b>>>=(3);k-=(3);}
-
- mode = CODES;
- break;
- case 2: // dynamic
-
- {b>>>=(3);k-=(3);}
-
- mode = TABLE;
- break;
- case 3: // illegal
-
- {b>>>=(3);k-=(3);}
- mode = BAD;
- z.msg = "invalid block type";
- r = Z_DATA_ERROR;
-
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
- break;
- case LENS:
-
- while(k<(32)){
- if(n!=0){
- r=Z_OK;
- }
- else{
- bitb=b; bitk=k;
- z.avail_in=n;
- z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- };
- n--;
- b|=(z.next_in[p++]&0xff)<>> 16) & 0xffff) != (b & 0xffff)){
- mode = BAD;
- z.msg = "invalid stored block lengths";
- r = Z_DATA_ERROR;
-
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
- left = (b & 0xffff);
- b = k = 0; // dump bits
- mode = left!=0 ? STORED : (last!=0 ? DRY : TYPE);
- break;
- case STORED:
- if (n == 0){
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
-
- if(m==0){
- if(q==end&&read!=0){
- q=0; m=(int)(qn) t = n;
- if(t>m) t = m;
- System.arraycopy(z.next_in, p, window, q, t);
- p += t; n -= t;
- q += t; m -= t;
- if ((left -= t) != 0)
- break;
- mode = last!=0 ? DRY : TYPE;
- break;
- case TABLE:
-
- while(k<(14)){
- if(n!=0){
- r=Z_OK;
- }
- else{
- bitb=b; bitk=k;
- z.avail_in=n;
- z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- };
- n--;
- b|=(z.next_in[p++]&0xff)< 29 || ((t >> 5) & 0x1f) > 29)
- {
- mode = BAD;
- z.msg = "too many length or distance symbols";
- r = Z_DATA_ERROR;
-
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
- t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
- if(blens==null || blens.length>>=(14);k-=(14);}
-
- index = 0;
- mode = BTREE;
- case BTREE:
- while (index < 4 + (table >>> 10)){
- while(k<(3)){
- if(n!=0){
- r=Z_OK;
- }
- else{
- bitb=b; bitk=k;
- z.avail_in=n;
- z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- };
- n--;
- b|=(z.next_in[p++]&0xff)<>>=(3);k-=(3);}
- }
-
- while(index < 19){
- blens[border[index++]] = 0;
- }
-
- bb[0] = 7;
- t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
- if (t != Z_OK){
- r = t;
- if (r == Z_DATA_ERROR){
- blens=null;
- mode = BAD;
- }
-
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
-
- index = 0;
- mode = DTREE;
- case DTREE:
- while (true){
- t = table;
- if(!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){
- break;
- }
-
- int[] h;
- int i, j, c;
-
- t = bb[0];
-
- while(k<(t)){
- if(n!=0){
- r=Z_OK;
- }
- else{
- bitb=b; bitk=k;
- z.avail_in=n;
- z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- };
- n--;
- b|=(z.next_in[p++]&0xff)<>>=(t);k-=(t);
- blens[index++] = c;
- }
- else { // c == 16..18
- i = c == 18 ? 7 : c - 14;
- j = c == 18 ? 11 : 3;
-
- while(k<(t+i)){
- if(n!=0){
- r=Z_OK;
- }
- else{
- bitb=b; bitk=k;
- z.avail_in=n;
- z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- };
- n--;
- b|=(z.next_in[p++]&0xff)<>>=(t);k-=(t);
-
- j += (b & inflate_mask[i]);
-
- b>>>=(i);k-=(i);
-
- i = index;
- t = table;
- if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
- (c == 16 && i < 1)){
- blens=null;
- mode = BAD;
- z.msg = "invalid bit length repeat";
- r = Z_DATA_ERROR;
-
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
-
- c = c == 16 ? blens[i-1] : 0;
- do{
- blens[i++] = c;
- }
- while (--j!=0);
- index = i;
- }
- }
-
- tb[0]=-1;
- {
- int[] bl=new int[1];
- int[] bd=new int[1];
- int[] tl=new int[1];
- int[] td=new int[1];
- bl[0] = 9; // must be <= 9 for lookahead assumptions
- bd[0] = 6; // must be <= 9 for lookahead assumptions
-
- t = table;
- t = inftree.inflate_trees_dynamic(257 + (t & 0x1f),
- 1 + ((t >> 5) & 0x1f),
- blens, bl, bd, tl, td, hufts, z);
-
- if (t != Z_OK){
- if (t == Z_DATA_ERROR){
- blens=null;
- mode = BAD;
- }
- r = t;
-
- bitb=b; bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
- return inflate_flush(z,r);
- }
- codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
- }
- mode = CODES;
- case CODES:
- bitb=b; bitk=k;
- z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p;
- write=q;
-
- if ((r = codes.proc(this, z, r)) != Z_STREAM_END){
- return inflate_flush(z, r);
- }
- r = Z_OK;
- codes.free(z);
-
- p=z.next_in_index; n=z.avail_in;b=bitb;k=bitk;
- q=write;m=(int)(q z.avail_out) n = z.avail_out;
- if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
-
- // update counters
- z.avail_out -= n;
- z.total_out += n;
-
- // update check information
- if(checkfn != null)
- z.adler=check=z._adler.adler32(check, window, q, n);
-
- // copy as far as end of window
- System.arraycopy(window, q, z.next_out, p, n);
- p += n;
- q += n;
-
- // see if more to copy at beginning of window
- if (q == end){
- // wrap pointers
- q = 0;
- if (write == end)
- write = 0;
-
- // compute bytes to copy
- n = write - q;
- if (n > z.avail_out) n = z.avail_out;
- if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
-
- // update counters
- z.avail_out -= n;
- z.total_out += n;
-
- // update check information
- if(checkfn != null)
- z.adler=check=z._adler.adler32(check, window, q, n);
-
- // copy
- System.arraycopy(window, q, z.next_out, p, n);
- p += n;
- q += n;
- }
-
- // update pointers
- z.next_out_index = p;
- read = q;
-
- // done
- return r;
- }
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/InfCodes.java b/app/src/main/java/com/jcraft/jzlib/InfCodes.java
deleted file mode 100644
index c768fb1cbe..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/InfCodes.java
+++ /dev/null
@@ -1,605 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-final class InfCodes{
-
- static final private int[] inflate_mask = {
- 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
- 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
- 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
- 0x00007fff, 0x0000ffff
- };
-
- static final private int Z_OK=0;
- static final private int Z_STREAM_END=1;
- static final private int Z_NEED_DICT=2;
- static final private int Z_ERRNO=-1;
- static final private int Z_STREAM_ERROR=-2;
- static final private int Z_DATA_ERROR=-3;
- static final private int Z_MEM_ERROR=-4;
- static final private int Z_BUF_ERROR=-5;
- static final private int Z_VERSION_ERROR=-6;
-
- // waiting for "i:"=input,
- // "o:"=output,
- // "x:"=nothing
- static final private int START=0; // x: set up for LEN
- static final private int LEN=1; // i: get length/literal/eob next
- static final private int LENEXT=2; // i: getting length extra (have base)
- static final private int DIST=3; // i: get distance next
- static final private int DISTEXT=4;// i: getting distance extra
- static final private int COPY=5; // o: copying bytes in window, waiting for space
- static final private int LIT=6; // o: got literal, waiting for output space
- static final private int WASH=7; // o: got eob, possibly still output waiting
- static final private int END=8; // x: got eob and all data flushed
- static final private int BADCODE=9;// x: got error
-
- int mode; // current inflate_codes mode
-
- // mode dependent information
- int len;
-
- int[] tree; // pointer into tree
- int tree_index=0;
- int need; // bits needed
-
- int lit;
-
- // if EXT or COPY, where and how much
- int get; // bits to get for extra
- int dist; // distance back to copy from
-
- byte lbits; // ltree bits decoded per branch
- byte dbits; // dtree bits decoder per branch
- int[] ltree; // literal/length/eob tree
- int ltree_index; // literal/length/eob tree
- int[] dtree; // distance tree
- int dtree_index; // distance tree
-
- InfCodes(){
- }
- void init(int bl, int bd,
- int[] tl, int tl_index,
- int[] td, int td_index, ZStream z){
- mode=START;
- lbits=(byte)bl;
- dbits=(byte)bd;
- ltree=tl;
- ltree_index=tl_index;
- dtree = td;
- dtree_index=td_index;
- tree=null;
- }
-
- int proc(InfBlocks s, ZStream z, int r){
- int j; // temporary storage
- int[] t; // temporary pointer
- int tindex; // temporary pointer
- int e; // extra bits or operation
- int b=0; // bit buffer
- int k=0; // bits in bit buffer
- int p=0; // input data pointer
- int n; // bytes available there
- int q; // output window write pointer
- int m; // bytes to end of window or read pointer
- int f; // pointer to copy strings from
-
- // copy input/output information to locals (UPDATE macro restores)
- p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
- q=s.write;m=q= 258 && n >= 10){
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
- r = inflate_fast(lbits, dbits,
- ltree, ltree_index,
- dtree, dtree_index,
- s, z);
-
- p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
- q=s.write;m=q>>=(tree[tindex+1]);
- k-=(tree[tindex+1]);
-
- e=tree[tindex];
-
- if(e == 0){ // literal
- lit = tree[tindex+2];
- mode = LIT;
- break;
- }
- if((e & 16)!=0 ){ // length
- get = e & 15;
- len = tree[tindex+2];
- mode = LENEXT;
- break;
- }
- if ((e & 64) == 0){ // next table
- need = e;
- tree_index = tindex/3+tree[tindex+2];
- break;
- }
- if ((e & 32)!=0){ // end of block
- mode = WASH;
- break;
- }
- mode = BADCODE; // invalid code
- z.msg = "invalid literal/length code";
- r = Z_DATA_ERROR;
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
- return s.inflate_flush(z,r);
-
- case LENEXT: // i: getting length extra (have base)
- j = get;
-
- while(k<(j)){
- if(n!=0)r=Z_OK;
- else{
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
- return s.inflate_flush(z,r);
- }
- n--; b|=(z.next_in[p++]&0xff)<>=j;
- k-=j;
-
- need = dbits;
- tree = dtree;
- tree_index=dtree_index;
- mode = DIST;
- case DIST: // i: get distance next
- j = need;
-
- while(k<(j)){
- if(n!=0)r=Z_OK;
- else{
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
- return s.inflate_flush(z,r);
- }
- n--; b|=(z.next_in[p++]&0xff)<>=tree[tindex+1];
- k-=tree[tindex+1];
-
- e = (tree[tindex]);
- if((e & 16)!=0){ // distance
- get = e & 15;
- dist = tree[tindex+2];
- mode = DISTEXT;
- break;
- }
- if ((e & 64) == 0){ // next table
- need = e;
- tree_index = tindex/3 + tree[tindex+2];
- break;
- }
- mode = BADCODE; // invalid code
- z.msg = "invalid distance code";
- r = Z_DATA_ERROR;
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
- return s.inflate_flush(z,r);
-
- case DISTEXT: // i: getting distance extra
- j = get;
-
- while(k<(j)){
- if(n!=0)r=Z_OK;
- else{
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
- return s.inflate_flush(z,r);
- }
- n--; b|=(z.next_in[p++]&0xff)<>=j;
- k-=j;
-
- mode = COPY;
- case COPY: // o: copying bytes in window, waiting for space
- f = q - dist;
- while(f < 0){ // modulo window size-"while" instead
- f += s.end; // of "if" handles invalid distances
- }
- while (len!=0){
-
- if(m==0){
- if(q==s.end&&s.read!=0){q=0;m=q 7){ // return unused byte, if any
- k -= 8;
- n++;
- p--; // can always return one
- }
-
- s.write=q; r=s.inflate_flush(z,r);
- q=s.write;m=q= 258 && n >= 10
- // get literal/length code
- while(k<(20)){ // max bits for literal/length code
- n--;
- b|=(z.next_in[p++]&0xff)<>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
-
- s.window[q++] = (byte)tp[tp_index_t_3+2];
- m--;
- continue;
- }
- do {
-
- b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
-
- if((e&16)!=0){
- e &= 15;
- c = tp[tp_index_t_3+2] + ((int)b & inflate_mask[e]);
-
- b>>=e; k-=e;
-
- // decode distance base of block to copy
- while(k<(15)){ // max bits for distance code
- n--;
- b|=(z.next_in[p++]&0xff)<>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
-
- if((e&16)!=0){
- // get extra bits to add to distance base
- e &= 15;
- while(k<(e)){ // get extra bits (up to 13)
- n--;
- b|=(z.next_in[p++]&0xff)<>=(e); k-=(e);
-
- // do the copy
- m -= c;
- if (q >= d){ // offset before dest
- // just copy
- r=q-d;
- if(q-r>0 && 2>(q-r)){
- s.window[q++]=s.window[r++]; // minimum count is three,
- s.window[q++]=s.window[r++]; // so unroll loop a little
- c-=2;
- }
- else{
- System.arraycopy(s.window, r, s.window, q, 2);
- q+=2; r+=2; c-=2;
- }
- }
- else{ // else offset after destination
- r=q-d;
- do{
- r+=s.end; // force pointer in window
- }while(r<0); // covers invalid distances
- e=s.end-r;
- if(c>e){ // if source crosses,
- c-=e; // wrapped copy
- if(q-r>0 && e>(q-r)){
- do{s.window[q++] = s.window[r++];}
- while(--e!=0);
- }
- else{
- System.arraycopy(s.window, r, s.window, q, e);
- q+=e; r+=e; e=0;
- }
- r = 0; // copy rest from start of window
- }
-
- }
-
- // copy all or what's left
- if(q-r>0 && c>(q-r)){
- do{s.window[q++] = s.window[r++];}
- while(--c!=0);
- }
- else{
- System.arraycopy(s.window, r, s.window, q, c);
- q+=c; r+=c; c=0;
- }
- break;
- }
- else if((e&64)==0){
- t+=tp[tp_index_t_3+2];
- t+=(b&inflate_mask[e]);
- tp_index_t_3=(tp_index+t)*3;
- e=tp[tp_index_t_3];
- }
- else{
- z.msg = "invalid distance code";
-
- c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
-
- return Z_DATA_ERROR;
- }
- }
- while(true);
- break;
- }
-
- if((e&64)==0){
- t+=tp[tp_index_t_3+2];
- t+=(b&inflate_mask[e]);
- tp_index_t_3=(tp_index+t)*3;
- if((e=tp[tp_index_t_3])==0){
-
- b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
-
- s.window[q++]=(byte)tp[tp_index_t_3+2];
- m--;
- break;
- }
- }
- else if((e&32)!=0){
-
- c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
-
- return Z_STREAM_END;
- }
- else{
- z.msg="invalid literal/length code";
-
- c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
-
- return Z_DATA_ERROR;
- }
- }
- while(true);
- }
- while(m>=258 && n>= 10);
-
- // not enough input or output--restore pointers and return
- c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
-
- s.bitb=b;s.bitk=k;
- z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
- s.write=q;
-
- return Z_OK;
- }
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/InfTree.java b/app/src/main/java/com/jcraft/jzlib/InfTree.java
deleted file mode 100644
index cbca43667a..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/InfTree.java
+++ /dev/null
@@ -1,520 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-final class InfTree{
-
- static final private int MANY=1440;
-
- static final private int Z_OK=0;
- static final private int Z_STREAM_END=1;
- static final private int Z_NEED_DICT=2;
- static final private int Z_ERRNO=-1;
- static final private int Z_STREAM_ERROR=-2;
- static final private int Z_DATA_ERROR=-3;
- static final private int Z_MEM_ERROR=-4;
- static final private int Z_BUF_ERROR=-5;
- static final private int Z_VERSION_ERROR=-6;
-
- static final int fixed_bl = 9;
- static final int fixed_bd = 5;
-
- static final int[] fixed_tl = {
- 96,7,256, 0,8,80, 0,8,16, 84,8,115,
- 82,7,31, 0,8,112, 0,8,48, 0,9,192,
- 80,7,10, 0,8,96, 0,8,32, 0,9,160,
- 0,8,0, 0,8,128, 0,8,64, 0,9,224,
- 80,7,6, 0,8,88, 0,8,24, 0,9,144,
- 83,7,59, 0,8,120, 0,8,56, 0,9,208,
- 81,7,17, 0,8,104, 0,8,40, 0,9,176,
- 0,8,8, 0,8,136, 0,8,72, 0,9,240,
- 80,7,4, 0,8,84, 0,8,20, 85,8,227,
- 83,7,43, 0,8,116, 0,8,52, 0,9,200,
- 81,7,13, 0,8,100, 0,8,36, 0,9,168,
- 0,8,4, 0,8,132, 0,8,68, 0,9,232,
- 80,7,8, 0,8,92, 0,8,28, 0,9,152,
- 84,7,83, 0,8,124, 0,8,60, 0,9,216,
- 82,7,23, 0,8,108, 0,8,44, 0,9,184,
- 0,8,12, 0,8,140, 0,8,76, 0,9,248,
- 80,7,3, 0,8,82, 0,8,18, 85,8,163,
- 83,7,35, 0,8,114, 0,8,50, 0,9,196,
- 81,7,11, 0,8,98, 0,8,34, 0,9,164,
- 0,8,2, 0,8,130, 0,8,66, 0,9,228,
- 80,7,7, 0,8,90, 0,8,26, 0,9,148,
- 84,7,67, 0,8,122, 0,8,58, 0,9,212,
- 82,7,19, 0,8,106, 0,8,42, 0,9,180,
- 0,8,10, 0,8,138, 0,8,74, 0,9,244,
- 80,7,5, 0,8,86, 0,8,22, 192,8,0,
- 83,7,51, 0,8,118, 0,8,54, 0,9,204,
- 81,7,15, 0,8,102, 0,8,38, 0,9,172,
- 0,8,6, 0,8,134, 0,8,70, 0,9,236,
- 80,7,9, 0,8,94, 0,8,30, 0,9,156,
- 84,7,99, 0,8,126, 0,8,62, 0,9,220,
- 82,7,27, 0,8,110, 0,8,46, 0,9,188,
- 0,8,14, 0,8,142, 0,8,78, 0,9,252,
- 96,7,256, 0,8,81, 0,8,17, 85,8,131,
- 82,7,31, 0,8,113, 0,8,49, 0,9,194,
- 80,7,10, 0,8,97, 0,8,33, 0,9,162,
- 0,8,1, 0,8,129, 0,8,65, 0,9,226,
- 80,7,6, 0,8,89, 0,8,25, 0,9,146,
- 83,7,59, 0,8,121, 0,8,57, 0,9,210,
- 81,7,17, 0,8,105, 0,8,41, 0,9,178,
- 0,8,9, 0,8,137, 0,8,73, 0,9,242,
- 80,7,4, 0,8,85, 0,8,21, 80,8,258,
- 83,7,43, 0,8,117, 0,8,53, 0,9,202,
- 81,7,13, 0,8,101, 0,8,37, 0,9,170,
- 0,8,5, 0,8,133, 0,8,69, 0,9,234,
- 80,7,8, 0,8,93, 0,8,29, 0,9,154,
- 84,7,83, 0,8,125, 0,8,61, 0,9,218,
- 82,7,23, 0,8,109, 0,8,45, 0,9,186,
- 0,8,13, 0,8,141, 0,8,77, 0,9,250,
- 80,7,3, 0,8,83, 0,8,19, 85,8,195,
- 83,7,35, 0,8,115, 0,8,51, 0,9,198,
- 81,7,11, 0,8,99, 0,8,35, 0,9,166,
- 0,8,3, 0,8,131, 0,8,67, 0,9,230,
- 80,7,7, 0,8,91, 0,8,27, 0,9,150,
- 84,7,67, 0,8,123, 0,8,59, 0,9,214,
- 82,7,19, 0,8,107, 0,8,43, 0,9,182,
- 0,8,11, 0,8,139, 0,8,75, 0,9,246,
- 80,7,5, 0,8,87, 0,8,23, 192,8,0,
- 83,7,51, 0,8,119, 0,8,55, 0,9,206,
- 81,7,15, 0,8,103, 0,8,39, 0,9,174,
- 0,8,7, 0,8,135, 0,8,71, 0,9,238,
- 80,7,9, 0,8,95, 0,8,31, 0,9,158,
- 84,7,99, 0,8,127, 0,8,63, 0,9,222,
- 82,7,27, 0,8,111, 0,8,47, 0,9,190,
- 0,8,15, 0,8,143, 0,8,79, 0,9,254,
- 96,7,256, 0,8,80, 0,8,16, 84,8,115,
- 82,7,31, 0,8,112, 0,8,48, 0,9,193,
-
- 80,7,10, 0,8,96, 0,8,32, 0,9,161,
- 0,8,0, 0,8,128, 0,8,64, 0,9,225,
- 80,7,6, 0,8,88, 0,8,24, 0,9,145,
- 83,7,59, 0,8,120, 0,8,56, 0,9,209,
- 81,7,17, 0,8,104, 0,8,40, 0,9,177,
- 0,8,8, 0,8,136, 0,8,72, 0,9,241,
- 80,7,4, 0,8,84, 0,8,20, 85,8,227,
- 83,7,43, 0,8,116, 0,8,52, 0,9,201,
- 81,7,13, 0,8,100, 0,8,36, 0,9,169,
- 0,8,4, 0,8,132, 0,8,68, 0,9,233,
- 80,7,8, 0,8,92, 0,8,28, 0,9,153,
- 84,7,83, 0,8,124, 0,8,60, 0,9,217,
- 82,7,23, 0,8,108, 0,8,44, 0,9,185,
- 0,8,12, 0,8,140, 0,8,76, 0,9,249,
- 80,7,3, 0,8,82, 0,8,18, 85,8,163,
- 83,7,35, 0,8,114, 0,8,50, 0,9,197,
- 81,7,11, 0,8,98, 0,8,34, 0,9,165,
- 0,8,2, 0,8,130, 0,8,66, 0,9,229,
- 80,7,7, 0,8,90, 0,8,26, 0,9,149,
- 84,7,67, 0,8,122, 0,8,58, 0,9,213,
- 82,7,19, 0,8,106, 0,8,42, 0,9,181,
- 0,8,10, 0,8,138, 0,8,74, 0,9,245,
- 80,7,5, 0,8,86, 0,8,22, 192,8,0,
- 83,7,51, 0,8,118, 0,8,54, 0,9,205,
- 81,7,15, 0,8,102, 0,8,38, 0,9,173,
- 0,8,6, 0,8,134, 0,8,70, 0,9,237,
- 80,7,9, 0,8,94, 0,8,30, 0,9,157,
- 84,7,99, 0,8,126, 0,8,62, 0,9,221,
- 82,7,27, 0,8,110, 0,8,46, 0,9,189,
- 0,8,14, 0,8,142, 0,8,78, 0,9,253,
- 96,7,256, 0,8,81, 0,8,17, 85,8,131,
- 82,7,31, 0,8,113, 0,8,49, 0,9,195,
- 80,7,10, 0,8,97, 0,8,33, 0,9,163,
- 0,8,1, 0,8,129, 0,8,65, 0,9,227,
- 80,7,6, 0,8,89, 0,8,25, 0,9,147,
- 83,7,59, 0,8,121, 0,8,57, 0,9,211,
- 81,7,17, 0,8,105, 0,8,41, 0,9,179,
- 0,8,9, 0,8,137, 0,8,73, 0,9,243,
- 80,7,4, 0,8,85, 0,8,21, 80,8,258,
- 83,7,43, 0,8,117, 0,8,53, 0,9,203,
- 81,7,13, 0,8,101, 0,8,37, 0,9,171,
- 0,8,5, 0,8,133, 0,8,69, 0,9,235,
- 80,7,8, 0,8,93, 0,8,29, 0,9,155,
- 84,7,83, 0,8,125, 0,8,61, 0,9,219,
- 82,7,23, 0,8,109, 0,8,45, 0,9,187,
- 0,8,13, 0,8,141, 0,8,77, 0,9,251,
- 80,7,3, 0,8,83, 0,8,19, 85,8,195,
- 83,7,35, 0,8,115, 0,8,51, 0,9,199,
- 81,7,11, 0,8,99, 0,8,35, 0,9,167,
- 0,8,3, 0,8,131, 0,8,67, 0,9,231,
- 80,7,7, 0,8,91, 0,8,27, 0,9,151,
- 84,7,67, 0,8,123, 0,8,59, 0,9,215,
- 82,7,19, 0,8,107, 0,8,43, 0,9,183,
- 0,8,11, 0,8,139, 0,8,75, 0,9,247,
- 80,7,5, 0,8,87, 0,8,23, 192,8,0,
- 83,7,51, 0,8,119, 0,8,55, 0,9,207,
- 81,7,15, 0,8,103, 0,8,39, 0,9,175,
- 0,8,7, 0,8,135, 0,8,71, 0,9,239,
- 80,7,9, 0,8,95, 0,8,31, 0,9,159,
- 84,7,99, 0,8,127, 0,8,63, 0,9,223,
- 82,7,27, 0,8,111, 0,8,47, 0,9,191,
- 0,8,15, 0,8,143, 0,8,79, 0,9,255
- };
- static final int[] fixed_td = {
- 80,5,1, 87,5,257, 83,5,17, 91,5,4097,
- 81,5,5, 89,5,1025, 85,5,65, 93,5,16385,
- 80,5,3, 88,5,513, 84,5,33, 92,5,8193,
- 82,5,9, 90,5,2049, 86,5,129, 192,5,24577,
- 80,5,2, 87,5,385, 83,5,25, 91,5,6145,
- 81,5,7, 89,5,1537, 85,5,97, 93,5,24577,
- 80,5,4, 88,5,769, 84,5,49, 92,5,12289,
- 82,5,13, 90,5,3073, 86,5,193, 192,5,24577
- };
-
- // Tables for deflate from PKZIP's appnote.txt.
- static final int[] cplens = { // Copy lengths for literal codes 257..285
- 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
- 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
- };
-
- // see note #13 above about 258
- static final int[] cplext = { // Extra bits for literal codes 257..285
- 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
- 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid
- };
-
- static final int[] cpdist = { // Copy offsets for distance codes 0..29
- 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
- 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
- 8193, 12289, 16385, 24577
- };
-
- static final int[] cpdext = { // Extra bits for distance codes
- 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
- 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
- 12, 12, 13, 13};
-
- // If BMAX needs to be larger than 16, then h and x[] should be uLong.
- static final int BMAX=15; // maximum bit length of any code
-
- int[] hn = null; // hufts used in space
- int[] v = null; // work area for huft_build
- int[] c = null; // bit length count table
- int[] r = null; // table entry for structure assignment
- int[] u = null; // table stack
- int[] x = null; // bit offsets, then code stack
-
- private int huft_build(int[] b, // code lengths in bits (all assumed <= BMAX)
- int bindex,
- int n, // number of codes (assumed <= 288)
- int s, // number of simple-valued codes (0..s-1)
- int[] d, // list of base values for non-simple codes
- int[] e, // list of extra bits for non-simple codes
- int[] t, // result: starting table
- int[] m, // maximum lookup bits, returns actual
- int[] hp,// space for trees
- int[] hn,// hufts used in space
- int[] v // working area: values in order of bit length
- ){
- // Given a list of code lengths and a maximum table size, make a set of
- // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
- // if the given code set is incomplete (the tables are still built in this
- // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
- // lengths), or Z_MEM_ERROR if not enough memory.
-
- int a; // counter for codes of length k
- int f; // i repeats in table every f entries
- int g; // maximum code length
- int h; // table level
- int i; // counter, current code
- int j; // counter
- int k; // number of bits in current code
- int l; // bits per table (returned in m)
- int mask; // (1 << w) - 1, to avoid cc -O bug on HP
- int p; // pointer into c[], b[], or v[]
- int q; // points to current table
- int w; // bits before this table == (l * h)
- int xp; // pointer into x
- int y; // number of dummy codes added
- int z; // number of entries in current table
-
- // Generate counts for each bit length
-
- p = 0; i = n;
- do {
- c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX
- }while(i!=0);
-
- if(c[0] == n){ // null input--all zero length codes
- t[0] = -1;
- m[0] = 0;
- return Z_OK;
- }
-
- // Find minimum and maximum length, bound *m by those
- l = m[0];
- for (j = 1; j <= BMAX; j++)
- if(c[j]!=0) break;
- k = j; // minimum code length
- if(l < j){
- l = j;
- }
- for (i = BMAX; i!=0; i--){
- if(c[i]!=0) break;
- }
- g = i; // maximum code length
- if(l > i){
- l = i;
- }
- m[0] = l;
-
- // Adjust last length count to fill out codes, if needed
- for (y = 1 << j; j < i; j++, y <<= 1){
- if ((y -= c[j]) < 0){
- return Z_DATA_ERROR;
- }
- }
- if ((y -= c[i]) < 0){
- return Z_DATA_ERROR;
- }
- c[i] += y;
-
- // Generate starting offsets into the value table for each length
- x[1] = j = 0;
- p = 1; xp = 2;
- while (--i!=0) { // note that i == g from above
- x[xp] = (j += c[p]);
- xp++;
- p++;
- }
-
- // Make a table of values in order of bit lengths
- i = 0; p = 0;
- do {
- if ((j = b[bindex+p]) != 0){
- v[x[j]++] = i;
- }
- p++;
- }
- while (++i < n);
- n = x[g]; // set n to length of v
-
- // Generate the Huffman codes and for each, make the table entries
- x[0] = i = 0; // first Huffman code is zero
- p = 0; // grab values in bit order
- h = -1; // no tables yet--level -1
- w = -l; // bits decoded == (l * h)
- u[0] = 0; // just to keep compilers happy
- q = 0; // ditto
- z = 0; // ditto
-
- // go through the bit lengths (k already is bits in shortest code)
- for (; k <= g; k++){
- a = c[k];
- while (a--!=0){
- // here i is the Huffman code of length k bits for value *p
- // make tables up to required level
- while (k > w + l){
- h++;
- w += l; // previous table always l bits
- // compute minimum size table less than or equal to l bits
- z = g - w;
- z = (z > l) ? l : z; // table size upper limit
- if((f=1<<(j=k-w))>a+1){ // try a k-w bit table
- // too few codes for k-w bit table
- f -= a + 1; // deduct codes from patterns left
- xp = k;
- if(j < z){
- while (++j < z){ // try smaller tables up to z bits
- if((f <<= 1) <= c[++xp])
- break; // enough codes to use up j bits
- f -= c[xp]; // else deduct codes from patterns
- }
- }
- }
- z = 1 << j; // table entries for j-bit table
-
- // allocate new table
- if (hn[0] + z > MANY){ // (note: doesn't matter for fixed)
- return Z_DATA_ERROR; // overflow of MANY
- }
- u[h] = q = /*hp+*/ hn[0]; // DEBUG
- hn[0] += z;
-
- // connect to last table, if there is one
- if(h!=0){
- x[h]=i; // save pattern for backing up
- r[0]=(byte)j; // bits in this table
- r[1]=(byte)l; // bits to dump before this table
- j=i>>>(w - l);
- r[2] = (int)(q - u[h-1] - j); // offset to this table
- System.arraycopy(r, 0, hp, (u[h-1]+j)*3, 3); // connect to last table
- }
- else{
- t[0] = q; // first table is returned result
- }
- }
-
- // set up table entry in r
- r[1] = (byte)(k - w);
- if (p >= n){
- r[0] = 128 + 64; // out of values--invalid code
- }
- else if (v[p] < s){
- r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block
- r[2] = v[p++]; // simple code is just the value
- }
- else{
- r[0]=(byte)(e[v[p]-s]+16+64); // non-simple--look up in lists
- r[2]=d[v[p++] - s];
- }
-
- // fill code-like entries with r
- f=1<<(k-w);
- for (j=i>>>w;j>>= 1){
- i ^= j;
- }
- i ^= j;
-
- // backup over finished tables
- mask = (1 << w) - 1; // needed on HP, cc -O bug
- while ((i & mask) != x[h]){
- h--; // don't need to update q
- w -= l;
- mask = (1 << w) - 1;
- }
- }
- }
- // Return Z_BUF_ERROR if we were given an incomplete table
- return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
- }
-
- int inflate_trees_bits(int[] c, // 19 code lengths
- int[] bb, // bits tree desired/actual depth
- int[] tb, // bits tree result
- int[] hp, // space for trees
- ZStream z // for messages
- ){
- int result;
- initWorkArea(19);
- hn[0]=0;
- result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
-
- if(result == Z_DATA_ERROR){
- z.msg = "oversubscribed dynamic bit lengths tree";
- }
- else if(result == Z_BUF_ERROR || bb[0] == 0){
- z.msg = "incomplete dynamic bit lengths tree";
- result = Z_DATA_ERROR;
- }
- return result;
- }
-
- int inflate_trees_dynamic(int nl, // number of literal/length codes
- int nd, // number of distance codes
- int[] c, // that many (total) code lengths
- int[] bl, // literal desired/actual bit depth
- int[] bd, // distance desired/actual bit depth
- int[] tl, // literal/length tree result
- int[] td, // distance tree result
- int[] hp, // space for trees
- ZStream z // for messages
- ){
- int result;
-
- // build literal/length tree
- initWorkArea(288);
- hn[0]=0;
- result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
- if (result != Z_OK || bl[0] == 0){
- if(result == Z_DATA_ERROR){
- z.msg = "oversubscribed literal/length tree";
- }
- else if (result != Z_MEM_ERROR){
- z.msg = "incomplete literal/length tree";
- result = Z_DATA_ERROR;
- }
- return result;
- }
-
- // build distance tree
- initWorkArea(288);
- result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
-
- if (result != Z_OK || (bd[0] == 0 && nl > 257)){
- if (result == Z_DATA_ERROR){
- z.msg = "oversubscribed distance tree";
- }
- else if (result == Z_BUF_ERROR) {
- z.msg = "incomplete distance tree";
- result = Z_DATA_ERROR;
- }
- else if (result != Z_MEM_ERROR){
- z.msg = "empty distance tree with lengths";
- result = Z_DATA_ERROR;
- }
- return result;
- }
-
- return Z_OK;
- }
-
- static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth
- int[] bd, //distance desired/actual bit depth
- int[][] tl,//literal/length tree result
- int[][] td,//distance tree result
- ZStream z //for memory allocation
- ){
- bl[0]=fixed_bl;
- bd[0]=fixed_bd;
- tl[0]=fixed_tl;
- td[0]=fixed_td;
- return Z_OK;
- }
-
- private void initWorkArea(int vsize){
- if(hn==null){
- hn=new int[1];
- v=new int[vsize];
- c=new int[BMAX+1];
- r=new int[3];
- u=new int[BMAX];
- x=new int[BMAX+1];
- }
- if(v.lengthstate);
- return Z_OK;
- }
-
- int inflateInit(ZStream z, int w){
- z.msg = null;
- blocks = null;
-
- // handle undocumented nowrap option (no zlib header or check)
- nowrap = 0;
- if(w < 0){
- w = - w;
- nowrap = 1;
- }
-
- // set window size
- if(w<8 ||w>15){
- inflateEnd(z);
- return Z_STREAM_ERROR;
- }
- wbits=w;
-
- z.istate.blocks=new InfBlocks(z,
- z.istate.nowrap!=0 ? null : this,
- 1<>4)+8>z.istate.wbits){
- z.istate.mode = BAD;
- z.msg="invalid window size";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
- z.istate.mode=FLAG;
- case FLAG:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- b = (z.next_in[z.next_in_index++])&0xff;
-
- if((((z.istate.method << 8)+b) % 31)!=0){
- z.istate.mode = BAD;
- z.msg = "incorrect header check";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
-
- if((b&PRESET_DICT)==0){
- z.istate.mode = BLOCKS;
- break;
- }
- z.istate.mode = DICT4;
- case DICT4:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
- z.istate.mode=DICT3;
- case DICT3:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
- z.istate.mode=DICT2;
- case DICT2:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
- z.istate.mode=DICT1;
- case DICT1:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (z.next_in[z.next_in_index++]&0xffL);
- z.adler = z.istate.need;
- z.istate.mode = DICT0;
- return Z_NEED_DICT;
- case DICT0:
- z.istate.mode = BAD;
- z.msg = "need dictionary";
- z.istate.marker = 0; // can try inflateSync
- return Z_STREAM_ERROR;
- case BLOCKS:
-
- r = z.istate.blocks.proc(z, r);
- if(r == Z_DATA_ERROR){
- z.istate.mode = BAD;
- z.istate.marker = 0; // can try inflateSync
- break;
- }
- if(r == Z_OK){
- r = f;
- }
- if(r != Z_STREAM_END){
- return r;
- }
- r = f;
- z.istate.blocks.reset(z, z.istate.was);
- if(z.istate.nowrap!=0){
- z.istate.mode=DONE;
- break;
- }
- z.istate.mode=CHECK4;
- case CHECK4:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
- z.istate.mode=CHECK3;
- case CHECK3:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
- z.istate.mode = CHECK2;
- case CHECK2:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
- z.istate.mode = CHECK1;
- case CHECK1:
-
- if(z.avail_in==0)return r;r=f;
-
- z.avail_in--; z.total_in++;
- z.istate.need+=(z.next_in[z.next_in_index++]&0xffL);
-
- if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){
- z.istate.mode = BAD;
- z.msg = "incorrect data check";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
-
- z.istate.mode = DONE;
- case DONE:
- return Z_STREAM_END;
- case BAD:
- return Z_DATA_ERROR;
- default:
- return Z_STREAM_ERROR;
- }
- }
- }
-
-
- int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){
- int index=0;
- int length = dictLength;
- if(z==null || z.istate == null|| z.istate.mode != DICT0)
- return Z_STREAM_ERROR;
-
- if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){
- return Z_DATA_ERROR;
- }
-
- z.adler = z._adler.adler32(0, null, 0, 0);
-
- if(length >= (1<>>7)]);
- }
-
- short[] dyn_tree; // the dynamic tree
- int max_code; // largest code with non zero frequency
- StaticTree stat_desc; // the corresponding static tree
-
- // Compute the optimal bit lengths for a tree and update the total bit length
- // for the current block.
- // IN assertion: the fields freq and dad are set, heap[heap_max] and
- // above are the tree nodes sorted by increasing frequency.
- // OUT assertions: the field len is set to the optimal bit length, the
- // array bl_count contains the frequencies for each bit length.
- // The length opt_len is updated; static_len is also updated if stree is
- // not null.
- void gen_bitlen(Deflate s){
- short[] tree = dyn_tree;
- short[] stree = stat_desc.static_tree;
- int[] extra = stat_desc.extra_bits;
- int base = stat_desc.extra_base;
- int max_length = stat_desc.max_length;
- int h; // heap index
- int n, m; // iterate over the tree elements
- int bits; // bit length
- int xbits; // extra bits
- short f; // frequency
- int overflow = 0; // number of elements with bit length too large
-
- for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
-
- // In a first pass, compute the optimal bit lengths (which may
- // overflow in the case of the bit length tree).
- tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
-
- for(h=s.heap_max+1; h max_length){ bits = max_length; overflow++; }
- tree[n*2+1] = (short)bits;
- // We overwrite tree[n*2+1] which is no longer needed
-
- if (n > max_code) continue; // not a leaf node
-
- s.bl_count[bits]++;
- xbits = 0;
- if (n >= base) xbits = extra[n-base];
- f = tree[n*2];
- s.opt_len += f * (bits + xbits);
- if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
- }
- if (overflow == 0) return;
-
- // This happens for example on obj2 and pic of the Calgary corpus
- // Find the first bit length which could increase:
- do {
- bits = max_length-1;
- while(s.bl_count[bits]==0) bits--;
- s.bl_count[bits]--; // move one leaf down the tree
- s.bl_count[bits+1]+=2; // move one overflow item as its brother
- s.bl_count[max_length]--;
- // The brother of the overflow item also moves one step up,
- // but this does not affect bl_count[max_length]
- overflow -= 2;
- }
- while (overflow > 0);
-
- for (bits = max_length; bits != 0; bits--) {
- n = s.bl_count[bits];
- while (n != 0) {
- m = s.heap[--h];
- if (m > max_code) continue;
- if (tree[m*2+1] != bits) {
- s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
- tree[m*2+1] = (short)bits;
- }
- n--;
- }
- }
- }
-
- // Construct one Huffman tree and assigns the code bit strings and lengths.
- // Update the total bit length for the current block.
- // IN assertion: the field freq is set for all tree elements.
- // OUT assertions: the fields len and code are set to the optimal bit length
- // and corresponding code. The length opt_len is updated; static_len is
- // also updated if stree is not null. The field max_code is set.
- void build_tree(Deflate s){
- short[] tree=dyn_tree;
- short[] stree=stat_desc.static_tree;
- int elems=stat_desc.elems;
- int n, m; // iterate over heap elements
- int max_code=-1; // largest code with non zero frequency
- int node; // new node being created
-
- // Construct the initial heap, with least frequent element in
- // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
- // heap[0] is not used.
- s.heap_len = 0;
- s.heap_max = HEAP_SIZE;
-
- for(n=0; n=1; n--)
- s.pqdownheap(tree, n);
-
- // Construct the Huffman tree by repeatedly combining the least two
- // frequent nodes.
-
- node=elems; // next internal node of the tree
- do{
- // n = node of least frequency
- n=s.heap[1];
- s.heap[1]=s.heap[s.heap_len--];
- s.pqdownheap(tree, 1);
- m=s.heap[1]; // m = node of next least frequency
-
- s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
- s.heap[--s.heap_max] = m;
-
- // Create a new node father of n and m
- tree[node*2] = (short)(tree[n*2] + tree[m*2]);
- s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
- tree[n*2+1] = tree[m*2+1] = (short)node;
-
- // and insert the new node in the heap
- s.heap[1] = node++;
- s.pqdownheap(tree, 1);
- }
- while(s.heap_len>=2);
-
- s.heap[--s.heap_max] = s.heap[1];
-
- // At this point, the fields freq and dad are set. We can now
- // generate the bit lengths.
-
- gen_bitlen(s);
-
- // The field len is now set, we can generate the bit codes
- gen_codes(tree, max_code, s.bl_count);
- }
-
- // Generate the codes for a given tree and bit counts (which need not be
- // optimal).
- // IN assertion: the array bl_count contains the bit length statistics for
- // the given tree and the field len is set for all tree elements.
- // OUT assertion: the field code is set for all tree elements of non
- // zero code length.
- static void gen_codes(short[] tree, // the tree to decorate
- int max_code, // largest code with non zero frequency
- short[] bl_count // number of codes at each bit length
- ){
- short[] next_code=new short[MAX_BITS+1]; // next code value for each bit length
- short code = 0; // running code value
- int bits; // bit index
- int n; // code index
-
- // The distribution counts are first used to generate the code values
- // without bit reversal.
- for (bits = 1; bits <= MAX_BITS; bits++) {
- next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
- }
-
- // Check that the bit counts in bl_count are consistent. The last code
- // must be all ones.
- //Assert (code + bl_count[MAX_BITS]-1 == (1<>>=1;
- res<<=1;
- }
- while(--len>0);
- return res>>>1;
- }
-}
-
diff --git a/app/src/main/java/com/jcraft/jzlib/ZInputStream.java b/app/src/main/java/com/jcraft/jzlib/ZInputStream.java
deleted file mode 100644
index 3f97c4483b..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/ZInputStream.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
-/*
-Copyright (c) 2001 Lapo Luchini.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-import java.io.*;
-
-public class ZInputStream extends FilterInputStream {
-
- protected ZStream z=new ZStream();
- protected int bufsize=512;
- protected int flush=JZlib.Z_NO_FLUSH;
- protected byte[] buf=new byte[bufsize],
- buf1=new byte[1];
- protected boolean compress;
-
- protected InputStream in=null;
-
- public ZInputStream(InputStream in) {
- this(in, false);
- }
- public ZInputStream(InputStream in, boolean nowrap) {
- super(in);
- this.in=in;
- z.inflateInit(nowrap);
- compress=false;
- z.next_in=buf;
- z.next_in_index=0;
- z.avail_in=0;
- }
-
- public ZInputStream(InputStream in, int level) {
- super(in);
- this.in=in;
- z.deflateInit(level);
- compress=true;
- z.next_in=buf;
- z.next_in_index=0;
- z.avail_in=0;
- }
-
- /*public int available() throws IOException {
- return inf.finished() ? 0 : 1;
- }*/
-
- public int read() throws IOException {
- if(read(buf1, 0, 1)==-1)
- return(-1);
- return(buf1[0]&0xFF);
- }
-
- private boolean nomoreinput=false;
-
- public int read(byte[] b, int off, int len) throws IOException {
- if(len==0)
- return(0);
- int err;
- z.next_out=b;
- z.next_out_index=off;
- z.avail_out=len;
- do {
- if((z.avail_in==0)&&(!nomoreinput)) { // if buffer is empty and more input is avaiable, refill it
- z.next_in_index=0;
- z.avail_in=in.read(buf, 0, bufsize);//(bufsize0 || z.avail_out==0);
- }
-
- public int getFlushMode() {
- return(flush);
- }
-
- public void setFlushMode(int flush) {
- this.flush=flush;
- }
-
- public void finish() throws IOException {
- int err;
- do{
- z.next_out=buf;
- z.next_out_index=0;
- z.avail_out=bufsize;
- if(compress){ err=z.deflate(JZlib.Z_FINISH); }
- else{ err=z.inflate(JZlib.Z_FINISH); }
- if(err!=JZlib.Z_STREAM_END && err != JZlib.Z_OK)
- throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg);
- if(bufsize-z.avail_out>0){
- out.write(buf, 0, bufsize-z.avail_out);
- }
- }
- while(z.avail_in>0 || z.avail_out==0);
- flush();
- }
- public void end() {
- if(z==null)
- return;
- if(compress){ z.deflateEnd(); }
- else{ z.inflateEnd(); }
- z.free();
- z=null;
- }
- public void close() throws IOException {
- try{
- try{finish();}
- catch (IOException ignored) {}
- }
- finally{
- end();
- out.close();
- out=null;
- }
- }
-
- /**
- * Returns the total number of bytes input so far.
- */
- public long getTotalIn() {
- return z.total_in;
- }
-
- /**
- * Returns the total number of bytes output so far.
- */
- public long getTotalOut() {
- return z.total_out;
- }
-
- public void flush() throws IOException {
- out.flush();
- }
-
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/ZStream.java b/app/src/main/java/com/jcraft/jzlib/ZStream.java
deleted file mode 100644
index 334475e987..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/ZStream.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-final public class ZStream{
-
- static final private int MAX_WBITS=15; // 32K LZ77 window
- static final private int DEF_WBITS=MAX_WBITS;
-
- static final private int Z_NO_FLUSH=0;
- static final private int Z_PARTIAL_FLUSH=1;
- static final private int Z_SYNC_FLUSH=2;
- static final private int Z_FULL_FLUSH=3;
- static final private int Z_FINISH=4;
-
- static final private int MAX_MEM_LEVEL=9;
-
- static final private int Z_OK=0;
- static final private int Z_STREAM_END=1;
- static final private int Z_NEED_DICT=2;
- static final private int Z_ERRNO=-1;
- static final private int Z_STREAM_ERROR=-2;
- static final private int Z_DATA_ERROR=-3;
- static final private int Z_MEM_ERROR=-4;
- static final private int Z_BUF_ERROR=-5;
- static final private int Z_VERSION_ERROR=-6;
-
- public byte[] next_in; // next input byte
- public int next_in_index;
- public int avail_in; // number of bytes available at next_in
- public long total_in; // total nb of input bytes read so far
-
- public byte[] next_out; // next output byte should be put there
- public int next_out_index;
- public int avail_out; // remaining free space at next_out
- public long total_out; // total nb of bytes output so far
-
- public String msg;
-
- Deflate dstate;
- Inflate istate;
-
- int data_type; // best guess about the data type: ascii or binary
-
- public long adler;
- Adler32 _adler=new Adler32();
-
- public int inflateInit(){
- return inflateInit(DEF_WBITS);
- }
- public int inflateInit(boolean nowrap){
- return inflateInit(DEF_WBITS, nowrap);
- }
- public int inflateInit(int w){
- return inflateInit(w, false);
- }
-
- public int inflateInit(int w, boolean nowrap){
- istate=new Inflate();
- return istate.inflateInit(this, nowrap?-w:w);
- }
-
- public int inflate(int f){
- if(istate==null) return Z_STREAM_ERROR;
- return istate.inflate(this, f);
- }
- public int inflateEnd(){
- if(istate==null) return Z_STREAM_ERROR;
- int ret=istate.inflateEnd(this);
- istate = null;
- return ret;
- }
- public int inflateSync(){
- if(istate == null)
- return Z_STREAM_ERROR;
- return istate.inflateSync(this);
- }
- public int inflateSetDictionary(byte[] dictionary, int dictLength){
- if(istate == null)
- return Z_STREAM_ERROR;
- return istate.inflateSetDictionary(this, dictionary, dictLength);
- }
-
- public int deflateInit(int level){
- return deflateInit(level, MAX_WBITS);
- }
- public int deflateInit(int level, boolean nowrap){
- return deflateInit(level, MAX_WBITS, nowrap);
- }
- public int deflateInit(int level, int bits){
- return deflateInit(level, bits, false);
- }
- public int deflateInit(int level, int bits, boolean nowrap){
- dstate=new Deflate();
- return dstate.deflateInit(this, level, nowrap?-bits:bits);
- }
- public int deflate(int flush){
- if(dstate==null){
- return Z_STREAM_ERROR;
- }
- return dstate.deflate(this, flush);
- }
- public int deflateEnd(){
- if(dstate==null) return Z_STREAM_ERROR;
- int ret=dstate.deflateEnd();
- dstate=null;
- return ret;
- }
- public int deflateParams(int level, int strategy){
- if(dstate==null) return Z_STREAM_ERROR;
- return dstate.deflateParams(this, level, strategy);
- }
- public int deflateSetDictionary (byte[] dictionary, int dictLength){
- if(dstate == null)
- return Z_STREAM_ERROR;
- return dstate.deflateSetDictionary(this, dictionary, dictLength);
- }
-
- // Flush as much pending output as possible. All deflate() output goes
- // through this function so some applications may wish to modify it
- // to avoid allocating a large strm->next_out buffer and copying into it.
- // (See also read_buf()).
- void flush_pending(){
- int len=dstate.pending;
-
- if(len>avail_out) len=avail_out;
- if(len==0) return;
-
- if(dstate.pending_buf.length<=dstate.pending_out ||
- next_out.length<=next_out_index ||
- dstate.pending_buf.length<(dstate.pending_out+len) ||
- next_out.length<(next_out_index+len)){
- System.out.println(dstate.pending_buf.length+", "+dstate.pending_out+
- ", "+next_out.length+", "+next_out_index+", "+len);
- System.out.println("avail_out="+avail_out);
- }
-
- System.arraycopy(dstate.pending_buf, dstate.pending_out,
- next_out, next_out_index, len);
-
- next_out_index+=len;
- dstate.pending_out+=len;
- total_out+=len;
- avail_out-=len;
- dstate.pending-=len;
- if(dstate.pending==0){
- dstate.pending_out=0;
- }
- }
-
- // Read a new buffer from the current input stream, update the adler32
- // and total number of bytes read. All deflate() input goes through
- // this function so some applications may wish to modify it to avoid
- // allocating a large strm->next_in buffer and copying from it.
- // (See also flush_pending()).
- int read_buf(byte[] buf, int start, int size) {
- int len=avail_in;
-
- if(len>size) len=size;
- if(len==0) return 0;
-
- avail_in-=len;
-
- if(dstate.noheader==0) {
- adler=_adler.adler32(adler, next_in, next_in_index, len);
- }
- System.arraycopy(next_in, next_in_index, buf, start, len);
- next_in_index += len;
- total_in += len;
- return len;
- }
-
- public void free(){
- next_in=null;
- next_out=null;
- msg=null;
- _adler=null;
- }
-}
diff --git a/app/src/main/java/com/jcraft/jzlib/ZStreamException.java b/app/src/main/java/com/jcraft/jzlib/ZStreamException.java
deleted file mode 100644
index 308bb8a1e5..0000000000
--- a/app/src/main/java/com/jcraft/jzlib/ZStreamException.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/* -*-mode:java; c-basic-offset:2; -*- */
-/*
-Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- 1. Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the distribution.
-
- 3. The names of the authors may not be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
-INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
-OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-/*
- * This program is based on zlib-1.1.3, so all credit should go authors
- * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
- * and contributors of zlib.
- */
-
-package com.jcraft.jzlib;
-
-public class ZStreamException extends java.io.IOException {
- public ZStreamException() {
- super();
- }
- public ZStreamException(String s) {
- super(s);
- }
-}
diff --git a/app/src/main/java/com/novell/sasl/client/DigestChallenge.java b/app/src/main/java/com/novell/sasl/client/DigestChallenge.java
index 90e6247ea9..6c2a5da774 100644
--- a/app/src/main/java/com/novell/sasl/client/DigestChallenge.java
+++ b/app/src/main/java/com/novell/sasl/client/DigestChallenge.java
@@ -15,41 +15,40 @@
package com.novell.sasl.client;
import java.util.*;
+
import org.apache.harmony.javax.security.sasl.*;
/**
* Implements the DigestChallenge class which will be used by the
* DigestMD5SaslClient class
*/
-class DigestChallenge extends Object
-{
- public static final int QOP_AUTH = 0x01;
- public static final int QOP_AUTH_INT = 0x02;
- public static final int QOP_AUTH_CONF = 0x04;
- public static final int QOP_UNRECOGNIZED = 0x08;
-
- private static final int CIPHER_3DES = 0x01;
- private static final int CIPHER_DES = 0x02;
- private static final int CIPHER_RC4_40 = 0x04;
- private static final int CIPHER_RC4 = 0x08;
- private static final int CIPHER_RC4_56 = 0x10;
- private static final int CIPHER_UNRECOGNIZED = 0x20;
+class DigestChallenge extends Object {
+ public static final int QOP_AUTH = 0x01;
+ public static final int QOP_AUTH_INT = 0x02;
+ public static final int QOP_AUTH_CONF = 0x04;
+ public static final int QOP_UNRECOGNIZED = 0x08;
+
+ private static final int CIPHER_3DES = 0x01;
+ private static final int CIPHER_DES = 0x02;
+ private static final int CIPHER_RC4_40 = 0x04;
+ private static final int CIPHER_RC4 = 0x08;
+ private static final int CIPHER_RC4_56 = 0x10;
+ private static final int CIPHER_UNRECOGNIZED = 0x20;
private static final int CIPHER_RECOGNIZED_MASK =
- CIPHER_3DES | CIPHER_DES | CIPHER_RC4_40 | CIPHER_RC4 | CIPHER_RC4_56;
+ CIPHER_3DES | CIPHER_DES | CIPHER_RC4_40 | CIPHER_RC4 | CIPHER_RC4_56;
private ArrayList m_realms;
- private String m_nonce;
- private int m_qop;
- private boolean m_staleFlag;
- private int m_maxBuf;
- private String m_characterSet;
- private String m_algorithm;
- private int m_cipherOptions;
+ private String m_nonce;
+ private int m_qop;
+ private boolean m_staleFlag;
+ private int m_maxBuf;
+ private String m_characterSet;
+ private String m_algorithm;
+ private int m_cipherOptions;
DigestChallenge(
- byte[] challenge)
- throws SaslException
- {
+ byte[] challenge)
+ throws SaslException {
m_realms = new ArrayList(5);
m_nonce = null;
m_qop = 0;
@@ -60,13 +59,10 @@ class DigestChallenge extends Object
m_cipherOptions = 0;
DirectiveList dirList = new DirectiveList(challenge);
- try
- {
+ try {
dirList.parseDirectives();
checkSemantics(dirList);
- }
- catch (SaslException e)
- {
+ } catch (SaslException e) {
}
}
@@ -74,69 +70,64 @@ class DigestChallenge extends Object
* Checks the semantics of the directives in the directive list as parsed
* from the digest challenge byte array.
*
- * @param dirList the list of directives parsed from the digest challenge
- *
- * @exception SaslException If a semantic error occurs
+ * @param dirList the list of directives parsed from the digest challenge
+ * @throws SaslException If a semantic error occurs
*/
void checkSemantics(
- DirectiveList dirList) throws SaslException
- {
- Iterator directives = dirList.getIterator();
- ParsedDirective directive;
- String name;
-
- while (directives.hasNext())
- {
- directive = (ParsedDirective)directives.next();
- name = directive.getName();
- if (name.equals("realm"))
- handleRealm(directive);
- else if (name.equals("nonce"))
- handleNonce(directive);
- else if (name.equals("qop"))
- handleQop(directive);
- else if (name.equals("maxbuf"))
- handleMaxbuf(directive);
- else if (name.equals("charset"))
- handleCharset(directive);
- else if (name.equals("algorithm"))
- handleAlgorithm(directive);
- else if (name.equals("cipher"))
- handleCipher(directive);
- else if (name.equals("stale"))
- handleStale(directive);
- }
+ DirectiveList dirList) throws SaslException {
+ Iterator directives = dirList.getIterator();
+ ParsedDirective directive;
+ String name;
+
+ while (directives.hasNext()) {
+ directive = (ParsedDirective) directives.next();
+ name = directive.getName();
+ if (name.equals("realm"))
+ handleRealm(directive);
+ else if (name.equals("nonce"))
+ handleNonce(directive);
+ else if (name.equals("qop"))
+ handleQop(directive);
+ else if (name.equals("maxbuf"))
+ handleMaxbuf(directive);
+ else if (name.equals("charset"))
+ handleCharset(directive);
+ else if (name.equals("algorithm"))
+ handleAlgorithm(directive);
+ else if (name.equals("cipher"))
+ handleCipher(directive);
+ else if (name.equals("stale"))
+ handleStale(directive);
+ }
/* post semantic check */
- if (-1 == m_maxBuf)
- m_maxBuf = 65536;
-
- if (m_qop == 0)
- m_qop = QOP_AUTH;
- else if ( (m_qop & QOP_AUTH) != QOP_AUTH )
- throw new SaslException("Only qop-auth is supported by client");
- else if ( ((m_qop & QOP_AUTH_CONF) == QOP_AUTH_CONF) &&
- (0 == (m_cipherOptions & CIPHER_RECOGNIZED_MASK)) )
- throw new SaslException("Invalid cipher options");
- else if (null == m_nonce)
- throw new SaslException("Missing nonce directive");
- else if (m_staleFlag)
- throw new SaslException("Unexpected stale flag");
- else if ( null == m_algorithm )
- throw new SaslException("Missing algorithm directive");
+ if (-1 == m_maxBuf)
+ m_maxBuf = 65536;
+
+ if (m_qop == 0)
+ m_qop = QOP_AUTH;
+ else if ((m_qop & QOP_AUTH) != QOP_AUTH)
+ throw new SaslException("Only qop-auth is supported by client");
+ else if (((m_qop & QOP_AUTH_CONF) == QOP_AUTH_CONF) &&
+ (0 == (m_cipherOptions & CIPHER_RECOGNIZED_MASK)))
+ throw new SaslException("Invalid cipher options");
+ else if (null == m_nonce)
+ throw new SaslException("Missing nonce directive");
+ else if (m_staleFlag)
+ throw new SaslException("Unexpected stale flag");
+ else if (null == m_algorithm)
+ throw new SaslException("Missing algorithm directive");
}
/**
* This function implements the semenatics of the nonce directive.
*
- * @param pd ParsedDirective
- *
- * @exception SaslException If an error occurs due to too many nonce
- * values
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occurs due to too many nonce
+ * values
*/
void handleNonce(
- ParsedDirective pd) throws SaslException
- {
+ ParsedDirective pd) throws SaslException {
if (null != m_nonce)
throw new SaslException("Too many nonce values.");
@@ -146,31 +137,28 @@ void handleNonce(
/**
* This function implements the semenatics of the realm directive.
*
- * @param pd ParsedDirective
+ * @param pd ParsedDirective
*/
void handleRealm(
- ParsedDirective pd)
- {
+ ParsedDirective pd) {
m_realms.add(pd.getValue());
}
/**
* This function implements the semenatics of the qop (quality of protection)
* directive. The value of the qop directive is as defined below:
- * qop-options = "qop" "=" <"> qop-list <">
- * qop-list = 1#qop-value
- * qop-value = "auth" | "auth-int" | "auth-conf" | token
- *
- * @param pd ParsedDirective
+ * qop-options = "qop" "=" <"> qop-list <">
+ * qop-list = 1#qop-value
+ * qop-value = "auth" | "auth-int" | "auth-conf" | token
*
- * @exception SaslException If an error occurs due to too many qop
- * directives
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occurs due to too many qop
+ * directives
*/
void handleQop(
- ParsedDirective pd) throws SaslException
- {
- String token;
- TokenParser parser;
+ ParsedDirective pd) throws SaslException {
+ String token;
+ TokenParser parser;
if (m_qop != 0)
throw new SaslException("Too many qop directives.");
@@ -178,12 +166,11 @@ void handleQop(
parser = new TokenParser(pd.getValue());
for (token = parser.parseToken();
token != null;
- token = parser.parseToken())
- {
+ token = parser.parseToken()) {
if (token.equals("auth"))
- m_qop |= QOP_AUTH;
- else if (token.equals("auth-int"))
- m_qop |= QOP_AUTH_INT;
+ m_qop |= QOP_AUTH;
+ else if (token.equals("auth-int"))
+ m_qop |= QOP_AUTH_INT;
else if (token.equals("auth-conf"))
m_qop |= QOP_AUTH_CONF;
else
@@ -195,13 +182,11 @@ else if (token.equals("auth-conf"))
* This function implements the semenatics of the Maxbuf directive.
* the value is defined as: 1*DIGIT
*
- * @param pd ParsedDirective
- *
- * @exception SaslException If an error occur
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occur
*/
void handleMaxbuf(
- ParsedDirective pd) throws SaslException
- {
+ ParsedDirective pd) throws SaslException {
if (-1 != m_maxBuf) /*it's initialized to -1 */
throw new SaslException("Too many maxBuf directives.");
@@ -215,15 +200,13 @@ void handleMaxbuf(
* This function implements the semenatics of the charset directive.
* the value is defined as: 1*DIGIT
*
- * @param pd ParsedDirective
- *
- * @exception SaslException If an error occurs dur to too many charset
- * directives or Invalid character encoding
- * directive
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occurs dur to too many charset
+ * directives or Invalid character encoding
+ * directive
*/
void handleCharset(
- ParsedDirective pd) throws SaslException
- {
+ ParsedDirective pd) throws SaslException {
if (null != m_characterSet)
throw new SaslException("Too many charset directives.");
@@ -237,41 +220,37 @@ void handleCharset(
* This function implements the semenatics of the charset directive.
* the value is defined as: 1*DIGIT
*
- * @param pd ParsedDirective
- *
- * @exception SaslException If an error occurs due to too many algorith
- * directive or Invalid algorithm directive
- * value
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occurs due to too many algorith
+ * directive or Invalid algorithm directive
+ * value
*/
void handleAlgorithm(
- ParsedDirective pd) throws SaslException
- {
+ ParsedDirective pd) throws SaslException {
if (null != m_algorithm)
throw new SaslException("Too many algorithm directives.");
- m_algorithm = pd.getValue();
+ m_algorithm = pd.getValue();
if (!"md5-sess".equals(m_algorithm))
throw new SaslException("Invalid algorithm directive value: " +
- m_algorithm);
+ m_algorithm);
}
/**
* This function implements the semenatics of the cipher-opts directive
* directive. The value of the qop directive is as defined below:
- * qop-options = "qop" "=" <"> qop-list <">
- * qop-list = 1#qop-value
- * qop-value = "auth" | "auth-int" | "auth-conf" | token
+ * qop-options = "qop" "=" <"> qop-list <">
+ * qop-list = 1#qop-value
+ * qop-value = "auth" | "auth-int" | "auth-conf" | token
*
- * @param pd ParsedDirective
- *
- * @exception SaslException If an error occurs due to Too many cipher
- * directives
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occurs due to Too many cipher
+ * directives
*/
void handleCipher(
- ParsedDirective pd) throws SaslException
- {
- String token;
+ ParsedDirective pd) throws SaslException {
+ String token;
TokenParser parser;
if (0 != m_cipherOptions)
@@ -281,12 +260,11 @@ void handleCipher(
token = parser.parseToken();
for (token = parser.parseToken();
token != null;
- token = parser.parseToken())
- {
- if ("3des".equals(token))
- m_cipherOptions |= CIPHER_3DES;
- else if ("des".equals(token))
- m_cipherOptions |= CIPHER_DES;
+ token = parser.parseToken()) {
+ if ("3des".equals(token))
+ m_cipherOptions |= CIPHER_3DES;
+ else if ("des".equals(token))
+ m_cipherOptions |= CIPHER_DES;
else if ("rc4-40".equals(token))
m_cipherOptions |= CIPHER_RC4_40;
else if ("rc4".equals(token))
@@ -304,14 +282,12 @@ else if ("rc4-56".equals(token))
/**
* This function implements the semenatics of the stale directive.
*
- * @param pd ParsedDirective
- *
- * @exception SaslException If an error occurs due to Too many stale
- * directives or Invalid stale directive value
+ * @param pd ParsedDirective
+ * @throws SaslException If an error occurs due to Too many stale
+ * directives or Invalid stale directive value
*/
void handleStale(
- ParsedDirective pd) throws SaslException
- {
+ ParsedDirective pd) throws SaslException {
if (false != m_staleFlag)
throw new SaslException("Too many stale directives.");
@@ -319,74 +295,66 @@ void handleStale(
m_staleFlag = true;
else
throw new SaslException("Invalid stale directive value: " +
- pd.getValue());
+ pd.getValue());
}
/**
* Return the list of the All the Realms
*
- * @return List of all the realms
+ * @return List of all the realms
*/
- public ArrayList getRealms()
- {
+ public ArrayList getRealms() {
return m_realms;
}
/**
* @return Returns the Nonce
*/
- public String getNonce()
- {
+ public String getNonce() {
return m_nonce;
}
/**
* Return the quality-of-protection
- *
+ *
* @return The quality-of-protection
*/
- public int getQop()
- {
+ public int getQop() {
return m_qop;
}
/**
* @return The state of the Staleflag
*/
- public boolean getStaleFlag()
- {
+ public boolean getStaleFlag() {
return m_staleFlag;
}
/**
* @return The Maximum Buffer value
*/
- public int getMaxBuf()
- {
+ public int getMaxBuf() {
return m_maxBuf;
}
/**
* @return character set values as string
*/
- public String getCharacterSet()
- {
+ public String getCharacterSet() {
return m_characterSet;
}
/**
* @return The String value of the algorithm
*/
- public String getAlgorithm()
- {
+ public String getAlgorithm() {
return m_algorithm;
}
/**
* @return The cipher options
*/
- public int getCipherOptions()
- {
+ public int getCipherOptions() {
return m_cipherOptions;
}
}
diff --git a/app/src/main/java/com/novell/sasl/client/DigestMD5SaslClient.java b/app/src/main/java/com/novell/sasl/client/DigestMD5SaslClient.java
index 141c96b3df..d86879649f 100644
--- a/app/src/main/java/com/novell/sasl/client/DigestMD5SaslClient.java
+++ b/app/src/main/java/com/novell/sasl/client/DigestMD5SaslClient.java
@@ -16,6 +16,7 @@
import org.apache.harmony.javax.security.sasl.*;
import org.apache.harmony.javax.security.auth.callback.*;
+
import java.security.SecureRandom;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -26,30 +27,29 @@
/**
* Implements the Client portion of DigestMD5 Sasl mechanism.
*/
-public class DigestMD5SaslClient implements SaslClient
-{
- private String m_authorizationId = "";
- private String m_protocol = "";
- private String m_serverName = "";
- private Map m_props;
- private CallbackHandler m_cbh;
- private int m_state;
- private String m_qopValue = "";
- private char[] m_HA1 = null;
- private String m_digestURI;
- private DigestChallenge m_dc;
- private String m_clientNonce = "";
- private String m_realm = "";
- private String m_name = "";
-
- private static final int STATE_INITIAL = 0;
- private static final int STATE_DIGEST_RESPONSE_SENT = 1;
- private static final int STATE_VALID_SERVER_RESPONSE = 2;
- private static final int STATE_INVALID_SERVER_RESPONSE = 3;
- private static final int STATE_DISPOSED = 4;
-
- private static final int NONCE_BYTE_COUNT = 32;
- private static final int NONCE_HEX_COUNT = 2*NONCE_BYTE_COUNT;
+public class DigestMD5SaslClient implements SaslClient {
+ private String m_authorizationId = "";
+ private String m_protocol = "";
+ private String m_serverName = "";
+ private Map m_props;
+ private CallbackHandler m_cbh;
+ private int m_state;
+ private String m_qopValue = "";
+ private char[] m_HA1 = null;
+ private String m_digestURI;
+ private DigestChallenge m_dc;
+ private String m_clientNonce = "";
+ private String m_realm = "";
+ private String m_name = "";
+
+ private static final int STATE_INITIAL = 0;
+ private static final int STATE_DIGEST_RESPONSE_SENT = 1;
+ private static final int STATE_VALID_SERVER_RESPONSE = 2;
+ private static final int STATE_INVALID_SERVER_RESPONSE = 3;
+ private static final int STATE_DISPOSED = 4;
+
+ private static final int NONCE_BYTE_COUNT = 32;
+ private static final int NONCE_HEX_COUNT = 2 * NONCE_BYTE_COUNT;
private static final String DIGEST_METHOD = "AUTHENTICATE";
@@ -58,57 +58,50 @@ public class DigestMD5SaslClient implements SaslClient
* Assumes that the QOP, STRENGTH, and SERVER_AUTH properties are
* contained in props
*
- * @param authorizationId The possibly null protocol-dependent
- * identification to be used for authorization. If
- * null or empty, the server derives an authorization
- * ID from the client's authentication credentials.
- * When the SASL authentication completes
- * successfully, the specified entity is granted
- * access.
- *
- * @param protocol The non-null string name of the protocol for which
- * the authentication is being performed (e.g. "ldap")
- *
- * @param serverName The non-null fully qualified host name of the server
- * to authenticate to
- *
- * @param props The possibly null set of properties used to select
- * the SASL mechanism and to configure the
- * authentication exchange of the selected mechanism.
- * See the Sasl class for a list of standard properties.
- * Other, possibly mechanism-specific, properties can
- * be included. Properties not relevant to the selected
- * mechanism are ignored.
- *
- * @param cbh The possibly null callback handler to used by the
- * SASL mechanisms to get further information from the
- * application/library to complete the authentication.
- * For example, a SASL mechanism might require the
- * authentication ID, password and realm from the
- * caller. The authentication ID is requested by using
- * a NameCallback. The password is requested by using
- * a PasswordCallback. The realm is requested by using
- * a RealmChoiceCallback if there is a list of realms
- * to choose from, and by using a RealmCallback if the
- * realm must be entered.
- *
- * @return A possibly null SaslClient created using the
- * parameters supplied. If null, this factory cannot
- * produce a SaslClient using the parameters supplied.
- *
- * @exception SaslException If a SaslClient instance cannot be created
- * because of an error
+ * @param authorizationId The possibly null protocol-dependent
+ * identification to be used for authorization. If
+ * null or empty, the server derives an authorization
+ * ID from the client's authentication credentials.
+ * When the SASL authentication completes
+ * successfully, the specified entity is granted
+ * access.
+ * @param protocol The non-null string name of the protocol for which
+ * the authentication is being performed (e.g. "ldap")
+ * @param serverName The non-null fully qualified host name of the server
+ * to authenticate to
+ * @param props The possibly null set of properties used to select
+ * the SASL mechanism and to configure the
+ * authentication exchange of the selected mechanism.
+ * See the Sasl class for a list of standard properties.
+ * Other, possibly mechanism-specific, properties can
+ * be included. Properties not relevant to the selected
+ * mechanism are ignored.
+ * @param cbh The possibly null callback handler to used by the
+ * SASL mechanisms to get further information from the
+ * application/library to complete the authentication.
+ * For example, a SASL mechanism might require the
+ * authentication ID, password and realm from the
+ * caller. The authentication ID is requested by using
+ * a NameCallback. The password is requested by using
+ * a PasswordCallback. The realm is requested by using
+ * a RealmChoiceCallback if there is a list of realms
+ * to choose from, and by using a RealmCallback if the
+ * realm must be entered.
+ * @return A possibly null SaslClient created using the
+ * parameters supplied. If null, this factory cannot
+ * produce a SaslClient using the parameters supplied.
+ * @throws SaslException If a SaslClient instance cannot be created
+ * because of an error
*/
public static SaslClient getClient(
- String authorizationId,
- String protocol,
- String serverName,
- Map props,
- CallbackHandler cbh)
- {
- String desiredQOP = (String)props.get(Sasl.QOP);
- String desiredStrength = (String)props.get(Sasl.STRENGTH);
- String serverAuth = (String)props.get(Sasl.SERVER_AUTH);
+ String authorizationId,
+ String protocol,
+ String serverName,
+ Map props,
+ CallbackHandler cbh) {
+ String desiredQOP = (String) props.get(Sasl.QOP);
+ String desiredStrength = (String) props.get(Sasl.STRENGTH);
+ String serverAuth = (String) props.get(Sasl.SERVER_AUTH);
//only support qop equal to auth
if ((desiredQOP != null) && !"auth".equals(desiredQOP))
@@ -123,7 +116,7 @@ public static SaslClient getClient(
return null;
return new DigestMD5SaslClient(authorizationId, protocol,
- serverName, props, cbh);
+ serverName, props, cbh);
}
/**
@@ -131,48 +124,42 @@ public static SaslClient getClient(
* Assumes that the QOP, STRENGTH, and SERVER_AUTH properties are
* contained in props
*
- * @param authorizationId The possibly null protocol-dependent
- * identification to be used for authorization. If
- * null or empty, the server derives an authorization
- * ID from the client's authentication credentials.
- * When the SASL authentication completes
- * successfully, the specified entity is granted
- * access.
- *
- * @param protocol The non-null string name of the protocol for which
- * the authentication is being performed (e.g. "ldap")
- *
- * @param serverName The non-null fully qualified host name of the server
- * to authenticate to
- *
- * @param props The possibly null set of properties used to select
- * the SASL mechanism and to configure the
- * authentication exchange of the selected mechanism.
- * See the Sasl class for a list of standard properties.
- * Other, possibly mechanism-specific, properties can
- * be included. Properties not relevant to the selected
- * mechanism are ignored.
- *
- * @param cbh The possibly null callback handler to used by the
- * SASL mechanisms to get further information from the
- * application/library to complete the authentication.
- * For example, a SASL mechanism might require the
- * authentication ID, password and realm from the
- * caller. The authentication ID is requested by using
- * a NameCallback. The password is requested by using
- * a PasswordCallback. The realm is requested by using
- * a RealmChoiceCallback if there is a list of realms
- * to choose from, and by using a RealmCallback if the
- * realm must be entered.
- *
+ * @param authorizationId The possibly null protocol-dependent
+ * identification to be used for authorization. If
+ * null or empty, the server derives an authorization
+ * ID from the client's authentication credentials.
+ * When the SASL authentication completes
+ * successfully, the specified entity is granted
+ * access.
+ * @param protocol The non-null string name of the protocol for which
+ * the authentication is being performed (e.g. "ldap")
+ * @param serverName The non-null fully qualified host name of the server
+ * to authenticate to
+ * @param props The possibly null set of properties used to select
+ * the SASL mechanism and to configure the
+ * authentication exchange of the selected mechanism.
+ * See the Sasl class for a list of standard properties.
+ * Other, possibly mechanism-specific, properties can
+ * be included. Properties not relevant to the selected
+ * mechanism are ignored.
+ * @param cbh The possibly null callback handler to used by the
+ * SASL mechanisms to get further information from the
+ * application/library to complete the authentication.
+ * For example, a SASL mechanism might require the
+ * authentication ID, password and realm from the
+ * caller. The authentication ID is requested by using
+ * a NameCallback. The password is requested by using
+ * a PasswordCallback. The realm is requested by using
+ * a RealmChoiceCallback if there is a list of realms
+ * to choose from, and by using a RealmCallback if the
+ * realm must be entered.
*/
- private DigestMD5SaslClient(
- String authorizationId,
- String protocol,
- String serverName,
- Map props,
- CallbackHandler cbh)
- {
+ private DigestMD5SaslClient(
+ String authorizationId,
+ String protocol,
+ String serverName,
+ Map props,
+ CallbackHandler cbh) {
m_authorizationId = authorizationId;
m_protocol = protocol;
m_serverName = serverName;
@@ -187,10 +174,9 @@ private DigestMD5SaslClient(
* caller should call evaluateChallenge() with an empty array to get the
* initial response.
*
- * @return true if this mechanism has an initial response
+ * @return true if this mechanism has an initial response
*/
- public boolean hasInitialResponse()
- {
+ public boolean hasInitialResponse() {
return false;
}
@@ -200,14 +186,13 @@ public boolean hasInitialResponse()
* the caller has received indication from the server (in a protocol-
* specific manner) that the exchange has completed.
*
- * @return true if the authentication exchange has completed;
- * false otherwise.
+ * @return true if the authentication exchange has completed;
+ * false otherwise.
*/
- public boolean isComplete()
- {
+ public boolean isComplete() {
if ((m_state == STATE_VALID_SERVER_RESPONSE) ||
- (m_state == STATE_INVALID_SERVER_RESPONSE) ||
- (m_state == STATE_DISPOSED))
+ (m_state == STATE_INVALID_SERVER_RESPONSE) ||
+ (m_state == STATE_DISPOSED))
return true;
else
return false;
@@ -219,28 +204,24 @@ public boolean isComplete()
* isComplete() returns true) and only if the authentication exchange has
* negotiated integrity and/or privacy as the quality of protection;
* otherwise, an IllegalStateException is thrown.
- *
+ *
* incoming is the contents of the SASL buffer as defined in RFC 2222
* without the leading four octet field that represents the length.
* offset and len specify the portion of incoming to use.
*
- * @param incoming A non-null byte array containing the encoded bytes
- * from the server
- * @param offset The starting position at incoming of the bytes to use
- *
- * @param len The number of bytes from incoming to use
- *
- * @return A non-null byte array containing the decoded bytes
- *
+ * @param incoming A non-null byte array containing the encoded bytes
+ * from the server
+ * @param offset The starting position at incoming of the bytes to use
+ * @param len The number of bytes from incoming to use
+ * @return A non-null byte array containing the decoded bytes
*/
public byte[] unwrap(
- byte[] incoming,
- int offset,
- int len)
- throws SaslException
- {
+ byte[] incoming,
+ int offset,
+ int len)
+ throws SaslException {
throw new IllegalStateException(
- "unwrap: QOP has neither integrity nor privacy>");
+ "unwrap: QOP has neither integrity nor privacy>");
}
/**
@@ -249,31 +230,27 @@ public byte[] unwrap(
* isComplete() returns true) and only if the authentication exchange has
* negotiated integrity and/or privacy as the quality of protection;
* otherwise, an IllegalStateException is thrown.
- *
+ *
* The result of this method will make up the contents of the SASL buffer as
* defined in RFC 2222 without the leading four octet field that represents
* the length. offset and len specify the portion of outgoing to use.
*
- * @param outgoing A non-null byte array containing the bytes to encode
- * @param offset The starting position at outgoing of the bytes to use
- * @param len The number of bytes from outgoing to use
- *
+ * @param outgoing A non-null byte array containing the bytes to encode
+ * @param offset The starting position at outgoing of the bytes to use
+ * @param len The number of bytes from outgoing to use
* @return A non-null byte array containing the encoded bytes
- *
- * @exception SaslException if incoming cannot be successfully unwrapped.
- *
- * @exception IllegalStateException if the authentication exchange has
- * not completed, or if the negotiated quality of
- * protection has neither integrity nor privacy.
+ * @throws SaslException if incoming cannot be successfully unwrapped.
+ * @throws IllegalStateException if the authentication exchange has
+ * not completed, or if the negotiated quality of
+ * protection has neither integrity nor privacy.
*/
public byte[] wrap(
- byte[] outgoing,
- int offset,
- int len)
- throws SaslException
- {
+ byte[] outgoing,
+ int offset,
+ int len)
+ throws SaslException {
throw new IllegalStateException(
- "wrap: QOP has neither integrity nor privacy>");
+ "wrap: QOP has neither integrity nor privacy>");
}
/**
@@ -281,20 +258,17 @@ public byte[] wrap(
* the authentication exchange has completed (i.e., when isComplete()
* returns true); otherwise, an IllegalStateException is thrown.
*
- * @param propName The non-null property name
- *
- * @return The value of the negotiated property. If null, the property was
- * not negotiated or is not applicable to this mechanism.
- *
- * @exception IllegalStateException if this authentication exchange has
- * not completed
+ * @param propName The non-null property name
+ * @return The value of the negotiated property. If null, the property was
+ * not negotiated or is not applicable to this mechanism.
+ * @throws IllegalStateException if this authentication exchange has
+ * not completed
*/
public Object getNegotiatedProperty(
- String propName)
- {
+ String propName) {
if (m_state != STATE_VALID_SERVER_RESPONSE)
throw new IllegalStateException(
- "getNegotiatedProperty: authentication exchange not complete.");
+ "getNegotiatedProperty: authentication exchange not complete.");
if (Sasl.QOP.equals(propName))
return "auth";
@@ -307,14 +281,12 @@ public Object getNegotiatedProperty(
* SaslClient might be using. Invoking this method invalidates the
* SaslClient instance. This method is idempotent.
*
- * @exception SaslException if a problem was encountered while disposing
- * of the resources
+ * @throws SaslException if a problem was encountered while disposing
+ * of the resources
*/
public void dispose()
- throws SaslException
- {
- if (m_state != STATE_DISPOSED)
- {
+ throws SaslException {
+ if (m_state != STATE_DISPOSED) {
m_state = STATE_DISPOSED;
}
}
@@ -325,61 +297,53 @@ public void dispose()
* method is called to prepare an appropriate next response to submit to
* the server.
*
- * @param challenge The non-null challenge sent from the server. The
- * challenge array may have zero length.
- *
- * @return The possibly null reponse to send to the server. It is null
- * if the challenge accompanied a "SUCCESS" status and the
- * challenge only contains data for the client to update its
- * state and no response needs to be sent to the server.
- * The response is a zero-length byte array if the client is to
- * send a response with no data.
- *
- * @exception SaslException If an error occurred while processing the
- * challenge or generating a response.
+ * @param challenge The non-null challenge sent from the server. The
+ * challenge array may have zero length.
+ * @return The possibly null reponse to send to the server. It is null
+ * if the challenge accompanied a "SUCCESS" status and the
+ * challenge only contains data for the client to update its
+ * state and no response needs to be sent to the server.
+ * The response is a zero-length byte array if the client is to
+ * send a response with no data.
+ * @throws SaslException If an error occurred while processing the
+ * challenge or generating a response.
*/
public byte[] evaluateChallenge(
- byte[] challenge)
- throws SaslException
- {
+ byte[] challenge)
+ throws SaslException {
byte[] response = null;
//printState();
- switch (m_state)
- {
- case STATE_INITIAL:
- if (challenge.length == 0)
- throw new SaslException("response = byte[0]");
- else
- try
- {
- response = createDigestResponse(challenge).
- getBytes("UTF-8");
- m_state = STATE_DIGEST_RESPONSE_SENT;
+ switch (m_state) {
+ case STATE_INITIAL:
+ if (challenge.length == 0)
+ throw new SaslException("response = byte[0]");
+ else
+ try {
+ response = createDigestResponse(challenge).
+ getBytes("UTF-8");
+ m_state = STATE_DIGEST_RESPONSE_SENT;
+ } catch (java.io.UnsupportedEncodingException e) {
+ throw new SaslException(
+ "UTF-8 encoding not suppported by platform", e);
+ }
+ break;
+ case STATE_DIGEST_RESPONSE_SENT:
+ if (checkServerResponseAuth(challenge))
+ m_state = STATE_VALID_SERVER_RESPONSE;
+ else {
+ m_state = STATE_INVALID_SERVER_RESPONSE;
+ throw new SaslException("Could not validate response-auth " +
+ "value from server");
}
- catch (java.io.UnsupportedEncodingException e)
- {
- throw new SaslException(
- "UTF-8 encoding not suppported by platform", e);
- }
- break;
- case STATE_DIGEST_RESPONSE_SENT:
- if (checkServerResponseAuth(challenge))
- m_state = STATE_VALID_SERVER_RESPONSE;
- else
- {
- m_state = STATE_INVALID_SERVER_RESPONSE;
- throw new SaslException("Could not validate response-auth " +
- "value from server");
- }
- break;
- case STATE_VALID_SERVER_RESPONSE:
- case STATE_INVALID_SERVER_RESPONSE:
- throw new SaslException("Authentication sequence is complete");
- case STATE_DISPOSED:
- throw new SaslException("Client has been disposed");
- default:
- throw new SaslException("Unknown client state.");
+ break;
+ case STATE_VALID_SERVER_RESPONSE:
+ case STATE_INVALID_SERVER_RESPONSE:
+ throw new SaslException("Authentication sequence is complete");
+ case STATE_DISPOSED:
+ throw new SaslException("Client has been disposed");
+ default:
+ throw new SaslException("Unknown client state.");
}
return response;
@@ -387,28 +351,25 @@ public byte[] evaluateChallenge(
/**
* This function takes a 16 byte binary md5-hash value and creates a 32
- * character (plus a terminating null character) hex-digit
+ * character (plus a terminating null character) hex-digit
* representation of binary data.
*
- * @param hash 16 byte binary md5-hash value in bytes
- *
- * @return 32 character (plus a terminating null character) hex-digit
- * representation of binary data.
+ * @param hash 16 byte binary md5-hash value in bytes
+ * @return 32 character (plus a terminating null character) hex-digit
+ * representation of binary data.
*/
char[] convertToHex(
- byte[] hash)
- {
- int i;
- byte j;
- byte fifteen = 15;
- char[] hex = new char[32];
-
- for (i = 0; i < 16; i++)
- {
+ byte[] hash) {
+ int i;
+ byte j;
+ byte fifteen = 15;
+ char[] hex = new char[32];
+
+ for (i = 0; i < 16; i++) {
//convert value of top 4 bits to hex char
- hex[i*2] = getHexChar((byte)((hash[i] & 0xf0) >> 4));
+ hex[i * 2] = getHexChar((byte) ((hash[i] & 0xf0) >> 4));
//convert value of bottom 4 bits to hex char
- hex[(i*2)+1] = getHexChar((byte)(hash[i] & 0x0f));
+ hex[(i * 2) + 1] = getHexChar((byte) (hash[i] & 0x0f));
}
return hex;
@@ -417,29 +378,25 @@ char[] convertToHex(
/**
* Calculates the HA1 portion of the response
*
- * @param algorithm Algorith to use.
- * @param userName User being authenticated
- * @param realm realm information
- * @param password password of teh user
- * @param nonce nonce value
- * @param clientNonce Clients Nonce value
- *
- * @return HA1 portion of the response in a character array
- *
- * @exception SaslException If an error occurs
+ * @param algorithm Algorith to use.
+ * @param userName User being authenticated
+ * @param realm realm information
+ * @param password password of teh user
+ * @param nonce nonce value
+ * @param clientNonce Clients Nonce value
+ * @return HA1 portion of the response in a character array
+ * @throws SaslException If an error occurs
*/
char[] DigestCalcHA1(
- String algorithm,
- String userName,
- String realm,
- String password,
- String nonce,
- String clientNonce) throws SaslException
- {
- byte[] hash;
-
- try
- {
+ String algorithm,
+ String userName,
+ String realm,
+ String password,
+ String nonce,
+ String clientNonce) throws SaslException {
+ byte[] hash;
+
+ try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(userName.getBytes("UTF-8"));
@@ -449,8 +406,7 @@ char[] DigestCalcHA1(
md.update(password.getBytes("UTF-8"));
hash = md.digest();
- if ("md5-sess".equals(algorithm))
- {
+ if ("md5-sess".equals(algorithm)) {
md.update(hash);
md.update(":".getBytes("UTF-8"));
md.update(nonce.getBytes("UTF-8"));
@@ -458,15 +414,11 @@ char[] DigestCalcHA1(
md.update(clientNonce.getBytes("UTF-8"));
hash = md.digest();
}
- }
- catch(NoSuchAlgorithmException e)
- {
+ } catch (NoSuchAlgorithmException e) {
throw new SaslException("No provider found for MD5 hash", e);
- }
- catch(UnsupportedEncodingException e)
- {
+ } catch (UnsupportedEncodingException e) {
throw new SaslException(
- "UTF-8 encoding not supported by platform.", e);
+ "UTF-8 encoding not supported by platform.", e);
}
return convertToHex(hash);
@@ -477,44 +429,39 @@ char[] DigestCalcHA1(
* This function calculates the response-value of the response directive of
* the digest-response as documented in RFC 2831
*
- * @param HA1 H(A1)
- * @param serverNonce nonce from server
- * @param nonceCount 8 hex digits
- * @param clientNonce client nonce
- * @param qop qop-value: "", "auth", "auth-int"
- * @param method method from the request
- * @param digestUri requested URL
- * @param clientResponseFlag request-digest or response-digest
- *
+ * @param HA1 H(A1)
+ * @param serverNonce nonce from server
+ * @param nonceCount 8 hex digits
+ * @param clientNonce client nonce
+ * @param qop qop-value: "", "auth", "auth-int"
+ * @param method method from the request
+ * @param digestUri requested URL
+ * @param clientResponseFlag request-digest or response-digest
* @return Response-value of the response directive of the digest-response
- *
- * @exception SaslException If an error occurs
+ * @throws SaslException If an error occurs
*/
char[] DigestCalcResponse(
- char[] HA1, /* H(A1) */
- String serverNonce, /* nonce from server */
- String nonceCount, /* 8 hex digits */
- String clientNonce, /* client nonce */
- String qop, /* qop-value: "", "auth", "auth-int" */
- String method, /* method from the request */
- String digestUri, /* requested URL */
- boolean clientResponseFlag) /* request-digest or response-digest */
- throws SaslException
- {
- byte[] HA2;
- byte[] respHash;
- char[] HA2Hex;
+ char[] HA1, /* H(A1) */
+ String serverNonce, /* nonce from server */
+ String nonceCount, /* 8 hex digits */
+ String clientNonce, /* client nonce */
+ String qop, /* qop-value: "", "auth", "auth-int" */
+ String method, /* method from the request */
+ String digestUri, /* requested URL */
+ boolean clientResponseFlag) /* request-digest or response-digest */
+ throws SaslException {
+ byte[] HA2;
+ byte[] respHash;
+ char[] HA2Hex;
// calculate H(A2)
- try
- {
+ try {
MessageDigest md = MessageDigest.getInstance("MD5");
if (clientResponseFlag)
- md.update(method.getBytes("UTF-8"));
+ md.update(method.getBytes("UTF-8"));
md.update(":".getBytes("UTF-8"));
md.update(digestUri.getBytes("UTF-8"));
- if ("auth-int".equals(qop))
- {
+ if ("auth-int".equals(qop)) {
md.update(":".getBytes("UTF-8"));
md.update("00000000000000000000000000000000".getBytes("UTF-8"));
}
@@ -526,8 +473,7 @@ char[] DigestCalcResponse(
md.update(":".getBytes("UTF-8"));
md.update(serverNonce.getBytes("UTF-8"));
md.update(":".getBytes("UTF-8"));
- if (qop.length() > 0)
- {
+ if (qop.length() > 0) {
md.update(nonceCount.getBytes("UTF-8"));
md.update(":".getBytes("UTF-8"));
md.update(clientNonce.getBytes("UTF-8"));
@@ -537,15 +483,11 @@ char[] DigestCalcResponse(
}
md.update(new String(HA2Hex).getBytes("UTF-8"));
respHash = md.digest();
- }
- catch(NoSuchAlgorithmException e)
- {
+ } catch (NoSuchAlgorithmException e) {
throw new SaslException("No provider found for MD5 hash", e);
- }
- catch(UnsupportedEncodingException e)
- {
+ } catch (UnsupportedEncodingException e) {
throw new SaslException(
- "UTF-8 encoding not supported by platform.", e);
+ "UTF-8 encoding not supported by platform.", e);
}
return convertToHex(respHash);
@@ -555,24 +497,22 @@ char[] DigestCalcResponse(
/**
* Creates the intial response to be sent to the server.
*
- * @param challenge Challenge in bytes recived form the Server
- *
+ * @param challenge Challenge in bytes recived form the Server
* @return Initial response to be sent to the server
*/
private String createDigestResponse(
- byte[] challenge)
- throws SaslException
- {
- char[] response;
- StringBuffer digestResponse = new StringBuffer(512);
- int realmSize;
+ byte[] challenge)
+ throws SaslException {
+ char[] response;
+ StringBuffer digestResponse = new StringBuffer(512);
+ int realmSize;
m_dc = new DigestChallenge(challenge);
m_digestURI = m_protocol + "/" + m_serverName;
if ((m_dc.getQop() & DigestChallenge.QOP_AUTH)
- == DigestChallenge.QOP_AUTH )
+ == DigestChallenge.QOP_AUTH)
m_qopValue = "auth";
else
throw new SaslException("Client only supports qop of 'auth'");
@@ -581,25 +521,20 @@ private String createDigestResponse(
Callback[] callbacks = new Callback[3];
ArrayList realms = m_dc.getRealms();
realmSize = realms.size();
- if (realmSize == 0)
- {
+ if (realmSize == 0) {
callbacks[0] = new RealmCallback("Realm");
- }
- else if (realmSize == 1)
- {
- callbacks[0] = new RealmCallback("Realm", (String)realms.get(0));
- }
- else
- {
+ } else if (realmSize == 1) {
+ callbacks[0] = new RealmCallback("Realm", (String) realms.get(0));
+ } else {
callbacks[0] =
- new RealmChoiceCallback(
- "Realm",
- (String[])realms.toArray(new String[realmSize]),
- 0, //the default choice index
- false); //no multiple selections
+ new RealmChoiceCallback(
+ "Realm",
+ (String[]) realms.toArray(new String[realmSize]),
+ 0, //the default choice index
+ false); //no multiple selections
}
- callbacks[1] = new PasswordCallback("Password", false);
+ callbacks[1] = new PasswordCallback("Password", false);
//false = no echo
if (m_authorizationId == null || m_authorizationId.length() == 0)
@@ -607,63 +542,55 @@ else if (realmSize == 1)
else
callbacks[2] = new NameCallback("Name", m_authorizationId);
- try
- {
+ try {
m_cbh.handle(callbacks);
- }
- catch(UnsupportedCallbackException e)
- {
+ } catch (UnsupportedCallbackException e) {
throw new SaslException("Handler does not support" +
- " necessary callbacks",e);
- }
- catch(IOException e)
- {
+ " necessary callbacks", e);
+ } catch (IOException e) {
throw new SaslException("IO exception in CallbackHandler.", e);
}
- if (realmSize > 1)
- {
+ if (realmSize > 1) {
int[] selections =
- ((RealmChoiceCallback)callbacks[0]).getSelectedIndexes();
+ ((RealmChoiceCallback) callbacks[0]).getSelectedIndexes();
if (selections.length > 0)
m_realm =
- ((RealmChoiceCallback)callbacks[0]).getChoices()[selections[0]];
+ ((RealmChoiceCallback) callbacks[0]).getChoices()[selections[0]];
else
- m_realm = ((RealmChoiceCallback)callbacks[0]).getChoices()[0];
- }
- else
- m_realm = ((RealmCallback)callbacks[0]).getText();
+ m_realm = ((RealmChoiceCallback) callbacks[0]).getChoices()[0];
+ } else
+ m_realm = ((RealmCallback) callbacks[0]).getText();
m_clientNonce = getClientNonce();
- m_name = ((NameCallback)callbacks[2]).getName();
+ m_name = ((NameCallback) callbacks[2]).getName();
if (m_name == null)
- m_name = ((NameCallback)callbacks[2]).getDefaultName();
+ m_name = ((NameCallback) callbacks[2]).getDefaultName();
if (m_name == null)
throw new SaslException("No user name was specified.");
m_HA1 = DigestCalcHA1(
- m_dc.getAlgorithm(),
- m_name,
- m_realm,
- new String(((PasswordCallback)callbacks[1]).getPassword()),
- m_dc.getNonce(),
- m_clientNonce);
+ m_dc.getAlgorithm(),
+ m_name,
+ m_realm,
+ new String(((PasswordCallback) callbacks[1]).getPassword()),
+ m_dc.getNonce(),
+ m_clientNonce);
response = DigestCalcResponse(m_HA1,
- m_dc.getNonce(),
- "00000001",
- m_clientNonce,
- m_qopValue,
- "AUTHENTICATE",
- m_digestURI,
- true);
+ m_dc.getNonce(),
+ "00000001",
+ m_clientNonce,
+ m_qopValue,
+ "AUTHENTICATE",
+ m_digestURI,
+ true);
digestResponse.append("username=\"");
digestResponse.append(m_authorizationId);
- if (0 != m_realm.length())
- {
+ if (0 != m_realm.length()) {
digestResponse.append("\",realm=\"");
digestResponse.append(m_realm);
}
@@ -674,7 +601,7 @@ else if (realmSize == 1)
digestResponse.append(",qop=");
digestResponse.append(m_qopValue);
digestResponse.append(",digest-uri=\"");
- digestResponse.append(m_digestURI);
+ digestResponse.append(m_digestURI);
digestResponse.append("\",response=");
digestResponse.append(response);
digestResponse.append(",charset=utf-8,nonce=\"");
@@ -682,38 +609,35 @@ else if (realmSize == 1)
digestResponse.append("\"");
return digestResponse.toString();
- }
-
-
+ }
+
+
/**
- * This function validates the server response. This step performs a
+ * This function validates the server response. This step performs a
* modicum of mutual authentication by verifying that the server knows
* the user's password
*
- * @param serverResponse Response recived form Server
- *
- * @return true if the mutual authentication succeeds;
- * else return false
- *
- * @exception SaslException If an error occurs
+ * @param serverResponse Response recived form Server
+ * @return true if the mutual authentication succeeds;
+ * else return false
+ * @throws SaslException If an error occurs
*/
boolean checkServerResponseAuth(
- byte[] serverResponse) throws SaslException
- {
- char[] response;
- ResponseAuth responseAuth = null;
- String responseStr;
+ byte[] serverResponse) throws SaslException {
+ char[] response;
+ ResponseAuth responseAuth = null;
+ String responseStr;
responseAuth = new ResponseAuth(serverResponse);
response = DigestCalcResponse(m_HA1,
- m_dc.getNonce(),
- "00000001",
- m_clientNonce,
- m_qopValue,
- DIGEST_METHOD,
- m_digestURI,
- false);
+ m_dc.getNonce(),
+ "00000001",
+ m_clientNonce,
+ m_qopValue,
+ DIGEST_METHOD,
+ m_digestURI,
+ false);
responseStr = new String(response);
@@ -723,96 +647,86 @@ boolean checkServerResponseAuth(
/**
* This function returns hex character representing the value of the input
- *
- * @param value Input value in byte
*
+ * @param value Input value in byte
* @return Hex value of the Input byte value
*/
private static char getHexChar(
- byte value)
- {
- switch (value)
- {
- case 0:
- return '0';
- case 1:
- return '1';
- case 2:
- return '2';
- case 3:
- return '3';
- case 4:
- return '4';
- case 5:
- return '5';
- case 6:
- return '6';
- case 7:
- return '7';
- case 8:
- return '8';
- case 9:
- return '9';
- case 10:
- return 'a';
- case 11:
- return 'b';
- case 12:
- return 'c';
- case 13:
- return 'd';
- case 14:
- return 'e';
- case 15:
- return 'f';
- default:
- return 'Z';
+ byte value) {
+ switch (value) {
+ case 0:
+ return '0';
+ case 1:
+ return '1';
+ case 2:
+ return '2';
+ case 3:
+ return '3';
+ case 4:
+ return '4';
+ case 5:
+ return '5';
+ case 6:
+ return '6';
+ case 7:
+ return '7';
+ case 8:
+ return '8';
+ case 9:
+ return '9';
+ case 10:
+ return 'a';
+ case 11:
+ return 'b';
+ case 12:
+ return 'c';
+ case 13:
+ return 'd';
+ case 14:
+ return 'e';
+ case 15:
+ return 'f';
+ default:
+ return 'Z';
}
}
/**
* Calculates the Nonce value of the Client
- *
- * @return Nonce value of the client
*
- * @exception SaslException If an error Occurs
+ * @return Nonce value of the client
+ * @throws SaslException If an error Occurs
*/
- String getClientNonce() throws SaslException
- {
- byte[] nonceBytes = new byte[NONCE_BYTE_COUNT];
- SecureRandom prng;
- byte nonceByte;
- char[] hexNonce = new char[NONCE_HEX_COUNT];
-
- try
- {
+ String getClientNonce() throws SaslException {
+ byte[] nonceBytes = new byte[NONCE_BYTE_COUNT];
+ SecureRandom prng;
+ byte nonceByte;
+ char[] hexNonce = new char[NONCE_HEX_COUNT];
+
+ try {
prng = SecureRandom.getInstance("SHA1PRNG");
prng.nextBytes(nonceBytes);
- for(int i=0; i> 4));
+ hexNonce[(i * 2) + 1] = getHexChar((byte) ((nonceBytes[i] & 0xf0)
+ >> 4));
}
return new String(hexNonce);
- }
- catch(NoSuchAlgorithmException e)
- {
+ } catch (NoSuchAlgorithmException e) {
throw new SaslException("No random number generator available", e);
}
}
/**
* Returns the IANA-registered mechanism name of this SASL client.
- * (e.g. "CRAM-MD5", "GSSAPI")
+ * (e.g. "CRAM-MD5", "GSSAPI")
*
- * @return "DIGEST-MD5"the IANA-registered mechanism name of this SASL
- * client.
+ * @return "DIGEST-MD5"the IANA-registered mechanism name of this SASL
+ * client.
*/
- public String getMechanismName()
- {
+ public String getMechanismName() {
return "DIGEST-MD5";
}
diff --git a/app/src/main/java/com/novell/sasl/client/DirectiveList.java b/app/src/main/java/com/novell/sasl/client/DirectiveList.java
index fc26a6b0ee..b3d710ecfb 100644
--- a/app/src/main/java/com/novell/sasl/client/DirectiveList.java
+++ b/app/src/main/java/com/novell/sasl/client/DirectiveList.java
@@ -15,50 +15,47 @@
package com.novell.sasl.client;
import java.util.*;
+
import org.apache.harmony.javax.security.sasl.*;
+
import java.io.UnsupportedEncodingException;
/**
- * Implements the DirectiveList class whihc will be used by the
+ * Implements the DirectiveList class whihc will be used by the
* DigestMD5SaslClient class
*/
-class DirectiveList extends Object
-{
- private static final int STATE_LOOKING_FOR_FIRST_DIRECTIVE = 1;
- private static final int STATE_LOOKING_FOR_DIRECTIVE = 2;
- private static final int STATE_SCANNING_NAME = 3;
- private static final int STATE_LOOKING_FOR_EQUALS = 4;
- private static final int STATE_LOOKING_FOR_VALUE = 5;
- private static final int STATE_LOOKING_FOR_COMMA = 6;
- private static final int STATE_SCANNING_QUOTED_STRING_VALUE = 7;
- private static final int STATE_SCANNING_TOKEN_VALUE = 8;
- private static final int STATE_NO_UTF8_SUPPORT = 9;
-
- private int m_curPos;
- private int m_errorPos;
- private String m_directives;
- private int m_state;
- private ArrayList m_directiveList;
- private String m_curName;
- private int m_scanStart;
+class DirectiveList extends Object {
+ private static final int STATE_LOOKING_FOR_FIRST_DIRECTIVE = 1;
+ private static final int STATE_LOOKING_FOR_DIRECTIVE = 2;
+ private static final int STATE_SCANNING_NAME = 3;
+ private static final int STATE_LOOKING_FOR_EQUALS = 4;
+ private static final int STATE_LOOKING_FOR_VALUE = 5;
+ private static final int STATE_LOOKING_FOR_COMMA = 6;
+ private static final int STATE_SCANNING_QUOTED_STRING_VALUE = 7;
+ private static final int STATE_SCANNING_TOKEN_VALUE = 8;
+ private static final int STATE_NO_UTF8_SUPPORT = 9;
+
+ private int m_curPos;
+ private int m_errorPos;
+ private String m_directives;
+ private int m_state;
+ private ArrayList m_directiveList;
+ private String m_curName;
+ private int m_scanStart;
/**
- * Constructs a new DirectiveList.
+ * Constructs a new DirectiveList.
*/
- DirectiveList(
- byte[] directives)
- {
+ DirectiveList(
+ byte[] directives) {
m_curPos = 0;
m_state = STATE_LOOKING_FOR_FIRST_DIRECTIVE;
m_directiveList = new ArrayList(10);
m_scanStart = 0;
m_errorPos = -1;
- try
- {
+ try {
m_directives = new String(directives, "UTF-8");
- }
- catch(UnsupportedEncodingException e)
- {
+ } catch (UnsupportedEncodingException e) {
m_state = STATE_NO_UTF8_SUPPORT;
}
}
@@ -70,149 +67,113 @@ class DirectiveList extends Object
* name followed by an equal sign (=) and the directive value. The value is
* either a token or a quoted string
*
- * @exception SaslException If an error Occurs
+ * @throws SaslException If an error Occurs
*/
- void parseDirectives() throws SaslException
- {
- char prevChar;
- char currChar;
- int rc = 0;
- boolean haveQuotedPair = false;
- String currentName = "";
+ void parseDirectives() throws SaslException {
+ char prevChar;
+ char currChar;
+ int rc = 0;
+ boolean haveQuotedPair = false;
+ String currentName = "";
if (m_state == STATE_NO_UTF8_SUPPORT)
throw new SaslException("No UTF-8 support on platform");
prevChar = 0;
- while (m_curPos < m_directives.length())
- {
+ while (m_curPos < m_directives.length()) {
currChar = m_directives.charAt(m_curPos);
- switch (m_state)
- {
- case STATE_LOOKING_FOR_FIRST_DIRECTIVE:
- case STATE_LOOKING_FOR_DIRECTIVE:
- if (isWhiteSpace(currChar))
- {
+ switch (m_state) {
+ case STATE_LOOKING_FOR_FIRST_DIRECTIVE:
+ case STATE_LOOKING_FOR_DIRECTIVE:
+ if (isWhiteSpace(currChar)) {
+ break;
+ } else if (isValidTokenChar(currChar)) {
+ m_scanStart = m_curPos;
+ m_state = STATE_SCANNING_NAME;
+ } else {
+ m_errorPos = m_curPos;
+ throw new SaslException("Parse error: Invalid name character");
+ }
break;
- }
- else if (isValidTokenChar(currChar))
- {
- m_scanStart = m_curPos;
- m_state = STATE_SCANNING_NAME;
- }
- else
- {
- m_errorPos = m_curPos;
- throw new SaslException("Parse error: Invalid name character");
- }
- break;
- case STATE_SCANNING_NAME:
- if (isValidTokenChar(currChar))
- {
+ case STATE_SCANNING_NAME:
+ if (isValidTokenChar(currChar)) {
+ break;
+ } else if (isWhiteSpace(currChar)) {
+ currentName = m_directives.substring(m_scanStart, m_curPos);
+ m_state = STATE_LOOKING_FOR_EQUALS;
+ } else if ('=' == currChar) {
+ currentName = m_directives.substring(m_scanStart, m_curPos);
+ m_state = STATE_LOOKING_FOR_VALUE;
+ } else {
+ m_errorPos = m_curPos;
+ throw new SaslException("Parse error: Invalid name character");
+ }
break;
- }
- else if (isWhiteSpace(currChar))
- {
- currentName = m_directives.substring(m_scanStart, m_curPos);
- m_state = STATE_LOOKING_FOR_EQUALS;
- }
- else if ('=' == currChar)
- {
- currentName = m_directives.substring(m_scanStart, m_curPos);
- m_state = STATE_LOOKING_FOR_VALUE;
- }
- else
- {
- m_errorPos = m_curPos;
- throw new SaslException("Parse error: Invalid name character");
- }
- break;
- case STATE_LOOKING_FOR_EQUALS:
- if (isWhiteSpace(currChar))
- {
+ case STATE_LOOKING_FOR_EQUALS:
+ if (isWhiteSpace(currChar)) {
+ break;
+ } else if ('=' == currChar) {
+ m_state = STATE_LOOKING_FOR_VALUE;
+ } else {
+ m_errorPos = m_curPos;
+ throw new SaslException("Parse error: Expected equals sign '='.");
+ }
break;
- }
- else if ('=' == currChar)
- {
- m_state = STATE_LOOKING_FOR_VALUE;
- }
- else
- {
- m_errorPos = m_curPos;
- throw new SaslException("Parse error: Expected equals sign '='.");
- }
- break;
- case STATE_LOOKING_FOR_VALUE:
- if (isWhiteSpace(currChar))
- {
+ case STATE_LOOKING_FOR_VALUE:
+ if (isWhiteSpace(currChar)) {
+ break;
+ } else if ('"' == currChar) {
+ m_scanStart = m_curPos + 1; /* don't include the quote */
+ m_state = STATE_SCANNING_QUOTED_STRING_VALUE;
+ } else if (isValidTokenChar(currChar)) {
+ m_scanStart = m_curPos;
+ m_state = STATE_SCANNING_TOKEN_VALUE;
+ } else {
+ m_errorPos = m_curPos;
+ throw new SaslException("Parse error: Unexpected character");
+ }
break;
- }
- else if ('"' == currChar)
- {
- m_scanStart = m_curPos+1; /* don't include the quote */
- m_state = STATE_SCANNING_QUOTED_STRING_VALUE;
- }
- else if (isValidTokenChar(currChar))
- {
- m_scanStart = m_curPos;
- m_state = STATE_SCANNING_TOKEN_VALUE;
- }
- else
- {
- m_errorPos = m_curPos;
- throw new SaslException("Parse error: Unexpected character");
- }
- break;
- case STATE_SCANNING_TOKEN_VALUE:
- if (isValidTokenChar(currChar))
- {
+ case STATE_SCANNING_TOKEN_VALUE:
+ if (isValidTokenChar(currChar)) {
+ break;
+ } else if (isWhiteSpace(currChar)) {
+ addDirective(currentName, false);
+ m_state = STATE_LOOKING_FOR_COMMA;
+ } else if (',' == currChar) {
+ addDirective(currentName, false);
+ m_state = STATE_LOOKING_FOR_DIRECTIVE;
+ } else {
+ m_errorPos = m_curPos;
+ throw new SaslException("Parse error: Invalid value character");
+ }
break;
- }
- else if (isWhiteSpace(currChar))
- {
- addDirective(currentName, false);
- m_state = STATE_LOOKING_FOR_COMMA;
- }
- else if (',' == currChar)
- {
- addDirective(currentName, false);
- m_state = STATE_LOOKING_FOR_DIRECTIVE;
- }
- else
- {
- m_errorPos = m_curPos;
- throw new SaslException("Parse error: Invalid value character");
- }
- break;
- case STATE_SCANNING_QUOTED_STRING_VALUE:
- if ('\\' == currChar)
- haveQuotedPair = true;
- if ( ('"' == currChar) &&
- ('\\' != prevChar) )
- {
- addDirective(currentName, haveQuotedPair);
- haveQuotedPair = false;
- m_state = STATE_LOOKING_FOR_COMMA;
- }
- break;
+ case STATE_SCANNING_QUOTED_STRING_VALUE:
+ if ('\\' == currChar)
+ haveQuotedPair = true;
+ if (('"' == currChar) &&
+ ('\\' != prevChar)) {
+ addDirective(currentName, haveQuotedPair);
+ haveQuotedPair = false;
+ m_state = STATE_LOOKING_FOR_COMMA;
+ }
+ break;
- case STATE_LOOKING_FOR_COMMA:
- if (isWhiteSpace(currChar))
+ case STATE_LOOKING_FOR_COMMA:
+ if (isWhiteSpace(currChar))
+ break;
+ else if (currChar == ',')
+ m_state = STATE_LOOKING_FOR_DIRECTIVE;
+ else {
+ m_errorPos = m_curPos;
+ throw new SaslException("Parse error: Expected a comma.");
+ }
break;
- else if (currChar == ',')
- m_state = STATE_LOOKING_FOR_DIRECTIVE;
- else
- {
- m_errorPos = m_curPos;
- throw new SaslException("Parse error: Expected a comma.");
- }
- break;
}
if (0 != rc)
break;
@@ -221,28 +182,26 @@ else if (currChar == ',')
} /* end while loop */
- if (rc == 0)
- {
+ if (rc == 0) {
/* check the ending state */
- switch (m_state)
- {
- case STATE_SCANNING_TOKEN_VALUE:
- addDirective(currentName, false);
- break;
+ switch (m_state) {
+ case STATE_SCANNING_TOKEN_VALUE:
+ addDirective(currentName, false);
+ break;
- case STATE_LOOKING_FOR_FIRST_DIRECTIVE:
- case STATE_LOOKING_FOR_COMMA:
- break;
+ case STATE_LOOKING_FOR_FIRST_DIRECTIVE:
+ case STATE_LOOKING_FOR_COMMA:
+ break;
- case STATE_LOOKING_FOR_DIRECTIVE:
+ case STATE_LOOKING_FOR_DIRECTIVE:
throw new SaslException("Parse error: Trailing comma.");
- case STATE_SCANNING_NAME:
- case STATE_LOOKING_FOR_EQUALS:
- case STATE_LOOKING_FOR_VALUE:
+ case STATE_SCANNING_NAME:
+ case STATE_LOOKING_FOR_EQUALS:
+ case STATE_LOOKING_FOR_VALUE:
throw new SaslException("Parse error: Missing value.");
- case STATE_SCANNING_QUOTED_STRING_VALUE:
+ case STATE_SCANNING_QUOTED_STRING_VALUE:
throw new SaslException("Parse error: Missing closing quote.");
}
}
@@ -251,36 +210,34 @@ else if (currChar == ',')
/**
* This function returns TRUE if the character is a valid token character.
+ *
+ * token = 1*
+ *
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
+ *
+ * CTL =
+ *
+ * CHAR =
*
- * token = 1*
- *
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- *
- * CTL =
- *
- * CHAR =
- *
- * @param c character to be tested
- *
+ * @param c character to be tested
* @return Returns TRUE if the character is a valid token character.
*/
boolean isValidTokenChar(
- char c)
- {
- if ( ( (c >= '\u0000') && (c <='\u0020') ) ||
- ( (c >= '\u003a') && (c <= '\u0040') ) ||
- ( (c >= '\u005b') && (c <= '\u005d') ) ||
- ('\u002c' == c) ||
- ('\u0025' == c) ||
- ('\u0028' == c) ||
- ('\u0029' == c) ||
- ('\u007b' == c) ||
- ('\u007d' == c) ||
- ('\u007f' == c) )
+ char c) {
+ if (((c >= '\u0000') && (c <= '\u0020')) ||
+ ((c >= '\u003a') && (c <= '\u0040')) ||
+ ((c >= '\u005b') && (c <= '\u005d')) ||
+ ('\u002c' == c) ||
+ ('\u0025' == c) ||
+ ('\u0028' == c) ||
+ ('\u0029' == c) ||
+ ('\u007b' == c) ||
+ ('\u007d' == c) ||
+ ('\u007f' == c))
return false;
return true;
@@ -288,18 +245,17 @@ boolean isValidTokenChar(
/**
* This function returns TRUE if the character is linear white space (LWS).
- * LWS = [CRLF] 1*( SP | HT )
- * @param c Input charcter to be tested
+ * LWS = [CRLF] 1*( SP | HT )
*
+ * @param c Input charcter to be tested
* @return Returns TRUE if the character is linear white space (LWS)
*/
boolean isWhiteSpace(
- char c)
- {
- if ( ('\t' == c) || // HORIZONTAL TABULATION.
- ('\n' == c) || // LINE FEED.
- ('\r' == c) || // CARRIAGE RETURN.
- ('\u0020' == c) )
+ char c) {
+ if (('\t' == c) || // HORIZONTAL TABULATION.
+ ('\n' == c) || // LINE FEED.
+ ('\r' == c) || // CARRIAGE RETURN.
+ ('\u0020' == c))
return true;
return false;
@@ -309,30 +265,25 @@ boolean isWhiteSpace(
* This function creates a directive record and adds it to the list, the
* value will be added later after it is parsed.
*
- * @param name Name
+ * @param name Name
* @param haveQuotedPair true if quoted pair is there else false
*/
void addDirective(
- String name,
- boolean haveQuotedPair)
- {
+ String name,
+ boolean haveQuotedPair) {
String value;
- int inputIndex;
- int valueIndex;
- char valueChar;
- int type;
+ int inputIndex;
+ int valueIndex;
+ char valueChar;
+ int type;
- if (!haveQuotedPair)
- {
+ if (!haveQuotedPair) {
value = m_directives.substring(m_scanStart, m_curPos);
- }
- else
- { //copy one character at a time skipping backslash excapes.
+ } else { //copy one character at a time skipping backslash excapes.
StringBuffer valueBuf = new StringBuffer(m_curPos - m_scanStart);
valueIndex = 0;
inputIndex = m_scanStart;
- while (inputIndex < m_curPos)
- {
+ while (inputIndex < m_curPos) {
if ('\\' == (valueChar = m_directives.charAt(inputIndex)))
inputIndex++;
valueBuf.setCharAt(valueIndex, m_directives.charAt(inputIndex));
@@ -353,10 +304,9 @@ void addDirective(
/**
* Returns the List iterator.
*
- * @return Returns the Iterator Object for the List.
+ * @return Returns the Iterator Object for the List.
*/
- Iterator getIterator()
- {
+ Iterator getIterator() {
return m_directiveList.iterator();
}
}
diff --git a/app/src/main/java/com/novell/sasl/client/ParsedDirective.java b/app/src/main/java/com/novell/sasl/client/ParsedDirective.java
index 17bf70e04a..921a99bc61 100644
--- a/app/src/main/java/com/novell/sasl/client/ParsedDirective.java
+++ b/app/src/main/java/com/novell/sasl/client/ParsedDirective.java
@@ -18,37 +18,32 @@
* Implements the ParsedDirective class which will be used in the
* DigestMD5SaslClient mechanism.
*/
-class ParsedDirective
-{
- public static final int QUOTED_STRING_VALUE = 1;
- public static final int TOKEN_VALUE = 2;
+class ParsedDirective {
+ public static final int QUOTED_STRING_VALUE = 1;
+ public static final int TOKEN_VALUE = 2;
- private int m_valueType;
- private String m_name;
- private String m_value;
+ private int m_valueType;
+ private String m_name;
+ private String m_value;
ParsedDirective(
- String name,
- String value,
- int type)
- {
+ String name,
+ String value,
+ int type) {
m_name = name;
m_value = value;
m_valueType = type;
}
- String getValue()
- {
+ String getValue() {
return m_value;
}
- String getName()
- {
+ String getName() {
return m_name;
}
- int getValueType()
- {
+ int getValueType() {
return m_valueType;
}
diff --git a/app/src/main/java/com/novell/sasl/client/ResponseAuth.java b/app/src/main/java/com/novell/sasl/client/ResponseAuth.java
index 0aef955d05..885b32fd50 100644
--- a/app/src/main/java/com/novell/sasl/client/ResponseAuth.java
+++ b/app/src/main/java/com/novell/sasl/client/ResponseAuth.java
@@ -15,30 +15,26 @@
package com.novell.sasl.client;
import java.util.*;
+
import org.apache.harmony.javax.security.sasl.*;
/**
* Implements the ResponseAuth class used by the DigestMD5SaslClient mechanism
*/
-class ResponseAuth
-{
+class ResponseAuth {
private String m_responseValue;
ResponseAuth(
- byte[] responseAuth)
- throws SaslException
- {
+ byte[] responseAuth)
+ throws SaslException {
m_responseValue = null;
DirectiveList dirList = new DirectiveList(responseAuth);
- try
- {
+ try {
dirList.parseDirectives();
checkSemantics(dirList);
- }
- catch (SaslException e)
- {
+ } catch (SaslException e) {
}
}
@@ -46,20 +42,17 @@ class ResponseAuth
* Checks the semantics of the directives in the directive list as parsed
* from the digest challenge byte array.
*
- * @param dirList the list of directives parsed from the digest challenge
- *
- * @exception SaslException If a semantic error occurs
+ * @param dirList the list of directives parsed from the digest challenge
+ * @throws SaslException If a semantic error occurs
*/
void checkSemantics(
- DirectiveList dirList) throws SaslException
- {
- Iterator directives = dirList.getIterator();
+ DirectiveList dirList) throws SaslException {
+ Iterator directives = dirList.getIterator();
ParsedDirective directive;
- String name;
+ String name;
- while (directives.hasNext())
- {
- directive = (ParsedDirective)directives.next();
+ while (directives.hasNext()) {
+ directive = (ParsedDirective) directives.next();
name = directive.getName();
if (name.equals("rspauth"))
m_responseValue = directive.getValue();
@@ -75,8 +68,7 @@ void checkSemantics(
*
* @return the ResponseValue as a String.
*/
- public String getResponseValue()
- {
+ public String getResponseValue() {
return m_responseValue;
}
}
diff --git a/app/src/main/java/com/novell/sasl/client/TokenParser.java b/app/src/main/java/com/novell/sasl/client/TokenParser.java
index 3d3491de92..d2711cd87a 100644
--- a/app/src/main/java/com/novell/sasl/client/TokenParser.java
+++ b/app/src/main/java/com/novell/sasl/client/TokenParser.java
@@ -15,131 +15,111 @@
package com.novell.sasl.client;
import org.apache.harmony.javax.security.sasl.*;
+
/**
* The TokenParser class will parse individual tokens from a list of tokens that
* are a directive value for a DigestMD5 authentication.The tokens are separated
* commas.
*/
-class TokenParser extends Object
-{
+class TokenParser extends Object {
private static final int STATE_LOOKING_FOR_FIRST_TOKEN = 1;
- private static final int STATE_LOOKING_FOR_TOKEN = 2;
- private static final int STATE_SCANNING_TOKEN = 3;
- private static final int STATE_LOOKING_FOR_COMMA = 4;
- private static final int STATE_PARSING_ERROR = 5;
- private static final int STATE_DONE = 6;
+ private static final int STATE_LOOKING_FOR_TOKEN = 2;
+ private static final int STATE_SCANNING_TOKEN = 3;
+ private static final int STATE_LOOKING_FOR_COMMA = 4;
+ private static final int STATE_PARSING_ERROR = 5;
+ private static final int STATE_DONE = 6;
- private int m_curPos;
- private int m_scanStart;
- private int m_state;
- private String m_tokens;
+ private int m_curPos;
+ private int m_scanStart;
+ private int m_state;
+ private String m_tokens;
TokenParser(
- String tokens)
- {
+ String tokens) {
m_tokens = tokens;
m_curPos = 0;
m_scanStart = 0;
- m_state = STATE_LOOKING_FOR_FIRST_TOKEN;
+ m_state = STATE_LOOKING_FOR_FIRST_TOKEN;
}
/**
* This function parses the next token from the tokens string and returns
* it as a string. If there are no more tokens a null reference is returned.
*
- * @return the parsed token or a null reference if there are no more
+ * @return the parsed token or a null reference if there are no more
* tokens
- *
- * @exception SASLException if an error occurs while parsing
+ * @throws SASLException if an error occurs while parsing
*/
- String parseToken() throws SaslException
- {
- char currChar;
- String token = null;
+ String parseToken() throws SaslException {
+ char currChar;
+ String token = null;
if (m_state == STATE_DONE)
return null;
- while (m_curPos < m_tokens.length() && (token == null))
- {
+ while (m_curPos < m_tokens.length() && (token == null)) {
currChar = m_tokens.charAt(m_curPos);
- switch (m_state)
- {
- case STATE_LOOKING_FOR_FIRST_TOKEN:
- case STATE_LOOKING_FOR_TOKEN:
- if (isWhiteSpace(currChar))
- {
+ switch (m_state) {
+ case STATE_LOOKING_FOR_FIRST_TOKEN:
+ case STATE_LOOKING_FOR_TOKEN:
+ if (isWhiteSpace(currChar)) {
+ break;
+ } else if (isValidTokenChar(currChar)) {
+ m_scanStart = m_curPos;
+ m_state = STATE_SCANNING_TOKEN;
+ } else {
+ m_state = STATE_PARSING_ERROR;
+ throw new SaslException("Invalid token character at position " + m_curPos);
+ }
break;
- }
- else if (isValidTokenChar(currChar))
- {
- m_scanStart = m_curPos;
- m_state = STATE_SCANNING_TOKEN;
- }
- else
- {
- m_state = STATE_PARSING_ERROR;
- throw new SaslException("Invalid token character at position " + m_curPos);
- }
- break;
-
- case STATE_SCANNING_TOKEN:
- if (isValidTokenChar(currChar))
- {
+
+ case STATE_SCANNING_TOKEN:
+ if (isValidTokenChar(currChar)) {
+ break;
+ } else if (isWhiteSpace(currChar)) {
+ token = m_tokens.substring(m_scanStart, m_curPos);
+ m_state = STATE_LOOKING_FOR_COMMA;
+ } else if (',' == currChar) {
+ token = m_tokens.substring(m_scanStart, m_curPos);
+ m_state = STATE_LOOKING_FOR_TOKEN;
+ } else {
+ m_state = STATE_PARSING_ERROR;
+ throw new SaslException("Invalid token character at position " + m_curPos);
+ }
break;
- }
- else if (isWhiteSpace(currChar))
- {
- token = m_tokens.substring(m_scanStart, m_curPos);
- m_state = STATE_LOOKING_FOR_COMMA;
- }
- else if (',' == currChar)
- {
- token = m_tokens.substring(m_scanStart, m_curPos);
- m_state = STATE_LOOKING_FOR_TOKEN;
- }
- else
- {
- m_state = STATE_PARSING_ERROR;
- throw new SaslException("Invalid token character at position " + m_curPos);
- }
- break;
-
-
- case STATE_LOOKING_FOR_COMMA:
- if (isWhiteSpace(currChar))
+
+
+ case STATE_LOOKING_FOR_COMMA:
+ if (isWhiteSpace(currChar))
+ break;
+ else if (currChar == ',')
+ m_state = STATE_LOOKING_FOR_TOKEN;
+ else {
+ m_state = STATE_PARSING_ERROR;
+ throw new SaslException("Expected a comma, found '" +
+ currChar + "' at postion " +
+ m_curPos);
+ }
break;
- else if (currChar == ',')
- m_state = STATE_LOOKING_FOR_TOKEN;
- else
- {
- m_state = STATE_PARSING_ERROR;
- throw new SaslException("Expected a comma, found '" +
- currChar + "' at postion " +
- m_curPos);
- }
- break;
}
m_curPos++;
} /* end while loop */
- if (token == null)
- { /* check the ending state */
- switch (m_state)
- {
- case STATE_SCANNING_TOKEN:
- token = m_tokens.substring(m_scanStart);
- m_state = STATE_DONE;
- break;
-
- case STATE_LOOKING_FOR_FIRST_TOKEN:
- case STATE_LOOKING_FOR_COMMA:
- break;
-
- case STATE_LOOKING_FOR_TOKEN:
- throw new SaslException("Trialing comma");
+ if (token == null) { /* check the ending state */
+ switch (m_state) {
+ case STATE_SCANNING_TOKEN:
+ token = m_tokens.substring(m_scanStart);
+ m_state = STATE_DONE;
+ break;
+
+ case STATE_LOOKING_FOR_FIRST_TOKEN:
+ case STATE_LOOKING_FOR_COMMA:
+ break;
+
+ case STATE_LOOKING_FOR_TOKEN:
+ throw new SaslException("Trialing comma");
}
}
@@ -148,37 +128,35 @@ else if (currChar == ',')
/**
* This function returns TRUE if the character is a valid token character.
+ *
+ * token = 1*
+ *
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
+ *
+ * CTL =
+ *
+ * CHAR =
*
- * token = 1*
- *
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- *
- * CTL =
- *
- * CHAR =
- *
- * @param c character to be validated
- *
- * @return True if character is valid Token character else it returns
+ * @param c character to be validated
+ * @return True if character is valid Token character else it returns
* false
*/
boolean isValidTokenChar(
- char c)
- {
- if ( ( (c >= '\u0000') && (c <='\u0020') ) ||
- ( (c >= '\u003a') && (c <= '\u0040') ) ||
- ( (c >= '\u005b') && (c <= '\u005d') ) ||
- ('\u002c' == c) ||
- ('\u0025' == c) ||
- ('\u0028' == c) ||
- ('\u0029' == c) ||
- ('\u007b' == c) ||
- ('\u007d' == c) ||
- ('\u007f' == c) )
+ char c) {
+ if (((c >= '\u0000') && (c <= '\u0020')) ||
+ ((c >= '\u003a') && (c <= '\u0040')) ||
+ ((c >= '\u005b') && (c <= '\u005d')) ||
+ ('\u002c' == c) ||
+ ('\u0025' == c) ||
+ ('\u0028' == c) ||
+ ('\u0029' == c) ||
+ ('\u007b' == c) ||
+ ('\u007d' == c) ||
+ ('\u007f' == c))
return false;
return true;
@@ -186,19 +164,17 @@ boolean isValidTokenChar(
/**
* This function returns TRUE if the character is linear white space (LWS).
- * LWS = [CRLF] 1*( SP | HT )
- *
- * @param c character to be validated
+ * LWS = [CRLF] 1*( SP | HT )
*
+ * @param c character to be validated
* @return True if character is liner whitespace else it returns false
*/
boolean isWhiteSpace(
- char c)
- {
- if ( ('\t' == c) || // HORIZONTAL TABULATION.
- ('\n' == c) || // LINE FEED.
- ('\r' == c) || // CARRIAGE RETURN.
- ('\u0020' == c) )
+ char c) {
+ if (('\t' == c) || // HORIZONTAL TABULATION.
+ ('\n' == c) || // LINE FEED.
+ ('\r' == c) || // CARRIAGE RETURN.
+ ('\u0020' == c))
return true;
return false;
diff --git a/app/src/main/java/com/xabber/android/data/AbstractTable.java b/app/src/main/java/com/xabber/android/data/AbstractTable.java
index f507443d11..c082f12f25 100644
--- a/app/src/main/java/com/xabber/android/data/AbstractTable.java
+++ b/app/src/main/java/com/xabber/android/data/AbstractTable.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
- *
+ *
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
- *
+ *
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
@@ -19,39 +19,38 @@
/**
* Abstract database table.
- *
+ *
* @author alexander.ivanov
- *
*/
public abstract class AbstractTable implements DatabaseTable {
- protected abstract String getTableName();
-
- protected abstract String[] getProjection();
-
- protected String getListOrder() {
- return null;
- }
-
- @Override
- public void migrate(SQLiteDatabase db, int toVersion) {
- }
-
- /**
- * Query table.
- *
- * @return Result set with defined projection and in defined order.
- */
- public Cursor list() {
- SQLiteDatabase db = DatabaseManager.getInstance().getReadableDatabase();
- return db.query(getTableName(), getProjection(), null, null, null,
- null, getListOrder());
- }
-
- @Override
- public void clear() {
- SQLiteDatabase db = DatabaseManager.getInstance().getWritableDatabase();
- db.delete(getTableName(), null, null);
- }
+ protected abstract String getTableName();
+
+ protected abstract String[] getProjection();
+
+ protected String getListOrder() {
+ return null;
+ }
+
+ @Override
+ public void migrate(SQLiteDatabase db, int toVersion) {
+ }
+
+ /**
+ * Query table.
+ *
+ * @return Result set with defined projection and in defined order.
+ */
+ public Cursor list() {
+ SQLiteDatabase db = DatabaseManager.getInstance().getReadableDatabase();
+ return db.query(getTableName(), getProjection(), null, null, null,
+ null, getListOrder());
+ }
+
+ @Override
+ public void clear() {
+ SQLiteDatabase db = DatabaseManager.getInstance().getWritableDatabase();
+ db.delete(getTableName(), null, null);
+ }
}
diff --git a/app/src/main/java/com/xabber/android/data/ActivityManager.java b/app/src/main/java/com/xabber/android/data/ActivityManager.java
index 0871f70235..017923c907 100644
--- a/app/src/main/java/com/xabber/android/data/ActivityManager.java
+++ b/app/src/main/java/com/xabber/android/data/ActivityManager.java
@@ -1,322 +1,295 @@
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
- *
+ *
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
- *
+ *
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.xabber.android.data;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map.Entry;
-import java.util.WeakHashMap;
-
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
-import android.content.res.TypedArray;
import android.os.Bundle;
import android.widget.Toast;
-import com.xabber.android.data.SettingsManager.InterfaceTheme;
+import com.xabber.android.R;
import com.xabber.android.ui.ContactList;
import com.xabber.android.ui.LoadActivity;
-import com.xabber.android.ui.PreferenceEditor;
-import com.xabber.androiddev.R;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Map.Entry;
+import java.util.WeakHashMap;
/**
* Activity stack manager.
- *
+ *
* @author alexander.ivanov
- *
*/
public class ActivityManager implements OnUnloadListener {
- private static final String EXTRA_TASK_INDEX = "com.xabber.android.data.ActivityManager.EXTRA_TASK_INDEX";
-
- private static final boolean LOG = true;
-
- private final Application application;
-
- /**
- * List of launched activities.
- */
- private final ArrayList activities;
-
- /**
- * Next index of task.
- */
- private int nextTaskIndex;
-
- /**
- * Activity with index of it task.
- */
- private final WeakHashMap taskIndexes;
+ private static final String EXTRA_TASK_INDEX = "com.xabber.android.data.ActivityManager.EXTRA_TASK_INDEX";
- /**
- * Listener for errors.
- */
- private OnErrorListener onErrorListener;
+ private static final boolean LOG = true;
+ private final static ActivityManager instance;
- private final static ActivityManager instance;
+ static {
+ instance = new ActivityManager();
+ Application.getInstance().addManager(instance);
+ }
- static {
- instance = new ActivityManager();
- Application.getInstance().addManager(instance);
- }
+ private final Application application;
+ /**
+ * List of launched activities.
+ */
+ private final ArrayList activities;
+ /**
+ * Activity with index of it task.
+ */
+ private final WeakHashMap taskIndexes;
+ /**
+ * Next index of task.
+ */
+ private int nextTaskIndex;
+ /**
+ * Listener for errors.
+ */
+ private OnErrorListener onErrorListener;
- public static ActivityManager getInstance() {
- return instance;
- }
+ private ActivityManager() {
+ this.application = Application.getInstance();
+ activities = new ArrayList();
+ nextTaskIndex = 0;
+ taskIndexes = new WeakHashMap();
+ }
- private ActivityManager() {
- this.application = Application.getInstance();
- activities = new ArrayList();
- nextTaskIndex = 0;
- taskIndexes = new WeakHashMap();
- }
+ public static ActivityManager getInstance() {
+ return instance;
+ }
- /**
- * Removes finished activities from stask.
- */
- private void rebuildStack() {
- Iterator iterator = activities.iterator();
- while (iterator.hasNext())
- if (iterator.next().isFinishing())
- iterator.remove();
- }
+ /**
+ * Removes finished activities from stask.
+ */
+ private void rebuildStack() {
+ Iterator iterator = activities.iterator();
+ while (iterator.hasNext())
+ if (iterator.next().isFinishing())
+ iterator.remove();
+ }
- /**
- * Finish all activities in stack till the root contact list.
- *
- * @param finishRoot
- * also finish root contact list.
- */
- public void clearStack(boolean finishRoot) {
- ContactList root = null;
- rebuildStack();
- for (Activity activity : activities) {
- if (!finishRoot && root == null && activity instanceof ContactList)
- root = (ContactList) activity;
- else
- activity.finish();
- }
- rebuildStack();
- }
+ /**
+ * Finish all activities in stack till the root contact list.
+ *
+ * @param finishRoot also finish root contact list.
+ */
+ public void clearStack(boolean finishRoot) {
+ ContactList root = null;
+ rebuildStack();
+ for (Activity activity : activities) {
+ if (!finishRoot && root == null && activity instanceof ContactList)
+ root = (ContactList) activity;
+ else
+ activity.finish();
+ }
+ rebuildStack();
+ }
- /**
- * @return Whether contact list is in the activity stack.
- */
- public boolean hasContactList(Context context) {
- rebuildStack();
- for (Activity activity : activities)
- if (activity instanceof ContactList)
- return true;
- return false;
- }
+ /**
+ * @return Whether contact list is in the activity stack.
+ */
+ public boolean hasContactList(Context context) {
+ rebuildStack();
+ for (Activity activity : activities)
+ if (activity instanceof ContactList)
+ return true;
+ return false;
+ }
- /**
- * Apply theme settings.
- *
- * @param activity
- */
- private void applyTheme(Activity activity) {
- if (activity instanceof PreferenceEditor)
- return;
- TypedArray title = activity.getTheme().obtainStyledAttributes(
- new int[] { android.R.attr.windowNoTitle,
- android.R.attr.windowIsFloating });
- boolean noTitle = title.getBoolean(0, false);
- boolean isFloating = title.getBoolean(1, false);
- title.recycle();
- if (isFloating)
- return;
- InterfaceTheme theme = SettingsManager.interfaceTheme();
- if (theme == SettingsManager.InterfaceTheme.light)
- activity.setTheme(noTitle ? R.style.Theme_Light_NoTitleBar
- : R.style.Theme_Light);
- else if (theme == SettingsManager.InterfaceTheme.dark)
- activity.setTheme(noTitle ? R.style.Theme_Dark_NoTitleBar
- : R.style.Theme_Dark);
- }
+ /**
+ * Apply theme settings.
+ *
+ * @param activity
+ */
+ private void applyTheme(Activity activity) {
+ activity.setTheme(R.style.Theme);
+ }
- /**
- * Push activity to stack.
- *
- * Must be called from {@link Activity#onCreate(Bundle)}.
- *
- * @param activity
- */
- public void onCreate(Activity activity) {
- if (LOG)
- LogManager.i(activity, "onCreate: " + activity.getIntent());
- applyTheme(activity);
- if (application.isClosing() && !(activity instanceof LoadActivity)) {
- activity.startActivity(LoadActivity.createIntent(activity));
- activity.finish();
- }
- activities.add(activity);
- rebuildStack();
- fetchTaskIndex(activity, activity.getIntent());
- }
+ /**
+ * Push activity to stack.
+ *
+ * Must be called from {@link Activity#onCreate(Bundle)}.
+ *
+ * @param activity
+ */
+ public void onCreate(Activity activity) {
+ if (LOG)
+ LogManager.i(activity, "onCreate: " + activity.getIntent());
+ if (application.isClosing() && !(activity instanceof LoadActivity)) {
+ activity.startActivity(LoadActivity.createIntent(activity));
+ activity.finish();
+ }
+ activities.add(activity);
+ rebuildStack();
+ fetchTaskIndex(activity, activity.getIntent());
+ }
- /**
- * Pop activity from stack.
- *
- * Must be called from {@link Activity#onDestroy()}.
- *
- * @param activity
- */
- public void onDestroy(Activity activity) {
- if (LOG)
- LogManager.i(activity, "onDestroy");
- activities.remove(activity);
- }
+ /**
+ * Pop activity from stack.
+ *
+ * Must be called from {@link Activity#onDestroy()}.
+ *
+ * @param activity
+ */
+ public void onDestroy(Activity activity) {
+ if (LOG)
+ LogManager.i(activity, "onDestroy");
+ activities.remove(activity);
+ }
- /**
- * Pause activity.
- *
- * Must be called from {@link Activity#onPause()}.
- *
- * @param activity
- */
- public void onPause(Activity activity) {
- if (LOG)
- LogManager.i(activity, "onPause");
- if (onErrorListener != null)
- application
- .removeUIListener(OnErrorListener.class, onErrorListener);
- onErrorListener = null;
- }
+ /**
+ * Pause activity.
+ *
+ * Must be called from {@link Activity#onPause()}.
+ *
+ * @param activity
+ */
+ public void onPause(Activity activity) {
+ if (LOG)
+ LogManager.i(activity, "onPause");
+ if (onErrorListener != null)
+ application
+ .removeUIListener(OnErrorListener.class, onErrorListener);
+ onErrorListener = null;
+ }
- /**
- * Resume activity.
- *
- * Must be called from {@link Activity#onResume()}.
- *
- * @param activity
- */
- public void onResume(final Activity activity) {
- if (LOG)
- LogManager.i(activity, "onResume");
- if (!application.isInitialized() && !(activity instanceof LoadActivity)) {
- if (LOG)
- LogManager.i(this, "Wait for loading");
- activity.startActivity(LoadActivity.createIntent(activity));
- }
- if (onErrorListener != null)
- application
- .removeUIListener(OnErrorListener.class, onErrorListener);
- onErrorListener = new OnErrorListener() {
- @Override
- public void onError(final int resourceId) {
- Toast.makeText(activity, activity.getString(resourceId),
- Toast.LENGTH_LONG).show();
- }
- };
- application.addUIListener(OnErrorListener.class, onErrorListener);
- }
+ /**
+ * Resume activity.
+ *
+ * Must be called from {@link Activity#onResume()}.
+ *
+ * @param activity
+ */
+ public void onResume(final Activity activity) {
+ if (LOG)
+ LogManager.i(activity, "onResume");
+ if (!application.isInitialized() && !(activity instanceof LoadActivity)) {
+ if (LOG)
+ LogManager.i(this, "Wait for loading");
+ activity.startActivity(LoadActivity.createIntent(activity));
+ }
+ if (onErrorListener != null) {
+ application.removeUIListener(OnErrorListener.class, onErrorListener);
+ }
+ onErrorListener = new OnErrorListener() {
+ @Override
+ public void onError(final int resourceId) {
+ Toast.makeText(activity, activity.getString(resourceId),
+ Toast.LENGTH_LONG).show();
+ }
+ };
+ application.addUIListener(OnErrorListener.class, onErrorListener);
+ }
- /**
- * New intent received.
- *
- * Must be called from {@link Activity#onNewIntent(Intent)}.
- *
- * @param activity
- * @param intent
- */
- public void onNewIntent(Activity activity, Intent intent) {
- if (LOG)
- LogManager.i(activity, "onNewIntent: " + intent);
- }
+ /**
+ * New intent received.
+ *
+ * Must be called from {@link Activity#onNewIntent(Intent)}.
+ *
+ * @param activity
+ * @param intent
+ */
+ public void onNewIntent(Activity activity, Intent intent) {
+ if (LOG)
+ LogManager.i(activity, "onNewIntent: " + intent);
+ }
- /**
- * Result has been received.
- *
- * Must be called from {@link Activity#onActivityResult(int, int, Intent)}.
- *
- * @param activity
- * @param requestCode
- * @param resultCode
- * @param data
- */
- public void onActivityResult(Activity activity, int requestCode,
- int resultCode, Intent data) {
- if (LOG)
- LogManager.i(activity, "onActivityResult: " + requestCode + ", "
- + resultCode + ", " + data);
- }
+ /**
+ * Result has been received.
+ *
+ * Must be called from {@link Activity#onActivityResult(int, int, Intent)}.
+ *
+ * @param activity
+ * @param requestCode
+ * @param resultCode
+ * @param data
+ */
+ public void onActivityResult(Activity activity, int requestCode,
+ int resultCode, Intent data) {
+ if (LOG)
+ LogManager.i(activity, "onActivityResult: " + requestCode + ", "
+ + resultCode + ", " + data);
+ }
- /**
- * Adds task index to the intent if specified for the source activity.
- *
- * Must be used when source activity starts new own activity from
- * {@link Activity#startActivity(Intent)} and
- * {@link Activity#startActivityForResult(Intent, int)}.
- *
- * @param source
- * @param intent
- */
- public void updateIntent(Activity source, Intent intent) {
- Integer index = taskIndexes.get(source);
- if (index == null)
- return;
- intent.putExtra(EXTRA_TASK_INDEX, index);
- }
+ /**
+ * Adds task index to the intent if specified for the source activity.
+ *
+ * Must be used when source activity starts new own activity from
+ * {@link Activity#startActivity(Intent)} and
+ * {@link Activity#startActivityForResult(Intent, int)}.
+ *
+ * @param source
+ * @param intent
+ */
+ public void updateIntent(Activity source, Intent intent) {
+ Integer index = taskIndexes.get(source);
+ if (index == null)
+ return;
+ intent.putExtra(EXTRA_TASK_INDEX, index);
+ }
- /**
- * Mark activity to be in separate activity stack.
- *
- * @param activity
- */
- public void startNewTask(Activity activity) {
- taskIndexes.put(activity, nextTaskIndex);
- LogManager.i(activity, "Start new task " + nextTaskIndex);
- nextTaskIndex += 1;
- }
+ /**
+ * Mark activity to be in separate activity stack.
+ *
+ * @param activity
+ */
+ public void startNewTask(Activity activity) {
+ taskIndexes.put(activity, nextTaskIndex);
+ LogManager.i(activity, "Start new task " + nextTaskIndex);
+ nextTaskIndex += 1;
+ }
- /**
- * Either move main task to back, either close all activities in subtask.
- *
- * @param activity
- */
- public void cancelTask(Activity activity) {
- Integer index = taskIndexes.get(activity);
- LogManager.i(activity, "Cancel task " + index);
- if (index == null) {
- activity.moveTaskToBack(true);
- } else {
- for (Entry entry : taskIndexes.entrySet())
- if (entry.getValue() == index)
- entry.getKey().finish();
- }
- }
+ /**
+ * Either move main task to back, either close all activities in subtask.
+ *
+ * @param activity
+ */
+ public void cancelTask(Activity activity) {
+ Integer index = taskIndexes.get(activity);
+ LogManager.i(activity, "Cancel task " + index);
+ if (index == null) {
+ activity.moveTaskToBack(true);
+ } else {
+ for (Entry entry : taskIndexes.entrySet())
+ if (entry.getValue() == index)
+ entry.getKey().finish();
+ }
+ }
- /**
- * Fetch task index from the intent and mark specified activity.
- *
- * @param activity
- * @param intent
- */
- private void fetchTaskIndex(Activity activity, Intent intent) {
- int index = intent.getIntExtra(EXTRA_TASK_INDEX, -1);
- if (index == -1)
- return;
- LogManager.i(activity, "Fetch task index " + index);
- taskIndexes.put(activity, index);
- }
+ /**
+ * Fetch task index from the intent and mark specified activity.
+ *
+ * @param activity
+ * @param intent
+ */
+ private void fetchTaskIndex(Activity activity, Intent intent) {
+ int index = intent.getIntExtra(EXTRA_TASK_INDEX, -1);
+ if (index == -1)
+ return;
+ LogManager.i(activity, "Fetch task index " + index);
+ taskIndexes.put(activity, index);
+ }
- @Override
- public void onUnload() {
- clearStack(true);
- }
+ @Override
+ public void onUnload() {
+ clearStack(true);
+ }
}
diff --git a/app/src/main/java/com/xabber/android/data/Application.java b/app/src/main/java/com/xabber/android/data/Application.java
index d919ac7f99..d261d85fe5 100644
--- a/app/src/main/java/com/xabber/android/data/Application.java
+++ b/app/src/main/java/com/xabber/android/data/Application.java
@@ -1,19 +1,27 @@
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
- *
+ *
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
- *
+ *
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
- *
+ *
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.xabber.android.data;
+import android.app.Activity;
+import android.content.pm.PackageManager;
+import android.content.res.TypedArray;
+import android.os.Handler;
+
+import com.xabber.android.R;
+import com.xabber.android.service.XabberService;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -26,481 +34,455 @@
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
-import android.app.Activity;
-import android.content.pm.PackageManager;
-import android.content.res.TypedArray;
-import android.os.Build;
-import android.os.Handler;
-
-import com.xabber.android.service.XabberService;
-import com.xabber.androiddev.R;
-
/**
* Base entry point.
- *
+ *
* @author alexander.ivanov
*/
public class Application extends android.app.Application {
- public static final int SDK_INT = Integer.valueOf(Build.VERSION.SDK);
-
- private static Application instance;
-
- public static Application getInstance() {
- if (instance == null)
- throw new IllegalStateException();
- return instance;
- }
-
- private final ArrayList