repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/KeyCachingService.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.service;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.ConversationListActivity;
import org.thoughtcrime.securesms.DatabaseUpgradeActivity;
import org.thoughtcrime.securesms.DummyActivity;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.InvalidPassphraseException;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUtil;
import org.thoughtcrime.securesms.jobs.MasterSecretDecryptJob;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.util.DynamicLanguage;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.util.concurrent.TimeUnit;
/**
* Small service that stays running to keep a key cached in memory.
*
* @author Moxie Marlinspike
*/
public class KeyCachingService extends Service {
public static final int SERVICE_RUNNING_ID = 4141;
public static final String KEY_PERMISSION = "org.thoughtcrime.securesms.ACCESS_SECRETS";
public static final String NEW_KEY_EVENT = "org.thoughtcrime.securesms.service.action.NEW_KEY_EVENT";
public static final String CLEAR_KEY_EVENT = "org.thoughtcrime.securesms.service.action.CLEAR_KEY_EVENT";
private static final String PASSPHRASE_EXPIRED_EVENT = "org.thoughtcrime.securesms.service.action.PASSPHRASE_EXPIRED_EVENT";
public static final String CLEAR_KEY_ACTION = "org.thoughtcrime.securesms.service.action.CLEAR_KEY";
public static final String DISABLE_ACTION = "org.thoughtcrime.securesms.service.action.DISABLE";
public static final String ACTIVITY_START_EVENT = "org.thoughtcrime.securesms.service.action.ACTIVITY_START_EVENT";
public static final String ACTIVITY_STOP_EVENT = "org.thoughtcrime.securesms.service.action.ACTIVITY_STOP_EVENT";
public static final String LOCALE_CHANGE_EVENT = "org.thoughtcrime.securesms.service.action.LOCALE_CHANGE_EVENT";
private DynamicLanguage dynamicLanguage = new DynamicLanguage();
private PendingIntent pending;
private int activitiesRunning = 0;
private final IBinder binder = new KeySetBinder();
private static MasterSecret masterSecret;
public KeyCachingService() {}
public static synchronized @Nullable MasterSecret getMasterSecret(Context context) {
if (masterSecret == null && TextSecurePreferences.isPasswordDisabled(context)) {
try {
MasterSecret masterSecret = MasterSecretUtil.getMasterSecret(context, MasterSecretUtil.UNENCRYPTED_PASSPHRASE);
Intent intent = new Intent(context, KeyCachingService.class);
context.startService(intent);
return masterSecret;
} catch (InvalidPassphraseException e) {
Log.w("KeyCachingService", e);
}
}
return masterSecret;
}
public void setMasterSecret(final MasterSecret masterSecret) {
synchronized (KeyCachingService.class) {
KeyCachingService.masterSecret = masterSecret;
foregroundService();
broadcastNewSecret();
startTimeoutIfAppropriate();
if (!TextSecurePreferences.isPasswordDisabled(this)) {
ApplicationContext.getInstance(this).getJobManager().add(new MasterSecretDecryptJob(this));
}
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
if (!DatabaseUpgradeActivity.isUpdate(KeyCachingService.this)) {
MessageNotifier.updateNotification(KeyCachingService.this, masterSecret);
}
return null;
}
}.execute();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) return START_NOT_STICKY;
Log.w("KeyCachingService", "onStartCommand, " + intent.getAction());
if (intent.getAction() != null) {
switch (intent.getAction()) {
case CLEAR_KEY_ACTION: handleClearKey(); break;
case ACTIVITY_START_EVENT: handleActivityStarted(); break;
case ACTIVITY_STOP_EVENT: handleActivityStopped(); break;
case PASSPHRASE_EXPIRED_EVENT: handleClearKey(); break;
case DISABLE_ACTION: handleDisableService(); break;
case LOCALE_CHANGE_EVENT: handleLocaleChanged(); break;
}
}
return START_NOT_STICKY;
}
@Override
public void onCreate() {
Log.w("KeyCachingService", "onCreate()");
super.onCreate();
this.pending = PendingIntent.getService(this, 0, new Intent(PASSPHRASE_EXPIRED_EVENT, null,
this, KeyCachingService.class), 0);
if (TextSecurePreferences.isPasswordDisabled(this)) {
try {
MasterSecret masterSecret = MasterSecretUtil.getMasterSecret(this, MasterSecretUtil.UNENCRYPTED_PASSPHRASE);
setMasterSecret(masterSecret);
} catch (InvalidPassphraseException e) {
Log.w("KeyCachingService", e);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.w("KeyCachingService", "KCS Is Being Destroyed!");
handleClearKey();
}
/**
* Workaround for Android bug:
* https://code.google.com/p/android/issues/detail?id=53313
*/
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent intent = new Intent(this, DummyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void handleActivityStarted() {
Log.w("KeyCachingService", "Incrementing activity count...");
AlarmManager alarmManager = (AlarmManager)this.getSystemService(ALARM_SERVICE);
alarmManager.cancel(pending);
activitiesRunning++;
}
private void handleActivityStopped() {
Log.w("KeyCachingService", "Decrementing activity count...");
activitiesRunning--;
startTimeoutIfAppropriate();
}
private void handleClearKey() {
Log.w("KeyCachingService", "handleClearKey()");
KeyCachingService.masterSecret = null;
stopForeground(true);
Intent intent = new Intent(CLEAR_KEY_EVENT);
intent.setPackage(getApplicationContext().getPackageName());
sendBroadcast(intent, KEY_PERMISSION);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
MessageNotifier.updateNotification(KeyCachingService.this, null);
return null;
}
}.execute();
}
private void handleDisableService() {
if (TextSecurePreferences.isPasswordDisabled(this))
stopForeground(true);
}
private void handleLocaleChanged() {
dynamicLanguage.updateServiceLocale(this);
foregroundService();
}
private void startTimeoutIfAppropriate() {
boolean timeoutEnabled = TextSecurePreferences.isPassphraseTimeoutEnabled(this);
if ((activitiesRunning == 0) && (KeyCachingService.masterSecret != null) && timeoutEnabled && !TextSecurePreferences.isPasswordDisabled(this)) {
long timeoutMinutes = TextSecurePreferences.getPassphraseTimeoutInterval(this);
long timeoutMillis = TimeUnit.MINUTES.toMillis(timeoutMinutes);
Log.w("KeyCachingService", "Starting timeout: " + timeoutMillis);
AlarmManager alarmManager = (AlarmManager)this.getSystemService(ALARM_SERVICE);
alarmManager.cancel(pending);
alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeoutMillis, pending);
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void foregroundServiceModern() {
Log.w("KeyCachingService", "foregrounding KCS");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getString(R.string.KeyCachingService_passphrase_cached));
builder.setContentText(getString(R.string.KeyCachingService_signal_passphrase_cached));
builder.setSmallIcon(R.drawable.icon_cached);
builder.setWhen(0);
builder.setPriority(Notification.PRIORITY_MIN);
builder.addAction(R.drawable.ic_menu_lock_holo_dark, getString(R.string.KeyCachingService_lock), buildLockIntent());
builder.setContentIntent(buildLaunchIntent());
stopForeground(true);
startForeground(SERVICE_RUNNING_ID, builder.build());
}
private void foregroundServiceICS() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.key_caching_notification);
remoteViews.setOnClickPendingIntent(R.id.lock_cache_icon, buildLockIntent());
builder.setSmallIcon(R.drawable.icon_cached);
builder.setContent(remoteViews);
builder.setContentIntent(buildLaunchIntent());
stopForeground(true);
startForeground(SERVICE_RUNNING_ID, builder.build());
}
private void foregroundServiceLegacy() {
Notification notification = new Notification(R.drawable.icon_cached,
getString(R.string.KeyCachingService_signal_passphrase_cached),
System.currentTimeMillis());
notification.setLatestEventInfo(getApplicationContext(),
getString(R.string.KeyCachingService_passphrase_cached),
getString(R.string.KeyCachingService_signal_passphrase_cached),
buildLaunchIntent());
notification.tickerText = null;
stopForeground(true);
startForeground(SERVICE_RUNNING_ID, notification);
}
private void foregroundService() {
if (TextSecurePreferences.isPasswordDisabled(this)) {
stopForeground(true);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
foregroundServiceModern();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
foregroundServiceICS();
} else {
foregroundServiceLegacy();
}
}
private void broadcastNewSecret() {
Log.w("service", "Broadcasting new secret...");
Intent intent = new Intent(NEW_KEY_EVENT);
intent.setPackage(getApplicationContext().getPackageName());
sendBroadcast(intent, KEY_PERMISSION);
}
private PendingIntent buildLockIntent() {
Intent intent = new Intent(this, KeyCachingService.class);
intent.setAction(PASSPHRASE_EXPIRED_EVENT);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
return pendingIntent;
}
private PendingIntent buildLaunchIntent() {
Intent intent = new Intent(this, ConversationListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
return launchIntent;
}
@Override
public IBinder onBind(Intent arg0) {
return binder;
}
public class KeySetBinder extends Binder {
public KeyCachingService getService() {
return KeyCachingService.this;
}
}
public static void registerPassphraseActivityStarted(Context activity) {
Intent intent = new Intent(activity, KeyCachingService.class);
intent.setAction(KeyCachingService.ACTIVITY_START_EVENT);
activity.startService(intent);
}
public static void registerPassphraseActivityStopped(Context activity) {
Intent intent = new Intent(activity, KeyCachingService.class);
intent.setAction(KeyCachingService.ACTIVITY_STOP_EVENT);
activity.startService(intent);
}
}
| 12,750 | 36.283626 | 148 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/MasterSecretIntentService.java | package org.thoughtcrime.securesms.service;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import org.thoughtcrime.securesms.crypto.MasterSecret;
public abstract class MasterSecretIntentService extends IntentService {
public MasterSecretIntentService(String name) {
super(name);
}
@Override
protected final void onHandleIntent(Intent intent) {
onHandleIntent(intent, KeyCachingService.getMasterSecret(this));
}
protected abstract void onHandleIntent(Intent intent, @Nullable MasterSecret masterSecret);
}
| 593 | 26 | 93 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/MessageRetrievalService.java | package org.thoughtcrime.securesms.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.gcm.GcmBroadcastReceiver;
import org.thoughtcrime.securesms.jobs.PushContentReceiveJob;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.jobqueue.requirements.NetworkRequirementProvider;
import org.whispersystems.jobqueue.requirements.RequirementListener;
import org.whispersystems.libaxolotl.InvalidVersionException;
import org.whispersystems.textsecure.api.TextSecureMessagePipe;
import org.whispersystems.textsecure.api.TextSecureMessageReceiver;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
public class MessageRetrievalService extends Service implements Runnable, InjectableType, RequirementListener {
private static final String TAG = MessageRetrievalService.class.getSimpleName();
public static final String ACTION_ACTIVITY_STARTED = "ACTIVITY_STARTED";
public static final String ACTION_ACTIVITY_FINISHED = "ACTIVITY_FINISHED";
public static final String ACTION_PUSH_RECEIVED = "PUSH_RECEIVED";
private static final long REQUEST_TIMEOUT_MINUTES = 1;
private NetworkRequirement networkRequirement;
private NetworkRequirementProvider networkRequirementProvider;
@Inject
public TextSecureMessageReceiver receiver;
private int activeActivities = 0;
private List<Intent> pushPending = new LinkedList<>();
@Override
public void onCreate() {
super.onCreate();
ApplicationContext.getInstance(this).injectDependencies(this);
networkRequirement = new NetworkRequirement(this);
networkRequirementProvider = new NetworkRequirementProvider(this);
networkRequirementProvider.setListener(this);
new Thread(this, "MessageRetrievalService").start();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) return START_STICKY;
if (ACTION_ACTIVITY_STARTED.equals(intent.getAction())) incrementActive();
else if (ACTION_ACTIVITY_FINISHED.equals(intent.getAction())) decrementActive();
else if (ACTION_PUSH_RECEIVED.equals(intent.getAction())) incrementPushReceived(intent);
return START_STICKY;
}
@Override
public void run() {
while (true) {
Log.w(TAG, "Waiting for websocket state change....");
waitForConnectionNecessary();
Log.w(TAG, "Making websocket connection....");
TextSecureMessagePipe pipe = receiver.createMessagePipe();
try {
while (isConnectionNecessary()) {
try {
Log.w(TAG, "Reading message...");
pipe.read(REQUEST_TIMEOUT_MINUTES, TimeUnit.MINUTES,
new TextSecureMessagePipe.MessagePipeCallback() {
@Override
public void onMessage(TextSecureEnvelope envelope) {
Log.w(TAG, "Retrieved envelope! " + envelope.getSource());
PushContentReceiveJob receiveJob = new PushContentReceiveJob(MessageRetrievalService.this);
receiveJob.handle(envelope, false);
decrementPushReceived();
}
});
} catch (TimeoutException e) {
Log.w(TAG, "Application level read timeout...");
} catch (InvalidVersionException e) {
Log.w(TAG, e);
}
}
} catch (Throwable e) {
Log.w(TAG, e);
} finally {
Log.w(TAG, "Shutting down pipe...");
shutdown(pipe);
}
Log.w(TAG, "Looping...");
}
}
@Override
public void onRequirementStatusChanged() {
synchronized (this) {
notifyAll();
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private synchronized void incrementActive() {
activeActivities++;
Log.w(TAG, "Active Count: " + activeActivities);
notifyAll();
}
private synchronized void decrementActive() {
activeActivities--;
Log.w(TAG, "Active Count: " + activeActivities);
notifyAll();
}
private synchronized void incrementPushReceived(Intent intent) {
pushPending.add(intent);
notifyAll();
}
private synchronized void decrementPushReceived() {
if (!pushPending.isEmpty()) {
Intent intent = pushPending.remove(0);
GcmBroadcastReceiver.completeWakefulIntent(intent);
notifyAll();
}
}
private synchronized boolean isConnectionNecessary() {
Log.w(TAG, String.format("Network requirement: %s, active activities: %s, push pending: %s",
networkRequirement.isPresent(), activeActivities, pushPending.size()));
return TextSecurePreferences.isWebsocketRegistered(this) &&
(activeActivities > 0 || !pushPending.isEmpty()) &&
networkRequirement.isPresent();
}
private synchronized void waitForConnectionNecessary() {
try {
while (!isConnectionNecessary()) wait();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
private void shutdown(TextSecureMessagePipe pipe) {
try {
pipe.shutdown();
} catch (Throwable t) {
Log.w(TAG, t);
}
}
public static void registerActivityStarted(Context activity) {
Intent intent = new Intent(activity, MessageRetrievalService.class);
intent.setAction(MessageRetrievalService.ACTION_ACTIVITY_STARTED);
activity.startService(intent);
}
public static void registerActivityStopped(Context activity) {
Intent intent = new Intent(activity, MessageRetrievalService.class);
intent.setAction(MessageRetrievalService.ACTION_ACTIVITY_FINISHED);
activity.startService(intent);
}
}
| 6,192 | 32.475676 | 117 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/MmsListener.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Telephony;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.jobs.MmsReceiveJob;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
public class MmsListener extends BroadcastReceiver {
private static final String TAG = MmsListener.class.getSimpleName();
private boolean isRelevant(Context context, Intent intent) {
if (!ApplicationMigrationService.isDatabaseImported(context)) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) &&
Util.isDefaultSmsProvider(context))
{
return false;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT &&
TextSecurePreferences.isInterceptAllMmsEnabled(context))
{
return true;
}
return false;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "Got MMS broadcast..." + intent.getAction());
if ((Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION.equals(intent.getAction()) &&
Util.isDefaultSmsProvider(context)) ||
(Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) &&
isRelevant(context, intent)))
{
Log.w(TAG, "Relevant!");
ApplicationContext.getInstance(context)
.getJobManager()
.add(new MmsReceiveJob(context, intent.getByteArrayExtra("data")));
abortBroadcast();
}
}
}
| 2,525 | 31.805195 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/QuickResponseService.java | package org.thoughtcrime.securesms.service;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.mms.SlideDeck;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.sms.MessageSender;
import org.thoughtcrime.securesms.sms.OutgoingTextMessage;
import org.thoughtcrime.securesms.util.Rfc5724Uri;
import java.net.URISyntaxException;
import java.net.URLDecoder;
public class QuickResponseService extends MasterSecretIntentService {
private static final String TAG = QuickResponseService.class.getSimpleName();
public QuickResponseService() {
super("QuickResponseService");
}
@Override
protected void onHandleIntent(Intent intent, @Nullable MasterSecret masterSecret) {
if (!TelephonyManager.ACTION_RESPOND_VIA_MESSAGE.equals(intent.getAction())) {
Log.w(TAG, "Received unknown intent: " + intent.getAction());
return;
}
if (masterSecret == null) {
Log.w(TAG, "Got quick response request when locked...");
Toast.makeText(this, R.string.QuickResponseService_quick_response_unavailable_when_Signal_is_locked, Toast.LENGTH_LONG).show();
return;
}
try {
Rfc5724Uri uri = new Rfc5724Uri(intent.getDataString());
String content = intent.getStringExtra(Intent.EXTRA_TEXT);
String numbers = uri.getPath();
if(numbers.contains("%")){
numbers = URLDecoder.decode(numbers);
}
Recipients recipients = RecipientFactory.getRecipientsFromString(this, numbers, false);
if (!TextUtils.isEmpty(content)) {
if (recipients.isSingleRecipient()) {
MessageSender.send(this, masterSecret, new OutgoingTextMessage(recipients, content), -1, false);
} else {
MessageSender.send(this, masterSecret, new OutgoingMediaMessage(recipients, new SlideDeck(), content, System.currentTimeMillis(),
ThreadDatabase.DistributionTypes.DEFAULT), -1, false);
}
}
} catch (URISyntaxException e) {
Toast.makeText(this, R.string.QuickResponseService_problem_sending_message, Toast.LENGTH_LONG).show();
Log.w(TAG, e);
}
}
}
| 2,660 | 38.132353 | 139 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/RegistrationNotifier.java | package org.thoughtcrime.securesms.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import org.thoughtcrime.securesms.ConversationListActivity;
import org.thoughtcrime.securesms.R;
public class RegistrationNotifier extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.icon_notification);
builder.setContentTitle(intent.getStringExtra(RegistrationService.NOTIFICATION_TITLE));
builder.setContentText(intent.getStringExtra(RegistrationService.NOTIFICATION_TEXT));
builder.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, ConversationListActivity.class), 0));
builder.setWhen(System.currentTimeMillis());
builder.setDefaults(Notification.DEFAULT_VIBRATE);
builder.setAutoCancel(true);
Notification notification = builder.build();
((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(31337, notification);
}
}
| 1,287 | 41.933333 | 124 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/RegistrationService.java | package org.thoughtcrime.securesms.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.thoughtcrime.redphone.signaling.RedPhoneAccountAttributes;
import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager;
import org.thoughtcrime.redphone.signaling.RedPhoneTrustStore;
import org.thoughtcrime.securesms.BuildConfig;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.IdentityKeyUtil;
import org.thoughtcrime.securesms.crypto.PreKeyUtil;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.jobs.GcmRefreshJob;
import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.util.DirectoryHelper;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.state.PreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.util.KeyHelper;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.exceptions.ExpectationFailedException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The RegisterationService handles the process of PushService registration and verification.
* If it receives an intent with a REGISTER_NUMBER_ACTION, it does the following through
* an executor:
*
* 1) Generate secrets.
* 2) Register the specified number and those secrets with the server.
* 3) Wait for a challenge SMS.
* 4) Verify the challenge with the server.
* 5) Start the GCM registration process.
* 6) Retrieve the current directory.
*
* The RegistrationService broadcasts its state throughout this process, and also makes its
* state available through service binding. This enables a View to display progress.
*
* @author Moxie Marlinspike
*
*/
public class RegistrationService extends Service {
public static final String REGISTER_NUMBER_ACTION = "org.thoughtcrime.securesms.RegistrationService.REGISTER_NUMBER";
public static final String VOICE_REQUESTED_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REQUESTED";
public static final String VOICE_REGISTER_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REGISTER";
public static final String NOTIFICATION_TITLE = "org.thoughtcrime.securesms.NOTIFICATION_TITLE";
public static final String NOTIFICATION_TEXT = "org.thoughtcrime.securesms.NOTIFICATION_TEXT";
public static final String CHALLENGE_EVENT = "org.thoughtcrime.securesms.CHALLENGE_EVENT";
public static final String REGISTRATION_EVENT = "org.thoughtcrime.securesms.REGISTRATION_EVENT";
public static final String CHALLENGE_EXTRA = "CAAChallenge";
private static final long REGISTRATION_TIMEOUT_MILLIS = 120000;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final Binder binder = new RegistrationServiceBinder();
private volatile RegistrationState registrationState = new RegistrationState(RegistrationState.STATE_IDLE);
private volatile WeakReference<Handler> registrationStateHandler;
private volatile ChallengeReceiver challengeReceiver;
private String challenge;
private long verificationStartTime;
private boolean generatingPreKeys;
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (intent != null) {
executor.execute(new Runnable() {
@Override
public void run() {
if (REGISTER_NUMBER_ACTION.equals(intent.getAction())) handleSmsRegistrationIntent(intent);
else if (VOICE_REQUESTED_ACTION.equals(intent.getAction())) handleVoiceRequestedIntent(intent);
else if (VOICE_REGISTER_ACTION.equals(intent.getAction())) handleVoiceRegistrationIntent(intent);
}
});
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
executor.shutdown();
shutdown();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void shutdown() {
shutdownChallengeListener();
markAsVerifying(false);
registrationState = new RegistrationState(RegistrationState.STATE_IDLE);
}
public synchronized int getSecondsRemaining() {
long millisPassed;
if (verificationStartTime == 0) millisPassed = 0;
else millisPassed = System.currentTimeMillis() - verificationStartTime;
return Math.max((int)(REGISTRATION_TIMEOUT_MILLIS - millisPassed) / 1000, 0);
}
public RegistrationState getRegistrationState() {
return registrationState;
}
private void initializeChallengeListener() {
this.challenge = null;
challengeReceiver = new ChallengeReceiver();
IntentFilter filter = new IntentFilter(CHALLENGE_EVENT);
registerReceiver(challengeReceiver, filter);
}
private synchronized void shutdownChallengeListener() {
if (challengeReceiver != null) {
unregisterReceiver(challengeReceiver);
challengeReceiver = null;
}
}
private void handleVoiceRequestedIntent(Intent intent) {
setState(new RegistrationState(RegistrationState.STATE_VOICE_REQUESTED,
intent.getStringExtra("e164number"),
intent.getStringExtra("password")));
}
private void handleVoiceRegistrationIntent(Intent intent) {
markAsVerifying(true);
String number = intent.getStringExtra("e164number");
String password = intent.getStringExtra("password");
String signalingKey = intent.getStringExtra("signaling_key");
try {
TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password);
handleCommonRegistration(accountManager, number, password, signalingKey);
markAsVerified(number, password, signalingKey);
setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number));
broadcastComplete(true);
} catch (UnsupportedOperationException uoe) {
Log.w("RegistrationService", uoe);
setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number));
broadcastComplete(false);
} catch (IOException e) {
Log.w("RegistrationService", e);
setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number));
broadcastComplete(false);
}
}
private void handleSmsRegistrationIntent(Intent intent) {
markAsVerifying(true);
String number = intent.getStringExtra("e164number");
int registrationId = TextSecurePreferences.getLocalRegistrationId(this);
if (registrationId == 0) {
registrationId = KeyHelper.generateRegistrationId(false);
TextSecurePreferences.setLocalRegistrationId(this, registrationId);
}
try {
String password = Util.getSecret(18);
String signalingKey = Util.getSecret(52);
initializeChallengeListener();
setState(new RegistrationState(RegistrationState.STATE_CONNECTING, number));
TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password);
accountManager.requestSmsVerificationCode();
setState(new RegistrationState(RegistrationState.STATE_VERIFYING, number));
String challenge = waitForChallenge();
accountManager.verifyAccountWithCode(challenge, signalingKey, registrationId, true);
handleCommonRegistration(accountManager, number, password, signalingKey);
markAsVerified(number, password, signalingKey);
setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number));
broadcastComplete(true);
} catch (ExpectationFailedException efe) {
Log.w("RegistrationService", efe);
setState(new RegistrationState(RegistrationState.STATE_MULTI_REGISTERED, number));
broadcastComplete(false);
} catch (UnsupportedOperationException uoe) {
Log.w("RegistrationService", uoe);
setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number));
broadcastComplete(false);
} catch (AccountVerificationTimeoutException avte) {
Log.w("RegistrationService", avte);
setState(new RegistrationState(RegistrationState.STATE_TIMEOUT, number));
broadcastComplete(false);
} catch (IOException e) {
Log.w("RegistrationService", e);
setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number));
broadcastComplete(false);
} finally {
shutdownChallengeListener();
}
}
private void handleCommonRegistration(TextSecureAccountManager accountManager, String number, String password, String signalingKey)
throws IOException
{
setState(new RegistrationState(RegistrationState.STATE_GENERATING_KEYS, number));
Recipient self = RecipientFactory.getRecipientsFromString(this, number, false).getPrimaryRecipient();
IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(this);
List<PreKeyRecord> records = PreKeyUtil.generatePreKeys(this);
PreKeyRecord lastResort = PreKeyUtil.generateLastResortKey(this);
SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(this, identityKey);
accountManager.setPreKeys(identityKey.getPublicKey(),lastResort, signedPreKey, records);
setState(new RegistrationState(RegistrationState.STATE_GCM_REGISTERING, number));
String gcmRegistrationId = GoogleCloudMessaging.getInstance(this).register(GcmRefreshJob.REGISTRATION_ID);
accountManager.setGcmId(Optional.of(gcmRegistrationId));
TextSecurePreferences.setGcmRegistrationId(this, gcmRegistrationId);
TextSecurePreferences.setWebsocketRegistered(this, true);
DatabaseFactory.getIdentityDatabase(this).saveIdentity(self.getRecipientId(), identityKey.getPublicKey());
DirectoryHelper.refreshDirectory(this, accountManager, number);
RedPhoneAccountManager redPhoneAccountManager = new RedPhoneAccountManager(BuildConfig.REDPHONE_MASTER_URL,
new RedPhoneTrustStore(this),
number, password);
String verificationToken = accountManager.getAccountVerificationToken();
redPhoneAccountManager.createAccount(verificationToken, new RedPhoneAccountAttributes(signalingKey, gcmRegistrationId));
DirectoryRefreshListener.schedule(this);
}
private synchronized String waitForChallenge() throws AccountVerificationTimeoutException {
this.verificationStartTime = System.currentTimeMillis();
if (this.challenge == null) {
try {
wait(REGISTRATION_TIMEOUT_MILLIS);
} catch (InterruptedException e) {
throw new IllegalArgumentException(e);
}
}
if (this.challenge == null)
throw new AccountVerificationTimeoutException();
return this.challenge;
}
private synchronized void challengeReceived(String challenge) {
this.challenge = challenge;
notifyAll();
}
private void markAsVerifying(boolean verifying) {
TextSecurePreferences.setVerifying(this, verifying);
if (verifying) {
TextSecurePreferences.setPushRegistered(this, false);
}
}
private void markAsVerified(String number, String password, String signalingKey) {
TextSecurePreferences.setVerifying(this, false);
TextSecurePreferences.setPushRegistered(this, true);
TextSecurePreferences.setLocalNumber(this, number);
TextSecurePreferences.setPushServerPassword(this, password);
TextSecurePreferences.setSignalingKey(this, signalingKey);
TextSecurePreferences.setSignedPreKeyRegistered(this, true);
TextSecurePreferences.setPromptedPushRegistration(this, true);
}
private void setState(RegistrationState state) {
this.registrationState = state;
Handler registrationStateHandler = this.registrationStateHandler.get();
if (registrationStateHandler != null) {
registrationStateHandler.obtainMessage(state.state, state).sendToTarget();
}
}
private void broadcastComplete(boolean success) {
Intent intent = new Intent();
intent.setAction(REGISTRATION_EVENT);
if (success) {
intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_complete));
intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_successfully_completed));
} else {
intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_error));
intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_encountered_a_problem));
}
this.sendOrderedBroadcast(intent, null);
}
public void setRegistrationStateHandler(Handler registrationStateHandler) {
this.registrationStateHandler = new WeakReference<>(registrationStateHandler);
}
public class RegistrationServiceBinder extends Binder {
public RegistrationService getService() {
return RegistrationService.this;
}
}
private class ChallengeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("RegistrationService", "Got a challenge broadcast...");
challengeReceived(intent.getStringExtra(CHALLENGE_EXTRA));
}
}
public static class RegistrationState {
public static final int STATE_IDLE = 0;
public static final int STATE_CONNECTING = 1;
public static final int STATE_VERIFYING = 2;
public static final int STATE_TIMER = 3;
public static final int STATE_COMPLETE = 4;
public static final int STATE_TIMEOUT = 5;
public static final int STATE_NETWORK_ERROR = 6;
public static final int STATE_GCM_UNSUPPORTED = 8;
public static final int STATE_GCM_REGISTERING = 9;
public static final int STATE_GCM_TIMEOUT = 10;
public static final int STATE_VOICE_REQUESTED = 12;
public static final int STATE_GENERATING_KEYS = 13;
public static final int STATE_MULTI_REGISTERED = 14;
public final int state;
public final String number;
public final String password;
public RegistrationState(int state) {
this(state, null);
}
public RegistrationState(int state, String number) {
this(state, number, null);
}
public RegistrationState(int state, String number, String password) {
this.state = state;
this.number = number;
this.password = password;
}
}
}
| 15,468 | 38.971576 | 133 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/SmsDeliveryListener.java | package org.thoughtcrime.securesms.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.jobs.SmsSentJob;
import org.whispersystems.jobqueue.JobManager;
public class SmsDeliveryListener extends BroadcastReceiver {
private static final String TAG = SmsDeliveryListener.class.getSimpleName();
public static final String SENT_SMS_ACTION = "org.thoughtcrime.securesms.SendReceiveService.SENT_SMS_ACTION";
public static final String DELIVERED_SMS_ACTION = "org.thoughtcrime.securesms.SendReceiveService.DELIVERED_SMS_ACTION";
@Override
public void onReceive(Context context, Intent intent) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
long messageId = intent.getLongExtra("message_id", -1);
switch (intent.getAction()) {
case SENT_SMS_ACTION:
int result = getResultCode();
jobManager.add(new SmsSentJob(context, messageId, SENT_SMS_ACTION, result));
break;
case DELIVERED_SMS_ACTION:
byte[] pdu = intent.getByteArrayExtra("pdu");
if (pdu == null) {
Log.w(TAG, "No PDU in delivery receipt!");
break;
}
SmsMessage message = SmsMessage.createFromPdu(pdu);
if (message == null) {
Log.w(TAG, "Delivery receipt failed to parse!");
break;
}
jobManager.add(new SmsSentJob(context, messageId, DELIVERED_SMS_ACTION, message.getStatus()));
break;
default:
Log.w(TAG, "Unknown action: " + intent.getAction());
}
}
}
| 1,753 | 32.09434 | 121 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/SmsListener.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.jobs.SmsReceiveJob;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SmsListener extends BroadcastReceiver {
private static final String SMS_RECEIVED_ACTION = Telephony.Sms.Intents.SMS_RECEIVED_ACTION;
private static final String SMS_DELIVERED_ACTION = Telephony.Sms.Intents.SMS_DELIVER_ACTION;
private static final Pattern CHALLENGE_PATTERN = Pattern.compile(".*Your TextSecure verification code: ([0-9]{3,4})-([0-9]{3,4}).*", Pattern.DOTALL);
private boolean isExemption(SmsMessage message, String messageBody) {
// ignore CLASS0 ("flash") messages
if (message.getMessageClass() == SmsMessage.MessageClass.CLASS_0)
return true;
// ignore OTP messages from Sparebank1 (Norwegian bank)
if (messageBody.startsWith("Sparebank1://otp?")) {
return true;
}
return
message.getOriginatingAddress().length() < 7 &&
(messageBody.toUpperCase().startsWith("//ANDROID:") || // Sprint Visual Voicemail
messageBody.startsWith("//BREW:")); //BREW stands for “Binary Runtime Environment for Wireless"
}
private SmsMessage getSmsMessageFromIntent(Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[])bundle.get("pdus");
if (pdus == null || pdus.length == 0)
return null;
return SmsMessage.createFromPdu((byte[])pdus[0]);
}
private String getSmsMessageBodyFromIntent(Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[])bundle.get("pdus");
StringBuilder bodyBuilder = new StringBuilder();
if (pdus == null)
return null;
for (Object pdu : pdus)
bodyBuilder.append(SmsMessage.createFromPdu((byte[])pdu).getDisplayMessageBody());
return bodyBuilder.toString();
}
// private ArrayList<IncomingTextMessage> getAsTextMessages(Intent intent) {
// Object[] pdus = (Object[])intent.getExtras().get("pdus");
// ArrayList<IncomingTextMessage> messages = new ArrayList<IncomingTextMessage>(pdus.length);
//
// for (int i=0;i<pdus.length;i++)
// messages.add(new IncomingTextMessage(SmsMessage.createFromPdu((byte[])pdus[i])));
//
// return messages;
// }
private boolean isRelevant(Context context, Intent intent) {
SmsMessage message = getSmsMessageFromIntent(intent);
String messageBody = getSmsMessageBodyFromIntent(intent);
if (message == null && messageBody == null)
return false;
if (isExemption(message, messageBody))
return false;
if (!ApplicationMigrationService.isDatabaseImported(context))
return false;
if (isChallenge(context, intent))
return false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
SMS_RECEIVED_ACTION.equals(intent.getAction()) &&
Util.isDefaultSmsProvider(context))
{
return false;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT &&
TextSecurePreferences.isInterceptAllSmsEnabled(context))
{
return true;
}
return false;
}
private boolean isChallenge(Context context, Intent intent) {
String messageBody = getSmsMessageBodyFromIntent(intent);
if (messageBody == null)
return false;
if (CHALLENGE_PATTERN.matcher(messageBody).matches() &&
TextSecurePreferences.isVerifying(context))
{
return true;
}
return false;
}
private String parseChallenge(Context context, Intent intent) {
String messageBody = getSmsMessageBodyFromIntent(intent);
Matcher challengeMatcher = CHALLENGE_PATTERN.matcher(messageBody);
if (!challengeMatcher.matches()) {
throw new AssertionError("Expression should match.");
}
return challengeMatcher.group(1) + challengeMatcher.group(2);
}
@Override
public void onReceive(Context context, Intent intent) {
Log.w("SMSListener", "Got SMS broadcast...");
if (SMS_RECEIVED_ACTION.equals(intent.getAction()) && isChallenge(context, intent)) {
Log.w("SmsListener", "Got challenge!");
Intent challengeIntent = new Intent(RegistrationService.CHALLENGE_EVENT);
challengeIntent.putExtra(RegistrationService.CHALLENGE_EXTRA, parseChallenge(context, intent));
context.sendBroadcast(challengeIntent);
abortBroadcast();
} else if ((intent.getAction().equals(SMS_DELIVERED_ACTION)) ||
(intent.getAction().equals(SMS_RECEIVED_ACTION)) && isRelevant(context, intent))
{
Object[] pdus = (Object[])intent.getExtras().get("pdus");
ApplicationContext.getInstance(context).getJobManager().add(new SmsReceiveJob(context, pdus));
// Intent receivedIntent = new Intent(context, SendReceiveService.class);
// receivedIntent.setAction(SendReceiveService.RECEIVE_SMS_ACTION);
// receivedIntent.putExtra("ResultCode", this.getResultCode());
// receivedIntent.putParcelableArrayListExtra("text_messages",getAsTextMessages(intent));
// context.startService(receivedIntent);
abortBroadcast();
}
}
}
| 6,243 | 33.882682 | 151 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/IncomingEncryptedMessage.java | package org.thoughtcrime.securesms.sms;
public class IncomingEncryptedMessage extends IncomingTextMessage {
public IncomingEncryptedMessage(IncomingTextMessage base, String newBody) {
super(base, newBody);
}
@Override
public IncomingTextMessage withMessageBody(String body) {
return new IncomingEncryptedMessage(this, body);
}
@Override
public boolean isSecureMessage() {
return true;
}
}
| 421 | 21.210526 | 77 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/IncomingEndSessionMessage.java | package org.thoughtcrime.securesms.sms;
public class IncomingEndSessionMessage extends IncomingTextMessage {
public IncomingEndSessionMessage(IncomingTextMessage base) {
this(base, base.getMessageBody());
}
public IncomingEndSessionMessage(IncomingTextMessage base, String newBody) {
super(base, newBody);
}
@Override
public IncomingEndSessionMessage withMessageBody(String messageBody) {
return new IncomingEndSessionMessage(this, messageBody);
}
@Override
public boolean isEndSession() {
return true;
}
}
| 548 | 22.869565 | 78 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/IncomingGroupMessage.java | package org.thoughtcrime.securesms.sms;
import static org.whispersystems.textsecure.internal.push.TextSecureProtos.GroupContext;
public class IncomingGroupMessage extends IncomingTextMessage {
private final GroupContext groupContext;
public IncomingGroupMessage(IncomingTextMessage base, GroupContext groupContext, String body) {
super(base, body);
this.groupContext = groupContext;
}
@Override
public IncomingGroupMessage withMessageBody(String body) {
return new IncomingGroupMessage(this, groupContext, body);
}
@Override
public boolean isGroup() {
return true;
}
public boolean isUpdate() {
return groupContext.getType().getNumber() == GroupContext.Type.UPDATE_VALUE;
}
public boolean isQuit() {
return groupContext.getType().getNumber() == GroupContext.Type.QUIT_VALUE;
}
}
| 838 | 24.424242 | 97 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/IncomingJoinedMessage.java | package org.thoughtcrime.securesms.sms;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.messages.TextSecureGroup;
public class IncomingJoinedMessage extends IncomingTextMessage {
public IncomingJoinedMessage(String sender) {
super(sender, 1, System.currentTimeMillis(), null, Optional.<TextSecureGroup>absent());
}
@Override
public boolean isJoined() {
return true;
}
@Override
public boolean isSecureMessage() {
return true;
}
}
| 515 | 21.434783 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/IncomingPreKeyBundleMessage.java | package org.thoughtcrime.securesms.sms;
public class IncomingPreKeyBundleMessage extends IncomingTextMessage {
public IncomingPreKeyBundleMessage(IncomingTextMessage base, String newBody) {
super(base, newBody);
}
@Override
public IncomingPreKeyBundleMessage withMessageBody(String messageBody) {
return new IncomingPreKeyBundleMessage(this, messageBody);
}
@Override
public boolean isPreKeyBundle() {
return true;
}
}
| 452 | 21.65 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/IncomingTextMessage.java | package org.thoughtcrime.securesms.sms;
import android.os.Parcel;
import android.os.Parcelable;
import android.telephony.SmsMessage;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.messages.TextSecureGroup;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import java.util.List;
public class IncomingTextMessage implements Parcelable {
public static final Parcelable.Creator<IncomingTextMessage> CREATOR = new Parcelable.Creator<IncomingTextMessage>() {
@Override
public IncomingTextMessage createFromParcel(Parcel in) {
return new IncomingTextMessage(in);
}
@Override
public IncomingTextMessage[] newArray(int size) {
return new IncomingTextMessage[size];
}
};
private final String message;
private final String sender;
private final int senderDeviceId;
private final int protocol;
private final String serviceCenterAddress;
private final boolean replyPathPresent;
private final String pseudoSubject;
private final long sentTimestampMillis;
private final String groupId;
private final boolean push;
public IncomingTextMessage(SmsMessage message) {
this.message = message.getDisplayMessageBody();
this.sender = message.getDisplayOriginatingAddress();
this.senderDeviceId = TextSecureAddress.DEFAULT_DEVICE_ID;
this.protocol = message.getProtocolIdentifier();
this.serviceCenterAddress = message.getServiceCenterAddress();
this.replyPathPresent = message.isReplyPathPresent();
this.pseudoSubject = message.getPseudoSubject();
this.sentTimestampMillis = message.getTimestampMillis();
this.groupId = null;
this.push = false;
}
public IncomingTextMessage(String sender, int senderDeviceId, long sentTimestampMillis,
String encodedBody, Optional<TextSecureGroup> group)
{
this.message = encodedBody;
this.sender = sender;
this.senderDeviceId = senderDeviceId;
this.protocol = 31337;
this.serviceCenterAddress = "GCM";
this.replyPathPresent = true;
this.pseudoSubject = "";
this.sentTimestampMillis = sentTimestampMillis;
this.push = true;
if (group.isPresent()) {
this.groupId = GroupUtil.getEncodedId(group.get().getGroupId());
} else {
this.groupId = null;
}
}
public IncomingTextMessage(Parcel in) {
this.message = in.readString();
this.sender = in.readString();
this.senderDeviceId = in.readInt();
this.protocol = in.readInt();
this.serviceCenterAddress = in.readString();
this.replyPathPresent = (in.readInt() == 1);
this.pseudoSubject = in.readString();
this.sentTimestampMillis = in.readLong();
this.groupId = in.readString();
this.push = (in.readInt() == 1);
}
public IncomingTextMessage(IncomingTextMessage base, String newBody) {
this.message = newBody;
this.sender = base.getSender();
this.senderDeviceId = base.getSenderDeviceId();
this.protocol = base.getProtocol();
this.serviceCenterAddress = base.getServiceCenterAddress();
this.replyPathPresent = base.isReplyPathPresent();
this.pseudoSubject = base.getPseudoSubject();
this.sentTimestampMillis = base.getSentTimestampMillis();
this.groupId = base.getGroupId();
this.push = base.isPush();
}
public IncomingTextMessage(List<IncomingTextMessage> fragments) {
StringBuilder body = new StringBuilder();
for (IncomingTextMessage message : fragments) {
body.append(message.getMessageBody());
}
this.message = body.toString();
this.sender = fragments.get(0).getSender();
this.senderDeviceId = fragments.get(0).getSenderDeviceId();
this.protocol = fragments.get(0).getProtocol();
this.serviceCenterAddress = fragments.get(0).getServiceCenterAddress();
this.replyPathPresent = fragments.get(0).isReplyPathPresent();
this.pseudoSubject = fragments.get(0).getPseudoSubject();
this.sentTimestampMillis = fragments.get(0).getSentTimestampMillis();
this.groupId = fragments.get(0).getGroupId();
this.push = fragments.get(0).isPush();
}
protected IncomingTextMessage(String sender, String groupId)
{
this.message = "";
this.sender = sender;
this.senderDeviceId = TextSecureAddress.DEFAULT_DEVICE_ID;
this.protocol = 31338;
this.serviceCenterAddress = "Outgoing";
this.replyPathPresent = true;
this.pseudoSubject = "";
this.sentTimestampMillis = System.currentTimeMillis();
this.groupId = groupId;
this.push = true;
}
public long getSentTimestampMillis() {
return sentTimestampMillis;
}
public String getPseudoSubject() {
return pseudoSubject;
}
public String getMessageBody() {
return message;
}
public IncomingTextMessage withMessageBody(String message) {
return new IncomingTextMessage(this, message);
}
public String getSender() {
return sender;
}
public int getSenderDeviceId() {
return senderDeviceId;
}
public int getProtocol() {
return protocol;
}
public String getServiceCenterAddress() {
return serviceCenterAddress;
}
public boolean isReplyPathPresent() {
return replyPathPresent;
}
public boolean isSecureMessage() {
return false;
}
public boolean isPreKeyBundle() {
return false;
}
public boolean isEndSession() {
return false;
}
public boolean isPush() {
return push;
}
public String getGroupId() {
return groupId;
}
public boolean isGroup() {
return false;
}
public boolean isJoined() {
return false;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(message);
out.writeString(sender);
out.writeInt(senderDeviceId);
out.writeInt(protocol);
out.writeString(serviceCenterAddress);
out.writeInt(replyPathPresent ? 1 : 0);
out.writeString(pseudoSubject);
out.writeLong(sentTimestampMillis);
out.writeString(groupId);
out.writeInt(push ? 1 : 0);
}
}
| 6,638 | 30.023364 | 119 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/MessageSender.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.sms;
import android.content.Context;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.EncryptingSmsDatabase;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.NotInDirectoryException;
import org.thoughtcrime.securesms.database.TextSecureDirectory;
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.thoughtcrime.securesms.jobs.MmsSendJob;
import org.thoughtcrime.securesms.jobs.PushGroupSendJob;
import org.thoughtcrime.securesms.jobs.PushMediaSendJob;
import org.thoughtcrime.securesms.jobs.PushTextSendJob;
import org.thoughtcrime.securesms.jobs.SmsSendJob;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobManager;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.ContactTokenDetails;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.IOException;
import ws.com.google.android.mms.MmsException;
public class MessageSender {
private static final String TAG = MessageSender.class.getSimpleName();
public static long send(final Context context,
final MasterSecret masterSecret,
final OutgoingTextMessage message,
final long threadId,
final boolean forceSms)
{
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
Recipients recipients = message.getRecipients();
boolean keyExchange = message.isKeyExchange();
long allocatedThreadId;
if (threadId == -1) {
allocatedThreadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
} else {
allocatedThreadId = threadId;
}
long messageId = database.insertMessageOutbox(new MasterSecretUnion(masterSecret), allocatedThreadId, message, forceSms, System.currentTimeMillis());
sendTextMessage(context, recipients, forceSms, keyExchange, messageId);
return allocatedThreadId;
}
public static long send(final Context context,
final MasterSecret masterSecret,
final OutgoingMediaMessage message,
final long threadId,
final boolean forceSms)
{
try {
ThreadDatabase threadDatabase = DatabaseFactory.getThreadDatabase(context);
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
long allocatedThreadId;
if (threadId == -1) {
allocatedThreadId = threadDatabase.getThreadIdFor(message.getRecipients(), message.getDistributionType());
} else {
allocatedThreadId = threadId;
}
Recipients recipients = message.getRecipients();
long messageId = database.insertMessageOutbox(new MasterSecretUnion(masterSecret), message, allocatedThreadId, forceSms);
sendMediaMessage(context, masterSecret, recipients, forceSms, messageId);
return allocatedThreadId;
} catch (MmsException e) {
Log.w(TAG, e);
return threadId;
}
}
public static void resendGroupMessage(Context context, MasterSecret masterSecret, MessageRecord messageRecord, long filterRecipientId) {
if (!messageRecord.isMms()) throw new AssertionError("Not Group");
Recipients recipients = DatabaseFactory.getMmsAddressDatabase(context).getRecipientsForId(messageRecord.getId());
sendGroupPush(context, recipients, messageRecord.getId(), filterRecipientId);
}
public static void resend(Context context, MasterSecret masterSecret, MessageRecord messageRecord) {
try {
long messageId = messageRecord.getId();
boolean forceSms = messageRecord.isForcedSms();
boolean keyExchange = messageRecord.isKeyExchange();
if (messageRecord.isMms()) {
Recipients recipients = DatabaseFactory.getMmsAddressDatabase(context).getRecipientsForId(messageId);
sendMediaMessage(context, masterSecret, recipients, forceSms, messageId);
} else {
Recipients recipients = messageRecord.getRecipients();
sendTextMessage(context, recipients, forceSms, keyExchange, messageId);
}
} catch (MmsException e) {
Log.w(TAG, e);
}
}
private static void sendMediaMessage(Context context, MasterSecret masterSecret,
Recipients recipients, boolean forceSms, long messageId)
throws MmsException
{
if (!forceSms && isSelfSend(context, recipients)) {
sendMediaSelf(context, masterSecret, messageId);
} else if (isGroupPushSend(recipients)) {
sendGroupPush(context, recipients, messageId, -1);
} else if (!forceSms && isPushMediaSend(context, recipients)) {
sendMediaPush(context, recipients, messageId);
} else {
sendMms(context, messageId);
}
}
private static void sendTextMessage(Context context, Recipients recipients,
boolean forceSms, boolean keyExchange, long messageId)
{
if (!forceSms && isSelfSend(context, recipients)) {
sendTextSelf(context, messageId);
} else if (!forceSms && isPushTextSend(context, recipients, keyExchange)) {
sendTextPush(context, recipients, messageId);
} else {
sendSms(context, recipients, messageId);
}
}
private static void sendTextSelf(Context context, long messageId) {
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
database.markAsSent(messageId);
database.markAsPush(messageId);
Pair<Long, Long> messageAndThreadId = database.copyMessageInbox(messageId);
database.markAsPush(messageAndThreadId.first);
}
private static void sendMediaSelf(Context context, MasterSecret masterSecret, long messageId)
throws MmsException
{
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
database.markAsSent(messageId);
database.markAsPush(messageId);
long newMessageId = database.copyMessageInbox(masterSecret, messageId);
database.markAsPush(newMessageId);
}
private static void sendTextPush(Context context, Recipients recipients, long messageId) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
jobManager.add(new PushTextSendJob(context, messageId, recipients.getPrimaryRecipient().getNumber()));
}
private static void sendMediaPush(Context context, Recipients recipients, long messageId) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
jobManager.add(new PushMediaSendJob(context, messageId, recipients.getPrimaryRecipient().getNumber()));
}
private static void sendGroupPush(Context context, Recipients recipients, long messageId, long filterRecipientId) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
jobManager.add(new PushGroupSendJob(context, messageId, recipients.getPrimaryRecipient().getNumber(), filterRecipientId));
}
private static void sendSms(Context context, Recipients recipients, long messageId) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
jobManager.add(new SmsSendJob(context, messageId, recipients.getPrimaryRecipient().getName()));
}
private static void sendMms(Context context, long messageId) {
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
jobManager.add(new MmsSendJob(context, messageId));
}
private static boolean isPushTextSend(Context context, Recipients recipients, boolean keyExchange) {
try {
if (!TextSecurePreferences.isPushRegistered(context)) {
return false;
}
if (keyExchange) {
return false;
}
Recipient recipient = recipients.getPrimaryRecipient();
String destination = Util.canonicalizeNumber(context, recipient.getNumber());
return isPushDestination(context, destination);
} catch (InvalidNumberException e) {
Log.w(TAG, e);
return false;
}
}
private static boolean isPushMediaSend(Context context, Recipients recipients) {
try {
if (!TextSecurePreferences.isPushRegistered(context)) {
return false;
}
if (recipients.getRecipientsList().size() > 1) {
return false;
}
Recipient recipient = recipients.getPrimaryRecipient();
String destination = Util.canonicalizeNumber(context, recipient.getNumber());
return isPushDestination(context, destination);
} catch (InvalidNumberException e) {
Log.w(TAG, e);
return false;
}
}
private static boolean isGroupPushSend(Recipients recipients) {
return GroupUtil.isEncodedGroup(recipients.getPrimaryRecipient().getNumber());
}
private static boolean isSelfSend(Context context, Recipients recipients) {
try {
if (!TextSecurePreferences.isPushRegistered(context)) {
return false;
}
if (!recipients.isSingleRecipient()) {
return false;
}
if (recipients.isGroupRecipient()) {
return false;
}
String e164number = Util.canonicalizeNumber(context, recipients.getPrimaryRecipient().getNumber());
return TextSecurePreferences.getLocalNumber(context).equals(e164number);
} catch (InvalidNumberException e) {
Log.w("MessageSender", e);
return false;
}
}
private static boolean isPushDestination(Context context, String destination) {
TextSecureDirectory directory = TextSecureDirectory.getInstance(context);
try {
return directory.isSecureTextSupported(destination);
} catch (NotInDirectoryException e) {
try {
TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(context);
Optional<ContactTokenDetails> registeredUser = accountManager.getContact(destination);
if (!registeredUser.isPresent()) {
registeredUser = Optional.of(new ContactTokenDetails());
registeredUser.get().setNumber(destination);
directory.setNumber(registeredUser.get(), false);
return false;
} else {
registeredUser.get().setNumber(destination);
directory.setNumber(registeredUser.get(), true);
return true;
}
} catch (IOException e1) {
Log.w(TAG, e1);
return false;
}
}
}
}
| 11,937 | 38.013072 | 153 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/OutgoingEncryptedMessage.java | package org.thoughtcrime.securesms.sms;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
public class OutgoingEncryptedMessage extends OutgoingTextMessage {
public OutgoingEncryptedMessage(Recipients recipients, String body) {
super(recipients, body);
}
private OutgoingEncryptedMessage(OutgoingEncryptedMessage base, String body) {
super(base, body);
}
@Override
public boolean isSecureMessage() {
return true;
}
@Override
public OutgoingTextMessage withBody(String body) {
return new OutgoingEncryptedMessage(this, body);
}
}
| 634 | 23.423077 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/OutgoingEndSessionMessage.java | package org.thoughtcrime.securesms.sms;
public class OutgoingEndSessionMessage extends OutgoingTextMessage {
public OutgoingEndSessionMessage(OutgoingTextMessage base) {
this(base, base.getMessageBody());
}
public OutgoingEndSessionMessage(OutgoingTextMessage message, String body) {
super(message, body);
}
@Override
public boolean isEndSession() {
return true;
}
@Override
public OutgoingTextMessage withBody(String body) {
return new OutgoingEndSessionMessage(this, body);
}
}
| 521 | 21.695652 | 78 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/OutgoingKeyExchangeMessage.java | package org.thoughtcrime.securesms.sms;
import org.thoughtcrime.securesms.recipients.Recipients;
public class OutgoingKeyExchangeMessage extends OutgoingTextMessage {
public OutgoingKeyExchangeMessage(Recipients recipients, String message) {
super(recipients, message);
}
private OutgoingKeyExchangeMessage(OutgoingKeyExchangeMessage base, String body) {
super(base, body);
}
@Override
public boolean isKeyExchange() {
return true;
}
@Override
public OutgoingTextMessage withBody(String body) {
return new OutgoingKeyExchangeMessage(this, body);
}
}
| 592 | 22.72 | 84 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/OutgoingPrekeyBundleMessage.java | package org.thoughtcrime.securesms.sms;
public class OutgoingPrekeyBundleMessage extends OutgoingTextMessage {
public OutgoingPrekeyBundleMessage(OutgoingTextMessage message, String body) {
super(message, body);
}
@Override
public boolean isPreKeyBundle() {
return true;
}
@Override
public OutgoingTextMessage withBody(String body) {
return new OutgoingPrekeyBundleMessage(this, body);
}
}
| 423 | 20.2 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/OutgoingTextMessage.java | package org.thoughtcrime.securesms.sms;
import org.thoughtcrime.securesms.database.model.SmsMessageRecord;
import org.thoughtcrime.securesms.recipients.Recipients;
public class OutgoingTextMessage {
private final Recipients recipients;
private final String message;
public OutgoingTextMessage(Recipients recipients, String message) {
this.recipients = recipients;
this.message = message;
}
protected OutgoingTextMessage(OutgoingTextMessage base, String body) {
this.recipients = base.getRecipients();
this.message = body;
}
public String getMessageBody() {
return message;
}
public Recipients getRecipients() {
return recipients;
}
public boolean isKeyExchange() {
return false;
}
public boolean isSecureMessage() {
return false;
}
public boolean isEndSession() {
return false;
}
public boolean isPreKeyBundle() {
return false;
}
public static OutgoingTextMessage from(SmsMessageRecord record) {
if (record.isSecure()) {
return new OutgoingEncryptedMessage(record.getRecipients(), record.getBody().getBody());
} else if (record.isKeyExchange()) {
return new OutgoingKeyExchangeMessage(record.getRecipients(), record.getBody().getBody());
} else if (record.isEndSession()) {
return new OutgoingEndSessionMessage(new OutgoingTextMessage(record.getRecipients(), record.getBody().getBody()));
} else {
return new OutgoingTextMessage(record.getRecipients(), record.getBody().getBody());
}
}
public OutgoingTextMessage withBody(String body) {
return new OutgoingTextMessage(this, body);
}
}
| 1,640 | 25.901639 | 120 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/SmsTransportDetails.java | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.sms;
public class SmsTransportDetails {
public static final int SMS_SIZE = 160;
public static final int MULTIPART_SMS_SIZE = 153;
}
| 924 | 34.576923 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/sms/TelephonyServiceState.java | package org.thoughtcrime.securesms.sms;
import android.content.Context;
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
public class TelephonyServiceState {
public boolean isConnected(Context context) {
ListenThread listenThread = new ListenThread(context);
listenThread.start();
return listenThread.get();
}
private static class ListenThread extends Thread {
private final Context context;
private boolean complete;
private boolean result;
public ListenThread(Context context) {
this.context = context.getApplicationContext();
}
@Override
public void run() {
Looper looper = initializeLooper();
ListenCallback callback = new ListenCallback(looper);
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(callback, PhoneStateListener.LISTEN_SERVICE_STATE);
Looper.loop();
telephonyManager.listen(callback, PhoneStateListener.LISTEN_NONE);
set(callback.isConnected());
}
private Looper initializeLooper() {
Looper looper = Looper.myLooper();
if (looper == null) {
Looper.prepare();
}
return Looper.myLooper();
}
public synchronized boolean get() {
while (!complete) {
try {
wait();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
return result;
}
private synchronized void set(boolean result) {
this.result = result;
this.complete = true;
notifyAll();
}
}
private static class ListenCallback extends PhoneStateListener {
private final Looper looper;
private volatile boolean connected;
public ListenCallback(Looper looper) {
this.looper = looper;
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
this.connected = (serviceState.getState() == ServiceState.STATE_IN_SERVICE);
looper.quit();
}
public boolean isConnected() {
return connected;
}
}
}
| 2,211 | 22.784946 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/transport/InsecureFallbackApprovalException.java | package org.thoughtcrime.securesms.transport;
public class InsecureFallbackApprovalException extends Exception {
public InsecureFallbackApprovalException(String detailMessage) {
super(detailMessage);
}
public InsecureFallbackApprovalException(Throwable e) {
super(e);
}
}
| 290 | 23.25 | 66 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/transport/RetryLaterException.java | package org.thoughtcrime.securesms.transport;
import java.io.IOException;
public class RetryLaterException extends Exception {
public RetryLaterException(Exception e) {
super(e);
}
}
| 193 | 18.4 | 52 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/transport/UndeliverableMessageException.java | package org.thoughtcrime.securesms.transport;
public class UndeliverableMessageException extends Exception {
public UndeliverableMessageException() {
}
public UndeliverableMessageException(String detailMessage) {
super(detailMessage);
}
public UndeliverableMessageException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public UndeliverableMessageException(Throwable throwable) {
super(throwable);
}
}
| 468 | 23.684211 | 83 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/AbstractCursorLoader.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.AsyncTaskLoader;
/**
* A Loader similar to CursorLoader that doesn't require queries to go through the ContentResolver
* to get the benefits of reloading when content has changed.
*/
public abstract class AbstractCursorLoader extends AsyncTaskLoader<Cursor> {
private static final String TAG = AbstractCursorLoader.class.getSimpleName();
protected final ForceLoadContentObserver observer;
protected final Context context;
protected Cursor cursor;
public AbstractCursorLoader(Context context) {
super(context);
this.context = context.getApplicationContext();
this.observer = new ForceLoadContentObserver();
}
public abstract Cursor getCursor();
@Override
public void deliverResult(Cursor newCursor) {
if (isReset()) {
if (newCursor != null) {
newCursor.close();
}
return;
}
Cursor oldCursor = this.cursor;
this.cursor = newCursor;
if (isStarted()) {
super.deliverResult(newCursor);
}
if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
oldCursor.close();
}
}
@Override
protected void onStartLoading() {
if (cursor != null) {
deliverResult(cursor);
}
if (takeContentChanged() || cursor == null) {
forceLoad();
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
public void onCanceled(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
@Override
public Cursor loadInBackground() {
Cursor newCursor = getCursor();
if (newCursor != null) {
newCursor.getCount();
newCursor.registerContentObserver(observer);
}
return newCursor;
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor = null;
}
}
| 2,081 | 21.879121 | 98 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Base64.java | package org.thoughtcrime.securesms.util;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>Example:</p>
*
* <code>String encoded = Base64.encode( myByteArray );</code>
* <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
* several pieces of information to the encoder. In the "higher level" methods such as
* encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds,
* and encoding using the URL-safe and Ordered dialects.</p>
*
* <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
* Section 2.1, implementations should not add line feeds unless explicitly told
* to do so. I've got Base64 set to this behavior now, although earlier versions
* broke lines by default.</p>
*
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>to compress the data before encoding it and then making the output have newline characters.</p>
* <p>Also...</p>
* <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
*
*
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
* the Base64.OutputStream closed the Base64 encoding (by padding with equals
* signs) too soon. Also added an option to suppress the automatic decoding
* of gzipped streams. Also added experimental support for specifying a
* class loader when using the
* {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
* method.</li>
* <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
* footprint with its CharEncoders and so forth. Fixed some javadocs that were
* inconsistent. Removed imports and specified things like java.io.IOException
* explicitly inline.</li>
* <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
* final encoded data will be so that the code doesn't have to create two output
* arrays: an oversized initial one and then a final, exact-sized one. Big win
* when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
* using the gzip options which uses a different mechanism with streams and stuff).</li>
* <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
* similar helper methods to be more efficient with memory by not returning a
* String but just a byte array.</li>
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
* and bug fixes queued up and finally executed. Thanks to everyone who sent
* me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
* Much bad coding was cleaned up including throwing exceptions where necessary
* instead of returning null values or something similar. Here are some changes
* that may affect you:
* <ul>
* <li><em>Does not break lines, by default.</em> This is to keep in compliance with
* <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
* <li><em>Throws exceptions instead of returning null values.</em> Because some operations
* (especially those that may permit the GZIP option) use IO streams, there
* is a possiblity of an java.io.IOException being thrown. After some discussion and
* thought, I've changed the behavior of the methods to throw java.io.IOExceptions
* rather than return null if ever there's an error. I think this is more
* appropriate, though it will require some changes to your code. Sorry,
* it should have been done this way to begin with.</li>
* <li><em>Removed all references to System.out, System.err, and the like.</em>
* Shame on me. All I can say is sorry they were ever there.</li>
* <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
* such as when passed arrays are null or offsets are invalid.</li>
* <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
* This was especially annoying before for people who were thorough in their
* own projects and then had gobs of javadoc warnings on this file.</li>
* </ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author [email protected]
* @version 2.3.3
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/** Defeats instantiation. */
private Base64(){}
public static int getEncodedLengthWithoutPadding(int unencodedLength) {
int remainderBytes = unencodedLength % 3;
int paddingBytes = 0;
if (remainderBytes != 0)
paddingBytes = 3 - remainderBytes;
return (((int)((unencodedLength+2)/3))*4) - paddingBytes;
}
public static int getEncodedBytesForTarget(int targetSize) {
return ((int)(targetSize * 3)) / 4;
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
return b4;
} // end encode3to4
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> ByteBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> CharBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
for( int i = 0; i < 4; i++ ){
encoded.put( (char)(enc4[i] & 0xFF) );
}
} // end input remaining
}
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException if there is an error
* @throws NullPointerException if serializedObject is null
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
throws java.io.IOException {
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
throws java.io.IOException {
if( serializableObject == null ){
throw new NullPointerException( "Cannot serialize a null object." );
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
if( (options & GZIP) != 0 ){
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream( gzos );
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream( b64os );
}
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try {
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue){
// Fall back to some Java default
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
* @since 1.4
*/
public static String encodeBytes( byte[] source ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
public static String encodeBytesWithoutPadding(byte[] source, int offset, int length) {
String encoded = null;
try {
encoded = encodeBytes(source, offset, length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
}
assert encoded != null;
if (encoded.charAt(encoded.length()-2) == '=') return encoded.substring(0, encoded.length()-2);
else if (encoded.charAt(encoded.length()-1) == '=') return encoded.substring(0, encoded.length()-1);
else return encoded;
}
public static String encodeBytesWithoutPadding(byte[] source) {
return encodeBytesWithoutPadding(source, 0, source.length);
}
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* <p>As of v 2.3, if there is an error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes( source, off, len, NO_OPTIONS );
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
byte[] encoded = encodeBytesToBytes( source, off, len, options );
// Return value according to relevant encoding.
try {
return new String( encoded, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String( encoded );
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source ) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
} catch( java.io.IOException ex ) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
if( source == null ){
throw new NullPointerException( "Cannot serialize a null array." );
} // end if: null
if( off < 0 ){
throw new IllegalArgumentException( "Cannot have negative offset: " + off );
} // end if: off < 0
if( len < 0 ){
throw new IllegalArgumentException( "Cannot have length offset: " + len );
} // end if: len < 0
if( off + len > source.length ){
throw new IllegalArgumentException(
String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
} // end if: off < 0
// Compress?
if( (options & GZIP) != 0 ) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) > 0;
//int len43 = len * 4 / 3;
//byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
if( breakLines ){
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[ encLen ];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 ) {
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len ) {
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if( e < outBuff.length - 1 ){
byte[] finalOut = new byte[e];
System.arraycopy(outBuff,0, finalOut,0,e);
//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
//System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode( byte[] source ){
byte[] decoded = null;
try {
decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
} catch( java.io.IOException ex ) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return decoded;
}
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @param options Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len, int options )
throws java.io.IOException {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
} // end if
if( off < 0 || off + len > source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
} // end if
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiCrop = 0; // Low seven bits (ASCII) of input
byte sbiDecode = 0; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ]; // Special value
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN ) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException( String.format(
"Bad Base64 input character '%c' in array position %d", source[i], i ) );
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode( String s ) throws java.io.IOException {
return decode( s, NO_OPTIONS );
}
public static byte[] decodeWithoutPadding(String source) throws java.io.IOException {
int padding = source.length() % 4;
if (padding == 1) source = source + "=";
else if (padding == 2) source = source + "==";
else if (padding == 3) source = source + "=";
return decode(source);
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode( String s, int options ) throws java.io.IOException {
if( s == null ){
throw new NullPointerException( "Input string was null." );
} // end if
byte[] bytes;
try {
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee ) {
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length, options );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 ) {
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e ) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
* If <tt>loader</tt> is not null, it will be the class loader
* used when deserializing.
*
* @param encodedObject The Base64 data to decode
* @param options Various parameters related to decoding
* @param loader Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 2.3.4
*/
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile( byte[] dataToEncode, String filename )
throws java.io.IOException {
if( dataToEncode == null ){
throw new NullPointerException( "Data to encode was null." );
} // end iff
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static void decodeToFile( String dataToDecode, String filename )
throws java.io.IOException {
Base64.OutputStream bos = null;
try{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static String encodeFromFile( String filename )
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void encodeFileToFile( String infile, String outfile )
throws java.io.IOException {
String encoded = Base64.encodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end encodeFileToFile
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void decodeFileToFile( String infile, String outfile )
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in ) {
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options ) {
super( in );
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ ) {
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 ) {
b3[i] = (byte)b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ ) {
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 ) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes ){
return -1;
} // end if: got data
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength ) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read( byte[] dest, int off, int len )
throws java.io.IOException {
int i;
int b;
for( i = 0; i < len; i++ ) {
b = read();
if( b >= 0 ) {
dest[off + i] = (byte) b;
}
else if( i == 0 ) {
return -1;
}
else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out ) {
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options ) {
super( out );
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
@Override
public void write(int theByte)
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to encode.
this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
this.out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to output.
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write( byte[] theBytes, int off, int len )
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
* @throws java.io.IOException if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if( position > 0 ) {
if( encode ) {
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else {
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @throws java.io.IOException if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
| 87,371 | 40.665236 | 137 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/BitmapDecodingException.java | package org.thoughtcrime.securesms.util;
public class BitmapDecodingException extends Throwable {
public BitmapDecodingException(String s) {
super(s);
}
}
| 164 | 19.625 | 56 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/BitmapUtil.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import com.bumptech.glide.load.resource.bitmap.Downsampler;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import org.thoughtcrime.securesms.mms.MediaConstraints;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
public class BitmapUtil {
private static final String TAG = BitmapUtil.class.getSimpleName();
private static final int MAX_COMPRESSION_QUALITY = 80;
private static final int MIN_COMPRESSION_QUALITY = 45;
private static final int MAX_COMPRESSION_ATTEMPTS = 4;
public static <T> byte[] createScaledBytes(Context context, T model, MediaConstraints constraints)
throws ExecutionException, IOException
{
int quality = MAX_COMPRESSION_QUALITY;
int attempts = 0;
byte[] bytes;
Bitmap scaledBitmap = createScaledBitmap(context,
model,
constraints.getImageMaxWidth(context),
constraints.getImageMaxHeight(context));
try {
do {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
scaledBitmap.compress(CompressFormat.JPEG, quality, baos);
bytes = baos.toByteArray();
Log.w(TAG, "iteration with quality " + quality + " size " + (bytes.length / 1024) + "kb");
if (quality == MIN_COMPRESSION_QUALITY) break;
quality = Math.max((quality * constraints.getImageMaxSize()) / bytes.length, MIN_COMPRESSION_QUALITY);
}
while (bytes.length > constraints.getImageMaxSize() && attempts++ < MAX_COMPRESSION_ATTEMPTS);
if (bytes.length > constraints.getImageMaxSize()) {
throw new IOException("Unable to scale image below: " + bytes.length);
}
Log.w(TAG, "createScaledBytes(" + model.toString() + ") -> quality " + Math.min(quality, MAX_COMPRESSION_QUALITY) + ", " + attempts + " attempt(s)");
return bytes;
} finally {
if (scaledBitmap != null) scaledBitmap.recycle();
}
}
public static <T> Bitmap createScaledBitmap(Context context, T model, int maxWidth, int maxHeight)
throws ExecutionException
{
final Pair<Integer, Integer> dimensions = getDimensions(getInputStreamForModel(context, model));
final Pair<Integer, Integer> clamped = clampDimensions(dimensions.first, dimensions.second,
maxWidth, maxHeight);
return createScaledBitmapInto(context, model, clamped.first, clamped.second);
}
private static <T> InputStream getInputStreamForModel(Context context, T model)
throws ExecutionException
{
try {
return Glide.buildStreamModelLoader(model, context)
.getResourceFetcher(model, -1, -1)
.loadData(Priority.NORMAL);
} catch (Exception e) {
throw new ExecutionException(e);
}
}
private static <T> Bitmap createScaledBitmapInto(Context context, T model, int width, int height)
throws ExecutionException
{
final Bitmap rough = Downsampler.AT_LEAST.decode(getInputStreamForModel(context, model),
Glide.get(context).getBitmapPool(),
width, height,
DecodeFormat.PREFER_RGB_565);
final Resource<Bitmap> resource = BitmapResource.obtain(rough, Glide.get(context).getBitmapPool());
final Resource<Bitmap> result = new FitCenter(context).transform(resource, width, height);
if (result == null) {
throw new ExecutionException(new BitmapDecodingException("unable to transform Bitmap"));
}
return result.get();
}
public static <T> Bitmap createScaledBitmap(Context context, T model, float scale)
throws ExecutionException
{
Pair<Integer, Integer> dimens = getDimensions(getInputStreamForModel(context, model));
return createScaledBitmapInto(context, model,
(int)(dimens.first * scale), (int)(dimens.second * scale));
}
private static BitmapFactory.Options getImageDimensions(InputStream inputStream) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BufferedInputStream fis = new BufferedInputStream(inputStream);
BitmapFactory.decodeStream(fis, null, options);
try {
fis.close();
} catch (IOException ioe) {
Log.w(TAG, "failed to close the InputStream after reading image dimensions");
}
return options;
}
public static Pair<Integer, Integer> getDimensions(InputStream inputStream) {
BitmapFactory.Options options = getImageDimensions(inputStream);
return new Pair<>(options.outWidth, options.outHeight);
}
public static InputStream toCompressedJpeg(Bitmap bitmap) {
ByteArrayOutputStream thumbnailBytes = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 85, thumbnailBytes);
return new ByteArrayInputStream(thumbnailBytes.toByteArray());
}
public static @Nullable byte[] toByteArray(@Nullable Bitmap bitmap) {
if (bitmap == null) return null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
public static @Nullable Bitmap fromByteArray(@Nullable byte[] bytes) {
if (bytes == null) return null;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public static byte[] createFromNV21(@NonNull final byte[] data,
final int width,
final int height,
int rotation,
final Rect croppingRect)
throws IOException
{
byte[] rotated = rotateNV21(data, width, height, rotation);
final int rotatedWidth = rotation % 180 > 0 ? height : width;
final int rotatedHeight = rotation % 180 > 0 ? width : height;
YuvImage previewImage = new YuvImage(rotated, ImageFormat.NV21,
rotatedWidth, rotatedHeight, null);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
previewImage.compressToJpeg(croppingRect, 80, outputStream);
byte[] bytes = outputStream.toByteArray();
outputStream.close();
return bytes;
}
/*
* NV21 a.k.a. YUV420sp
* YUV 4:2:0 planar image, with 8 bit Y samples, followed by interleaved V/U plane with 8bit 2x2
* subsampled chroma samples.
*
* http://www.fourcc.org/yuv.php#NV21
*/
public static byte[] rotateNV21(@NonNull final byte[] yuv,
final int width,
final int height,
final int rotation)
throws IOException
{
if (rotation == 0) return yuv;
if (rotation % 90 != 0 || rotation < 0 || rotation > 270) {
throw new IllegalArgumentException("0 <= rotation < 360, rotation % 90 == 0");
} else if ((width * height * 3) / 2 != yuv.length) {
throw new IOException("provided width and height don't jive with the data length");
}
final byte[] output = new byte[yuv.length];
final int frameSize = width * height;
final boolean swap = rotation % 180 != 0;
final boolean xflip = rotation % 270 != 0;
final boolean yflip = rotation >= 180;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
final int yIn = j * width + i;
final int uIn = frameSize + (j >> 1) * width + (i & ~1);
final int vIn = uIn + 1;
final int wOut = swap ? height : width;
final int hOut = swap ? width : height;
final int iSwapped = swap ? j : i;
final int jSwapped = swap ? i : j;
final int iOut = xflip ? wOut - iSwapped - 1 : iSwapped;
final int jOut = yflip ? hOut - jSwapped - 1 : jSwapped;
final int yOut = jOut * wOut + iOut;
final int uOut = frameSize + (jOut >> 1) * wOut + (iOut & ~1);
final int vOut = uOut + 1;
output[yOut] = (byte)(0xff & yuv[yIn]);
output[uOut] = (byte)(0xff & yuv[uIn]);
output[vOut] = (byte)(0xff & yuv[vIn]);
}
}
return output;
}
private static Pair<Integer, Integer> clampDimensions(int inWidth, int inHeight, int maxWidth, int maxHeight) {
if (inWidth > maxWidth || inHeight > maxHeight) {
final float aspectWidth, aspectHeight;
if (inWidth == 0 || inHeight == 0) {
aspectWidth = maxWidth;
aspectHeight = maxHeight;
} else if (inWidth >= inHeight) {
aspectWidth = maxWidth;
aspectHeight = (aspectWidth / inWidth) * inHeight;
} else {
aspectHeight = maxHeight;
aspectWidth = (aspectHeight / inHeight) * inWidth;
}
return new Pair<>(Math.round(aspectWidth), Math.round(aspectHeight));
} else {
return new Pair<>(inWidth, inHeight);
}
}
public static Bitmap createFromDrawable(final Drawable drawable, final int width, final int height) {
final AtomicBoolean created = new AtomicBoolean(false);
final Bitmap[] result = new Bitmap[1];
Runnable runnable = new Runnable() {
@Override
public void run() {
if (drawable instanceof BitmapDrawable) {
result[0] = ((BitmapDrawable) drawable).getBitmap();
} else {
int canvasWidth = drawable.getIntrinsicWidth();
if (canvasWidth <= 0) canvasWidth = width;
int canvasHeight = drawable.getIntrinsicHeight();
if (canvasHeight <= 0) canvasHeight = height;
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
} catch (Exception e) {
Log.w(TAG, e);
bitmap = null;
}
result[0] = bitmap;
}
synchronized (result) {
created.set(true);
result.notifyAll();
}
}
};
Util.runOnMain(runnable);
synchronized (result) {
while (!created.get()) Util.wait(result, 0);
return result[0];
}
}
}
| 11,435 | 37.897959 | 155 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/CharacterCalculator.java | /**
* Copyright (C) 2015 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
public abstract class CharacterCalculator {
public abstract CharacterState calculateCharacters(int charactersSpent);
public static class CharacterState {
public int charactersRemaining;
public int messagesSpent;
public int maxMessageSize;
public CharacterState(int messagesSpent, int charactersRemaining, int maxMessageSize) {
this.messagesSpent = messagesSpent;
this.charactersRemaining = charactersRemaining;
this.maxMessageSize = maxMessageSize;
}
}
}
| 1,251 | 33.777778 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Conversions.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
public class Conversions {
public static byte intsToByteHighAndLow(int highValue, int lowValue) {
return (byte)((highValue << 4 | lowValue) & 0xFF);
}
public static int highBitsToInt(byte value) {
return (value & 0xFF) >> 4;
}
public static int lowBitsToInt(byte value) {
return (value & 0xF);
}
public static int highBitsToMedium(int value) {
return (value >> 12);
}
public static int lowBitsToMedium(int value) {
return (value & 0xFFF);
}
public static byte[] shortToByteArray(int value) {
byte[] bytes = new byte[2];
shortToByteArray(bytes, 0, value);
return bytes;
}
public static int shortToByteArray(byte[] bytes, int offset, int value) {
bytes[offset+1] = (byte)value;
bytes[offset] = (byte)(value >> 8);
return 2;
}
public static int shortToLittleEndianByteArray(byte[] bytes, int offset, int value) {
bytes[offset] = (byte)value;
bytes[offset+1] = (byte)(value >> 8);
return 2;
}
public static byte[] mediumToByteArray(int value) {
byte[] bytes = new byte[3];
mediumToByteArray(bytes, 0, value);
return bytes;
}
public static int mediumToByteArray(byte[] bytes, int offset, int value) {
bytes[offset + 2] = (byte)value;
bytes[offset + 1] = (byte)(value >> 8);
bytes[offset] = (byte)(value >> 16);
return 3;
}
public static byte[] intToByteArray(int value) {
byte[] bytes = new byte[4];
intToByteArray(bytes, 0, value);
return bytes;
}
public static int intToByteArray(byte[] bytes, int offset, int value) {
bytes[offset + 3] = (byte)value;
bytes[offset + 2] = (byte)(value >> 8);
bytes[offset + 1] = (byte)(value >> 16);
bytes[offset] = (byte)(value >> 24);
return 4;
}
public static int intToLittleEndianByteArray(byte[] bytes, int offset, int value) {
bytes[offset] = (byte)value;
bytes[offset+1] = (byte)(value >> 8);
bytes[offset+2] = (byte)(value >> 16);
bytes[offset+3] = (byte)(value >> 24);
return 4;
}
public static byte[] longToByteArray(long l) {
byte[] bytes = new byte[8];
longToByteArray(bytes, 0, l);
return bytes;
}
public static int longToByteArray(byte[] bytes, int offset, long value) {
bytes[offset + 7] = (byte)value;
bytes[offset + 6] = (byte)(value >> 8);
bytes[offset + 5] = (byte)(value >> 16);
bytes[offset + 4] = (byte)(value >> 24);
bytes[offset + 3] = (byte)(value >> 32);
bytes[offset + 2] = (byte)(value >> 40);
bytes[offset + 1] = (byte)(value >> 48);
bytes[offset] = (byte)(value >> 56);
return 8;
}
public static int longTo4ByteArray(byte[] bytes, int offset, long value) {
bytes[offset + 3] = (byte)value;
bytes[offset + 2] = (byte)(value >> 8);
bytes[offset + 1] = (byte)(value >> 16);
bytes[offset + 0] = (byte)(value >> 24);
return 4;
}
public static int byteArrayToShort(byte[] bytes) {
return byteArrayToShort(bytes, 0);
}
public static int byteArrayToShort(byte[] bytes, int offset) {
return
(bytes[offset] & 0xff) << 8 | (bytes[offset + 1] & 0xff);
}
// The SSL patented 3-byte Value.
public static int byteArrayToMedium(byte[] bytes, int offset) {
return
(bytes[offset] & 0xff) << 16 |
(bytes[offset + 1] & 0xff) << 8 |
(bytes[offset + 2] & 0xff);
}
public static int byteArrayToInt(byte[] bytes) {
return byteArrayToInt(bytes, 0);
}
public static int byteArrayToInt(byte[] bytes, int offset) {
return
(bytes[offset] & 0xff) << 24 |
(bytes[offset + 1] & 0xff) << 16 |
(bytes[offset + 2] & 0xff) << 8 |
(bytes[offset + 3] & 0xff);
}
public static int byteArrayToIntLittleEndian(byte[] bytes, int offset) {
return
(bytes[offset + 3] & 0xff) << 24 |
(bytes[offset + 2] & 0xff) << 16 |
(bytes[offset + 1] & 0xff) << 8 |
(bytes[offset] & 0xff);
}
public static long byteArrayToLong(byte[] bytes) {
return byteArrayToLong(bytes, 0);
}
public static long byteArray4ToLong(byte[] bytes, int offset) {
return
((bytes[offset + 0] & 0xffL) << 24) |
((bytes[offset + 1] & 0xffL) << 16) |
((bytes[offset + 2] & 0xffL) << 8) |
((bytes[offset + 3] & 0xffL));
}
public static long byteArrayToLong(byte[] bytes, int offset) {
return
((bytes[offset] & 0xffL) << 56) |
((bytes[offset + 1] & 0xffL) << 48) |
((bytes[offset + 2] & 0xffL) << 40) |
((bytes[offset + 3] & 0xffL) << 32) |
((bytes[offset + 4] & 0xffL) << 24) |
((bytes[offset + 5] & 0xffL) << 16) |
((bytes[offset + 6] & 0xffL) << 8) |
((bytes[offset + 7] & 0xffL));
}
}
| 5,465 | 29.198895 | 87 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/DateUtils.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.content.Context;
import android.text.format.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.thoughtcrime.securesms.R;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Utility methods to help display dates in a nice, easily readable way.
*/
public class DateUtils extends android.text.format.DateUtils {
private static boolean isWithin(final long millis, final long span, final TimeUnit unit) {
return System.currentTimeMillis() - millis <= unit.toMillis(span);
}
private static int convertDelta(final long millis, TimeUnit to) {
return (int) to.convert(System.currentTimeMillis() - millis, TimeUnit.MILLISECONDS);
}
private static String getFormattedDateTime(long time, String template, Locale locale) {
String localizedPattern = new SimpleDateFormat(template, locale).toLocalizedPattern();
return new SimpleDateFormat(localizedPattern, locale).format(new Date(time));
}
public static String getBriefRelativeTimeSpanString(final Context c, final Locale locale, final long timestamp) {
if (isWithin(timestamp, 1, TimeUnit.MINUTES)) {
return c.getString(R.string.DateUtils_now);
} else if (isWithin(timestamp, 1, TimeUnit.HOURS)) {
int mins = convertDelta(timestamp, TimeUnit.MINUTES);
return c.getResources().getString(R.string.DateUtils_minutes_ago, mins);
} else if (isWithin(timestamp, 1, TimeUnit.DAYS)) {
int hours = convertDelta(timestamp, TimeUnit.HOURS);
return c.getResources().getQuantityString(R.plurals.hours_ago, hours, hours);
} else if (isWithin(timestamp, 6, TimeUnit.DAYS)) {
return getFormattedDateTime(timestamp, "EEE", locale);
} else if (isWithin(timestamp, 365, TimeUnit.DAYS)) {
return getFormattedDateTime(timestamp, "MMM d", locale);
} else {
return getFormattedDateTime(timestamp, "MMM d, yyyy", locale);
}
}
public static String getExtendedRelativeTimeSpanString(final Context c, final Locale locale, final long timestamp) {
if (isWithin(timestamp, 1, TimeUnit.MINUTES)) {
return c.getString(R.string.DateUtils_now);
} else if (isWithin(timestamp, 1, TimeUnit.HOURS)) {
int mins = (int)TimeUnit.MINUTES.convert(System.currentTimeMillis() - timestamp, TimeUnit.MILLISECONDS);
return c.getResources().getString(R.string.DateUtils_minutes_ago, mins);
} else {
StringBuilder format = new StringBuilder();
if (isWithin(timestamp, 6, TimeUnit.DAYS)) format.append("EEE ");
else if (isWithin(timestamp, 365, TimeUnit.DAYS)) format.append("MMM d, ");
else format.append("MMM d, yyyy, ");
if (DateFormat.is24HourFormat(c)) format.append("HH:mm");
else format.append("hh:mm a");
return getFormattedDateTime(timestamp, format.toString(), locale);
}
}
public static SimpleDateFormat getDetailedDateFormatter(Context context, Locale locale) {
String dateFormatPattern;
if (DateFormat.is24HourFormat(context)) {
dateFormatPattern = "MMM d, yyyy HH:mm:ss zzz";
} else {
dateFormatPattern = "MMM d, yyyy hh:mm:ss a zzz";
}
return new SimpleDateFormat(dateFormatPattern, locale);
}
}
| 4,025 | 40.081633 | 118 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Dialogs.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import org.thoughtcrime.securesms.R;
public class Dialogs {
public static void showAlertDialog(Context context, String title, String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setIconAttribute(R.attr.dialog_alert_icon);
dialog.setPositiveButton(android.R.string.ok, null);
dialog.show();
}
public static void showInfoDialog(Context context, String title, String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setIconAttribute(R.attr.dialog_info_icon);
dialog.setPositiveButton(android.R.string.ok, null);
dialog.show();
}
}
| 1,571 | 35.55814 | 85 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/DirectoryHelper.java | package org.thoughtcrime.securesms.util;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.NotInDirectoryException;
import org.thoughtcrime.securesms.database.TextSecureDirectory;
import org.thoughtcrime.securesms.jobs.MultiDeviceContactUpdateJob;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.sms.IncomingJoinedMessage;
import org.thoughtcrime.securesms.util.DirectoryHelper.UserCapabilities.Capability;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.ContactTokenDetails;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class DirectoryHelper {
public static class UserCapabilities {
public static final UserCapabilities UNKNOWN = new UserCapabilities(Capability.UNKNOWN, Capability.UNKNOWN);
public static final UserCapabilities UNSUPPORTED = new UserCapabilities(Capability.UNSUPPORTED, Capability.UNSUPPORTED);
public enum Capability {
UNKNOWN, SUPPORTED, UNSUPPORTED
}
private final Capability text;
private final Capability voice;
public UserCapabilities(Capability text, Capability voice) {
this.text = text;
this.voice = voice;
}
public Capability getTextCapability() {
return text;
}
public Capability getVoiceCapability() {
return voice;
}
}
private static final String TAG = DirectoryHelper.class.getSimpleName();
public static void refreshDirectory(@NonNull Context context, @Nullable MasterSecret masterSecret)
throws IOException
{
List<String> newUsers = refreshDirectory(context,
TextSecureCommunicationFactory.createManager(context),
TextSecurePreferences.getLocalNumber(context));
if (!newUsers.isEmpty() && TextSecurePreferences.isMultiDevice(context)) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new MultiDeviceContactUpdateJob(context));
}
notifyNewUsers(context, masterSecret, newUsers);
}
public static @NonNull List<String> refreshDirectory(@NonNull Context context,
@NonNull TextSecureAccountManager accountManager,
@NonNull String localNumber)
throws IOException
{
TextSecureDirectory directory = TextSecureDirectory.getInstance(context);
Set<String> eligibleContactNumbers = directory.getPushEligibleContactNumbers(localNumber);
List<ContactTokenDetails> activeTokens = accountManager.getContacts(eligibleContactNumbers);
if (activeTokens != null) {
for (ContactTokenDetails activeToken : activeTokens) {
eligibleContactNumbers.remove(activeToken.getNumber());
activeToken.setNumber(activeToken.getNumber());
}
directory.setNumbers(activeTokens, eligibleContactNumbers);
return updateContactsDatabase(context, localNumber, activeTokens, true);
}
return new LinkedList<>();
}
public static UserCapabilities refreshDirectoryFor(@NonNull Context context,
@Nullable MasterSecret masterSecret,
@NonNull Recipients recipients,
@NonNull String localNumber)
throws IOException
{
try {
TextSecureDirectory directory = TextSecureDirectory.getInstance(context);
TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(context);
String number = Util.canonicalizeNumber(context, recipients.getPrimaryRecipient().getNumber());
Optional<ContactTokenDetails> details = accountManager.getContact(number);
if (details.isPresent()) {
directory.setNumber(details.get(), true);
List<String> newUsers = updateContactsDatabase(context, localNumber, details.get());
if (!newUsers.isEmpty() && TextSecurePreferences.isMultiDevice(context)) {
ApplicationContext.getInstance(context).getJobManager().add(new MultiDeviceContactUpdateJob(context));
}
notifyNewUsers(context, masterSecret, newUsers);
return new UserCapabilities(Capability.SUPPORTED, details.get().isVoice() ? Capability.SUPPORTED : Capability.UNSUPPORTED);
} else {
ContactTokenDetails absent = new ContactTokenDetails();
absent.setNumber(number);
directory.setNumber(absent, false);
return UserCapabilities.UNSUPPORTED;
}
} catch (InvalidNumberException e) {
Log.w(TAG, e);
return UserCapabilities.UNSUPPORTED;
}
}
public static @NonNull UserCapabilities getUserCapabilities(@NonNull Context context,
@Nullable Recipients recipients)
{
try {
if (recipients == null) {
return UserCapabilities.UNSUPPORTED;
}
if (!TextSecurePreferences.isPushRegistered(context)) {
return UserCapabilities.UNSUPPORTED;
}
if (!recipients.isSingleRecipient()) {
return UserCapabilities.UNSUPPORTED;
}
if (recipients.isGroupRecipient()) {
return new UserCapabilities(Capability.SUPPORTED, Capability.UNSUPPORTED);
}
final String number = recipients.getPrimaryRecipient().getNumber();
if (number == null) {
return UserCapabilities.UNSUPPORTED;
}
String e164number = Util.canonicalizeNumber(context, number);
boolean secureText = TextSecureDirectory.getInstance(context).isSecureTextSupported(e164number);
boolean secureVoice = TextSecureDirectory.getInstance(context).isSecureVoiceSupported(e164number);
return new UserCapabilities(secureText ? Capability.SUPPORTED : Capability.UNSUPPORTED,
secureVoice ? Capability.SUPPORTED : Capability.UNSUPPORTED);
} catch (InvalidNumberException e) {
Log.w(TAG, e);
return UserCapabilities.UNSUPPORTED;
} catch (NotInDirectoryException e) {
return UserCapabilities.UNKNOWN;
}
}
private static @NonNull List<String> updateContactsDatabase(@NonNull Context context,
@NonNull String localNumber,
@NonNull final ContactTokenDetails activeToken)
{
return updateContactsDatabase(context, localNumber,
new LinkedList<ContactTokenDetails>() {{add(activeToken);}},
false);
}
private static @NonNull List<String> updateContactsDatabase(@NonNull Context context,
@NonNull String localNumber,
@NonNull List<ContactTokenDetails> activeTokens,
boolean removeMissing)
{
Optional<Account> account = getOrCreateAccount(context);
if (account.isPresent()) {
try {
return DatabaseFactory.getContactsDatabase(context)
.setRegisteredUsers(account.get(), localNumber, activeTokens, removeMissing);
} catch (RemoteException | OperationApplicationException e) {
Log.w(TAG, e);
}
}
return new LinkedList<>();
}
private static void notifyNewUsers(@NonNull Context context,
@Nullable MasterSecret masterSecret,
@NonNull List<String> newUsers)
{
for (String newUser : newUsers) {
IncomingJoinedMessage message = new IncomingJoinedMessage(newUser);
Pair<Long, Long> smsAndThreadId = DatabaseFactory.getSmsDatabase(context).insertMessageInbox(message);
MessageNotifier.updateNotification(context, masterSecret, smsAndThreadId.second);
}
}
private static Optional<Account> getOrCreateAccount(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType("org.thoughtcrime.securesms");
Optional<Account> account;
if (accounts.length == 0) account = createAccount(context);
else account = Optional.of(accounts[0]);
if (account.isPresent() && !ContentResolver.getSyncAutomatically(account.get(), ContactsContract.AUTHORITY)) {
ContentResolver.setSyncAutomatically(account.get(), ContactsContract.AUTHORITY, true);
}
return account;
}
private static Optional<Account> createAccount(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account account = new Account(context.getString(R.string.app_name), "org.thoughtcrime.securesms");
if (accountManager.addAccountExplicitly(account, null, null)) {
Log.w(TAG, "Created new account...");
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
return Optional.of(account);
} else {
Log.w(TAG, "Failed to create account!");
return Optional.absent();
}
}
}
| 10,294 | 40.015936 | 132 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/DynamicIntroTheme.java | package org.thoughtcrime.securesms.util;
import android.app.Activity;
import org.thoughtcrime.securesms.R;
public class DynamicIntroTheme extends DynamicTheme {
@Override
protected int getSelectedTheme(Activity activity) {
String theme = TextSecurePreferences.getTheme(activity);
if (theme.equals("dark")) return R.style.TextSecure_DarkIntroTheme;
return R.style.TextSecure_LightIntroTheme;
}
}
| 418 | 23.647059 | 71 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/DynamicLanguage.java | package org.thoughtcrime.securesms.util;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.text.TextUtils;
import java.util.Locale;
public class DynamicLanguage {
private static final String DEFAULT = "zz";
private Locale currentLocale;
public void onCreate(Activity activity) {
currentLocale = getSelectedLocale(activity);
setContextLocale(activity, currentLocale);
}
public void onResume(Activity activity) {
if (!currentLocale.equals(getSelectedLocale(activity))) {
Intent intent = activity.getIntent();
activity.finish();
OverridePendingTransition.invoke(activity);
activity.startActivity(intent);
OverridePendingTransition.invoke(activity);
}
}
public void updateServiceLocale(Service service) {
currentLocale = getSelectedLocale(service);
setContextLocale(service, currentLocale);
}
public Locale getCurrentLocale() {
return currentLocale;
}
private static void setContextLocale(Context context, Locale selectedLocale) {
Configuration configuration = context.getResources().getConfiguration();
if (!configuration.locale.equals(selectedLocale)) {
configuration.locale = selectedLocale;
context.getResources().updateConfiguration(configuration,
context.getResources().getDisplayMetrics());
}
}
private static Locale getActivityLocale(Activity activity) {
return activity.getResources().getConfiguration().locale;
}
private static Locale getSelectedLocale(Context context) {
String language[] = TextUtils.split(TextSecurePreferences.getLanguage(context), "_");
if (language[0].equals(DEFAULT)) {
return Locale.getDefault();
} else if (language.length == 2) {
return new Locale(language[0], language[1]);
} else {
return new Locale(language[0]);
}
}
private static final class OverridePendingTransition {
static void invoke(Activity activity) {
activity.overridePendingTransition(0, 0);
}
}
}
| 2,162 | 27.84 | 94 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/DynamicNoActionBarTheme.java | package org.thoughtcrime.securesms.util;
import android.app.Activity;
import org.thoughtcrime.securesms.R;
public class DynamicNoActionBarTheme extends DynamicTheme {
@Override
protected int getSelectedTheme(Activity activity) {
String theme = TextSecurePreferences.getTheme(activity);
if (theme.equals("dark")) return R.style.TextSecure_DarkNoActionBar;
return R.style.TextSecure_LightNoActionBar;
}
}
| 426 | 24.117647 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/DynamicTheme.java | package org.thoughtcrime.securesms.util;
import android.app.Activity;
import android.content.Intent;
import org.thoughtcrime.securesms.R;
public class DynamicTheme {
public static final String DARK = "dark";
public static final String LIGHT = "light";
private int currentTheme;
public void onCreate(Activity activity) {
currentTheme = getSelectedTheme(activity);
activity.setTheme(currentTheme);
}
public void onResume(Activity activity) {
if (currentTheme != getSelectedTheme(activity)) {
Intent intent = activity.getIntent();
activity.finish();
OverridePendingTransition.invoke(activity);
activity.startActivity(intent);
OverridePendingTransition.invoke(activity);
}
}
protected int getSelectedTheme(Activity activity) {
String theme = TextSecurePreferences.getTheme(activity);
if (theme.equals(DARK)) return R.style.TextSecure_DarkTheme;
return R.style.TextSecure_LightTheme;
}
private static final class OverridePendingTransition {
static void invoke(Activity activity) {
activity.overridePendingTransition(0, 0);
}
}
}
| 1,130 | 24.704545 | 64 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/FutureTaskListener.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
public interface FutureTaskListener<V> {
public void onSuccess(V result);
public void onFailure(Throwable error);
}
| 862 | 36.521739 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/GroupUtil.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import java.io.IOException;
import static org.whispersystems.textsecure.internal.push.TextSecureProtos.GroupContext;
public class GroupUtil {
private static final String ENCODED_GROUP_PREFIX = "__textsecure_group__!";
private static final String TAG = GroupUtil.class.getSimpleName();
public static String getEncodedId(byte[] groupId) {
return ENCODED_GROUP_PREFIX + Hex.toStringCondensed(groupId);
}
public static byte[] getDecodedId(String groupId) throws IOException {
if (!isEncodedGroup(groupId)) {
throw new IOException("Invalid encoding");
}
return Hex.fromStringCondensed(groupId.split("!", 2)[1]);
}
public static boolean isEncodedGroup(@NonNull String groupId) {
return groupId.startsWith(ENCODED_GROUP_PREFIX);
}
public static @NonNull GroupDescription getDescription(@NonNull Context context, @Nullable String encodedGroup) {
if (encodedGroup == null) {
return new GroupDescription(context, null);
}
try {
GroupContext groupContext = GroupContext.parseFrom(Base64.decode(encodedGroup));
return new GroupDescription(context, groupContext);
} catch (IOException e) {
Log.w(TAG, e);
return new GroupDescription(context, null);
}
}
public static class GroupDescription {
@NonNull private final Context context;
@Nullable private final GroupContext groupContext;
@Nullable private final Recipients members;
public GroupDescription(@NonNull Context context, @Nullable GroupContext groupContext) {
this.context = context.getApplicationContext();
this.groupContext = groupContext;
if (groupContext == null || groupContext.getMembersList().isEmpty()) {
this.members = null;
} else {
this.members = RecipientFactory.getRecipientsFromString(context, Util.join(groupContext.getMembersList(), ", "), true);
}
}
public String toString() {
if (groupContext == null) {
return context.getString(R.string.GroupUtil_group_updated);
}
StringBuilder description = new StringBuilder();
String title = groupContext.getName();
if (members != null) {
description.append(context.getString(R.string.GroupUtil_joined_the_group, members.toShortString()));
}
if (title != null && !title.trim().isEmpty()) {
if (description.length() > 0) description.append(" ");
description.append(context.getString(R.string.GroupUtil_group_name_is_now, title));
}
if (description.length() > 0) {
return description.toString();
} else {
return context.getString(R.string.GroupUtil_group_updated);
}
}
public void addListener(Recipients.RecipientsModifiedListener listener) {
if (this.members != null) {
this.members.addListener(listener);
}
}
}
}
| 3,245 | 31.787879 | 127 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Hex.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import java.io.IOException;
/**
* Utility for generating hex dumps.
*/
public class Hex {
private final static int HEX_DIGITS_START = 10;
private final static int ASCII_TEXT_START = HEX_DIGITS_START + (16*2 + (16/2));
final static String EOL = System.getProperty("line.separator");
private final static char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
public static String toString(byte[] bytes) {
return toString(bytes, 0, bytes.length);
}
public static String toString(byte[] bytes, int offset, int length) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < length; i++) {
appendHexChar(buf, bytes[offset + i]);
buf.append(' ');
}
return buf.toString();
}
public static String toStringCondensed(byte[] bytes) {
StringBuffer buf = new StringBuffer();
for (int i=0;i<bytes.length;i++) {
appendHexChar(buf, bytes[i]);
}
return buf.toString();
}
public static byte[] fromStringCondensed(String encoded) throws IOException {
final char[] data = encoded.toCharArray();
final int len = data.length;
if ((len & 0x01) != 0) {
throw new IOException("Odd number of characters.");
}
final byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = Character.digit(data[j], 16) << 4;
j++;
f = f | Character.digit(data[j], 16);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
public static String dump(byte[] bytes) {
return dump(bytes, 0, bytes.length);
}
public static String dump(byte[] bytes, int offset, int length) {
StringBuffer buf = new StringBuffer();
int lines = ((length - 1) / 16) + 1;
int lineOffset;
int lineLength;
for (int i = 0; i < lines; i++) {
lineOffset = (i * 16) + offset;
lineLength = Math.min(16, (length - (i * 16)));
appendDumpLine(buf, i, bytes, lineOffset, lineLength);
buf.append(EOL);
}
return buf.toString();
}
private static void appendDumpLine(StringBuffer buf, int line, byte[] bytes, int lineOffset, int lineLength) {
buf.append(HEX_DIGITS[(line >> 28) & 0xf]);
buf.append(HEX_DIGITS[(line >> 24) & 0xf]);
buf.append(HEX_DIGITS[(line >> 20) & 0xf]);
buf.append(HEX_DIGITS[(line >> 16) & 0xf]);
buf.append(HEX_DIGITS[(line >> 12) & 0xf]);
buf.append(HEX_DIGITS[(line >> 8) & 0xf]);
buf.append(HEX_DIGITS[(line >> 4) & 0xf]);
buf.append(HEX_DIGITS[(line ) & 0xf]);
buf.append(": ");
for (int i = 0; i < 16; i++) {
int idx = i + lineOffset;
if (i < lineLength) {
int b = bytes[idx];
appendHexChar(buf, b);
} else {
buf.append(" ");
}
if ((i % 2) == 1) {
buf.append(' ');
}
}
for (int i = 0; i < 16 && i < lineLength; i++) {
int idx = i + lineOffset;
int b = bytes[idx];
if (b >= 0x20 && b <= 0x7e) {
buf.append((char)b);
} else {
buf.append('.');
}
}
}
private static void appendHexChar(StringBuffer buf, int b) {
buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.append(HEX_DIGITS[b & 0xf]);
}
}
| 4,012 | 27.870504 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/JsonUtils.java | package org.thoughtcrime.securesms.util;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JsonUtils {
private static final ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static <T> T fromJson(byte[] serialized, Class<T> clazz) throws IOException {
return fromJson(new String(serialized), clazz);
}
public static <T> T fromJson(String serialized, Class<T> clazz) throws IOException {
return objectMapper.readValue(serialized, clazz);
}
public static <T> T fromJson(InputStreamReader serialized, Class<T> clazz) throws IOException {
return objectMapper.readValue(serialized, clazz);
}
public static String toJson(Object object) throws IOException {
return objectMapper.writeValueAsString(object);
}
public static ObjectMapper getMapper() {
return objectMapper;
}
}
| 1,092 | 27.763158 | 97 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/LRUCache.java | package org.thoughtcrime.securesms.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K,V> extends LinkedHashMap<K,V> {
private final int maxSize;
public LRUCache(int maxSize) {
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
return size() > maxSize;
}
}
| 361 | 18.052632 | 63 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/LinkedBlockingLifoQueue.java | package org.thoughtcrime.securesms.util;
import org.thoughtcrime.securesms.util.deque.LinkedBlockingDeque;
public class LinkedBlockingLifoQueue<E> extends LinkedBlockingDeque<E> {
@Override
public void put(E runnable) throws InterruptedException {
super.putFirst(runnable);
}
@Override
public boolean add(E runnable) {
super.addFirst(runnable);
return true;
}
@Override
public boolean offer(E runnable) {
super.addFirst(runnable);
return true;
}
}
| 490 | 20.347826 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ListenableFutureTask.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.support.annotation.Nullable;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ListenableFutureTask<V> extends FutureTask<V> {
private final List<FutureTaskListener<V>> listeners = new LinkedList<>();
@Nullable
private final Object identifier;
public ListenableFutureTask(Callable<V> callable) {
this(callable, null);
}
public ListenableFutureTask(Callable<V> callable, @Nullable Object identifier) {
super(callable);
this.identifier = identifier;
}
public ListenableFutureTask(final V result) {
this(result, null);
}
public ListenableFutureTask(final V result, @Nullable Object identifier) {
super(new Callable<V>() {
@Override
public V call() throws Exception {
return result;
}
});
this.identifier = identifier;
this.run();
}
public synchronized void addListener(FutureTaskListener<V> listener) {
if (this.isDone()) {
callback(listener);
} else {
this.listeners.add(listener);
}
}
public synchronized void removeListener(FutureTaskListener<V> listener) {
this.listeners.remove(listener);
}
@Override
protected synchronized void done() {
callback();
}
private void callback() {
for (FutureTaskListener<V> listener : listeners) {
callback(listener);
}
}
private void callback(FutureTaskListener<V> listener) {
if (listener != null) {
try {
listener.onSuccess(get());
} catch (InterruptedException e) {
throw new AssertionError(e);
} catch (ExecutionException e) {
listener.onFailure(e);
}
}
}
@Override
public boolean equals(Object other) {
if (other != null && other instanceof ListenableFutureTask && this.identifier != null) {
return identifier.equals(other);
} else {
return super.equals(other);
}
}
@Override
public int hashCode() {
if (identifier != null) return identifier.hashCode();
else return super.hashCode();
}
}
| 2,907 | 25.925926 | 92 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/MediaUtil.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.mms.AudioSlide;
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri;
import org.thoughtcrime.securesms.mms.GifSlide;
import org.thoughtcrime.securesms.mms.ImageSlide;
import org.thoughtcrime.securesms.mms.PartAuthority;
import org.thoughtcrime.securesms.mms.Slide;
import org.thoughtcrime.securesms.mms.VideoSlide;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import ws.com.google.android.mms.ContentType;
public class MediaUtil {
private static final String TAG = MediaUtil.class.getSimpleName();
public static @Nullable ThumbnailData generateThumbnail(Context context, MasterSecret masterSecret, String contentType, Uri uri)
throws ExecutionException
{
long startMillis = System.currentTimeMillis();
ThumbnailData data = null;
if (ContentType.isImageType(contentType)) {
data = new ThumbnailData(generateImageThumbnail(context, masterSecret, uri));
}
if (data != null) {
Log.w(TAG, String.format("generated thumbnail for part, %dx%d (%.3f:1) in %dms",
data.getBitmap().getWidth(), data.getBitmap().getHeight(),
data.getAspectRatio(), System.currentTimeMillis() - startMillis));
}
return data;
}
private static Bitmap generateImageThumbnail(Context context, MasterSecret masterSecret, Uri uri)
throws ExecutionException
{
int maxSize = context.getResources().getDimensionPixelSize(R.dimen.media_bubble_height);
return BitmapUtil.createScaledBitmap(context, new DecryptableUri(masterSecret, uri), maxSize, maxSize);
}
public static Slide getSlideForAttachment(Context context, Attachment attachment) {
Slide slide = null;
if (isGif(attachment.getContentType())) {
slide = new GifSlide(context, attachment);
} else if (ContentType.isImageType(attachment.getContentType())) {
slide = new ImageSlide(context, attachment);
} else if (ContentType.isVideoType(attachment.getContentType())) {
slide = new VideoSlide(context, attachment);
} else if (ContentType.isAudioType(attachment.getContentType())) {
slide = new AudioSlide(context, attachment);
}
return slide;
}
public static @Nullable String getMimeType(Context context, Uri uri) {
String type = context.getContentResolver().getType(uri);
if (type == null) {
final String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
public static long getMediaSize(Context context, MasterSecret masterSecret, Uri uri) throws IOException {
InputStream in = PartAuthority.getAttachmentStream(context, masterSecret, uri);
if (in == null) throw new IOException("Couldn't obtain input stream.");
long size = 0;
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer)) != -1) {
size += read;
}
in.close();
return size;
}
public static boolean isGif(String contentType) {
return !TextUtils.isEmpty(contentType) && contentType.trim().equals("image/gif");
}
public static boolean isGif(Attachment attachment) {
return isGif(attachment.getContentType());
}
public static boolean isImage(Attachment attachment) {
return ContentType.isImageType(attachment.getContentType());
}
public static boolean isAudio(Attachment attachment) {
return ContentType.isAudioType(attachment.getContentType());
}
public static boolean isVideo(Attachment attachment) {
return ContentType.isVideoType(attachment.getContentType());
}
public static @Nullable String getDiscreteMimeType(@NonNull String mimeType) {
final String[] sections = mimeType.split("/", 2);
return sections.length > 1 ? sections[0] : null;
}
public static class ThumbnailData {
Bitmap bitmap;
float aspectRatio;
public ThumbnailData(Bitmap bitmap) {
this.bitmap = bitmap;
this.aspectRatio = (float) bitmap.getWidth() / (float) bitmap.getHeight();
}
public Bitmap getBitmap() {
return bitmap;
}
public float getAspectRatio() {
return aspectRatio;
}
public InputStream toDataStream() {
return BitmapUtil.toCompressedJpeg(bitmap);
}
}
}
| 4,848 | 32.441379 | 130 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/MmsCharacterCalculator.java | package org.thoughtcrime.securesms.util;
public class MmsCharacterCalculator extends CharacterCalculator {
private static final int MAX_SIZE = 5000;
@Override
public CharacterState calculateCharacters(int charactersSpent) {
return new CharacterState(1, MAX_SIZE - charactersSpent, MAX_SIZE);
}
}
| 311 | 25 | 71 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/NumberUtil.java | /**
* Copyright (C) 2012 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.telephony.PhoneNumberUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NumberUtil {
private static final Pattern emailPattern = android.util.Patterns.EMAIL_ADDRESS;
public static boolean isValidEmail(String number) {
Matcher matcher = emailPattern.matcher(number);
return matcher.matches();
}
public static boolean isValidSmsOrEmail(String number) {
return PhoneNumberUtils.isWellFormedSmsAddress(number) || isValidEmail(number);
}
public static boolean isValidSmsOrEmailOrGroup(String number) {
return PhoneNumberUtils.isWellFormedSmsAddress(number) ||
isValidEmail(number) ||
GroupUtil.isEncodedGroup(number);
}
public static String filterNumber(String number) {
if (number == null) return null;
int length = number.length();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char character = number.charAt(i);
if (Character.isDigit(character) || character == '+')
builder.append(character);
}
return builder.toString();
}
}
| 1,865 | 30.627119 | 83 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ParcelUtil.java | package org.thoughtcrime.securesms.util;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelUtil {
public static byte[] serialize(Parcelable parceable) {
Parcel parcel = Parcel.obtain();
parceable.writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle();
return bytes;
}
public static Parcel deserialize(byte[] bytes) {
Parcel parcel = Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0);
return parcel;
}
public static <T> T deserialize(byte[] bytes, Parcelable.Creator<T> creator) {
Parcel parcel = deserialize(bytes);
return creator.createFromParcel(parcel);
}
}
| 706 | 23.37931 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ProgressDialogAsyncTask.java | package org.thoughtcrime.securesms.util;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
public abstract class ProgressDialogAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
private final WeakReference<Context> contextReference;
private ProgressDialog progress;
private final String title;
private final String message;
public ProgressDialogAsyncTask(Context context, String title, String message) {
super();
this.contextReference = new WeakReference<>(context);
this.title = title;
this.message = message;
}
public ProgressDialogAsyncTask(Context context, int title, int message) {
this(context, context.getString(title), context.getString(message));
}
@Override
protected void onPreExecute() {
final Context context = contextReference.get();
if (context != null) progress = ProgressDialog.show(context, title, message, true);
}
@Override
protected void onPostExecute(Result result) {
if (progress != null) progress.dismiss();
}
protected Context getContext() {
return contextReference.get();
}
}
| 1,258 | 28.97619 | 117 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/PushCharacterCalculator.java | /**
* Copyright (C) 2015 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
public class PushCharacterCalculator extends CharacterCalculator {
private static final int MAX_SIZE = 2000;
@Override
public CharacterState calculateCharacters(int charactersSpent) {
return new CharacterState(1, MAX_SIZE - charactersSpent, MAX_SIZE);
}
}
| 1,006 | 36.296296 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/RedPhoneCallTypes.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
public interface RedPhoneCallTypes {
public static final int INCOMING = 1023;
public static final int OUTGOING = 1024;
public static final int MISSED = 1025;
}
| 905 | 36.75 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ResUtil.java | /**
* Copyright (C) 2015 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.annotation.ArrayRes;
import android.support.annotation.AttrRes;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
public class ResUtil {
public static int getColor(Context context, @AttrRes int attr) {
final TypedArray styledAttributes = context.obtainStyledAttributes(new int[]{attr});
final int result = styledAttributes.getColor(0, -1);
styledAttributes.recycle();
return result;
}
public static int getDrawableRes(Context c, @AttrRes int attr) {
return getDrawableRes(c.getTheme(), attr);
}
public static int getDrawableRes(Theme theme, @AttrRes int attr) {
final TypedValue out = new TypedValue();
theme.resolveAttribute(attr, out, true);
return out.resourceId;
}
public static Drawable getDrawable(Context c, @AttrRes int attr) {
return ContextCompat.getDrawable(c, getDrawableRes(c, attr));
}
public static int[] getResourceIds(Context c, @ArrayRes int array) {
final TypedArray typedArray = c.getResources().obtainTypedArray(array);
final int[] resourceIds = new int[typedArray.length()];
for (int i = 0; i < typedArray.length(); i++) {
resourceIds[i] = typedArray.getResourceId(i, 0);
}
typedArray.recycle();
return resourceIds;
}
}
| 2,331 | 34.876923 | 88 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Rfc5724Uri.java | /*
* Copyright (C) 2015 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
public class Rfc5724Uri {
private final String uri;
private final String schema;
private final String path;
private final Map<String, String> queryParams;
public Rfc5724Uri(String uri) throws URISyntaxException {
this.uri = uri;
this.schema = parseSchema();
this.path = parsePath();
this.queryParams = parseQueryParams();
}
private String parseSchema() throws URISyntaxException {
String[] parts = uri.split(":");
if (parts.length < 1 || parts[0].isEmpty()) throw new URISyntaxException(uri, "invalid schema");
else return parts[0];
}
private String parsePath() throws URISyntaxException {
String[] parts = uri.split("\\?")[0].split(":", 2);
if (parts.length < 2 || parts[1].isEmpty()) throw new URISyntaxException(uri, "invalid path");
else return parts[1];
}
private Map<String, String> parseQueryParams() throws URISyntaxException {
Map<String, String> queryParams = new HashMap<>();
if (uri.split("\\?").length < 2) {
return queryParams;
}
for (String keyValue : uri.split("\\?")[1].split("&")) {
String[] parts = keyValue.split("=");
if (parts.length == 1) queryParams.put(parts[0], "");
else queryParams.put(parts[0], URLDecoder.decode(parts[1]));
}
return queryParams;
}
public String getSchema() {
return schema;
}
public String getPath() {
return path;
}
public Map<String, String> getQueryParams() {
return queryParams;
}
}
| 2,492 | 29.777778 | 100 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/SaveAttachmentTask.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.mms.PartAuthority;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
public class SaveAttachmentTask extends ProgressDialogAsyncTask<SaveAttachmentTask.Attachment, Void, Integer> {
private static final String TAG = SaveAttachmentTask.class.getSimpleName();
private static final int SUCCESS = 0;
private static final int FAILURE = 1;
private static final int WRITE_ACCESS_FAILURE = 2;
private final WeakReference<Context> contextReference;
private final WeakReference<MasterSecret> masterSecretReference;
public SaveAttachmentTask(Context context, MasterSecret masterSecret) {
super(context, R.string.ConversationFragment_saving_attachment, R.string.ConversationFragment_saving_attachment_to_sd_card);
this.contextReference = new WeakReference<>(context);
this.masterSecretReference = new WeakReference<>(masterSecret);
}
@Override
protected Integer doInBackground(SaveAttachmentTask.Attachment... attachments) {
if (attachments == null || attachments.length != 1 || attachments[0] == null) {
throw new AssertionError("must pass in exactly one attachment");
}
Attachment attachment = attachments[0];
try {
Context context = contextReference.get();
MasterSecret masterSecret = masterSecretReference.get();
if (!Environment.getExternalStorageDirectory().canWrite()) {
return WRITE_ACCESS_FAILURE;
}
if (context == null) {
return FAILURE;
}
File mediaFile = constructOutputFile(attachment.contentType, attachment.date);
InputStream inputStream = PartAuthority.getAttachmentStream(context, masterSecret, attachment.uri);
if (inputStream == null) {
return FAILURE;
}
OutputStream outputStream = new FileOutputStream(mediaFile);
Util.copy(inputStream, outputStream);
MediaScannerConnection.scanFile(context, new String[]{mediaFile.getAbsolutePath()},
new String[]{attachment.contentType}, null);
return SUCCESS;
} catch (IOException ioe) {
Log.w(TAG, ioe);
return FAILURE;
}
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
Context context = contextReference.get();
if (context == null) return;
switch (result) {
case FAILURE:
Toast.makeText(context, R.string.ConversationFragment_error_while_saving_attachment_to_sd_card,
Toast.LENGTH_LONG).show();
break;
case SUCCESS:
Toast.makeText(context, R.string.ConversationFragment_success_exclamation,
Toast.LENGTH_LONG).show();
break;
case WRITE_ACCESS_FAILURE:
Toast.makeText(context, R.string.ConversationFragment_unable_to_write_to_sd_card_exclamation,
Toast.LENGTH_LONG).show();
break;
}
}
private File constructOutputFile(String contentType, long timestamp) throws IOException {
File sdCard = Environment.getExternalStorageDirectory();
File outputDirectory;
if (contentType.startsWith("video/")) {
outputDirectory = new File(sdCard.getAbsoluteFile() + File.separator + Environment.DIRECTORY_MOVIES);
} else if (contentType.startsWith("audio/")) {
outputDirectory = new File(sdCard.getAbsolutePath() + File.separator + Environment.DIRECTORY_MUSIC);
} else if (contentType.startsWith("image/")) {
outputDirectory = new File(sdCard.getAbsolutePath() + File.separator + Environment.DIRECTORY_PICTURES);
} else {
outputDirectory = new File(sdCard.getAbsolutePath() + File.separator + Environment.DIRECTORY_DOWNLOADS);
}
if (!outputDirectory.mkdirs()) Log.w(TAG, "mkdirs() returned false, attempting to continue");
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String extension = mimeTypeMap.getExtensionFromMimeType(contentType);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
String base = "textsecure-" + dateFormatter.format(timestamp);
if (extension == null)
extension = "attach";
int i = 0;
File file = new File(outputDirectory, base + "." + extension);
while (file.exists()) {
file = new File(outputDirectory, base + "-" + (++i) + "." + extension);
}
return file;
}
public static class Attachment {
public Uri uri;
public String contentType;
public long date;
public Attachment(Uri uri, String contentType, long date) {
if (uri == null || contentType == null || date < 0) {
throw new AssertionError("uri, content type, and date must all be specified");
}
this.uri = uri;
this.contentType = contentType;
this.date = date;
}
}
public static void showWarningDialog(Context context, OnClickListener onAcceptListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.ConversationFragment_save_to_sd_card);
builder.setIconAttribute(R.attr.dialog_alert_icon);
builder.setCancelable(true);
builder.setMessage(R.string.ConversationFragment_saving_this_media_to_storage_warning);
builder.setPositiveButton(R.string.yes, onAcceptListener);
builder.setNegativeButton(R.string.no, null);
builder.show();
}
}
| 6,008 | 36.092593 | 128 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/SelectedRecipientsAdapter.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class SelectedRecipientsAdapter extends BaseAdapter {
@NonNull private Context context;
@Nullable private OnRecipientDeletedListener onRecipientDeletedListener;
@NonNull private List<RecipientWrapper> recipients;
public SelectedRecipientsAdapter(@NonNull Context context) {
this(context, Collections.<Recipient>emptyList());
}
public SelectedRecipientsAdapter(@NonNull Context context,
@NonNull Collection<Recipient> existingRecipients)
{
this.context = context;
this.recipients = wrapExistingMembers(existingRecipients);
}
public void add(@NonNull Recipient recipient, boolean isPush) {
if (!find(recipient).isPresent()) {
RecipientWrapper wrapper = new RecipientWrapper(recipient, true, isPush);
this.recipients.add(0, wrapper);
notifyDataSetChanged();
}
}
public Optional<RecipientWrapper> find(@NonNull Recipient recipient) {
RecipientWrapper found = null;
for (RecipientWrapper wrapper : recipients) {
if (wrapper.getRecipient().equals(recipient)) found = wrapper;
}
return Optional.fromNullable(found);
}
public void remove(@NonNull Recipient recipient) {
Optional<RecipientWrapper> match = find(recipient);
if (match.isPresent()) {
recipients.remove(match.get());
notifyDataSetChanged();
}
}
public Set<Recipient> getRecipients() {
final Set<Recipient> recipientSet = new HashSet<>(recipients.size());
for (RecipientWrapper wrapper : recipients) {
recipientSet.add(wrapper.getRecipient());
}
return recipientSet;
}
@Override
public int getCount() {
return recipients.size();
}
public boolean hasNonPushMembers() {
for (RecipientWrapper wrapper : recipients) {
if (!wrapper.isPush()) return true;
}
return false;
}
@Override
public Object getItem(int position) {
return recipients.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View v, final ViewGroup parent) {
if (v == null) {
v = LayoutInflater.from(context).inflate(R.layout.selected_recipient_list_item, parent, false);
}
final RecipientWrapper rw = (RecipientWrapper)getItem(position);
final Recipient p = rw.getRecipient();
final boolean modifiable = rw.isModifiable();
TextView name = (TextView) v.findViewById(R.id.name);
TextView phone = (TextView) v.findViewById(R.id.phone);
ImageButton delete = (ImageButton) v.findViewById(R.id.delete);
name.setText(p.getName());
phone.setText(p.getNumber());
delete.setVisibility(modifiable ? View.VISIBLE : View.GONE);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onRecipientDeletedListener != null) {
onRecipientDeletedListener.onRecipientDeleted(recipients.get(position).getRecipient());
}
}
});
return v;
}
private static List<RecipientWrapper> wrapExistingMembers(Collection<Recipient> recipients) {
final LinkedList<RecipientWrapper> wrapperList = new LinkedList<>();
for (Recipient recipient : recipients) {
wrapperList.add(new RecipientWrapper(recipient, false, true));
}
return wrapperList;
}
public void setOnRecipientDeletedListener(@Nullable OnRecipientDeletedListener listener) {
onRecipientDeletedListener = listener;
}
public interface OnRecipientDeletedListener {
void onRecipientDeleted(Recipient recipient);
}
public static class RecipientWrapper {
private final Recipient recipient;
private final boolean modifiable;
private final boolean push;
public RecipientWrapper(final @NonNull Recipient recipient,
final boolean modifiable,
final boolean push)
{
this.recipient = recipient;
this.modifiable = modifiable;
this.push = push;
}
public @NonNull Recipient getRecipient() {
return recipient;
}
public boolean isModifiable() {
return modifiable;
}
public boolean isPush() {
return push;
}
}
} | 4,968 | 29.115152 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ServiceUtil.java | package org.thoughtcrime.securesms.util;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.telephony.TelephonyManager;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class ServiceUtil {
public static InputMethodManager getInputMethodManager(Context context) {
return (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
}
public static WindowManager getWindowManager(Context context) {
return (WindowManager) context.getSystemService(Activity.WINDOW_SERVICE);
}
public static ConnectivityManager getConnectivityManager(Context context) {
return (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);
}
public static NotificationManager getNotificationManager(Context context) {
return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public static TelephonyManager getTelephonyManager(Context context) {
return (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
}
public static AudioManager getAudioManager(Context context) {
return (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
}
}
| 1,341 | 35.27027 | 89 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ShortCodeUtil.java | package org.thoughtcrime.securesms.util;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.ShortNumberInfo;
import java.util.HashSet;
import java.util.Set;
public class ShortCodeUtil {
private static final String TAG = ShortCodeUtil.class.getSimpleName();
private static final Set<String> SHORT_COUNTRIES = new HashSet<String>() {{
add("NU");
add("TK");
add("NC");
add("AC");
}};
public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) {
try {
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber localNumberObject = util.parse(localNumber, null);
String localCountryCode = util.getRegionCodeForNumber(localNumberObject);
if (number.replaceAll("[^0-9+]", "").length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
return true;
} else {
Phonenumber.PhoneNumber shortCode = util.parse(number, localCountryCode);
return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(shortCode, localCountryCode);
}
} catch (NumberParseException e) {
Log.w(TAG, e);
return false;
}
}
}
| 1,417 | 31.227273 | 106 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/SmilUtil.java | package org.thoughtcrime.securesms.util;
import android.util.Log;
import org.thoughtcrime.securesms.dom.smil.SmilDocumentImpl;
import org.thoughtcrime.securesms.dom.smil.parser.SmilXmlSerializer;
import org.thoughtcrime.securesms.mms.PartParser;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.SMILMediaElement;
import org.w3c.dom.smil.SMILParElement;
import org.w3c.dom.smil.SMILRegionElement;
import org.w3c.dom.smil.SMILRegionMediaElement;
import org.w3c.dom.smil.SMILRootLayoutElement;
import java.io.ByteArrayOutputStream;
import ws.com.google.android.mms.ContentType;
import ws.com.google.android.mms.pdu.PduBody;
import ws.com.google.android.mms.pdu.PduPart;
public class SmilUtil {
private static final String TAG = SmilUtil.class.getSimpleName();
public static final int ROOT_HEIGHT = 1024;
public static final int ROOT_WIDTH = 1024;
public static PduBody getSmilBody(PduBody body) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
SmilXmlSerializer.serialize(SmilUtil.createSmilDocument(body), out);
PduPart smilPart = new PduPart();
smilPart.setContentId("smil".getBytes());
smilPart.setContentLocation("smil.xml".getBytes());
smilPart.setContentType(ContentType.APP_SMIL.getBytes());
smilPart.setData(out.toByteArray());
body.addPart(0, smilPart);
return body;
}
private static SMILDocument createSmilDocument(PduBody body) {
Log.w(TAG, "Creating SMIL document from PduBody.");
SMILDocument document = new SmilDocumentImpl();
SMILElement smilElement = (SMILElement) document.createElement("smil");
document.appendChild(smilElement);
SMILElement headElement = (SMILElement) document.createElement("head");
smilElement.appendChild(headElement);
SMILLayoutElement layoutElement = (SMILLayoutElement) document.createElement("layout");
headElement.appendChild(layoutElement);
SMILRootLayoutElement rootLayoutElement = (SMILRootLayoutElement) document.createElement("root-layout");
rootLayoutElement.setWidth(ROOT_WIDTH);
rootLayoutElement.setHeight(ROOT_HEIGHT);
layoutElement.appendChild(rootLayoutElement);
SMILElement bodyElement = (SMILElement) document.createElement("body");
smilElement.appendChild(bodyElement);
SMILParElement par = (SMILParElement) document.createElement("par");
bodyElement.appendChild(par);
for (int i=0; i<body.getPartsNum(); i++) {
PduPart part = body.getPart(i);
SMILRegionElement regionElement = getRegion(document, part);
SMILMediaElement mediaElement = getMediaElement(document, part);
if (regionElement != null) {
((SMILRegionMediaElement)mediaElement).setRegion(regionElement);
layoutElement.appendChild(regionElement);
}
par.appendChild(mediaElement);
}
return document;
}
private static SMILRegionElement getRegion(SMILDocument document, PduPart part) {
if (PartParser.isAudio(part)) return null;
SMILRegionElement region = (SMILRegionElement) document.createElement("region");
if (PartParser.isText(part)) {
region.setId("Text");
region.setTop(SmilUtil.ROOT_HEIGHT);
region.setHeight(50);
} else {
region.setId("Image");
region.setTop(0);
region.setHeight(SmilUtil.ROOT_HEIGHT);
}
region.setLeft(0);
region.setWidth(SmilUtil.ROOT_WIDTH);
region.setFit("meet");
return region;
}
private static SMILMediaElement getMediaElement(SMILDocument document, PduPart part) {
final String tag;
if (PartParser.isImage(part)) {
tag = "img";
} else if (PartParser.isAudio(part)) {
tag = "audio";
} else if (PartParser.isVideo(part)) {
tag = "video";
} else if (PartParser.isText(part)) {
tag = "text";
} else {
tag = "ref";
}
return createMediaElement(tag, document, new String(part.getName() == null
? new byte[]{}
: part.getName()));
}
private static SMILMediaElement createMediaElement(String tag, SMILDocument document, String src) {
SMILMediaElement mediaElement = (SMILMediaElement) document.createElement(tag);
mediaElement.setSrc(escapeXML(src));
return mediaElement;
}
private static String escapeXML(String str) {
return str.replaceAll("&","&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("\"", """)
.replaceAll("'", "'");
}
}
| 4,642 | 33.909774 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/SmsCharacterCalculator.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import org.thoughtcrime.securesms.sms.SmsTransportDetails;
public class SmsCharacterCalculator extends CharacterCalculator {
@Override
public CharacterState calculateCharacters(int charactersSpent) {
int maxMessageSize;
if (charactersSpent <= SmsTransportDetails.SMS_SIZE) {
maxMessageSize = SmsTransportDetails.SMS_SIZE;
} else {
maxMessageSize = SmsTransportDetails.MULTIPART_SMS_SIZE;
}
int messagesSpent = charactersSpent / maxMessageSize;
if (((charactersSpent % maxMessageSize) > 0) || (messagesSpent == 0))
messagesSpent++;
int charactersRemaining = (maxMessageSize * messagesSpent) - charactersSpent;
return new CharacterState(messagesSpent, charactersRemaining, maxMessageSize);
}
}
| 1,493 | 32.954545 | 82 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/SpanUtil.java | package org.thoughtcrime.securesms.util;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
public class SpanUtil {
public static CharSequence italic(CharSequence sequence) {
return italic(sequence, sequence.length());
}
public static CharSequence italic(CharSequence sequence, int length) {
SpannableString spannable = new SpannableString(sequence);
spannable.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
public static CharSequence small(CharSequence sequence) {
SpannableString spannable = new SpannableString(sequence);
spannable.setSpan(new RelativeSizeSpan(0.9f), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
public static CharSequence bold(CharSequence sequence) {
SpannableString spannable = new SpannableString(sequence);
spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
public static CharSequence color(int color, CharSequence sequence) {
SpannableString spannable = new SpannableString(sequence);
spannable.setSpan(new ForegroundColorSpan(color), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
}
| 1,488 | 36.225 | 118 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/TaggedFutureTask.java | /**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* FutureTask with a reference identifier tag.
*
* @author Jake McGinty
*/
public class TaggedFutureTask<V> extends FutureTask<V> {
private final Object tag;
public TaggedFutureTask(Runnable runnable, V result, Object tag) {
super(runnable, result);
this.tag = tag;
}
public TaggedFutureTask(Callable<V> callable, Object tag) {
super(callable);
this.tag = tag;
}
public Object getTag() {
return tag;
}
}
| 1,269 | 27.863636 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/TelephonyUtil.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.telephony.TelephonyManager;
import android.util.Log;
public class TelephonyUtil {
private static final String TAG = TelephonyUtil.class.getSimpleName();
public static TelephonyManager getManager(final Context context) {
return (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
}
public static String getMccMnc(final Context context) {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final int configMcc = context.getResources().getConfiguration().mcc;
final int configMnc = context.getResources().getConfiguration().mnc;
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
Log.w(TAG, "Choosing MCC+MNC info from TelephonyManager.getSimOperator()");
return tm.getSimOperator();
} else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
Log.w(TAG, "Choosing MCC+MNC info from TelephonyManager.getNetworkOperator()");
return tm.getNetworkOperator();
} else if (configMcc != 0 && configMnc != 0) {
Log.w(TAG, "Choosing MCC+MNC info from current context's Configuration");
return String.format("%03d%d",
configMcc,
configMnc == Configuration.MNC_ZERO ? 0 : configMnc);
} else {
return null;
}
}
public static String getApn(final Context context) {
final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getExtraInfo();
}
}
| 1,720 | 40.97561 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/TextSecurePreferences.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Camera.CameraInfo;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.ArrayRes;
import android.support.annotation.NonNull;
import android.util.Log;
import com.h6ah4i.android.compat.content.SharedPreferenceCompat;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.preferences.NotificationPrivacyPreference;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class TextSecurePreferences {
private static final String TAG = TextSecurePreferences.class.getSimpleName();
public static final String IDENTITY_PREF = "pref_choose_identity";
public static final String CHANGE_PASSPHRASE_PREF = "pref_change_passphrase";
public static final String DISABLE_PASSPHRASE_PREF = "pref_disable_passphrase";
public static final String THEME_PREF = "pref_theme";
public static final String LANGUAGE_PREF = "pref_language";
private static final String MMSC_CUSTOM_HOST_PREF = "pref_apn_mmsc_custom_host";
public static final String MMSC_HOST_PREF = "pref_apn_mmsc_host";
private static final String MMSC_CUSTOM_PROXY_PREF = "pref_apn_mms_custom_proxy";
public static final String MMSC_PROXY_HOST_PREF = "pref_apn_mms_proxy";
private static final String MMSC_CUSTOM_PROXY_PORT_PREF = "pref_apn_mms_custom_proxy_port";
public static final String MMSC_PROXY_PORT_PREF = "pref_apn_mms_proxy_port";
private static final String MMSC_CUSTOM_USERNAME_PREF = "pref_apn_mmsc_custom_username";
public static final String MMSC_USERNAME_PREF = "pref_apn_mmsc_username";
private static final String MMSC_CUSTOM_PASSWORD_PREF = "pref_apn_mmsc_custom_password";
public static final String MMSC_PASSWORD_PREF = "pref_apn_mmsc_password";
public static final String THREAD_TRIM_LENGTH = "pref_trim_length";
public static final String THREAD_TRIM_NOW = "pref_trim_now";
public static final String ENABLE_MANUAL_MMS_PREF = "pref_enable_manual_mms";
private static final String LAST_VERSION_CODE_PREF = "last_version_code";
private static final String LAST_EXPERIENCE_VERSION_PREF = "last_experience_version_code";
public static final String RINGTONE_PREF = "pref_key_ringtone";
private static final String VIBRATE_PREF = "pref_key_vibrate";
private static final String NOTIFICATION_PREF = "pref_key_enable_notifications";
public static final String LED_COLOR_PREF = "pref_led_color";
public static final String LED_BLINK_PREF = "pref_led_blink";
private static final String LED_BLINK_PREF_CUSTOM = "pref_led_blink_custom";
public static final String ALL_MMS_PREF = "pref_all_mms";
public static final String ALL_SMS_PREF = "pref_all_sms";
public static final String PASSPHRASE_TIMEOUT_INTERVAL_PREF = "pref_timeout_interval";
private static final String PASSPHRASE_TIMEOUT_PREF = "pref_timeout_passphrase";
public static final String SCREEN_SECURITY_PREF = "pref_screen_security";
private static final String ENTER_SENDS_PREF = "pref_enter_sends";
private static final String ENTER_PRESENT_PREF = "pref_enter_key";
private static final String SMS_DELIVERY_REPORT_PREF = "pref_delivery_report_sms";
public static final String MMS_USER_AGENT = "pref_mms_user_agent";
private static final String MMS_CUSTOM_USER_AGENT = "pref_custom_mms_user_agent";
private static final String THREAD_TRIM_ENABLED = "pref_trim_threads";
private static final String LOCAL_NUMBER_PREF = "pref_local_number";
private static final String VERIFYING_STATE_PREF = "pref_verifying";
public static final String REGISTERED_GCM_PREF = "pref_gcm_registered";
private static final String GCM_PASSWORD_PREF = "pref_gcm_password";
private static final String PROMPTED_PUSH_REGISTRATION_PREF = "pref_prompted_push_registration";
private static final String PROMPTED_DEFAULT_SMS_PREF = "pref_prompted_default_sms";
private static final String PROMPTED_SHARE_PREF = "pref_prompted_share";
private static final String SIGNALING_KEY_PREF = "pref_signaling_key";
private static final String DIRECTORY_FRESH_TIME_PREF = "pref_directory_refresh_time";
private static final String IN_THREAD_NOTIFICATION_PREF = "pref_key_inthread_notifications";
private static final String LOCAL_REGISTRATION_ID_PREF = "pref_local_registration_id";
private static final String SIGNED_PREKEY_REGISTERED_PREF = "pref_signed_prekey_registered";
private static final String WIFI_SMS_PREF = "pref_wifi_sms";
private static final String GCM_REGISTRATION_ID_PREF = "pref_gcm_registration_id";
private static final String GCM_REGISTRATION_ID_VERSION_PREF = "pref_gcm_registration_id_version";
private static final String WEBSOCKET_REGISTERED_PREF = "pref_websocket_registered";
private static final String RATING_LATER_PREF = "pref_rating_later";
private static final String RATING_ENABLED_PREF = "pref_rating_enabled";
public static final String REPEAT_ALERTS_PREF = "pref_repeat_alerts";
public static final String NOTIFICATION_PRIVACY_PREF = "pref_notification_privacy";
public static final String MEDIA_DOWNLOAD_MOBILE_PREF = "pref_media_download_mobile";
public static final String MEDIA_DOWNLOAD_WIFI_PREF = "pref_media_download_wifi";
public static final String MEDIA_DOWNLOAD_ROAMING_PREF = "pref_media_download_roaming";
public static final String SYSTEM_EMOJI_PREF = "pref_system_emoji";
private static final String MULTI_DEVICE_PROVISIONED_PREF = "pref_multi_device";
public static final String DIRECT_CAPTURE_CAMERA_ID = "pref_direct_capture_camera_id";
public static void setDirectCaptureCameraId(Context context, int value) {
setIntegerPrefrence(context, DIRECT_CAPTURE_CAMERA_ID, value);
}
@SuppressWarnings("deprecation")
public static int getDirectCaptureCameraId(Context context) {
return getIntegerPreference(context, DIRECT_CAPTURE_CAMERA_ID, CameraInfo.CAMERA_FACING_FRONT);
}
public static void setMultiDevice(Context context, boolean value) {
setBooleanPreference(context, MULTI_DEVICE_PROVISIONED_PREF, value);
}
public static boolean isMultiDevice(Context context) {
return getBooleanPreference(context, MULTI_DEVICE_PROVISIONED_PREF, false);
}
public static NotificationPrivacyPreference getNotificationPrivacy(Context context) {
return new NotificationPrivacyPreference(getStringPreference(context, NOTIFICATION_PRIVACY_PREF, "all"));
}
public static long getRatingLaterTimestamp(Context context) {
return getLongPreference(context, RATING_LATER_PREF, 0);
}
public static void setRatingLaterTimestamp(Context context, long timestamp) {
setLongPreference(context, RATING_LATER_PREF, timestamp);
}
public static boolean isRatingEnabled(Context context) {
return getBooleanPreference(context, RATING_ENABLED_PREF, true);
}
public static void setRatingEnabled(Context context, boolean enabled) {
setBooleanPreference(context, RATING_ENABLED_PREF, enabled);
}
public static boolean isWebsocketRegistered(Context context) {
return getBooleanPreference(context, WEBSOCKET_REGISTERED_PREF, false);
}
public static void setWebsocketRegistered(Context context, boolean registered) {
setBooleanPreference(context, WEBSOCKET_REGISTERED_PREF, registered);
}
public static boolean isWifiSmsEnabled(Context context) {
return getBooleanPreference(context, WIFI_SMS_PREF, false);
}
public static int getRepeatAlertsCount(Context context) {
try {
return Integer.parseInt(getStringPreference(context, REPEAT_ALERTS_PREF, "0"));
} catch (NumberFormatException e) {
Log.w(TAG, e);
return 0;
}
}
public static void setRepeatAlertsCount(Context context, int count) {
setStringPreference(context, REPEAT_ALERTS_PREF, String.valueOf(count));
}
public static boolean isSignedPreKeyRegistered(Context context) {
return getBooleanPreference(context, SIGNED_PREKEY_REGISTERED_PREF, false);
}
public static void setSignedPreKeyRegistered(Context context, boolean value) {
setBooleanPreference(context, SIGNED_PREKEY_REGISTERED_PREF, value);
}
public static void setGcmRegistrationId(Context context, String registrationId) {
setStringPreference(context, GCM_REGISTRATION_ID_PREF, registrationId);
setIntegerPrefrence(context, GCM_REGISTRATION_ID_VERSION_PREF, Util.getCurrentApkReleaseVersion(context));
}
public static String getGcmRegistrationId(Context context) {
int storedRegistrationIdVersion = getIntegerPreference(context, GCM_REGISTRATION_ID_VERSION_PREF, 0);
if (storedRegistrationIdVersion != Util.getCurrentApkReleaseVersion(context)) {
return null;
} else {
return getStringPreference(context, GCM_REGISTRATION_ID_PREF, null);
}
}
public static boolean isSmsEnabled(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
return Util.isDefaultSmsProvider(context);
} else {
return isInterceptAllSmsEnabled(context);
}
}
public static int getLocalRegistrationId(Context context) {
return getIntegerPreference(context, LOCAL_REGISTRATION_ID_PREF, 0);
}
public static void setLocalRegistrationId(Context context, int registrationId) {
setIntegerPrefrence(context, LOCAL_REGISTRATION_ID_PREF, registrationId);
}
public static boolean isInThreadNotifications(Context context) {
return getBooleanPreference(context, IN_THREAD_NOTIFICATION_PREF, true);
}
public static long getDirectoryRefreshTime(Context context) {
return getLongPreference(context, DIRECTORY_FRESH_TIME_PREF, 0L);
}
public static void setDirectoryRefreshTime(Context context, long value) {
setLongPreference(context, DIRECTORY_FRESH_TIME_PREF, value);
}
public static String getLocalNumber(Context context) {
return getStringPreference(context, LOCAL_NUMBER_PREF, "No Stored Number");
}
public static void setLocalNumber(Context context, String localNumber) {
setStringPreference(context, LOCAL_NUMBER_PREF, localNumber);
}
public static String getPushServerPassword(Context context) {
return getStringPreference(context, GCM_PASSWORD_PREF, null);
}
public static void setPushServerPassword(Context context, String password) {
setStringPreference(context, GCM_PASSWORD_PREF, password);
}
public static void setSignalingKey(Context context, String signalingKey) {
setStringPreference(context, SIGNALING_KEY_PREF, signalingKey);
}
public static String getSignalingKey(Context context) {
return getStringPreference(context, SIGNALING_KEY_PREF, null);
}
public static boolean isEnterImeKeyEnabled(Context context) {
return getBooleanPreference(context, ENTER_PRESENT_PREF, false);
}
public static boolean isEnterSendsEnabled(Context context) {
return getBooleanPreference(context, ENTER_SENDS_PREF, false);
}
public static boolean isPasswordDisabled(Context context) {
return getBooleanPreference(context, DISABLE_PASSPHRASE_PREF, false);
}
public static void setPasswordDisabled(Context context, boolean disabled) {
setBooleanPreference(context, DISABLE_PASSPHRASE_PREF, disabled);
}
public static boolean getUseCustomMmsc(Context context) {
boolean legacy = TextSecurePreferences.isLegacyUseLocalApnsEnabled(context);
return getBooleanPreference(context, MMSC_CUSTOM_HOST_PREF, legacy);
}
public static void setUseCustomMmsc(Context context, boolean value) {
setBooleanPreference(context, MMSC_CUSTOM_HOST_PREF, value);
}
public static String getMmscUrl(Context context) {
return getStringPreference(context, MMSC_HOST_PREF, "");
}
public static void setMmscUrl(Context context, String mmsc) {
setStringPreference(context, MMSC_HOST_PREF, mmsc);
}
public static boolean getUseCustomMmscProxy(Context context) {
boolean legacy = TextSecurePreferences.isLegacyUseLocalApnsEnabled(context);
return getBooleanPreference(context, MMSC_CUSTOM_PROXY_PREF, legacy);
}
public static void setUseCustomMmscProxy(Context context, boolean value) {
setBooleanPreference(context, MMSC_CUSTOM_PROXY_PREF, value);
}
public static String getMmscProxy(Context context) {
return getStringPreference(context, MMSC_PROXY_HOST_PREF, "");
}
public static void setMmscProxy(Context context, String value) {
setStringPreference(context, MMSC_PROXY_HOST_PREF, value);
}
public static boolean getUseCustomMmscProxyPort(Context context) {
boolean legacy = TextSecurePreferences.isLegacyUseLocalApnsEnabled(context);
return getBooleanPreference(context, MMSC_CUSTOM_PROXY_PORT_PREF, legacy);
}
public static void setUseCustomMmscProxyPort(Context context, boolean value) {
setBooleanPreference(context, MMSC_CUSTOM_PROXY_PORT_PREF, value);
}
public static String getMmscProxyPort(Context context) {
return getStringPreference(context, MMSC_PROXY_PORT_PREF, "");
}
public static void setMmscProxyPort(Context context, String value) {
setStringPreference(context, MMSC_PROXY_PORT_PREF, value);
}
public static boolean getUseCustomMmscUsername(Context context) {
boolean legacy = TextSecurePreferences.isLegacyUseLocalApnsEnabled(context);
return getBooleanPreference(context, MMSC_CUSTOM_USERNAME_PREF, legacy);
}
public static void setUseCustomMmscUsername(Context context, boolean value) {
setBooleanPreference(context, MMSC_CUSTOM_USERNAME_PREF, value);
}
public static String getMmscUsername(Context context) {
return getStringPreference(context, MMSC_USERNAME_PREF, "");
}
public static void setMmscUsername(Context context, String value) {
setStringPreference(context, MMSC_USERNAME_PREF, value);
}
public static boolean getUseCustomMmscPassword(Context context) {
boolean legacy = TextSecurePreferences.isLegacyUseLocalApnsEnabled(context);
return getBooleanPreference(context, MMSC_CUSTOM_PASSWORD_PREF, legacy);
}
public static void setUseCustomMmscPassword(Context context, boolean value) {
setBooleanPreference(context, MMSC_CUSTOM_PASSWORD_PREF, value);
}
public static String getMmscPassword(Context context) {
return getStringPreference(context, MMSC_PASSWORD_PREF, "");
}
public static void setMmscPassword(Context context, String value) {
setStringPreference(context, MMSC_PASSWORD_PREF, value);
}
public static String getMmsUserAgent(Context context, String defaultUserAgent) {
boolean useCustom = getBooleanPreference(context, MMS_CUSTOM_USER_AGENT, false);
if (useCustom) return getStringPreference(context, MMS_USER_AGENT, defaultUserAgent);
else return defaultUserAgent;
}
public static String getIdentityContactUri(Context context) {
return getStringPreference(context, IDENTITY_PREF, null);
}
public static void setIdentityContactUri(Context context, String identityUri) {
setStringPreference(context, IDENTITY_PREF, identityUri);
}
public static boolean isScreenSecurityEnabled(Context context) {
return getBooleanPreference(context, SCREEN_SECURITY_PREF, true);
}
public static boolean isLegacyUseLocalApnsEnabled(Context context) {
return getBooleanPreference(context, ENABLE_MANUAL_MMS_PREF, false);
}
public static int getLastVersionCode(Context context) {
return getIntegerPreference(context, LAST_VERSION_CODE_PREF, 0);
}
public static void setLastVersionCode(Context context, int versionCode) throws IOException {
if (!setIntegerPrefrenceBlocking(context, LAST_VERSION_CODE_PREF, versionCode)) {
throw new IOException("couldn't write version code to sharedpreferences");
}
}
public static int getLastExperienceVersionCode(Context context) {
return getIntegerPreference(context, LAST_EXPERIENCE_VERSION_PREF, 0);
}
public static void setLastExperienceVersionCode(Context context, int versionCode) {
setIntegerPrefrence(context, LAST_EXPERIENCE_VERSION_PREF, versionCode);
}
public static String getTheme(Context context) {
return getStringPreference(context, THEME_PREF, "light");
}
public static boolean isVerifying(Context context) {
return getBooleanPreference(context, VERIFYING_STATE_PREF, false);
}
public static void setVerifying(Context context, boolean verifying) {
setBooleanPreference(context, VERIFYING_STATE_PREF, verifying);
}
public static boolean isPushRegistered(Context context) {
return getBooleanPreference(context, REGISTERED_GCM_PREF, false);
}
public static void setPushRegistered(Context context, boolean registered) {
Log.w("TextSecurePreferences", "Setting push registered: " + registered);
setBooleanPreference(context, REGISTERED_GCM_PREF, registered);
}
public static boolean isPassphraseTimeoutEnabled(Context context) {
return getBooleanPreference(context, PASSPHRASE_TIMEOUT_PREF, false);
}
public static int getPassphraseTimeoutInterval(Context context) {
return getIntegerPreference(context, PASSPHRASE_TIMEOUT_INTERVAL_PREF, 5 * 60);
}
public static void setPassphraseTimeoutInterval(Context context, int interval) {
setIntegerPrefrence(context, PASSPHRASE_TIMEOUT_INTERVAL_PREF, interval);
}
public static String getLanguage(Context context) {
return getStringPreference(context, LANGUAGE_PREF, "zz");
}
public static void setLanguage(Context context, String language) {
setStringPreference(context, LANGUAGE_PREF, language);
}
public static boolean isSmsDeliveryReportsEnabled(Context context) {
return getBooleanPreference(context, SMS_DELIVERY_REPORT_PREF, false);
}
public static boolean hasPromptedPushRegistration(Context context) {
return getBooleanPreference(context, PROMPTED_PUSH_REGISTRATION_PREF, false);
}
public static void setPromptedPushRegistration(Context context, boolean value) {
setBooleanPreference(context, PROMPTED_PUSH_REGISTRATION_PREF, value);
}
public static boolean hasPromptedDefaultSmsProvider(Context context) {
return getBooleanPreference(context, PROMPTED_DEFAULT_SMS_PREF, false);
}
public static void setPromptedDefaultSmsProvider(Context context, boolean value) {
setBooleanPreference(context, PROMPTED_DEFAULT_SMS_PREF, value);
}
public static boolean hasPromptedShare(Context context) {
return getBooleanPreference(context, PROMPTED_SHARE_PREF, false);
}
public static void setPromptedShare(Context context, boolean value) {
setBooleanPreference(context, PROMPTED_SHARE_PREF, value);
}
public static boolean isInterceptAllMmsEnabled(Context context) {
return getBooleanPreference(context, ALL_MMS_PREF, true);
}
public static boolean isInterceptAllSmsEnabled(Context context) {
return getBooleanPreference(context, ALL_SMS_PREF, true);
}
public static boolean isNotificationsEnabled(Context context) {
return getBooleanPreference(context, NOTIFICATION_PREF, true);
}
public static String getNotificationRingtone(Context context) {
return getStringPreference(context, RINGTONE_PREF, Settings.System.DEFAULT_NOTIFICATION_URI.toString());
}
public static boolean isNotificationVibrateEnabled(Context context) {
return getBooleanPreference(context, VIBRATE_PREF, true);
}
public static String getNotificationLedColor(Context context) {
return getStringPreference(context, LED_COLOR_PREF, "blue");
}
public static String getNotificationLedPattern(Context context) {
return getStringPreference(context, LED_BLINK_PREF, "500,2000");
}
public static String getNotificationLedPatternCustom(Context context) {
return getStringPreference(context, LED_BLINK_PREF_CUSTOM, "500,2000");
}
public static void setNotificationLedPatternCustom(Context context, String pattern) {
setStringPreference(context, LED_BLINK_PREF_CUSTOM, pattern);
}
public static boolean isThreadLengthTrimmingEnabled(Context context) {
return getBooleanPreference(context, THREAD_TRIM_ENABLED, false);
}
public static int getThreadTrimLength(Context context) {
return Integer.parseInt(getStringPreference(context, THREAD_TRIM_LENGTH, "500"));
}
public static boolean isSystemEmojiPreferred(Context context) {
return getBooleanPreference(context, SYSTEM_EMOJI_PREF, false);
}
public static @NonNull Set<String> getMobileMediaDownloadAllowed(Context context) {
return getMediaDownloadAllowed(context, MEDIA_DOWNLOAD_MOBILE_PREF, R.array.pref_media_download_mobile_data_default);
}
public static @NonNull Set<String> getWifiMediaDownloadAllowed(Context context) {
return getMediaDownloadAllowed(context, MEDIA_DOWNLOAD_WIFI_PREF, R.array.pref_media_download_wifi_default);
}
public static @NonNull Set<String> getRoamingMediaDownloadAllowed(Context context) {
return getMediaDownloadAllowed(context, MEDIA_DOWNLOAD_ROAMING_PREF, R.array.pref_media_download_roaming_default);
}
private static @NonNull Set<String> getMediaDownloadAllowed(Context context, String key, @ArrayRes int defaultValuesRes) {
return getStringSetPreference(context,
key,
new HashSet<>(Arrays.asList(context.getResources().getStringArray(defaultValuesRes))));
}
public static void setBooleanPreference(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).apply();
}
public static boolean getBooleanPreference(Context context, String key, boolean defaultValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defaultValue);
}
public static void setStringPreference(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).apply();
}
public static String getStringPreference(Context context, String key, String defaultValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defaultValue);
}
private static int getIntegerPreference(Context context, String key, int defaultValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defaultValue);
}
private static void setIntegerPrefrence(Context context, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).apply();
}
private static boolean setIntegerPrefrenceBlocking(Context context, String key, int value) {
return PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
}
private static long getLongPreference(Context context, String key, long defaultValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getLong(key, defaultValue);
}
private static void setLongPreference(Context context, String key, long value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(key, value).apply();
}
private static Set<String> getStringSetPreference(Context context, String key, Set<String> defaultValues) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.contains(key)) {
return SharedPreferenceCompat.getStringSet(PreferenceManager.getDefaultSharedPreferences(context),
key,
Collections.<String>emptySet());
} else {
return defaultValues;
}
}
}
| 24,388 | 42.629696 | 124 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Trimmer.java | package org.thoughtcrime.securesms.util;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.ThreadDatabase;
public class Trimmer {
public static void trimAllThreads(Context context, int threadLengthLimit) {
new TrimmingProgressTask(context).execute(threadLengthLimit);
}
private static class TrimmingProgressTask extends AsyncTask<Integer, Integer, Void> implements ThreadDatabase.ProgressListener {
private ProgressDialog progressDialog;
private Context context;
public TrimmingProgressTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setTitle(R.string.trimmer__deleting);
progressDialog.setMessage(context.getString(R.string.trimmer__deleting_old_messages));
progressDialog.setMax(100);
progressDialog.show();
}
@Override
protected Void doInBackground(Integer... params) {
DatabaseFactory.getThreadDatabase(context).trimAllThreads(params[0], this);
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
double count = progress[1];
double index = progress[0];
progressDialog.setProgress((int)Math.round((index / count) * 100.0));
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
Toast.makeText(context,
R.string.trimmer__old_messages_successfully_deleted,
Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(int complete, int total) {
this.publishProgress(complete, total);
}
}
}
| 2,055 | 30.151515 | 130 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/Util.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Looper;
import android.provider.Telephony;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.widget.EditText;
import org.thoughtcrime.securesms.BuildConfig;
import org.thoughtcrime.securesms.mms.OutgoingLegacyMmsConnection;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import ws.com.google.android.mms.pdu.CharacterSets;
import ws.com.google.android.mms.pdu.EncodedStringValue;
public class Util {
public static Handler handler = new Handler(Looper.getMainLooper());
public static String join(String[] list, String delimiter) {
return join(Arrays.asList(list), delimiter);
}
public static String join(Collection<String> list, String delimiter) {
StringBuilder result = new StringBuilder();
int i = 0;
for (String item : list) {
result.append(item);
if (++i < list.size())
result.append(delimiter);
}
return result.toString();
}
public static String join(long[] list, String delimeter) {
StringBuilder sb = new StringBuilder();
for (int j=0;j<list.length;j++) {
if (j != 0) sb.append(delimeter);
sb.append(list[j]);
}
return sb.toString();
}
public static ExecutorService newSingleThreadedLifoExecutor() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingLifoQueue<Runnable>());
executor.execute(new Runnable() {
@Override
public void run() {
// Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
}
});
return executor;
}
public static boolean isEmpty(EncodedStringValue[] value) {
return value == null || value.length == 0;
}
public static boolean isEmpty(EditText value) {
return value == null || value.getText() == null || TextUtils.isEmpty(value.getText().toString());
}
public static CharSequence getBoldedString(String value) {
SpannableString spanned = new SpannableString(value);
spanned.setSpan(new StyleSpan(Typeface.BOLD), 0,
spanned.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spanned;
}
public static @NonNull String toIsoString(byte[] bytes) {
try {
return new String(bytes, CharacterSets.MIMENAME_ISO_8859_1);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("ISO_8859_1 must be supported!");
}
}
public static byte[] toIsoBytes(String isoString) {
try {
return isoString.getBytes(CharacterSets.MIMENAME_ISO_8859_1);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("ISO_8859_1 must be supported!");
}
}
public static byte[] toUtf8Bytes(String utf8String) {
try {
return utf8String.getBytes(CharacterSets.MIMENAME_UTF_8);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF_8 must be supported!");
}
}
public static void wait(Object lock, long timeout) {
try {
lock.wait(timeout);
} catch (InterruptedException ie) {
throw new AssertionError(ie);
}
}
public static String canonicalizeNumber(Context context, String number)
throws InvalidNumberException
{
String localNumber = TextSecurePreferences.getLocalNumber(context);
return PhoneNumberFormatter.formatNumber(number, localNumber);
}
public static String canonicalizeNumberOrGroup(@NonNull Context context, @NonNull String number)
throws InvalidNumberException
{
if (GroupUtil.isEncodedGroup(number)) return number;
else return canonicalizeNumber(context, number);
}
public static byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer)) != -1) {
bout.write(buffer, 0, read);
}
in.close();
return bout.toByteArray();
}
public static String readFullyAsString(InputStream in) throws IOException {
return new String(readFully(in));
}
public static long copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[4096];
int read;
long total = 0;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
total += read;
}
in.close();
out.close();
return total;
}
public static String getDeviceE164Number(Context context) {
String localNumber = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE))
.getLine1Number();
if (!TextUtils.isEmpty(localNumber) && !localNumber.startsWith("+"))
{
if (localNumber.length() == 10) localNumber = "+1" + localNumber;
else localNumber = "+" + localNumber;
return localNumber;
}
return null;
}
public static <T> List<List<T>> partition(List<T> list, int partitionSize) {
List<List<T>> results = new LinkedList<>();
for (int index=0;index<list.size();index+=partitionSize) {
int subListSize = Math.min(partitionSize, list.size() - index);
results.add(list.subList(index, index + subListSize));
}
return results;
}
public static List<String> split(String source, String delimiter) {
List<String> results = new LinkedList<>();
if (TextUtils.isEmpty(source)) {
return results;
}
String[] elements = source.split(delimiter);
Collections.addAll(results, elements);
return results;
}
public static byte[][] split(byte[] input, int firstLength, int secondLength) {
byte[][] parts = new byte[2][];
parts[0] = new byte[firstLength];
System.arraycopy(input, 0, parts[0], 0, firstLength);
parts[1] = new byte[secondLength];
System.arraycopy(input, firstLength, parts[1], 0, secondLength);
return parts;
}
public static byte[] combine(byte[]... elements) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (byte[] element : elements) {
baos.write(element);
}
return baos.toByteArray();
} catch (IOException e) {
throw new AssertionError(e);
}
}
public static byte[] trim(byte[] input, int length) {
byte[] result = new byte[length];
System.arraycopy(input, 0, result, 0, result.length);
return result;
}
@SuppressLint("NewApi")
public static boolean isDefaultSmsProvider(Context context){
return (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) ||
(context.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(context)));
}
public static int getCurrentApkReleaseVersion(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new AssertionError(e);
}
}
public static String getSecret(int size) {
byte[] secret = getSecretBytes(size);
return Base64.encodeBytes(secret);
}
public static byte[] getSecretBytes(int size) {
byte[] secret = new byte[size];
getSecureRandom().nextBytes(secret);
return secret;
}
public static SecureRandom getSecureRandom() {
try {
return SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public static boolean isBuildFresh() {
return BuildConfig.BUILD_TIMESTAMP + TimeUnit.DAYS.toMillis(90) > System.currentTimeMillis();
}
@TargetApi(VERSION_CODES.LOLLIPOP)
public static boolean isMmsCapable(Context context) {
return (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) || OutgoingLegacyMmsConnection.isConnectionPossible(context);
}
public static boolean isMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
public static void assertMainThread() {
if (!isMainThread()) {
throw new AssertionError("Main-thread assertion failed.");
}
}
public static void runOnMain(final @NonNull Runnable runnable) {
if (isMainThread()) runnable.run();
else handler.post(runnable);
}
public static void runOnMainSync(final @NonNull Runnable runnable) {
if (isMainThread()) {
runnable.run();
} else {
final CountDownLatch sync = new CountDownLatch(1);
runOnMain(new Runnable() {
@Override public void run() {
try {
runnable.run();
} finally {
sync.countDown();
}
}
});
try {
sync.await();
} catch (InterruptedException ie) {
throw new AssertionError(ie);
}
}
}
public static boolean equals(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
public static int hashCode(@Nullable Object... objects) {
return Arrays.hashCode(objects);
}
@TargetApi(VERSION_CODES.KITKAT)
public static boolean isLowMemory(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
return (VERSION.SDK_INT >= VERSION_CODES.KITKAT && activityManager.isLowRamDevice()) ||
activityManager.getMemoryClass() <= 64;
}
public static int clamp(int value, int min, int max) {
return Math.min(Math.max(value, min), max);
}
public static float clamp(float value, float min, float max) {
return Math.min(Math.max(value, min), max);
}
}
| 11,495 | 28.85974 | 131 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/VersionTracker.java | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.content.pm.PackageManager;
import java.io.IOException;
public class VersionTracker {
public static int getLastSeenVersion(Context context) {
return TextSecurePreferences.getLastVersionCode(context);
}
public static void updateLastSeenVersion(Context context) {
try {
int currentVersionCode = Util.getCurrentApkReleaseVersion(context);
TextSecurePreferences.setLastVersionCode(context, currentVersionCode);
} catch (IOException ioe) {
throw new AssertionError(ioe);
}
}
}
| 607 | 24.333333 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/ViewUtil.java | /**
* Copyright (C) 2015 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture;
import org.thoughtcrime.securesms.util.concurrent.SettableFuture;
public class ViewUtil {
@SuppressWarnings("deprecation")
public static void setBackground(final @NonNull View v, final @Nullable Drawable drawable) {
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
v.setBackground(drawable);
} else {
v.setBackgroundDrawable(drawable);
}
}
public static void setY(final @NonNull View v, final int y) {
if (VERSION.SDK_INT >= 11) {
ViewCompat.setY(v, y);
} else {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)v.getLayoutParams();
params.topMargin = y;
v.setLayoutParams(params);
}
}
public static float getY(final @NonNull View v) {
if (VERSION.SDK_INT >= 11) {
return ViewCompat.getY(v);
} else {
return ((ViewGroup.MarginLayoutParams)v.getLayoutParams()).topMargin;
}
}
public static void setX(final @NonNull View v, final int x) {
if (VERSION.SDK_INT >= 11) {
ViewCompat.setX(v, x);
} else {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)v.getLayoutParams();
params.leftMargin = x;
v.setLayoutParams(params);
}
}
public static float getX(final @NonNull View v) {
if (VERSION.SDK_INT >= 11) {
return ViewCompat.getX(v);
} else {
return ((LayoutParams)v.getLayoutParams()).leftMargin;
}
}
public static void swapChildInPlace(ViewGroup parent, View toRemove, View toAdd, int defaultIndex) {
int childIndex = parent.indexOfChild(toRemove);
if (childIndex > -1) parent.removeView(toRemove);
parent.addView(toAdd, childIndex > -1 ? childIndex : defaultIndex);
}
public static CharSequence ellipsize(@Nullable CharSequence text, @NonNull TextView view) {
if (TextUtils.isEmpty(text) || view.getWidth() == 0 || view.getEllipsize() != TruncateAt.END) {
return text;
} else {
return TextUtils.ellipsize(text,
view.getPaint(),
view.getWidth() - view.getPaddingRight() - view.getPaddingLeft(),
TruncateAt.END);
}
}
@SuppressWarnings("unchecked")
public static <T extends View> T inflateStub(@NonNull View parent, @IdRes int stubId) {
return (T)((ViewStub)parent.findViewById(stubId)).inflate();
}
@SuppressWarnings("unchecked")
public static <T extends View> T findById(@NonNull View parent, @IdRes int resId) {
return (T) parent.findViewById(resId);
}
@SuppressWarnings("unchecked")
public static <T extends View> T findById(@NonNull Activity parent, @IdRes int resId) {
return (T) parent.findViewById(resId);
}
private static Animation getAlphaAnimation(float from, float to, int duration) {
final Animation anim = new AlphaAnimation(from, to);
anim.setInterpolator(new FastOutSlowInInterpolator());
anim.setDuration(duration);
return anim;
}
public static void fadeIn(final @NonNull View view, final int duration) {
animateIn(view, getAlphaAnimation(0f, 1f, duration));
}
public static void fadeOut(final @NonNull View view, final int duration) {
animateOut(view, getAlphaAnimation(1f, 0f, duration));
}
public static ListenableFuture<Boolean> animateOut(final @NonNull View view, final @NonNull Animation animation) {
final SettableFuture future = new SettableFuture();
if (view.getVisibility() == View.GONE) {
future.set(true);
} else {
view.clearAnimation();
animation.reset();
animation.setStartTime(0);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
view.setVisibility(View.GONE);
future.set(true);
}
});
view.startAnimation(animation);
}
return future;
}
public static void animateIn(final @NonNull View view, final @NonNull Animation animation) {
if (view.getVisibility() == View.VISIBLE) return;
view.clearAnimation();
animation.reset();
animation.setStartTime(0);
view.setVisibility(View.VISIBLE);
view.startAnimation(animation);
}
@SuppressWarnings("unchecked")
public static <T extends View> T inflate(@NonNull LayoutInflater inflater,
@NonNull ViewGroup parent,
@LayoutRes int layoutResId)
{
return (T)(inflater.inflate(layoutResId, parent, false));
}
}
| 6,298 | 33.994444 | 116 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/VisibleForTesting.java | package org.thoughtcrime.securesms.util;
public @interface VisibleForTesting {
}
| 82 | 15.6 | 40 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/WorkerThread.java | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 org.thoughtcrime.securesms.util;
import java.util.List;
public class WorkerThread extends Thread {
private final List<Runnable> workQueue;
public WorkerThread(List<Runnable> workQueue, String name) {
super(name);
this.workQueue = workQueue;
}
private Runnable getWork() {
synchronized (workQueue) {
try {
while (workQueue.isEmpty())
workQueue.wait();
return workQueue.remove(0);
} catch (InterruptedException ie) {
throw new AssertionError(ie);
}
}
}
@Override
public void run() {
for (;;)
getWork().run();
}
}
| 1,315 | 25.857143 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/concurrent/AssertedSuccessListener.java | package org.thoughtcrime.securesms.util.concurrent;
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture.Listener;
import java.util.concurrent.ExecutionException;
public abstract class AssertedSuccessListener<T> implements Listener<T> {
@Override
public void onFailure(ExecutionException e) {
throw new AssertionError(e);
}
}
| 353 | 26.230769 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/concurrent/ListenableFuture.java | package org.thoughtcrime.securesms.util.concurrent;
import java.util.concurrent.ExecutionException;
public interface ListenableFuture<T> {
void addListener(Listener<T> listener);
public interface Listener<T> {
public void onSuccess(T result);
public void onFailure(ExecutionException e);
}
}
| 309 | 22.846154 | 51 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/concurrent/SettableFuture.java | package org.thoughtcrime.securesms.util.concurrent;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class SettableFuture<T> implements Future<T>, ListenableFuture<T> {
private final List<Listener<T>> listeners = new LinkedList<>();
private boolean completed;
private boolean canceled;
private volatile T result;
private volatile Throwable exception;
@Override
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
if (!completed && !canceled) {
canceled = true;
return true;
}
return false;
}
@Override
public synchronized boolean isCancelled() {
return canceled;
}
@Override
public synchronized boolean isDone() {
return completed;
}
public boolean set(T result) {
synchronized (this) {
if (completed || canceled) return false;
this.result = result;
this.completed = true;
}
notifyAllListeners();
return true;
}
public boolean setException(Throwable throwable) {
synchronized (this) {
if (completed || canceled) return false;
this.exception = throwable;
this.completed = true;
}
notifyAllListeners();
return true;
}
@Override
public synchronized T get() throws InterruptedException, ExecutionException {
while (!completed) wait();
if (exception != null) throw new ExecutionException(exception);
else return result;
}
@Override
public synchronized T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException
{
long startTime = System.currentTimeMillis();
while (!completed && System.currentTimeMillis() - startTime > unit.toMillis(timeout)) {
wait(unit.toMillis(timeout));
}
if (!completed) throw new TimeoutException();
else return get();
}
@Override
public void addListener(Listener<T> listener) {
synchronized (this) {
listeners.add(listener);
if (!completed) return;
}
notifyListener(listener);
}
private void notifyAllListeners() {
List<Listener<T>> localListeners;
synchronized (this) {
localListeners = new LinkedList<>(listeners);
}
for (Listener<T> listener : localListeners) {
notifyListener(listener);
}
}
private void notifyListener(Listener<T> listener) {
if (exception != null) listener.onFailure(new ExecutionException(exception));
else listener.onSuccess(result);
}
}
| 2,696 | 22.867257 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/deque/BlockingDeque.java | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
package org.thoughtcrime.securesms.util.deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A {@link Deque} that additionally supports blocking operations that wait
* for the deque to become non-empty when retrieving an element, and wait for
* space to become available in the deque when storing an element.
*
* <p><tt>BlockingDeque</tt> methods come in four forms, with different ways
* of handling operations that cannot be satisfied immediately, but may be
* satisfied at some point in the future:
* one throws an exception, the second returns a special value (either
* <tt>null</tt> or <tt>false</tt>, depending on the operation), the third
* blocks the current thread indefinitely until the operation can succeed,
* and the fourth blocks for only a given maximum time limit before giving
* up. These methods are summarized in the following table:
*
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td ALIGN=CENTER COLSPAN = 5> <b>First Element (Head)</b></td>
* </tr>
* <tr>
* <td></td>
* <td ALIGN=CENTER><em>Throws exception</em></td>
* <td ALIGN=CENTER><em>Special value</em></td>
* <td ALIGN=CENTER><em>Blocks</em></td>
* <td ALIGN=CENTER><em>Times out</em></td>
* </tr>
* <tr>
* <td><b>Insert</b></td>
* <td>{@link #addFirst addFirst(e)}</td>
* <td>{@link #offerFirst offerFirst(e)}</td>
* <td>{@link #putFirst putFirst(e)}</td>
* <td>{@link #offerFirst offerFirst(e, time, unit)}</td>
* </tr>
* <tr>
* <td><b>Remove</b></td>
* <td>{@link #removeFirst removeFirst()}</td>
* <td>{@link #pollFirst pollFirst()}</td>
* <td>{@link #takeFirst takeFirst()}</td>
* <td>{@link #pollFirst(long, TimeUnit) pollFirst(time, unit)}</td>
* </tr>
* <tr>
* <td><b>Examine</b></td>
* <td>{@link #getFirst getFirst()}</td>
* <td>{@link #peekFirst peekFirst()}</td>
* <td><em>not applicable</em></td>
* <td><em>not applicable</em></td>
* </tr>
* <tr>
* <td ALIGN=CENTER COLSPAN = 5> <b>Last Element (Tail)</b></td>
* </tr>
* <tr>
* <td></td>
* <td ALIGN=CENTER><em>Throws exception</em></td>
* <td ALIGN=CENTER><em>Special value</em></td>
* <td ALIGN=CENTER><em>Blocks</em></td>
* <td ALIGN=CENTER><em>Times out</em></td>
* </tr>
* <tr>
* <td><b>Insert</b></td>
* <td>{@link #addLast addLast(e)}</td>
* <td>{@link #offerLast offerLast(e)}</td>
* <td>{@link #putLast putLast(e)}</td>
* <td>{@link #offerLast offerLast(e, time, unit)}</td>
* </tr>
* <tr>
* <td><b>Remove</b></td>
* <td>{@link #removeLast() removeLast()}</td>
* <td>{@link #pollLast() pollLast()}</td>
* <td>{@link #takeLast takeLast()}</td>
* <td>{@link #pollLast(long, TimeUnit) pollLast(time, unit)}</td>
* </tr>
* <tr>
* <td><b>Examine</b></td>
* <td>{@link #getLast getLast()}</td>
* <td>{@link #peekLast peekLast()}</td>
* <td><em>not applicable</em></td>
* <td><em>not applicable</em></td>
* </tr>
* </table>
*
* <p>Like any {@link BlockingQueue}, a <tt>BlockingDeque</tt> is thread safe,
* does not permit null elements, and may (or may not) be
* capacity-constrained.
*
* <p>A <tt>BlockingDeque</tt> implementation may be used directly as a FIFO
* <tt>BlockingQueue</tt>. The methods inherited from the
* <tt>BlockingQueue</tt> interface are precisely equivalent to
* <tt>BlockingDeque</tt> methods as indicated in the following table:
*
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td ALIGN=CENTER> <b><tt>BlockingQueue</tt> Method</b></td>
* <td ALIGN=CENTER> <b>Equivalent <tt>BlockingDeque</tt> Method</b></td>
* </tr>
* <tr>
* <td ALIGN=CENTER COLSPAN = 2> <b>Insert</b></td>
* </tr>
* <tr>
* <td>{@link #add add(e)}</td>
* <td>{@link #addLast addLast(e)}</td>
* </tr>
* <tr>
* <td>{@link #offer offer(e)}</td>
* <td>{@link #offerLast offerLast(e)}</td>
* </tr>
* <tr>
* <td>{@link #put put(e)}</td>
* <td>{@link #putLast putLast(e)}</td>
* </tr>
* <tr>
* <td>{@link #offer offer(e, time, unit)}</td>
* <td>{@link #offerLast offerLast(e, time, unit)}</td>
* </tr>
* <tr>
* <td ALIGN=CENTER COLSPAN = 2> <b>Remove</b></td>
* </tr>
* <tr>
* <td>{@link #remove() remove()}</td>
* <td>{@link #removeFirst() removeFirst()}</td>
* </tr>
* <tr>
* <td>{@link #poll() poll()}</td>
* <td>{@link #pollFirst() pollFirst()}</td>
* </tr>
* <tr>
* <td>{@link #take() take()}</td>
* <td>{@link #takeFirst() takeFirst()}</td>
* </tr>
* <tr>
* <td>{@link #poll(long, TimeUnit) poll(time, unit)}</td>
* <td>{@link #pollFirst(long, TimeUnit) pollFirst(time, unit)}</td>
* </tr>
* <tr>
* <td ALIGN=CENTER COLSPAN = 2> <b>Examine</b></td>
* </tr>
* <tr>
* <td>{@link #element() element()}</td>
* <td>{@link #getFirst() getFirst()}</td>
* </tr>
* <tr>
* <td>{@link #peek() peek()}</td>
* <td>{@link #peekFirst() peekFirst()}</td>
* </tr>
* </table>
*
* <p>Memory consistency effects: As with other concurrent
* collections, actions in a thread prior to placing an object into a
* {@code BlockingDeque}
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
* actions subsequent to the access or removal of that element from
* the {@code BlockingDeque} in another thread.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.6
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
public interface BlockingDeque<E> extends BlockingQueue<E>, Deque<E> {
/*
* We have "diamond" multiple interface inheritance here, and that
* introduces ambiguities. Methods might end up with different
* specs depending on the branch chosen by javadoc. Thus a lot of
* methods specs here are copied from superinterfaces.
*/
/**
* Inserts the specified element at the front of this deque if it is
* possible to do so immediately without violating capacity restrictions,
* throwing an <tt>IllegalStateException</tt> if no space is currently
* available. When using a capacity-restricted deque, it is generally
* preferable to use {@link #offerFirst offerFirst}.
*
* @param e the element to add
* @throws IllegalStateException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException {@inheritDoc}
*/
void addFirst(E e);
/**
* Inserts the specified element at the end of this deque if it is
* possible to do so immediately without violating capacity restrictions,
* throwing an <tt>IllegalStateException</tt> if no space is currently
* available. When using a capacity-restricted deque, it is generally
* preferable to use {@link #offerLast offerLast}.
*
* @param e the element to add
* @throws IllegalStateException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException {@inheritDoc}
*/
void addLast(E e);
/**
* Inserts the specified element at the front of this deque if it is
* possible to do so immediately without violating capacity restrictions,
* returning <tt>true</tt> upon success and <tt>false</tt> if no space is
* currently available.
* When using a capacity-restricted deque, this method is generally
* preferable to the {@link #addFirst addFirst} method, which can
* fail to insert an element only by throwing an exception.
*
* @param e the element to add
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException {@inheritDoc}
*/
boolean offerFirst(E e);
/**
* Inserts the specified element at the end of this deque if it is
* possible to do so immediately without violating capacity restrictions,
* returning <tt>true</tt> upon success and <tt>false</tt> if no space is
* currently available.
* When using a capacity-restricted deque, this method is generally
* preferable to the {@link #addLast addLast} method, which can
* fail to insert an element only by throwing an exception.
*
* @param e the element to add
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException {@inheritDoc}
*/
boolean offerLast(E e);
/**
* Inserts the specified element at the front of this deque,
* waiting if necessary for space to become available.
*
* @param e the element to add
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
void putFirst(E e) throws InterruptedException;
/**
* Inserts the specified element at the end of this deque,
* waiting if necessary for space to become available.
*
* @param e the element to add
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
void putLast(E e) throws InterruptedException;
/**
* Inserts the specified element at the front of this deque,
* waiting up to the specified wait time if necessary for space to
* become available.
*
* @param e the element to add
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return <tt>true</tt> if successful, or <tt>false</tt> if
* the specified waiting time elapses before space is available
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offerFirst(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Inserts the specified element at the end of this deque,
* waiting up to the specified wait time if necessary for space to
* become available.
*
* @param e the element to add
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return <tt>true</tt> if successful, or <tt>false</tt> if
* the specified waiting time elapses before space is available
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offerLast(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Retrieves and removes the first element of this deque, waiting
* if necessary until an element becomes available.
*
* @return the head of this deque
* @throws InterruptedException if interrupted while waiting
*/
E takeFirst() throws InterruptedException;
/**
* Retrieves and removes the last element of this deque, waiting
* if necessary until an element becomes available.
*
* @return the tail of this deque
* @throws InterruptedException if interrupted while waiting
*/
E takeLast() throws InterruptedException;
/**
* Retrieves and removes the first element of this deque, waiting
* up to the specified wait time if necessary for an element to
* become available.
*
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return the head of this deque, or <tt>null</tt> if the specified
* waiting time elapses before an element is available
* @throws InterruptedException if interrupted while waiting
*/
E pollFirst(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Retrieves and removes the last element of this deque, waiting
* up to the specified wait time if necessary for an element to
* become available.
*
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return the tail of this deque, or <tt>null</tt> if the specified
* waiting time elapses before an element is available
* @throws InterruptedException if interrupted while waiting
*/
E pollLast(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element <tt>e</tt> such that
* <tt>o.equals(e)</tt> (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null (optional)
*/
boolean removeFirstOccurrence(Object o);
/**
* Removes the last occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the last element <tt>e</tt> such that
* <tt>o.equals(e)</tt> (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null (optional)
*/
boolean removeLastOccurrence(Object o);
// *** BlockingQueue methods ***
/**
* Inserts the specified element into the queue represented by this deque
* (in other words, at the tail of this deque) if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an
* <tt>IllegalStateException</tt> if no space is currently available.
* When using a capacity-restricted deque, it is generally preferable to
* use {@link #offer offer}.
*
* <p>This method is equivalent to {@link #addLast addLast}.
*
* @param e the element to add
* @throws IllegalStateException {@inheritDoc}
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean add(E e);
/**
* Inserts the specified element into the queue represented by this deque
* (in other words, at the tail of this deque) if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and <tt>false</tt> if no space is currently
* available. When using a capacity-restricted deque, this method is
* generally preferable to the {@link #add} method, which can fail to
* insert an element only by throwing an exception.
*
* <p>This method is equivalent to {@link #offerLast offerLast}.
*
* @param e the element to add
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offer(E e);
/**
* Inserts the specified element into the queue represented by this deque
* (in other words, at the tail of this deque), waiting if necessary for
* space to become available.
*
* <p>This method is equivalent to {@link #putLast putLast}.
*
* @param e the element to add
* @throws InterruptedException {@inheritDoc}
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
void put(E e) throws InterruptedException;
/**
* Inserts the specified element into the queue represented by this deque
* (in other words, at the tail of this deque), waiting up to the
* specified wait time if necessary for space to become available.
*
* <p>This method is equivalent to
* {@link #offerLast offerLast}.
*
* @param e the element to add
* @return <tt>true</tt> if the element was added to this deque, else
* <tt>false</tt>
* @throws InterruptedException {@inheritDoc}
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque).
* This method differs from {@link #poll poll} only in that it
* throws an exception if this deque is empty.
*
* <p>This method is equivalent to {@link #removeFirst() removeFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException if this deque is empty
*/
E remove();
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), or returns
* <tt>null</tt> if this deque is empty.
*
* <p>This method is equivalent to {@link #pollFirst()}.
*
* @return the head of this deque, or <tt>null</tt> if this deque is empty
*/
E poll();
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), waiting if
* necessary until an element becomes available.
*
* <p>This method is equivalent to {@link #takeFirst() takeFirst}.
*
* @return the head of this deque
* @throws InterruptedException if interrupted while waiting
*/
E take() throws InterruptedException;
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), waiting up to the
* specified wait time if necessary for an element to become available.
*
* <p>This method is equivalent to
* {@link #pollFirst(long,TimeUnit) pollFirst}.
*
* @return the head of this deque, or <tt>null</tt> if the
* specified waiting time elapses before an element is available
* @throws InterruptedException if interrupted while waiting
*/
E poll(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque (in other words, the first element of this deque).
* This method differs from {@link #peek peek} only in that it throws an
* exception if this deque is empty.
*
* <p>This method is equivalent to {@link #getFirst() getFirst}.
*
* @return the head of this deque
* @throws NoSuchElementException if this deque is empty
*/
E element();
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque (in other words, the first element of this deque), or
* returns <tt>null</tt> if this deque is empty.
*
* <p>This method is equivalent to {@link #peekFirst() peekFirst}.
*
* @return the head of this deque, or <tt>null</tt> if this deque is empty
*/
E peek();
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element <tt>e</tt> such that
* <tt>o.equals(e)</tt> (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* <p>This method is equivalent to
* {@link #removeFirstOccurrence removeFirstOccurrence}.
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if this deque changed as a result of the call
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null (optional)
*/
boolean remove(Object o);
/**
* Returns <tt>true</tt> if this deque contains the specified element.
* More formally, returns <tt>true</tt> if and only if this deque contains
* at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
*
* @param o object to be checked for containment in this deque
* @return <tt>true</tt> if this deque contains the specified element
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null (optional)
*/
public boolean contains(Object o);
/**
* Returns the number of elements in this deque.
*
* @return the number of elements in this deque
*/
public int size();
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* @return an iterator over the elements in this deque in proper sequence
*/
Iterator<E> iterator();
// *** Stack methods ***
/**
* Pushes an element onto the stack represented by this deque. In other
* words, inserts the element at the front of this deque unless it would
* violate capacity restrictions.
*
* <p>This method is equivalent to {@link #addFirst addFirst}.
*
* @throws IllegalStateException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException {@inheritDoc}
*/
void push(E e);
}
| 25,241 | 39.910859 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/deque/Deque.java | /*
* Written by Doug Lea and Josh Bloch with assistance from members of
* JCP JSR-166 Expert Group and released to the public domain, as explained
* at http://creativecommons.org/licenses/publicdomain
*/
package org.thoughtcrime.securesms.util.deque;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Stack;
// BEGIN android-note
// removed link to collections framework docs
// changed {@link #offer(Object)} to {@link #offer} to satisfy DroidDoc
// END android-note
/**
* A linear collection that supports element insertion and removal at
* both ends. The name <i>deque</i> is short for "double ended queue"
* and is usually pronounced "deck". Most <tt>Deque</tt>
* implementations place no fixed limits on the number of elements
* they may contain, but this interface supports capacity-restricted
* deques as well as those with no fixed size limit.
*
* <p>This interface defines methods to access the elements at both
* ends of the deque. Methods are provided to insert, remove, and
* examine the element. Each of these methods exists in two forms:
* one throws an exception if the operation fails, the other returns a
* special value (either <tt>null</tt> or <tt>false</tt>, depending on
* the operation). The latter form of the insert operation is
* designed specifically for use with capacity-restricted
* <tt>Deque</tt> implementations; in most implementations, insert
* operations cannot fail.
*
* <p>The twelve methods described above are summarized in the
* following table:
*
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td></td>
* <td ALIGN=CENTER COLSPAN = 2> <b>First Element (Head)</b></td>
* <td ALIGN=CENTER COLSPAN = 2> <b>Last Element (Tail)</b></td>
* </tr>
* <tr>
* <td></td>
* <td ALIGN=CENTER><em>Throws exception</em></td>
* <td ALIGN=CENTER><em>Special value</em></td>
* <td ALIGN=CENTER><em>Throws exception</em></td>
* <td ALIGN=CENTER><em>Special value</em></td>
* </tr>
* <tr>
* <td><b>Insert</b></td>
* <td>{@link #addFirst addFirst(e)}</td>
* <td>{@link #offerFirst offerFirst(e)}</td>
* <td>{@link #addLast addLast(e)}</td>
* <td>{@link #offerLast offerLast(e)}</td>
* </tr>
* <tr>
* <td><b>Remove</b></td>
* <td>{@link #removeFirst removeFirst()}</td>
* <td>{@link #pollFirst pollFirst()}</td>
* <td>{@link #removeLast removeLast()}</td>
* <td>{@link #pollLast pollLast()}</td>
* </tr>
* <tr>
* <td><b>Examine</b></td>
* <td>{@link #getFirst getFirst()}</td>
* <td>{@link #peekFirst peekFirst()}</td>
* <td>{@link #getLast getLast()}</td>
* <td>{@link #peekLast peekLast()}</td>
* </tr>
* </table>
*
* <p>This interface extends the {@link Queue} interface. When a deque is
* used as a queue, FIFO (First-In-First-Out) behavior results. Elements are
* added at the end of the deque and removed from the beginning. The methods
* inherited from the <tt>Queue</tt> interface are precisely equivalent to
* <tt>Deque</tt> methods as indicated in the following table:
*
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td ALIGN=CENTER> <b><tt>Queue</tt> Method</b></td>
* <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td>
* </tr>
* <tr>
* <td>{@link java.util.Queue#add add(e)}</td>
* <td>{@link #addLast addLast(e)}</td>
* </tr>
* <tr>
* <td>{@link java.util.Queue#offer offer(e)}</td>
* <td>{@link #offerLast offerLast(e)}</td>
* </tr>
* <tr>
* <td>{@link java.util.Queue#remove remove()}</td>
* <td>{@link #removeFirst removeFirst()}</td>
* </tr>
* <tr>
* <td>{@link java.util.Queue#poll poll()}</td>
* <td>{@link #pollFirst pollFirst()}</td>
* </tr>
* <tr>
* <td>{@link java.util.Queue#element element()}</td>
* <td>{@link #getFirst getFirst()}</td>
* </tr>
* <tr>
* <td>{@link java.util.Queue#peek peek()}</td>
* <td>{@link #peek peekFirst()}</td>
* </tr>
* </table>
*
* <p>Deques can also be used as LIFO (Last-In-First-Out) stacks. This
* interface should be used in preference to the legacy {@link Stack} class.
* When a deque is used as a stack, elements are pushed and popped from the
* beginning of the deque. Stack methods are precisely equivalent to
* <tt>Deque</tt> methods as indicated in the table below:
*
* <p>
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <tr>
* <td ALIGN=CENTER> <b>Stack Method</b></td>
* <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td>
* </tr>
* <tr>
* <td>{@link #push push(e)}</td>
* <td>{@link #addFirst addFirst(e)}</td>
* </tr>
* <tr>
* <td>{@link #pop pop()}</td>
* <td>{@link #removeFirst removeFirst()}</td>
* </tr>
* <tr>
* <td>{@link #peek peek()}</td>
* <td>{@link #peekFirst peekFirst()}</td>
* </tr>
* </table>
*
* <p>Note that the {@link #peek peek} method works equally well when
* a deque is used as a queue or a stack; in either case, elements are
* drawn from the beginning of the deque.
*
* <p>This interface provides two methods to remove interior
* elements, {@link #removeFirstOccurrence removeFirstOccurrence} and
* {@link #removeLastOccurrence removeLastOccurrence}.
*
* <p>Unlike the {@link List} interface, this interface does not
* provide support for indexed access to elements.
*
* <p>While <tt>Deque</tt> implementations are not strictly required
* to prohibit the insertion of null elements, they are strongly
* encouraged to do so. Users of any <tt>Deque</tt> implementations
* that do allow null elements are strongly encouraged <i>not</i> to
* take advantage of the ability to insert nulls. This is so because
* <tt>null</tt> is used as a special return value by various methods
* to indicated that the deque is empty.
*
* <p><tt>Deque</tt> implementations generally do not define
* element-based versions of the <tt>equals</tt> and <tt>hashCode</tt>
* methods, but instead inherit the identity-based versions from class
* <tt>Object</tt>.
*
* @author Doug Lea
* @author Josh Bloch
* @since 1.6
* @param <E> the type of elements held in this collection
*/
public interface Deque<E> extends Queue<E> {
/**
* Inserts the specified element at the front of this deque if it is
* possible to do so immediately without violating capacity restrictions.
* When using a capacity-restricted deque, it is generally preferable to
* use method {@link #offerFirst}.
*
* @param e the element to add
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
void addFirst(E e);
/**
* Inserts the specified element at the end of this deque if it is
* possible to do so immediately without violating capacity restrictions.
* When using a capacity-restricted deque, it is generally preferable to
* use method {@link #offerLast}.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
void addLast(E e);
/**
* Inserts the specified element at the front of this deque unless it would
* violate capacity restrictions. When using a capacity-restricted deque,
* this method is generally preferable to the {@link #addFirst} method,
* which can fail to insert an element only by throwing an exception.
*
* @param e the element to add
* @return <tt>true</tt> if the element was added to this deque, else
* <tt>false</tt>
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offerFirst(E e);
/**
* Inserts the specified element at the end of this deque unless it would
* violate capacity restrictions. When using a capacity-restricted deque,
* this method is generally preferable to the {@link #addLast} method,
* which can fail to insert an element only by throwing an exception.
*
* @param e the element to add
* @return <tt>true</tt> if the element was added to this deque, else
* <tt>false</tt>
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offerLast(E e);
/**
* Retrieves and removes the first element of this deque. This method
* differs from {@link #pollFirst pollFirst} only in that it throws an
* exception if this deque is empty.
*
* @return the head of this deque
* @throws NoSuchElementException if this deque is empty
*/
E removeFirst();
/**
* Retrieves and removes the last element of this deque. This method
* differs from {@link #pollLast pollLast} only in that it throws an
* exception if this deque is empty.
*
* @return the tail of this deque
* @throws NoSuchElementException if this deque is empty
*/
E removeLast();
/**
* Retrieves and removes the first element of this deque,
* or returns <tt>null</tt> if this deque is empty.
*
* @return the head of this deque, or <tt>null</tt> if this deque is empty
*/
E pollFirst();
/**
* Retrieves and removes the last element of this deque,
* or returns <tt>null</tt> if this deque is empty.
*
* @return the tail of this deque, or <tt>null</tt> if this deque is empty
*/
E pollLast();
/**
* Retrieves, but does not remove, the first element of this deque.
*
* This method differs from {@link #peekFirst peekFirst} only in that it
* throws an exception if this deque is empty.
*
* @return the head of this deque
* @throws NoSuchElementException if this deque is empty
*/
E getFirst();
/**
* Retrieves, but does not remove, the last element of this deque.
* This method differs from {@link #peekLast peekLast} only in that it
* throws an exception if this deque is empty.
*
* @return the tail of this deque
* @throws NoSuchElementException if this deque is empty
*/
E getLast();
/**
* Retrieves, but does not remove, the first element of this deque,
* or returns <tt>null</tt> if this deque is empty.
*
* @return the head of this deque, or <tt>null</tt> if this deque is empty
*/
E peekFirst();
/**
* Retrieves, but does not remove, the last element of this deque,
* or returns <tt>null</tt> if this deque is empty.
*
* @return the tail of this deque, or <tt>null</tt> if this deque is empty
*/
E peekLast();
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>
* (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements (optional)
*/
boolean removeFirstOccurrence(Object o);
/**
* Removes the last occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the last element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>
* (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements (optional)
*/
boolean removeLastOccurrence(Object o);
// *** Queue methods ***
/**
* Inserts the specified element into the queue represented by this deque
* (in other words, at the tail of this deque) if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an
* <tt>IllegalStateException</tt> if no space is currently available.
* When using a capacity-restricted deque, it is generally preferable to
* use {@link #offer offer}.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean add(E e);
/**
* Inserts the specified element into the queue represented by this deque
* (in other words, at the tail of this deque) if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and <tt>false</tt> if no space is currently
* available. When using a capacity-restricted deque, this method is
* generally preferable to the {@link #add} method, which can fail to
* insert an element only by throwing an exception.
*
* <p>This method is equivalent to {@link #offerLast}.
*
* @param e the element to add
* @return <tt>true</tt> if the element was added to this deque, else
* <tt>false</tt>
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
boolean offer(E e);
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque).
* This method differs from {@link #poll poll} only in that it throws an
* exception if this deque is empty.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException if this deque is empty
*/
E remove();
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), or returns
* <tt>null</tt> if this deque is empty.
*
* <p>This method is equivalent to {@link #pollFirst()}.
*
* @return the first element of this deque, or <tt>null</tt> if
* this deque is empty
*/
E poll();
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque (in other words, the first element of this deque).
* This method differs from {@link #peek peek} only in that it throws an
* exception if this deque is empty.
*
* <p>This method is equivalent to {@link #getFirst()}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException if this deque is empty
*/
E element();
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque (in other words, the first element of this deque), or
* returns <tt>null</tt> if this deque is empty.
*
* <p>This method is equivalent to {@link #peekFirst()}.
*
* @return the head of the queue represented by this deque, or
* <tt>null</tt> if this deque is empty
*/
E peek();
// *** Stack methods ***
/**
* Pushes an element onto the stack represented by this deque (in other
* words, at the head of this deque) if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an
* <tt>IllegalStateException</tt> if no space is currently available.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this deque
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this deque
*/
void push(E e);
/**
* Pops an element from the stack represented by this deque. In other
* words, removes and returns the first element of this deque.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this deque (which is the top
* of the stack represented by this deque)
* @throws NoSuchElementException if this deque is empty
*/
E pop();
// *** Collection methods ***
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>
* (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* <p>This method is equivalent to {@link #removeFirstOccurrence}.
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the class of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements (optional)
*/
boolean remove(Object o);
/**
* Returns <tt>true</tt> if this deque contains the specified element.
* More formally, returns <tt>true</tt> if and only if this deque contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this deque is to be tested
* @return <tt>true</tt> if this deque contains the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this deque (optional)
* @throws NullPointerException if the specified element is null and this
* deque does not permit null elements (optional)
*/
boolean contains(Object o);
/**
* Returns the number of elements in this deque.
*
* @return the number of elements in this deque
*/
public int size();
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* @return an iterator over the elements in this deque in proper sequence
*/
Iterator<E> iterator();
/**
* Returns an iterator over the elements in this deque in reverse
* sequential order. The elements will be returned in order from
* last (tail) to first (head).
*
* @return an iterator over the elements in this deque in reverse
* sequence
*/
Iterator<E> descendingIterator();
}
| 22,370 | 39.235612 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/util/deque/LinkedBlockingDeque.java | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
/*
* This wasn't included until Android API level 9, so we're duplicating
* it here for backwards compatibility.
*/
package org.thoughtcrime.securesms.util.deque;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* An optionally-bounded {@linkplain BlockingDeque blocking deque} based on
* linked nodes.
*
* <p> The optional capacity bound constructor argument serves as a
* way to prevent excessive expansion. The capacity, if unspecified,
* is equal to {@link Integer#MAX_VALUE}. Linked nodes are
* dynamically created upon each insertion unless this would bring the
* deque above capacity.
*
* <p>Most operations run in constant time (ignoring time spent
* blocking). Exceptions include {@link #remove(Object) remove},
* {@link #removeFirstOccurrence removeFirstOccurrence}, {@link
* #removeLastOccurrence removeLastOccurrence}, {@link #contains
* contains}, {@link #iterator iterator.remove()}, and the bulk
* operations, all of which run in linear time.
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces.
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.6
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
public class LinkedBlockingDeque<E>
extends AbstractQueue<E>
implements BlockingDeque<E>, java.io.Serializable {
/*
* Implemented as a simple doubly-linked list protected by a
* single lock and using conditions to manage blocking.
*
* To implement weakly consistent iterators, it appears we need to
* keep all Nodes GC-reachable from a predecessor dequeued Node.
* That would cause two problems:
* - allow a rogue Iterator to cause unbounded memory retention
* - cause cross-generational linking of old Nodes to new Nodes if
* a Node was tenured while live, which generational GCs have a
* hard time dealing with, causing repeated major collections.
* However, only non-deleted Nodes need to be reachable from
* dequeued Nodes, and reachability does not necessarily have to
* be of the kind understood by the GC. We use the trick of
* linking a Node that has just been dequeued to itself. Such a
* self-link implicitly means to jump to "first" (for next links)
* or "last" (for prev links).
*/
/*
* We have "diamond" multiple interface/abstract class inheritance
* here, and that introduces ambiguities. Often we want the
* BlockingDeque javadoc combined with the AbstractQueue
* implementation, so a lot of method specs are duplicated here.
*/
private static final long serialVersionUID = -387911632671998426L;
/** Doubly-linked list node class */
static final class Node<E> {
/**
* The item, or null if this node has been removed.
*/
E item;
/**
* One of:
* - the real predecessor Node
* - this Node, meaning the predecessor is tail
* - null, meaning there is no predecessor
*/
Node<E> prev;
/**
* One of:
* - the real successor Node
* - this Node, meaning the successor is head
* - null, meaning there is no successor
*/
Node<E> next;
Node(E x) {
item = x;
}
}
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/** Number of items in the deque */
private transient int count;
/** Maximum number of items in the deque */
private final int capacity;
/** Main lock guarding all access */
final ReentrantLock lock = new ReentrantLock();
/** Condition for waiting takes */
private final Condition notEmpty = lock.newCondition();
/** Condition for waiting puts */
private final Condition notFull = lock.newCondition();
/**
* Creates a {@code LinkedBlockingDeque} with a capacity of
* {@link Integer#MAX_VALUE}.
*/
public LinkedBlockingDeque() {
this(Integer.MAX_VALUE);
}
/**
* Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
*
* @param capacity the capacity of this deque
* @throws IllegalArgumentException if {@code capacity} is less than 1
*/
public LinkedBlockingDeque(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
}
/**
* Creates a {@code LinkedBlockingDeque} with a capacity of
* {@link Integer#MAX_VALUE}, initially containing the elements of
* the given collection, added in traversal order of the
* collection's iterator.
*
* @param c the collection of elements to initially contain
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public LinkedBlockingDeque(Collection<? extends E> c) {
this(Integer.MAX_VALUE);
final ReentrantLock lock = this.lock;
lock.lock(); // Never contended, but necessary for visibility
try {
for (E e : c) {
if (e == null)
throw new NullPointerException();
if (!linkLast(new Node<E>(e)))
throw new IllegalStateException("Deque full");
}
} finally {
lock.unlock();
}
}
// Basic linking and unlinking operations, called only while holding lock
/**
* Links node as first element, or returns false if full.
*/
private boolean linkFirst(Node<E> node) {
// assert lock.isHeldByCurrentThread();
if (count >= capacity)
return false;
Node<E> f = first;
node.next = f;
first = node;
if (last == null)
last = node;
else
f.prev = node;
++count;
notEmpty.signal();
return true;
}
/**
* Links node as last element, or returns false if full.
*/
private boolean linkLast(Node<E> node) {
// assert lock.isHeldByCurrentThread();
if (count >= capacity)
return false;
Node<E> l = last;
node.prev = l;
last = node;
if (first == null)
first = node;
else
l.next = node;
++count;
notEmpty.signal();
return true;
}
/**
* Removes and returns first element, or null if empty.
*/
private E unlinkFirst() {
// assert lock.isHeldByCurrentThread();
Node<E> f = first;
if (f == null)
return null;
Node<E> n = f.next;
E item = f.item;
f.item = null;
f.next = f; // help GC
first = n;
if (n == null)
last = null;
else
n.prev = null;
--count;
notFull.signal();
return item;
}
/**
* Removes and returns last element, or null if empty.
*/
private E unlinkLast() {
// assert lock.isHeldByCurrentThread();
Node<E> l = last;
if (l == null)
return null;
Node<E> p = l.prev;
E item = l.item;
l.item = null;
l.prev = l; // help GC
last = p;
if (p == null)
first = null;
else
p.next = null;
--count;
notFull.signal();
return item;
}
/**
* Unlinks x.
*/
void unlink(Node<E> x) {
// assert lock.isHeldByCurrentThread();
Node<E> p = x.prev;
Node<E> n = x.next;
if (p == null) {
unlinkFirst();
} else if (n == null) {
unlinkLast();
} else {
p.next = n;
n.prev = p;
x.item = null;
// Don't mess with x's links. They may still be in use by
// an iterator.
--count;
notFull.signal();
}
}
// BlockingDeque methods
/**
* @throws IllegalStateException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void addFirst(E e) {
if (!offerFirst(e))
throw new IllegalStateException("Deque full");
}
/**
* @throws IllegalStateException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void addLast(E e) {
if (!offerLast(e))
throw new IllegalStateException("Deque full");
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public boolean offerFirst(E e) {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
return linkFirst(node);
} finally {
lock.unlock();
}
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public boolean offerLast(E e) {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
return linkLast(node);
} finally {
lock.unlock();
}
}
/**
* @throws NullPointerException {@inheritDoc}
* @throws InterruptedException {@inheritDoc}
*/
public void putFirst(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
while (!linkFirst(node))
notFull.await();
} finally {
lock.unlock();
}
}
/**
* @throws NullPointerException {@inheritDoc}
* @throws InterruptedException {@inheritDoc}
*/
public void putLast(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
while (!linkLast(node))
notFull.await();
} finally {
lock.unlock();
}
}
/**
* @throws NullPointerException {@inheritDoc}
* @throws InterruptedException {@inheritDoc}
*/
public boolean offerFirst(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (!linkFirst(node)) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
return true;
} finally {
lock.unlock();
}
}
/**
* @throws NullPointerException {@inheritDoc}
* @throws InterruptedException {@inheritDoc}
*/
public boolean offerLast(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (!linkLast(node)) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
return true;
} finally {
lock.unlock();
}
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeFirst() {
E x = pollFirst();
if (x == null) throw new NoSuchElementException();
return x;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeLast() {
E x = pollLast();
if (x == null) throw new NoSuchElementException();
return x;
}
public E pollFirst() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return unlinkFirst();
} finally {
lock.unlock();
}
}
public E pollLast() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return unlinkLast();
} finally {
lock.unlock();
}
}
public E takeFirst() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
E x;
while ( (x = unlinkFirst()) == null)
notEmpty.await();
return x;
} finally {
lock.unlock();
}
}
public E takeLast() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
E x;
while ( (x = unlinkLast()) == null)
notEmpty.await();
return x;
} finally {
lock.unlock();
}
}
public E pollFirst(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
E x;
while ( (x = unlinkFirst()) == null) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
return x;
} finally {
lock.unlock();
}
}
public E pollLast(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
E x;
while ( (x = unlinkLast()) == null) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
return x;
} finally {
lock.unlock();
}
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
E x = peekFirst();
if (x == null) throw new NoSuchElementException();
return x;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getLast() {
E x = peekLast();
if (x == null) throw new NoSuchElementException();
return x;
}
public E peekFirst() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (first == null) ? null : first.item;
} finally {
lock.unlock();
}
}
public E peekLast() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (last == null) ? null : last.item;
} finally {
lock.unlock();
}
}
public boolean removeFirstOccurrence(Object o) {
if (o == null) return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node<E> p = first; p != null; p = p.next) {
if (o.equals(p.item)) {
unlink(p);
return true;
}
}
return false;
} finally {
lock.unlock();
}
}
public boolean removeLastOccurrence(Object o) {
if (o == null) return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node<E> p = last; p != null; p = p.prev) {
if (o.equals(p.item)) {
unlink(p);
return true;
}
}
return false;
} finally {
lock.unlock();
}
}
// BlockingQueue methods
/**
* Inserts the specified element at the end of this deque unless it would
* violate capacity restrictions. When using a capacity-restricted deque,
* it is generally preferable to use method {@link #offer offer}.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws NullPointerException if the specified element is null
*/
@Override
public boolean add(E e) {
addLast(e);
return true;
}
/**
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* @throws NullPointerException {@inheritDoc}
* @throws InterruptedException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
putLast(e);
}
/**
* @throws NullPointerException {@inheritDoc}
* @throws InterruptedException {@inheritDoc}
*/
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
return offerLast(e, timeout, unit);
}
/**
* Retrieves and removes the head of the queue represented by this deque.
* This method differs from {@link #poll poll} only in that it throws an
* exception if this deque is empty.
*
* <p>This method is equivalent to {@link #removeFirst() removeFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException if this deque is empty
*/
@Override
public E remove() {
return removeFirst();
}
public E poll() {
return pollFirst();
}
public E take() throws InterruptedException {
return takeFirst();
}
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
return pollFirst(timeout, unit);
}
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque. This method differs from {@link #peek peek} only in that
* it throws an exception if this deque is empty.
*
* <p>This method is equivalent to {@link #getFirst() getFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException if this deque is empty
*/
@Override
public E element() {
return getFirst();
}
public E peek() {
return peekFirst();
}
/**
* Returns the number of additional elements that this deque can ideally
* (in the absence of memory or resource constraints) accept without
* blocking. This is always equal to the initial capacity of this deque
* less the current {@code size} of this deque.
*
* <p>Note that you <em>cannot</em> always tell if an attempt to insert
* an element will succeed by inspecting {@code remainingCapacity}
* because it may be the case that another thread is about to
* insert or remove an element.
*/
public int remainingCapacity() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return capacity - count;
} finally {
lock.unlock();
}
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public int drainTo(Collection<? super E> c) {
return drainTo(c, Integer.MAX_VALUE);
}
/**
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public int drainTo(Collection<? super E> c, int maxElements) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
final ReentrantLock lock = this.lock;
lock.lock();
try {
int n = Math.min(maxElements, count);
for (int i = 0; i < n; i++) {
c.add(first.item); // In this order, in case add() throws.
unlinkFirst();
}
return n;
} finally {
lock.unlock();
}
}
// Stack methods
/**
* @throws IllegalStateException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void push(E e) {
addFirst(e);
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E pop() {
return removeFirst();
}
// Collection methods
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element {@code e} such that
* {@code o.equals(e)} (if such an element exists).
* Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* <p>This method is equivalent to
* {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if this deque changed as a result of the call
*/
@Override
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* Returns the number of elements in this deque.
*
* @return the number of elements in this deque
*/
@Override
public int size() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
/**
* Returns {@code true} if this deque contains the specified element.
* More formally, returns {@code true} if and only if this deque contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this deque
* @return {@code true} if this deque contains the specified element
*/
@Override
public boolean contains(Object o) {
if (o == null) return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node<E> p = first; p != null; p = p.next)
if (o.equals(p.item))
return true;
return false;
} finally {
lock.unlock();
}
}
/*
* TODO: Add support for more efficient bulk operations.
*
* We don't want to acquire the lock for every iteration, but we
* also want other threads a chance to interact with the
* collection, especially when count is close to capacity.
*/
// /**
// * Adds all of the elements in the specified collection to this
// * queue. Attempts to addAll of a queue to itself result in
// * {@code IllegalArgumentException}. Further, the behavior of
// * this operation is undefined if the specified collection is
// * modified while the operation is in progress.
// *
// * @param c collection containing elements to be added to this queue
// * @return {@code true} if this queue changed as a result of the call
// * @throws ClassCastException {@inheritDoc}
// * @throws NullPointerException {@inheritDoc}
// * @throws IllegalArgumentException {@inheritDoc}
// * @throws IllegalStateException {@inheritDoc}
// * @see #add(Object)
// */
// public boolean addAll(Collection<? extends E> c) {
// if (c == null)
// throw new NullPointerException();
// if (c == this)
// throw new IllegalArgumentException();
// final ReentrantLock lock = this.lock;
// lock.lock();
// try {
// boolean modified = false;
// for (E e : c)
// if (linkLast(e))
// modified = true;
// return modified;
// } finally {
// lock.unlock();
// }
// }
/**
* Returns an array containing all of the elements in this deque, in
* proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this deque. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this deque
*/
@Override
@SuppressWarnings("unchecked")
public Object[] toArray() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] a = new Object[count];
int k = 0;
for (Node<E> p = first; p != null; p = p.next)
a[k++] = p.item;
return a;
} finally {
lock.unlock();
}
}
/**
* Returns an array containing all of the elements in this deque, in
* proper sequence; the runtime type of the returned array is that of
* the specified array. If the deque fits in the specified array, it
* is returned therein. Otherwise, a new array is allocated with the
* runtime type of the specified array and the size of this deque.
*
* <p>If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
* {@code null}.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose {@code x} is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
* allocated array of {@code String}:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the deque are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this deque
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this deque
* @throws NullPointerException if the specified array is null
*/
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (a.length < count)
a = (T[])java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), count);
int k = 0;
for (Node<E> p = first; p != null; p = p.next)
a[k++] = (T)p.item;
if (a.length > k)
a[k] = null;
return a;
} finally {
lock.unlock();
}
}
@Override
public String toString() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Node<E> p = first;
if (p == null)
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = p.item;
sb.append(e == this ? "(this Collection)" : e);
p = p.next;
if (p == null)
return sb.append(']').toString();
sb.append(',').append(' ');
}
} finally {
lock.unlock();
}
}
/**
* Atomically removes all of the elements from this deque.
* The deque will be empty after this call returns.
*/
@Override
public void clear() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node<E> f = first; f != null; ) {
f.item = null;
Node<E> n = f.next;
f.prev = null;
f.next = null;
f = n;
}
first = last = null;
count = 0;
notFull.signalAll();
} finally {
lock.unlock();
}
}
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* <p>The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this deque in proper sequence
*/
@Override
public Iterator<E> iterator() {
return new Itr();
}
/**
* Returns an iterator over the elements in this deque in reverse
* sequential order. The elements will be returned in order from
* last (tail) to first (head).
*
* <p>The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this deque in reverse order
*/
public Iterator<E> descendingIterator() {
return new DescendingItr();
}
/**
* Base class for Iterators for LinkedBlockingDeque
*/
private abstract class AbstractItr implements Iterator<E> {
/**
* The next node to return in next()
*/
Node<E> next;
/**
* nextItem holds on to item fields because once we claim that
* an element exists in hasNext(), we must return item read
* under lock (in advance()) even if it was in the process of
* being removed when hasNext() was called.
*/
E nextItem;
/**
* Node returned by most recent call to next. Needed by remove.
* Reset to null if this element is deleted by a call to remove.
*/
private Node<E> lastRet;
abstract Node<E> firstNode();
abstract Node<E> nextNode(Node<E> n);
AbstractItr() {
// set to initial position
final ReentrantLock lock = LinkedBlockingDeque.this.lock;
lock.lock();
try {
next = firstNode();
nextItem = (next == null) ? null : next.item;
} finally {
lock.unlock();
}
}
/**
* Returns the successor node of the given non-null, but
* possibly previously deleted, node.
*/
private Node<E> succ(Node<E> n) {
// Chains of deleted nodes ending in null or self-links
// are possible if multiple interior nodes are removed.
for (;;) {
Node<E> s = nextNode(n);
if (s == null)
return null;
else if (s.item != null)
return s;
else if (s == n)
return firstNode();
else
n = s;
}
}
/**
* Advances next.
*/
void advance() {
final ReentrantLock lock = LinkedBlockingDeque.this.lock;
lock.lock();
try {
// assert next != null;
next = succ(next);
nextItem = (next == null) ? null : next.item;
} finally {
lock.unlock();
}
}
public boolean hasNext() {
return next != null;
}
public E next() {
if (next == null)
throw new NoSuchElementException();
lastRet = next;
E x = nextItem;
advance();
return x;
}
public void remove() {
Node<E> n = lastRet;
if (n == null)
throw new IllegalStateException();
lastRet = null;
final ReentrantLock lock = LinkedBlockingDeque.this.lock;
lock.lock();
try {
if (n.item != null)
unlink(n);
} finally {
lock.unlock();
}
}
}
/** Forward iterator */
private class Itr extends AbstractItr {
@Override
Node<E> firstNode() { return first; }
@Override
Node<E> nextNode(Node<E> n) { return n.next; }
}
/** Descending iterator */
private class DescendingItr extends AbstractItr {
@Override
Node<E> firstNode() { return last; }
@Override
Node<E> nextNode(Node<E> n) { return n.prev; }
}
/**
* Save the state of this deque to a stream (that is, serialize it).
*
* @serialData The capacity (int), followed by elements (each an
* {@code Object}) in the proper order, followed by a null
* @param s the stream
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
// Write out capacity and any hidden stuff
s.defaultWriteObject();
// Write out all elements in the proper order.
for (Node<E> p = first; p != null; p = p.next)
s.writeObject(p.item);
// Use trailing null as sentinel
s.writeObject(null);
} finally {
lock.unlock();
}
}
/**
* Reconstitute this deque from a stream (that is,
* deserialize it).
* @param s the stream
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
count = 0;
first = null;
last = null;
// Read in all elements and place in queue
for (;;) {
@SuppressWarnings("unchecked")
E item = (E)s.readObject();
if (item == null)
break;
add(item);
}
}
}
| 36,114 | 29.323258 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/ContentType.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms;
import java.util.ArrayList;
public class ContentType {
public static final String MMS_MESSAGE = "application/vnd.wap.mms-message";
// The phony content type for generic PDUs (e.g. ReadOrig.ind,
// Notification.ind, Delivery.ind).
public static final String MMS_GENERIC = "application/vnd.wap.mms-generic";
public static final String MULTIPART_MIXED = "application/vnd.wap.multipart.mixed";
public static final String MULTIPART_RELATED = "application/vnd.wap.multipart.related";
public static final String MULTIPART_ALTERNATIVE = "application/vnd.wap.multipart.alternative";
public static final String TEXT_PLAIN = "text/plain";
public static final String TEXT_HTML = "text/html";
public static final String TEXT_VCALENDAR = "text/x-vCalendar";
public static final String TEXT_VCARD = "text/x-vCard";
public static final String IMAGE_UNSPECIFIED = "image/*";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_JPG = "image/jpg";
public static final String IMAGE_GIF = "image/gif";
public static final String IMAGE_WBMP = "image/vnd.wap.wbmp";
public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_X_MS_BMP = "image/x-ms-bmp";
public static final String AUDIO_UNSPECIFIED = "audio/*";
public static final String AUDIO_AAC = "audio/aac";
public static final String AUDIO_AMR = "audio/amr";
public static final String AUDIO_IMELODY = "audio/imelody";
public static final String AUDIO_MID = "audio/mid";
public static final String AUDIO_MIDI = "audio/midi";
public static final String AUDIO_MP3 = "audio/mp3";
public static final String AUDIO_MPEG3 = "audio/mpeg3";
public static final String AUDIO_MPEG = "audio/mpeg";
public static final String AUDIO_MPG = "audio/mpg";
public static final String AUDIO_MP4 = "audio/mp4";
public static final String AUDIO_X_MID = "audio/x-mid";
public static final String AUDIO_X_MIDI = "audio/x-midi";
public static final String AUDIO_X_MP3 = "audio/x-mp3";
public static final String AUDIO_X_MPEG3 = "audio/x-mpeg3";
public static final String AUDIO_X_MPEG = "audio/x-mpeg";
public static final String AUDIO_X_MPG = "audio/x-mpg";
public static final String AUDIO_3GPP = "audio/3gpp";
public static final String AUDIO_X_WAV = "audio/x-wav";
public static final String AUDIO_OGG = "application/ogg";
public static final String VIDEO_UNSPECIFIED = "video/*";
public static final String VIDEO_3GPP = "video/3gpp";
public static final String VIDEO_3G2 = "video/3gpp2";
public static final String VIDEO_H263 = "video/h263";
public static final String VIDEO_MP4 = "video/mp4";
public static final String APP_SMIL = "application/smil";
public static final String APP_WAP_XHTML = "application/vnd.wap.xhtml+xml";
public static final String APP_XHTML = "application/xhtml+xml";
public static final String APP_DRM_CONTENT = "application/vnd.oma.drm.content";
public static final String APP_DRM_MESSAGE = "application/vnd.oma.drm.message";
private static final ArrayList<String> sSupportedContentTypes = new ArrayList<String>();
private static final ArrayList<String> sSupportedImageTypes = new ArrayList<String>();
private static final ArrayList<String> sSupportedAudioTypes = new ArrayList<String>();
private static final ArrayList<String> sSupportedVideoTypes = new ArrayList<String>();
static {
sSupportedContentTypes.add(TEXT_PLAIN);
sSupportedContentTypes.add(TEXT_HTML);
sSupportedContentTypes.add(TEXT_VCALENDAR);
sSupportedContentTypes.add(TEXT_VCARD);
sSupportedContentTypes.add(IMAGE_JPEG);
sSupportedContentTypes.add(IMAGE_GIF);
sSupportedContentTypes.add(IMAGE_WBMP);
sSupportedContentTypes.add(IMAGE_PNG);
sSupportedContentTypes.add(IMAGE_JPG);
sSupportedContentTypes.add(IMAGE_X_MS_BMP);
//supportedContentTypes.add(IMAGE_SVG); not yet supported.
sSupportedContentTypes.add(AUDIO_AAC);
sSupportedContentTypes.add(AUDIO_AMR);
sSupportedContentTypes.add(AUDIO_IMELODY);
sSupportedContentTypes.add(AUDIO_MID);
sSupportedContentTypes.add(AUDIO_MIDI);
sSupportedContentTypes.add(AUDIO_MP3);
sSupportedContentTypes.add(AUDIO_MPEG3);
sSupportedContentTypes.add(AUDIO_MPEG);
sSupportedContentTypes.add(AUDIO_MPG);
sSupportedContentTypes.add(AUDIO_X_MID);
sSupportedContentTypes.add(AUDIO_X_MIDI);
sSupportedContentTypes.add(AUDIO_X_MP3);
sSupportedContentTypes.add(AUDIO_X_MPEG3);
sSupportedContentTypes.add(AUDIO_X_MPEG);
sSupportedContentTypes.add(AUDIO_X_MPG);
sSupportedContentTypes.add(AUDIO_X_WAV);
sSupportedContentTypes.add(AUDIO_3GPP);
sSupportedContentTypes.add(AUDIO_OGG);
sSupportedContentTypes.add(VIDEO_3GPP);
sSupportedContentTypes.add(VIDEO_3G2);
sSupportedContentTypes.add(VIDEO_H263);
sSupportedContentTypes.add(VIDEO_MP4);
sSupportedContentTypes.add(APP_SMIL);
sSupportedContentTypes.add(APP_WAP_XHTML);
sSupportedContentTypes.add(APP_XHTML);
sSupportedContentTypes.add(APP_DRM_CONTENT);
sSupportedContentTypes.add(APP_DRM_MESSAGE);
// add supported image types
sSupportedImageTypes.add(IMAGE_JPEG);
sSupportedImageTypes.add(IMAGE_GIF);
sSupportedImageTypes.add(IMAGE_WBMP);
sSupportedImageTypes.add(IMAGE_PNG);
sSupportedImageTypes.add(IMAGE_JPG);
sSupportedImageTypes.add(IMAGE_X_MS_BMP);
// add supported audio types
sSupportedAudioTypes.add(AUDIO_AAC);
sSupportedAudioTypes.add(AUDIO_AMR);
sSupportedAudioTypes.add(AUDIO_IMELODY);
sSupportedAudioTypes.add(AUDIO_MID);
sSupportedAudioTypes.add(AUDIO_MIDI);
sSupportedAudioTypes.add(AUDIO_MP3);
sSupportedAudioTypes.add(AUDIO_MPEG3);
sSupportedAudioTypes.add(AUDIO_MPEG);
sSupportedAudioTypes.add(AUDIO_MPG);
sSupportedAudioTypes.add(AUDIO_MP4);
sSupportedAudioTypes.add(AUDIO_X_MID);
sSupportedAudioTypes.add(AUDIO_X_MIDI);
sSupportedAudioTypes.add(AUDIO_X_MP3);
sSupportedAudioTypes.add(AUDIO_X_MPEG3);
sSupportedAudioTypes.add(AUDIO_X_MPEG);
sSupportedAudioTypes.add(AUDIO_X_MPG);
sSupportedAudioTypes.add(AUDIO_X_WAV);
sSupportedAudioTypes.add(AUDIO_3GPP);
sSupportedAudioTypes.add(AUDIO_OGG);
// add supported video types
sSupportedVideoTypes.add(VIDEO_3GPP);
sSupportedVideoTypes.add(VIDEO_3G2);
sSupportedVideoTypes.add(VIDEO_H263);
sSupportedVideoTypes.add(VIDEO_MP4);
}
// This class should never be instantiated.
private ContentType() {
}
public static boolean isSupportedType(String contentType) {
return (null != contentType) && sSupportedContentTypes.contains(contentType);
}
public static boolean isSupportedImageType(String contentType) {
return isImageType(contentType) && isSupportedType(contentType);
}
public static boolean isSupportedAudioType(String contentType) {
return isAudioType(contentType) && isSupportedType(contentType);
}
public static boolean isSupportedVideoType(String contentType) {
return isVideoType(contentType) && isSupportedType(contentType);
}
public static boolean isTextType(String contentType) {
return (null != contentType) && contentType.startsWith("text/");
}
public static boolean isImageType(String contentType) {
return (null != contentType) && contentType.startsWith("image/");
}
public static boolean isAudioType(String contentType) {
return (null != contentType) && contentType.startsWith("audio/");
}
public static boolean isVideoType(String contentType) {
return (null != contentType) && contentType.startsWith("video/");
}
public static boolean isDrmType(String contentType) {
return (null != contentType)
&& (contentType.equals(APP_DRM_CONTENT)
|| contentType.equals(APP_DRM_MESSAGE));
}
public static boolean isUnspecified(String contentType) {
return (null != contentType) && contentType.endsWith("*");
}
@SuppressWarnings("unchecked")
public static ArrayList<String> getImageTypes() {
return (ArrayList<String>) sSupportedImageTypes.clone();
}
@SuppressWarnings("unchecked")
public static ArrayList<String> getAudioTypes() {
return (ArrayList<String>) sSupportedAudioTypes.clone();
}
@SuppressWarnings("unchecked")
public static ArrayList<String> getVideoTypes() {
return (ArrayList<String>) sSupportedVideoTypes.clone();
}
@SuppressWarnings("unchecked")
public static ArrayList<String> getSupportedTypes() {
return (ArrayList<String>) sSupportedContentTypes.clone();
}
}
| 10,060 | 42.743478 | 99 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/InvalidHeaderValueException.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms;
/**
* Thrown when an invalid header value was set.
*/
public class InvalidHeaderValueException extends MmsException {
private static final long serialVersionUID = -2053384496042052262L;
/**
* Constructs an InvalidHeaderValueException with no detailed message.
*/
public InvalidHeaderValueException() {
super();
}
/**
* Constructs an InvalidHeaderValueException with the specified detailed message.
*
* @param message the detailed message.
*/
public InvalidHeaderValueException(String message) {
super(message);
}
}
| 1,285 | 29.619048 | 85 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/MmsException.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms;
/**
* A generic exception that is thrown by the Mms client.
*/
public class MmsException extends Exception {
private static final long serialVersionUID = -7323249827281485390L;
/**
* Creates a new MmsException.
*/
public MmsException() {
super();
}
/**
* Creates a new MmsException with the specified detail message.
*
* @param message the detail message.
*/
public MmsException(String message) {
super(message);
}
/**
* Creates a new MmsException with the specified cause.
*
* @param cause the cause.
*/
public MmsException(Throwable cause) {
super(cause);
}
/**
* Creates a new MmsException with the specified detail message and cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public MmsException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,645 | 25.983607 | 78 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/AcknowledgeInd.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
/**
* M-Acknowledge.ind PDU.
*/
public class AcknowledgeInd extends GenericPdu {
/**
* Constructor, used when composing a M-Acknowledge.ind pdu.
*
* @param mmsVersion current viersion of mms
* @param transactionId the transaction-id value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if transactionId is null.
*/
public AcknowledgeInd(int mmsVersion, byte[] transactionId)
throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND);
setMmsVersion(mmsVersion);
setTransactionId(transactionId);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
AcknowledgeInd(PduHeaders headers) {
super(headers);
}
/**
* Get X-Mms-Report-Allowed field value.
*
* @return the X-Mms-Report-Allowed value
*/
public int getReportAllowed() {
return mPduHeaders.getOctet(PduHeaders.REPORT_ALLOWED);
}
/**
* Set X-Mms-Report-Allowed field value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReportAllowed(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.REPORT_ALLOWED);
}
/**
* Get X-Mms-Transaction-Id field value.
*
* @return the X-Mms-Report-Allowed value
*/
public byte[] getTransactionId() {
return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID);
}
/**
* Set X-Mms-Transaction-Id field value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTransactionId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID);
}
}
| 2,671 | 28.688889 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/Base64.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
public class Base64 {
/**
* Used to get the number of Quadruples.
*/
static final int FOURBYTE = 4;
/**
* Byte used to pad output.
*/
static final byte PAD = (byte) '=';
/**
* The base length.
*/
static final int BASELENGTH = 255;
// Create arrays to hold the base64 characters
private static byte[] base64Alphabet = new byte[BASELENGTH];
// Populating the character arrays
static {
for (int i = 0; i < BASELENGTH; i++) {
base64Alphabet[i] = (byte) -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
}
/**
* Decodes Base64 data into octects
*
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
// RFC 2045 requires that we discard ALL non-Base64 characters
base64Data = discardNonBase64(base64Data);
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0) {
return new byte[0];
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex = 0;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD) {
if (--lastData == 0) {
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++) {
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD) {
//No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
} else if (marker0 == PAD) {
//Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
} else if (marker1 == PAD) {
//One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
/**
* Check octect wheter it is a base64 encoding.
*
* @param octect to be checked byte
* @return ture if it is base64 encoding, false otherwise.
*/
private static boolean isBase64(byte octect) {
if (octect == PAD) {
return true;
} else if (base64Alphabet[octect] == -1) {
return false;
} else {
return true;
}
}
/**
* Discards any characters outside of the base64 alphabet, per
* the requirements on page 25 of RFC 2045 - "Any characters
* outside of the base64 alphabet are to be ignored in base64
* encoded data."
*
* @param data The base-64 encoded data to groom
* @return The data, less non-base64 characters (see RFC 2045).
*/
static byte[] discardNonBase64(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (int i = 0; i < data.length; i++) {
if (isBase64(data[i])) {
groomedData[bytesCopied++] = data[i];
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
}
| 5,356 | 30.886905 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/CharacterSets.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
public class CharacterSets {
/**
* IANA assigned MIB enum numbers.
*
* From wap-230-wsp-20010705-a.pdf
* Any-charset = <Octet 128>
* Equivalent to the special RFC2616 charset value "*"
*/
public static final int ANY_CHARSET = 0x00;
public static final int US_ASCII = 0x03;
public static final int ISO_8859_1 = 0x04;
public static final int ISO_8859_2 = 0x05;
public static final int ISO_8859_3 = 0x06;
public static final int ISO_8859_4 = 0x07;
public static final int ISO_8859_5 = 0x08;
public static final int ISO_8859_6 = 0x09;
public static final int ISO_8859_7 = 0x0A;
public static final int ISO_8859_8 = 0x0B;
public static final int ISO_8859_9 = 0x0C;
public static final int SHIFT_JIS = 0x11;
public static final int UTF_8 = 0x6A;
public static final int BIG5 = 0x07EA;
public static final int UCS2 = 0x03E8;
public static final int UTF_16 = 0x03F7;
/**
* If the encoding of given data is unsupported, use UTF_8 to decode it.
*/
public static final int DEFAULT_CHARSET = UTF_8;
/**
* Array of MIB enum numbers.
*/
private static final int[] MIBENUM_NUMBERS = {
ANY_CHARSET,
US_ASCII,
ISO_8859_1,
ISO_8859_2,
ISO_8859_3,
ISO_8859_4,
ISO_8859_5,
ISO_8859_6,
ISO_8859_7,
ISO_8859_8,
ISO_8859_9,
SHIFT_JIS,
UTF_8,
BIG5,
UCS2,
UTF_16,
};
/**
* The Well-known-charset Mime name.
*/
public static final String MIMENAME_ANY_CHARSET = "*";
public static final String MIMENAME_US_ASCII = "us-ascii";
public static final String MIMENAME_ISO_8859_1 = "iso-8859-1";
public static final String MIMENAME_ISO_8859_2 = "iso-8859-2";
public static final String MIMENAME_ISO_8859_3 = "iso-8859-3";
public static final String MIMENAME_ISO_8859_4 = "iso-8859-4";
public static final String MIMENAME_ISO_8859_5 = "iso-8859-5";
public static final String MIMENAME_ISO_8859_6 = "iso-8859-6";
public static final String MIMENAME_ISO_8859_7 = "iso-8859-7";
public static final String MIMENAME_ISO_8859_8 = "iso-8859-8";
public static final String MIMENAME_ISO_8859_9 = "iso-8859-9";
public static final String MIMENAME_SHIFT_JIS = "shift_JIS";
public static final String MIMENAME_UTF_8 = "utf-8";
public static final String MIMENAME_BIG5 = "big5";
public static final String MIMENAME_UCS2 = "iso-10646-ucs-2";
public static final String MIMENAME_UTF_16 = "utf-16";
public static final String DEFAULT_CHARSET_NAME = MIMENAME_UTF_8;
/**
* Array of the names of character sets.
*/
private static final String[] MIME_NAMES = {
MIMENAME_ANY_CHARSET,
MIMENAME_US_ASCII,
MIMENAME_ISO_8859_1,
MIMENAME_ISO_8859_2,
MIMENAME_ISO_8859_3,
MIMENAME_ISO_8859_4,
MIMENAME_ISO_8859_5,
MIMENAME_ISO_8859_6,
MIMENAME_ISO_8859_7,
MIMENAME_ISO_8859_8,
MIMENAME_ISO_8859_9,
MIMENAME_SHIFT_JIS,
MIMENAME_UTF_8,
MIMENAME_BIG5,
MIMENAME_UCS2,
MIMENAME_UTF_16,
};
private static final HashMap<Integer, String> MIBENUM_TO_NAME_MAP;
private static final HashMap<String, Integer> NAME_TO_MIBENUM_MAP;
static {
// Create the HashMaps.
MIBENUM_TO_NAME_MAP = new HashMap<Integer, String>();
NAME_TO_MIBENUM_MAP = new HashMap<String, Integer>();
assert(MIBENUM_NUMBERS.length == MIME_NAMES.length);
int count = MIBENUM_NUMBERS.length - 1;
for(int i = 0; i <= count; i++) {
MIBENUM_TO_NAME_MAP.put(MIBENUM_NUMBERS[i], MIME_NAMES[i]);
NAME_TO_MIBENUM_MAP.put(MIME_NAMES[i], MIBENUM_NUMBERS[i]);
}
}
private CharacterSets() {} // Non-instantiatable
/**
* Map an MIBEnum number to the name of the charset which this number
* is assigned to by IANA.
*
* @param mibEnumValue An IANA assigned MIBEnum number.
* @return The name string of the charset.
* @throws UnsupportedEncodingException
*/
public static String getMimeName(int mibEnumValue)
throws UnsupportedEncodingException {
String name = MIBENUM_TO_NAME_MAP.get(mibEnumValue);
if (name == null) {
throw new UnsupportedEncodingException();
}
return name;
}
/**
* Map a well-known charset name to its assigned MIBEnum number.
*
* @param mimeName The charset name.
* @return The MIBEnum number assigned by IANA for this charset.
* @throws UnsupportedEncodingException
*/
public static int getMibEnumValue(String mimeName)
throws UnsupportedEncodingException {
if(null == mimeName) {
return -1;
}
Integer mibEnumValue = NAME_TO_MIBENUM_MAP.get(mimeName);
if (mibEnumValue == null) {
throw new UnsupportedEncodingException();
}
return mibEnumValue;
}
}
| 5,934 | 33.306358 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/DeliveryInd.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
/**
* M-Delivery.Ind Pdu.
*/
public class DeliveryInd extends GenericPdu {
/**
* Empty constructor.
* Since the Pdu corresponding to this class is constructed
* by the Proxy-Relay server, this class is only instantiated
* by the Pdu Parser.
*
* @throws InvalidHeaderValueException if error occurs.
*/
public DeliveryInd() throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_DELIVERY_IND);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
DeliveryInd(PduHeaders headers) {
super(headers);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value, should not be null
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get Status value.
*
* @return the value
*/
public int getStatus() {
return mPduHeaders.getOctet(PduHeaders.STATUS);
}
/**
* Set Status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.STATUS);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* set To value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*
* public EncodedStringValue getStatusText() {return null;}
* public void setStatusText(EncodedStringValue value) {}
*/
}
| 3,680 | 25.482014 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/EncodedStringValue.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import android.util.Config;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
/**
* Encoded-string-value = Text-string | Value-length Char-set Text-string
*/
public class EncodedStringValue implements Cloneable {
private static final String TAG = "EncodedStringValue";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
/**
* The Char-set value.
*/
private int mCharacterSet;
/**
* The Text-string value.
*/
private byte[] mData;
/**
* Constructor.
*
* @param charset the Char-set value
* @param data the Text-string value
* @throws NullPointerException if Text-string value is null.
*/
public EncodedStringValue(int charset, byte[] data) {
// TODO: CharSet needs to be validated against MIBEnum.
if(null == data) {
throw new NullPointerException("EncodedStringValue: Text-string is null.");
}
mCharacterSet = charset;
mData = new byte[data.length];
System.arraycopy(data, 0, mData, 0, data.length);
}
/**
* Constructor.
*
* @param data the Text-string value
* @throws NullPointerException if Text-string value is null.
*/
public EncodedStringValue(byte[] data) {
this(CharacterSets.DEFAULT_CHARSET, data);
}
public EncodedStringValue(String data) {
try {
mData = data.getBytes(CharacterSets.DEFAULT_CHARSET_NAME);
mCharacterSet = CharacterSets.DEFAULT_CHARSET;
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Default encoding must be supported.", e);
}
}
/**
* Get Char-set value.
*
* @return the value
*/
public int getCharacterSet() {
return mCharacterSet;
}
/**
* Set Char-set value.
*
* @param charset the Char-set value
*/
public void setCharacterSet(int charset) {
// TODO: CharSet needs to be validated against MIBEnum.
mCharacterSet = charset;
}
/**
* Get Text-string value.
*
* @return the value
*/
public byte[] getTextString() {
byte[] byteArray = new byte[mData.length];
System.arraycopy(mData, 0, byteArray, 0, mData.length);
return byteArray;
}
/**
* Set Text-string value.
*
* @param textString the Text-string value
* @throws NullPointerException if Text-string value is null.
*/
public void setTextString(byte[] textString) {
if(null == textString) {
throw new NullPointerException("EncodedStringValue: Text-string is null.");
}
mData = new byte[textString.length];
System.arraycopy(textString, 0, mData, 0, textString.length);
}
/**
* Convert this object to a {@link java.lang.String}. If the encoding of
* the EncodedStringValue is null or unsupported, it will be
* treated as iso-8859-1 encoding.
*
* @return The decoded String.
*/
public String getString() {
if (CharacterSets.ANY_CHARSET == mCharacterSet) {
return new String(mData); // system default encoding.
} else {
try {
String name = CharacterSets.getMimeName(mCharacterSet);
return new String(mData, name);
} catch (UnsupportedEncodingException e) {
if (LOCAL_LOGV) {
Log.v(TAG, e.getMessage(), e);
}
try {
return new String(mData, CharacterSets.MIMENAME_ISO_8859_1);
} catch (UnsupportedEncodingException _) {
return new String(mData); // system default encoding.
}
}
}
}
/**
* Append to Text-string.
*
* @param textString the textString to append
* @throws NullPointerException if the text String is null
* or an IOException occured.
*/
public void appendTextString(byte[] textString) {
if(null == textString) {
throw new NullPointerException("Text-string is null.");
}
if(null == mData) {
mData = new byte[textString.length];
System.arraycopy(textString, 0, mData, 0, textString.length);
} else {
ByteArrayOutputStream newTextString = new ByteArrayOutputStream();
try {
newTextString.write(mData);
newTextString.write(textString);
} catch (IOException e) {
e.printStackTrace();
throw new NullPointerException(
"appendTextString: failed when write a new Text-string");
}
mData = newTextString.toByteArray();
}
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public Object clone() throws CloneNotSupportedException {
super.clone();
int len = mData.length;
byte[] dstBytes = new byte[len];
System.arraycopy(mData, 0, dstBytes, 0, len);
try {
return new EncodedStringValue(mCharacterSet, dstBytes);
} catch (Exception e) {
Log.e(TAG, "failed to clone an EncodedStringValue: " + this);
e.printStackTrace();
throw new CloneNotSupportedException(e.getMessage());
}
}
/**
* Split this encoded string around matches of the given pattern.
*
* @param pattern the delimiting pattern
* @return the array of encoded strings computed by splitting this encoded
* string around matches of the given pattern
*/
public EncodedStringValue[] split(String pattern) {
String[] temp = getString().split(pattern);
EncodedStringValue[] ret = new EncodedStringValue[temp.length];
for (int i = 0; i < ret.length; ++i) {
try {
ret[i] = new EncodedStringValue(mCharacterSet,
temp[i].getBytes());
} catch (NullPointerException _) {
// Can't arrive here
return null;
}
}
return ret;
}
/**
* Extract an EncodedStringValue[] from a given String.
*/
public static EncodedStringValue[] extract(String src) {
String[] values = src.split(";");
ArrayList<EncodedStringValue> list = new ArrayList<EncodedStringValue>();
for (int i = 0; i < values.length; i++) {
if (values[i].length() > 0) {
list.add(new EncodedStringValue(values[i]));
}
}
int len = list.size();
if (len > 0) {
return list.toArray(new EncodedStringValue[len]);
} else {
return null;
}
}
/**
* Concatenate an EncodedStringValue[] into a single String.
*/
public static String concat(EncodedStringValue[] addr) {
StringBuilder sb = new StringBuilder();
int maxIndex = addr.length - 1;
for (int i = 0; i <= maxIndex; i++) {
sb.append(addr[i].getString());
if (i < maxIndex) {
sb.append(";");
}
}
return sb.toString();
}
public static EncodedStringValue copy(EncodedStringValue value) {
if (value == null) {
return null;
}
return new EncodedStringValue(value.mCharacterSet, value.mData);
}
public static EncodedStringValue[] encodeStrings(String[] array) {
int count = array.length;
if (count > 0) {
EncodedStringValue[] encodedArray = new EncodedStringValue[count];
for (int i = 0; i < count; i++) {
encodedArray[i] = new EncodedStringValue(array[i]);
}
return encodedArray;
}
return null;
}
}
| 8,745 | 29.687719 | 87 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/GenericPdu.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class GenericPdu {
/**
* The headers of pdu.
*/
PduHeaders mPduHeaders = null;
/**
* Constructor.
*/
public GenericPdu() {
mPduHeaders = new PduHeaders();
}
/**
* Constructor.
*
* @param headers Headers for this PDU.
*/
GenericPdu(PduHeaders headers) {
mPduHeaders = headers;
}
/**
* Get the headers of this PDU.
*
* @return A PduHeaders of this PDU.
*/
public PduHeaders getPduHeaders() {
return mPduHeaders;
}
/**
* Get X-Mms-Message-Type field value.
*
* @return the X-Mms-Report-Allowed value
*/
public int getMessageType() {
return mPduHeaders.getOctet(PduHeaders.MESSAGE_TYPE);
}
/**
* Set X-Mms-Message-Type field value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
* RuntimeException if field's value is not Octet.
*/
public void setMessageType(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.MESSAGE_TYPE);
}
/**
* Get X-Mms-MMS-Version field value.
*
* @return the X-Mms-MMS-Version value
*/
public int getMmsVersion() {
return mPduHeaders.getOctet(PduHeaders.MMS_VERSION);
}
/**
* Set X-Mms-MMS-Version field value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
* RuntimeException if field's value is not Octet.
*/
public void setMmsVersion(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.MMS_VERSION);
}
/**
* Get From value.
* From-value = Value-length
* (Address-present-token Encoded-string-value | Insert-address-token)
*
* @return the value
*/
public EncodedStringValue getFrom() {
return mPduHeaders.getEncodedStringValue(PduHeaders.FROM);
}
/**
* Set From value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setFrom(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM);
}
}
| 3,041 | 25.684211 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/MultimediaMessagePdu.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
/**
* Multimedia message PDU.
*/
public class MultimediaMessagePdu extends GenericPdu{
/**
* The body.
*/
private PduBody mMessageBody;
/**
* Constructor.
*/
public MultimediaMessagePdu() {
super();
}
/**
* Constructor.
*
* @param header the header of this PDU
* @param body the body of this PDU
*/
public MultimediaMessagePdu(PduHeaders header, PduBody body) {
super(header);
mMessageBody = body;
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
MultimediaMessagePdu(PduHeaders headers) {
super(headers);
}
/**
* Get body of the PDU.
*
* @return the body
*/
public PduBody getBody() {
return mMessageBody;
}
/**
* Set body of the PDU.
*
* @param body the body
*/
public void setBody(PduBody body) {
mMessageBody = body;
}
/**
* Get subject.
*
* @return the value
*/
public EncodedStringValue getSubject() {
return mPduHeaders.getEncodedStringValue(PduHeaders.SUBJECT);
}
/**
* Set subject.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setSubject(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.SUBJECT);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* Add a "To" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void addTo(EncodedStringValue value) {
mPduHeaders.appendEncodedStringValue(value, PduHeaders.TO);
}
/**
* Get X-Mms-Priority value.
*
* @return the value
*/
public int getPriority() {
return mPduHeaders.getOctet(PduHeaders.PRIORITY);
}
/**
* Set X-Mms-Priority value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setPriority(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.PRIORITY);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value in seconds.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
}
| 3,475 | 22.019868 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/NotificationInd.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
/**
* M-Notification.ind PDU.
*/
public class NotificationInd extends GenericPdu {
/**
* Empty constructor.
* Since the Pdu corresponding to this class is constructed
* by the Proxy-Relay server, this class is only instantiated
* by the Pdu Parser.
*
* @throws InvalidHeaderValueException if error occurs.
* RuntimeException if an undeclared error occurs.
*/
public NotificationInd() throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
public NotificationInd(PduHeaders headers) {
super(headers);
}
public int getStatus() {
return mPduHeaders.getOctet(PduHeaders.STATUS);
}
/**
* Get X-Mms-Content-Class Value.
*
* @return the value
*/
public int getContentClass() {
return mPduHeaders.getOctet(PduHeaders.CONTENT_CLASS);
}
/**
* Set X-Mms-Content-Class Value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
* RuntimeException if an undeclared error occurs.
*/
public void setContentClass(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.CONTENT_CLASS);
}
/**
* Get X-Mms-Content-Location value.
* When used in a PDU other than M-Mbox-Delete.conf and M-Delete.conf:
* Content-location-value = Uri-value
*
* @return the value
*/
public byte[] getContentLocation() {
return mPduHeaders.getTextString(PduHeaders.CONTENT_LOCATION);
}
/**
* Set X-Mms-Content-Location value.
*
* @param value the value
* @throws NullPointerException if the value is null.
* RuntimeException if an undeclared error occurs.
*/
public void setContentLocation(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.CONTENT_LOCATION);
}
/**
* Get X-Mms-Expiry value.
*
* Expiry-value = Value-length
* (Absolute-token Date-value | Relative-token Delta-seconds-value)
*
* @return the value
*/
public long getExpiry() {
return mPduHeaders.getLongInteger(PduHeaders.EXPIRY);
}
/**
* Set X-Mms-Expiry value.
*
* @param value the value
* @throws RuntimeException if an undeclared error occurs.
*/
public void setExpiry(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.EXPIRY);
}
/**
* Get From value.
* From-value = Value-length
* (Address-present-token Encoded-string-value | Insert-address-token)
*
* @return the value
*/
public EncodedStringValue getFrom() {
return mPduHeaders.getEncodedStringValue(PduHeaders.FROM);
}
/**
* Set From value.
*
* @param value the value
* @throws NullPointerException if the value is null.
* RuntimeException if an undeclared error occurs.
*/
public void setFrom(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM);
}
/**
* Get X-Mms-Message-Class value.
* Message-class-value = Class-identifier | Token-text
* Class-identifier = Personal | Advertisement | Informational | Auto
*
* @return the value
*/
public byte[] getMessageClass() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_CLASS);
}
/**
* Set X-Mms-Message-Class value.
*
* @param value the value
* @throws NullPointerException if the value is null.
* RuntimeException if an undeclared error occurs.
*/
public void setMessageClass(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_CLASS);
}
/**
* Get X-Mms-Message-Size value.
* Message-size-value = Long-integer
*
* @return the value
*/
public long getMessageSize() {
return mPduHeaders.getLongInteger(PduHeaders.MESSAGE_SIZE);
}
/**
* Set X-Mms-Message-Size value.
*
* @param value the value
* @throws RuntimeException if an undeclared error occurs.
*/
public void setMessageSize(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.MESSAGE_SIZE);
}
/**
* Get subject.
*
* @return the value
*/
public EncodedStringValue getSubject() {
return mPduHeaders.getEncodedStringValue(PduHeaders.SUBJECT);
}
/**
* Set subject.
*
* @param value the value
* @throws NullPointerException if the value is null.
* RuntimeException if an undeclared error occurs.
*/
public void setSubject(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.SUBJECT);
}
/**
* Get X-Mms-Transaction-Id.
*
* @return the value
*/
public byte[] getTransactionId() {
return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID);
}
/**
* Set X-Mms-Transaction-Id.
*
* @param value the value
* @throws NullPointerException if the value is null.
* RuntimeException if an undeclared error occurs.
*/
public void setTransactionId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID);
}
/**
* Get X-Mms-Delivery-Report Value.
*
* @return the value
*/
public int getDeliveryReport() {
return mPduHeaders.getOctet(PduHeaders.DELIVERY_REPORT);
}
/**
* Set X-Mms-Delivery-Report Value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
* RuntimeException if an undeclared error occurs.
*/
public void setDeliveryReport(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.DELIVERY_REPORT);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte getDrmContent() {return 0x00;}
* public void setDrmContent(byte value) {}
*
* public byte getDistributionIndicator() {return 0x00;}
* public void setDistributionIndicator(byte value) {}
*
* public ElementDescriptorValue getElementDescriptor() {return null;}
* public void getElementDescriptor(ElementDescriptorValue value) {}
*
* public byte getPriority() {return 0x00;}
* public void setPriority(byte value) {}
*
* public byte getRecommendedRetrievalMode() {return 0x00;}
* public void setRecommendedRetrievalMode(byte value) {}
*
* public byte getRecommendedRetrievalModeText() {return 0x00;}
* public void setRecommendedRetrievalModeText(byte value) {}
*
* public byte[] getReplaceId() {return 0x00;}
* public void setReplaceId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*
* public byte getReplyCharging() {return 0x00;}
* public void setReplyCharging(byte value) {}
*
* public byte getReplyChargingDeadline() {return 0x00;}
* public void setReplyChargingDeadline(byte value) {}
*
* public byte[] getReplyChargingId() {return 0x00;}
* public void setReplyChargingId(byte[] value) {}
*
* public long getReplyChargingSize() {return 0;}
* public void setReplyChargingSize(long value) {}
*
* public byte getStored() {return 0x00;}
* public void setStored(byte value) {}
*/
}
| 8,762 | 29.217241 | 81 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/NotifyRespInd.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
/**
* M-NofifyResp.ind PDU.
*/
public class NotifyRespInd extends GenericPdu {
/**
* Constructor, used when composing a M-NotifyResp.ind pdu.
*
* @param mmsVersion current version of mms
* @param transactionId the transaction-id value
* @param status the status value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if transactionId is null.
* RuntimeException if an undeclared error occurs.
*/
public NotifyRespInd(int mmsVersion,
byte[] transactionId,
int status) throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND);
setMmsVersion(mmsVersion);
setTransactionId(transactionId);
setStatus(status);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
NotifyRespInd(PduHeaders headers) {
super(headers);
}
/**
* Get X-Mms-Report-Allowed field value.
*
* @return the X-Mms-Report-Allowed value
*/
public int getReportAllowed() {
return mPduHeaders.getOctet(PduHeaders.REPORT_ALLOWED);
}
/**
* Set X-Mms-Report-Allowed field value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
* RuntimeException if an undeclared error occurs.
*/
public void setReportAllowed(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.REPORT_ALLOWED);
}
/**
* Set X-Mms-Status field value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
* RuntimeException if an undeclared error occurs.
*/
public void setStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.STATUS);
}
/**
* GetX-Mms-Status field value.
*
* @return the X-Mms-Status value
*/
public int getStatus() {
return mPduHeaders.getOctet(PduHeaders.STATUS);
}
/**
* Get X-Mms-Transaction-Id field value.
*
* @return the X-Mms-Report-Allowed value
*/
public byte[] getTransactionId() {
return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID);
}
/**
* Set X-Mms-Transaction-Id field value.
*
* @param value the value
* @throws NullPointerException if the value is null.
* RuntimeException if an undeclared error occurs.
*/
public void setTransactionId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID);
}
}
| 3,518 | 29.6 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/PduBody.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
public class PduBody {
private Vector<PduPart> mParts = null;
private Map<String, PduPart> mPartMapByContentId = null;
private Map<String, PduPart> mPartMapByContentLocation = null;
private Map<String, PduPart> mPartMapByName = null;
private Map<String, PduPart> mPartMapByFileName = null;
/**
* Constructor.
*/
public PduBody() {
mParts = new Vector<PduPart>();
mPartMapByContentId = new HashMap<String, PduPart>();
mPartMapByContentLocation = new HashMap<String, PduPart>();
mPartMapByName = new HashMap<String, PduPart>();
mPartMapByFileName = new HashMap<String, PduPart>();
}
private void putPartToMaps(PduPart part) {
// Put part to mPartMapByContentId.
byte[] contentId = part.getContentId();
if(null != contentId) {
mPartMapByContentId.put(new String(contentId), part);
}
// Put part to mPartMapByContentLocation.
byte[] contentLocation = part.getContentLocation();
if(null != contentLocation) {
String clc = new String(contentLocation);
mPartMapByContentLocation.put(clc, part);
}
// Put part to mPartMapByName.
byte[] name = part.getName();
if(null != name) {
String clc = new String(name);
mPartMapByName.put(clc, part);
}
// Put part to mPartMapByFileName.
byte[] fileName = part.getFilename();
if(null != fileName) {
String clc = new String(fileName);
mPartMapByFileName.put(clc, part);
}
}
/**
* Appends the specified part to the end of this body.
*
* @param part part to be appended
* @return true when success, false when fail
* @throws NullPointerException when part is null
*/
public boolean addPart(PduPart part) {
if(null == part) {
throw new NullPointerException();
}
putPartToMaps(part);
return mParts.add(part);
}
/**
* Inserts the specified part at the specified position.
*
* @param index index at which the specified part is to be inserted
* @param part part to be inserted
* @throws NullPointerException when part is null
*/
public void addPart(int index, PduPart part) {
if(null == part) {
throw new NullPointerException();
}
putPartToMaps(part);
mParts.add(index, part);
}
/**
* Removes the part at the specified position.
*
* @param index index of the part to return
* @return part at the specified index
*/
public PduPart removePart(int index) {
return mParts.remove(index);
}
/**
* Remove all of the parts.
*/
public void removeAll() {
mParts.clear();
}
/**
* Get the part at the specified position.
*
* @param index index of the part to return
* @return part at the specified index
*/
public PduPart getPart(int index) {
return mParts.get(index);
}
/**
* Get the index of the specified part.
*
* @param part the part object
* @return index the index of the first occurrence of the part in this body
*/
public int getPartIndex(PduPart part) {
return mParts.indexOf(part);
}
/**
* Get the number of parts.
*
* @return the number of parts
*/
public int getPartsNum() {
return mParts.size();
}
/**
* Get pdu part by content id.
*
* @param cid the value of content id.
* @return the pdu part.
*/
public PduPart getPartByContentId(String cid) {
return mPartMapByContentId.get(cid);
}
/**
* Get pdu part by Content-Location. Content-Location of part is
* the same as filename and name(param of content-type).
*
* @param fileName the value of filename.
* @return the pdu part.
*/
public PduPart getPartByContentLocation(String contentLocation) {
return mPartMapByContentLocation.get(contentLocation);
}
/**
* Get pdu part by name.
*
* @param fileName the value of filename.
* @return the pdu part.
*/
public PduPart getPartByName(String name) {
return mPartMapByName.get(name);
}
/**
* Get pdu part by filename.
*
* @param fileName the value of filename.
* @return the pdu part.
*/
public PduPart getPartByFileName(String filename) {
return mPartMapByFileName.get(filename);
}
}
| 5,359 | 26.916667 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/PduComposer.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import android.content.ContentResolver;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
public class PduComposer {
/**
* Address type.
*/
static private final int PDU_PHONE_NUMBER_ADDRESS_TYPE = 1;
static private final int PDU_EMAIL_ADDRESS_TYPE = 2;
static private final int PDU_IPV4_ADDRESS_TYPE = 3;
static private final int PDU_IPV6_ADDRESS_TYPE = 4;
static private final int PDU_UNKNOWN_ADDRESS_TYPE = 5;
/**
* Address regular expression string.
*/
static final String REGEXP_PHONE_NUMBER_ADDRESS_TYPE = "\\+?[0-9|\\.|\\-]+";
static final String REGEXP_EMAIL_ADDRESS_TYPE = "[a-zA-Z| ]*\\<{0,1}[a-zA-Z| ]+@{1}" +
"[a-zA-Z| ]+\\.{1}[a-zA-Z| ]+\\>{0,1}";
static final String REGEXP_IPV6_ADDRESS_TYPE =
"[a-fA-F]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}" +
"[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}" +
"[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}";
static final String REGEXP_IPV4_ADDRESS_TYPE = "[0-9]{1,3}\\.{1}[0-9]{1,3}\\.{1}" +
"[0-9]{1,3}\\.{1}[0-9]{1,3}";
/**
* The postfix strings of address.
*/
static final String STRING_PHONE_NUMBER_ADDRESS_TYPE = "/TYPE=PLMN";
static final String STRING_IPV4_ADDRESS_TYPE = "/TYPE=IPV4";
static final String STRING_IPV6_ADDRESS_TYPE = "/TYPE=IPV6";
/**
* Error values.
*/
static private final int PDU_COMPOSE_SUCCESS = 0;
static private final int PDU_COMPOSE_CONTENT_ERROR = 1;
static private final int PDU_COMPOSE_FIELD_NOT_SET = 2;
static private final int PDU_COMPOSE_FIELD_NOT_SUPPORTED = 3;
/**
* WAP values defined in WSP spec.
*/
static private final int QUOTED_STRING_FLAG = 34;
static private final int END_STRING_FLAG = 0;
static private final int LENGTH_QUOTE = 31;
static private final int TEXT_MAX = 127;
static private final int SHORT_INTEGER_MAX = 127;
static private final int LONG_INTEGER_LENGTH_MAX = 8;
/**
* Block size when read data from InputStream.
*/
static private final int PDU_COMPOSER_BLOCK_SIZE = 1024;
/**
* The output message.
*/
protected ByteArrayOutputStream mMessage = null;
/**
* The PDU.
*/
private GenericPdu mPdu = null;
/**
* Current visiting position of the mMessage.
*/
protected int mPosition = 0;
/**
* Message compose buffer stack.
*/
private BufferStack mStack = null;
/**
* Content resolver.
*/
private final ContentResolver mResolver;
/**
* Header of this pdu.
*/
private PduHeaders mPduHeader = null;
/**
* Map of all content type
*/
private static HashMap<String, Integer> mContentTypeMap = null;
static {
mContentTypeMap = new HashMap<String, Integer>();
int i;
for (i = 0; i < PduContentTypes.contentTypes.length; i++) {
mContentTypeMap.put(PduContentTypes.contentTypes[i], i);
}
}
/**
* Constructor.
*
* @param context the context
* @param pdu the pdu to be composed
*/
public PduComposer(Context context, GenericPdu pdu) {
mPdu = pdu;
mResolver = context.getContentResolver();
mPduHeader = pdu.getPduHeaders();
mStack = new BufferStack();
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
/**
* Make the message. No need to check whether mandatory fields are set,
* because the constructors of outgoing pdus are taking care of this.
*
* @return OutputStream of maked message. Return null if
* the PDU is invalid.
*/
public byte[] make() {
// Get Message-type.
int type = mPdu.getMessageType();
/* make the message */
switch (type) {
case PduHeaders.MESSAGE_TYPE_SEND_REQ:
if (makeSendReqPdu() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND:
if (makeNotifyResp() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND:
if (makeAckInd() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
if (makeReadRecInd() != PDU_COMPOSE_SUCCESS) {
return null;
}
break;
default:
return null;
}
Log.w("PduComposer", "Returning: " + mMessage.size() + " bytes...");
return mMessage.toByteArray();
}
/**
* Copy buf to mMessage.
*/
protected void arraycopy(byte[] buf, int pos, int length) {
mMessage.write(buf, pos, length);
mPosition = mPosition + length;
}
/**
* Append a byte to mMessage.
*/
protected void append(int value) {
mMessage.write(value);
mPosition ++;
}
/**
* Append short integer value to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendShortInteger(int value) {
/*
* From WAP-230-WSP-20010705-a:
* Short-integer = OCTET
* ; Integers in range 0-127 shall be encoded as a one octet value
* ; with the most significant bit set to one (1xxx xxxx) and with
* ; the value in the remaining least significant bits.
* In our implementation, only low 7 bits are stored and otherwise
* bits are ignored.
*/
append((value | 0x80) & 0xff);
}
/**
* Append an octet number between 128 and 255 into mMessage.
* NOTE:
* A value between 0 and 127 should be appended by using appendShortInteger.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendOctet(int number) {
append(number);
}
/**
* Append a short length into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendShortLength(int value) {
/*
* From WAP-230-WSP-20010705-a:
* Short-length = <Any octet 0-30>
*/
append(value);
}
/**
* Append long integer into mMessage. it's used for really long integers.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendLongInteger(long longInt) {
/*
* From WAP-230-WSP-20010705-a:
* Long-integer = Short-length Multi-octet-integer
* ; The Short-length indicates the length of the Multi-octet-integer
* Multi-octet-integer = 1*30 OCTET
* ; The content octets shall be an unsigned integer value with the
* ; most significant octet encoded first (big-endian representation).
* ; The minimum number of octets must be used to encode the value.
*/
int size;
long temp = longInt;
// Count the length of the long integer.
for(size = 0; (temp != 0) && (size < LONG_INTEGER_LENGTH_MAX); size++) {
temp = (temp >>> 8);
}
// Set Length.
appendShortLength(size);
// Count and set the long integer.
int i;
int shift = (size -1) * 8;
for (i = 0; i < size; i++) {
append((int)((longInt >>> shift) & 0xff));
shift = shift - 8;
}
}
/**
* Append text string into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendTextString(byte[] text) {
/*
* From WAP-230-WSP-20010705-a:
* Text-string = [Quote] *TEXT End-of-string
* ; If the first character in the TEXT is in the range of 128-255,
* ; a Quote character must precede it. Otherwise the Quote character
* ;must be omitted. The Quote is not part of the contents.
*/
if (((text[0])&0xff) > TEXT_MAX) { // No need to check for <= 255
append(TEXT_MAX);
}
arraycopy(text, 0, text.length);
append(0);
}
/**
* Append text string into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendTextString(String str) {
/*
* From WAP-230-WSP-20010705-a:
* Text-string = [Quote] *TEXT End-of-string
* ; If the first character in the TEXT is in the range of 128-255,
* ; a Quote character must precede it. Otherwise the Quote character
* ;must be omitted. The Quote is not part of the contents.
*/
appendTextString(str.getBytes());
}
/**
* Append encoded string value to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendEncodedString(EncodedStringValue enStr) {
/*
* From OMA-TS-MMS-ENC-V1_3-20050927-C:
* Encoded-string-value = Text-string | Value-length Char-set Text-string
*/
assert(enStr != null);
int charset = enStr.getCharacterSet();
byte[] textString = enStr.getTextString();
if (null == textString) {
return;
}
/*
* In the implementation of EncodedStringValue, the charset field will
* never be 0. It will always be composed as
* Encoded-string-value = Value-length Char-set Text-string
*/
mStack.newbuf();
PositionMarker start = mStack.mark();
appendShortInteger(charset);
appendTextString(textString);
int len = start.getLength();
mStack.pop();
appendValueLength(len);
mStack.copy();
}
/**
* Append uintvar integer into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendUintvarInteger(long value) {
/*
* From WAP-230-WSP-20010705-a:
* To encode a large unsigned integer, split it into 7-bit fragments
* and place them in the payloads of multiple octets. The most significant
* bits are placed in the first octets with the least significant bits
* ending up in the last octet. All octets MUST set the Continue bit to 1
* except the last octet, which MUST set the Continue bit to 0.
*/
int i;
long max = SHORT_INTEGER_MAX;
for (i = 0; i < 5; i++) {
if (value < max) {
break;
}
max = (max << 7) | 0x7fl;
}
while(i > 0) {
long temp = value >>> (i * 7);
temp = temp & 0x7f;
append((int)((temp | 0x80) & 0xff));
i--;
}
append((int)(value & 0x7f));
}
/**
* Append date value into mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendDateValue(long date) {
/*
* From OMA-TS-MMS-ENC-V1_3-20050927-C:
* Date-value = Long-integer
*/
appendLongInteger(date);
}
/**
* Append value length to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendValueLength(long value) {
/*
* From WAP-230-WSP-20010705-a:
* Value-length = Short-length | (Length-quote Length)
* ; Value length is used to indicate the length of the value to follow
* Short-length = <Any octet 0-30>
* Length-quote = <Octet 31>
* Length = Uintvar-integer
*/
if (value < LENGTH_QUOTE) {
appendShortLength((int) value);
return;
}
append(LENGTH_QUOTE);
appendUintvarInteger(value);
}
/**
* Append quoted string to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendQuotedString(byte[] text) {
/*
* From WAP-230-WSP-20010705-a:
* Quoted-string = <Octet 34> *TEXT End-of-string
* ;The TEXT encodes an RFC2616 Quoted-string with the enclosing
* ;quotation-marks <"> removed.
*/
append(QUOTED_STRING_FLAG);
arraycopy(text, 0, text.length);
append(END_STRING_FLAG);
}
/**
* Append quoted string to mMessage.
* This implementation doesn't check the validity of parameter, since it
* assumes that the values are validated in the GenericPdu setter methods.
*/
protected void appendQuotedString(String str) {
/*
* From WAP-230-WSP-20010705-a:
* Quoted-string = <Octet 34> *TEXT End-of-string
* ;The TEXT encodes an RFC2616 Quoted-string with the enclosing
* ;quotation-marks <"> removed.
*/
appendQuotedString(str.getBytes());
}
private EncodedStringValue appendAddressType(EncodedStringValue address) {
EncodedStringValue temp = null;
try {
int addressType = checkAddressType(address.getString());
temp = EncodedStringValue.copy(address);
if (PDU_PHONE_NUMBER_ADDRESS_TYPE == addressType) {
// Phone number.
temp.appendTextString(STRING_PHONE_NUMBER_ADDRESS_TYPE.getBytes());
} else if (PDU_IPV4_ADDRESS_TYPE == addressType) {
// Ipv4 address.
temp.appendTextString(STRING_IPV4_ADDRESS_TYPE.getBytes());
} else if (PDU_IPV6_ADDRESS_TYPE == addressType) {
// Ipv6 address.
temp.appendTextString(STRING_IPV6_ADDRESS_TYPE.getBytes());
}
} catch (NullPointerException e) {
return null;
}
return temp;
}
/**
* Append header to mMessage.
*/
private int appendHeader(int field) {
switch (field) {
case PduHeaders.MMS_VERSION:
appendOctet(field);
int version = mPduHeader.getOctet(field);
if (0 == version) {
appendShortInteger(PduHeaders.CURRENT_MMS_VERSION);
} else {
appendShortInteger(version);
}
break;
case PduHeaders.MESSAGE_ID:
case PduHeaders.TRANSACTION_ID:
byte[] textString = mPduHeader.getTextString(field);
if (null == textString) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendTextString(textString);
break;
case PduHeaders.TO:
case PduHeaders.BCC:
case PduHeaders.CC:
EncodedStringValue[] addr = mPduHeader.getEncodedStringValues(field);
if (null == addr) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
EncodedStringValue temp;
for (int i = 0; i < addr.length; i++) {
temp = appendAddressType(addr[i]);
if (temp == null) {
return PDU_COMPOSE_CONTENT_ERROR;
}
appendOctet(field);
appendEncodedString(temp);
}
break;
case PduHeaders.FROM:
// Value-length (Address-present-token Encoded-string-value | Insert-address-token)
appendOctet(field);
EncodedStringValue from = mPduHeader.getEncodedStringValue(field);
if ((from == null)
|| TextUtils.isEmpty(from.getString())
|| new String(from.getTextString()).equals(
PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR)) {
// Length of from = 1
append(1);
// Insert-address-token = <Octet 129>
append(PduHeaders.FROM_INSERT_ADDRESS_TOKEN);
} else {
mStack.newbuf();
PositionMarker fstart = mStack.mark();
// Address-present-token = <Octet 128>
append(PduHeaders.FROM_ADDRESS_PRESENT_TOKEN);
temp = appendAddressType(from);
if (temp == null) {
return PDU_COMPOSE_CONTENT_ERROR;
}
appendEncodedString(temp);
int flen = fstart.getLength();
mStack.pop();
appendValueLength(flen);
mStack.copy();
}
break;
case PduHeaders.READ_STATUS:
case PduHeaders.STATUS:
case PduHeaders.REPORT_ALLOWED:
case PduHeaders.PRIORITY:
case PduHeaders.DELIVERY_REPORT:
case PduHeaders.READ_REPORT:
int octet = mPduHeader.getOctet(field);
if (0 == octet) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendOctet(octet);
break;
case PduHeaders.DATE:
long date = mPduHeader.getLongInteger(field);
if (-1 == date) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendDateValue(date);
break;
case PduHeaders.SUBJECT:
EncodedStringValue enString =
mPduHeader.getEncodedStringValue(field);
if (null == enString) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
appendEncodedString(enString);
break;
case PduHeaders.MESSAGE_CLASS:
byte[] messageClass = mPduHeader.getTextString(field);
if (null == messageClass) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_ADVERTISEMENT_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_ADVERTISEMENT);
} else if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_AUTO_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_AUTO);
} else if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_PERSONAL);
} else if (Arrays.equals(messageClass,
PduHeaders.MESSAGE_CLASS_INFORMATIONAL_STR.getBytes())) {
appendOctet(PduHeaders.MESSAGE_CLASS_INFORMATIONAL);
} else {
appendTextString(messageClass);
}
break;
case PduHeaders.EXPIRY:
long expiry = mPduHeader.getLongInteger(field);
if (-1 == expiry) {
return PDU_COMPOSE_FIELD_NOT_SET;
}
appendOctet(field);
mStack.newbuf();
PositionMarker expiryStart = mStack.mark();
append(PduHeaders.VALUE_RELATIVE_TOKEN);
appendLongInteger(expiry);
int expiryLength = expiryStart.getLength();
mStack.pop();
appendValueLength(expiryLength);
mStack.copy();
break;
default:
return PDU_COMPOSE_FIELD_NOT_SUPPORTED;
}
return PDU_COMPOSE_SUCCESS;
}
/**
* Make ReadRec.Ind.
*/
private int makeReadRecInd() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_READ_REC_IND);
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Message-ID
if (appendHeader(PduHeaders.MESSAGE_ID) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// To
if (appendHeader(PduHeaders.TO) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// From
if (appendHeader(PduHeaders.FROM) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Date Optional
appendHeader(PduHeaders.DATE);
// X-Mms-Read-Status
if (appendHeader(PduHeaders.READ_STATUS) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Applic-ID Optional(not support)
// X-Mms-Reply-Applic-ID Optional(not support)
// X-Mms-Aux-Applic-Info Optional(not support)
return PDU_COMPOSE_SUCCESS;
}
/**
* Make NotifyResp.Ind.
*/
private int makeNotifyResp() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND);
// X-Mms-Transaction-ID
if (appendHeader(PduHeaders.TRANSACTION_ID) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Status
if (appendHeader(PduHeaders.STATUS) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Report-Allowed Optional (not support)
return PDU_COMPOSE_SUCCESS;
}
/**
* Make Acknowledge.Ind.
*/
private int makeAckInd() {
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND);
// X-Mms-Transaction-ID
if (appendHeader(PduHeaders.TRANSACTION_ID) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// X-Mms-Report-Allowed Optional
appendHeader(PduHeaders.REPORT_ALLOWED);
return PDU_COMPOSE_SUCCESS;
}
/**
* Make Send.req.
*/
private int makeSendReqPdu() {
Log.w("PduComposer", "Making send request...");
if (mMessage == null) {
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
// X-Mms-Message-Type
appendOctet(PduHeaders.MESSAGE_TYPE);
appendOctet(PduHeaders.MESSAGE_TYPE_SEND_REQ);
// X-Mms-Transaction-ID
appendOctet(PduHeaders.TRANSACTION_ID);
byte[] trid = mPduHeader.getTextString(PduHeaders.TRANSACTION_ID);
if (trid == null) {
// Transaction-ID should be set(by Transaction) before make().
throw new IllegalArgumentException("Transaction-ID is null.");
}
appendTextString(trid);
// X-Mms-MMS-Version
if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Date Date-value Optional.
appendHeader(PduHeaders.DATE);
// From
if (appendHeader(PduHeaders.FROM) != PDU_COMPOSE_SUCCESS) {
return PDU_COMPOSE_CONTENT_ERROR;
}
boolean recipient = false;
// To
if (appendHeader(PduHeaders.TO) != PDU_COMPOSE_CONTENT_ERROR) {
recipient = true;
}
// Cc
if (appendHeader(PduHeaders.CC) != PDU_COMPOSE_CONTENT_ERROR) {
recipient = true;
}
// Bcc
if (appendHeader(PduHeaders.BCC) != PDU_COMPOSE_CONTENT_ERROR) {
recipient = true;
}
// Need at least one of "cc", "bcc" and "to".
if (false == recipient) {
return PDU_COMPOSE_CONTENT_ERROR;
}
// Subject Optional
appendHeader(PduHeaders.SUBJECT);
// X-Mms-Message-Class Optional
// Message-class-value = Class-identifier | Token-text
appendHeader(PduHeaders.MESSAGE_CLASS);
// X-Mms-Expiry Optional
appendHeader(PduHeaders.EXPIRY);
// X-Mms-Priority Optional
appendHeader(PduHeaders.PRIORITY);
// X-Mms-Delivery-Report Optional
appendHeader(PduHeaders.DELIVERY_REPORT);
// X-Mms-Read-Report Optional
appendHeader(PduHeaders.READ_REPORT);
// Content-Type
appendOctet(PduHeaders.CONTENT_TYPE);
// Message body
return makeMessageBody();
}
/**
* Make message body.
*/
private int makeMessageBody() {
Log.w("PduComposer", "Making message body...");
// 1. add body informations
mStack.newbuf(); // Switching buffer because we need to
PositionMarker ctStart = mStack.mark();
// This contentTypeIdentifier should be used for type of attachment...
String contentType = new String(mPduHeader.getTextString(PduHeaders.CONTENT_TYPE));
Integer contentTypeIdentifier = mContentTypeMap.get(contentType);
if (contentTypeIdentifier == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
appendShortInteger(contentTypeIdentifier.intValue());
// content-type parameter: start
PduBody body = ((SendReq) mPdu).getBody();
if (null == body || body.getPartsNum() == 0) {
// empty message
appendUintvarInteger(0);
mStack.pop();
mStack.copy();
return PDU_COMPOSE_SUCCESS;
}
PduPart part;
try {
part = body.getPart(0);
byte[] start = part.getContentId();
if (start != null) {
appendOctet(PduPart.P_DEP_START);
if (('<' == start[0]) && ('>' == start[start.length - 1])) {
appendTextString(start);
} else {
appendTextString("<" + new String(start) + ">");
}
}
// content-type parameter: type
appendOctet(PduPart.P_CT_MR_TYPE);
appendTextString(part.getContentType());
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
int ctLength = ctStart.getLength();
mStack.pop();
appendValueLength(ctLength);
mStack.copy();
// 3. add content
int partNum = body.getPartsNum();
appendUintvarInteger(partNum);
for (int i = 0; i < partNum; i++) {
part = body.getPart(i);
mStack.newbuf(); // Leaving space for header lengh and data length
PositionMarker attachment = mStack.mark();
mStack.newbuf(); // Leaving space for Content-Type length
PositionMarker contentTypeBegin = mStack.mark();
byte[] partContentType = part.getContentType();
if (partContentType == null) {
// content type is mandatory
return PDU_COMPOSE_CONTENT_ERROR;
}
// content-type value
Integer partContentTypeIdentifier =
mContentTypeMap.get(new String(partContentType));
if (partContentTypeIdentifier == null) {
appendTextString(partContentType);
} else {
appendShortInteger(partContentTypeIdentifier.intValue());
}
/* Content-type parameter : name.
* The value of name, filename, content-location is the same.
* Just one of them is enough for this PDU.
*/
byte[] name = part.getName();
if (null == name) {
name = part.getFilename();
if (null == name) {
name = part.getContentLocation();
if (null == name) {
/* at lease one of name, filename, Content-location
* should be available.
*/
return PDU_COMPOSE_CONTENT_ERROR;
}
}
}
appendOctet(PduPart.P_DEP_NAME);
appendTextString(name);
// content-type parameter : charset
int charset = part.getCharset();
if (charset != 0) {
appendOctet(PduPart.P_CHARSET);
appendShortInteger(charset);
}
int contentTypeLength = contentTypeBegin.getLength();
mStack.pop();
appendValueLength(contentTypeLength);
mStack.copy();
// content id
byte[] contentId = part.getContentId();
if (null != contentId) {
appendOctet(PduPart.P_CONTENT_ID);
if (('<' == contentId[0]) && ('>' == contentId[contentId.length - 1])) {
appendQuotedString(contentId);
} else {
appendQuotedString("<" + new String(contentId) + ">");
}
}
// content-location
byte[] contentLocation = part.getContentLocation();
if (null != contentLocation) {
appendOctet(PduPart.P_CONTENT_LOCATION);
appendTextString(contentLocation);
}
// content
int headerLength = attachment.getLength();
int dataLength = 0; // Just for safety...
byte[] partData = part.getData();
if (partData != null) {
arraycopy(partData, 0, partData.length);
dataLength = partData.length;
} else {
InputStream cr;
try {
byte[] buffer = new byte[PDU_COMPOSER_BLOCK_SIZE];
cr = mResolver.openInputStream(part.getDataUri());
int len = 0;
while ((len = cr.read(buffer)) != -1) {
mMessage.write(buffer, 0, len);
mPosition += len;
dataLength += len;
}
} catch (FileNotFoundException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (IOException e) {
return PDU_COMPOSE_CONTENT_ERROR;
} catch (RuntimeException e) {
return PDU_COMPOSE_CONTENT_ERROR;
}
}
if (dataLength != (attachment.getLength() - headerLength)) {
throw new RuntimeException("BUG: Length sanity check failed");
}
mStack.pop();
appendUintvarInteger(headerLength);
appendUintvarInteger(dataLength);
mStack.copy();
}
return PDU_COMPOSE_SUCCESS;
}
/**
* Record current message informations.
*/
static private class LengthRecordNode {
ByteArrayOutputStream currentMessage = null;
public int currentPosition = 0;
public LengthRecordNode next = null;
}
/**
* Mark current message position and stact size.
*/
private class PositionMarker {
private int c_pos; // Current position
private int currentStackSize; // Current stack size
int getLength() {
// If these assert fails, likely that you are finding the
// size of buffer that is deep in BufferStack you can only
// find the length of the buffer that is on top
if (currentStackSize != mStack.stackSize) {
throw new RuntimeException("BUG: Invalid call to getLength()");
}
return mPosition - c_pos;
}
}
/**
* This implementation can be OPTIMIZED to use only
* 2 buffers. This optimization involves changing BufferStack
* only... Its usage (interface) will not change.
*/
private class BufferStack {
private LengthRecordNode stack = null;
private LengthRecordNode toCopy = null;
int stackSize = 0;
/**
* Create a new message buffer and push it into the stack.
*/
void newbuf() {
// You can't create a new buff when toCopy != null
// That is after calling pop() and before calling copy()
// If you do, it is a bug
if (toCopy != null) {
throw new RuntimeException("BUG: Invalid newbuf() before copy()");
}
LengthRecordNode temp = new LengthRecordNode();
temp.currentMessage = mMessage;
temp.currentPosition = mPosition;
temp.next = stack;
stack = temp;
stackSize = stackSize + 1;
mMessage = new ByteArrayOutputStream();
mPosition = 0;
}
/**
* Pop the message before and record current message in the stack.
*/
void pop() {
ByteArrayOutputStream currentMessage = mMessage;
int currentPosition = mPosition;
mMessage = stack.currentMessage;
mPosition = stack.currentPosition;
toCopy = stack;
// Re using the top element of the stack to avoid memory allocation
stack = stack.next;
stackSize = stackSize - 1;
toCopy.currentMessage = currentMessage;
toCopy.currentPosition = currentPosition;
}
/**
* Append current message to the message before.
*/
void copy() {
arraycopy(toCopy.currentMessage.toByteArray(), 0,
toCopy.currentPosition);
toCopy = null;
}
/**
* Mark current message position
*/
PositionMarker mark() {
PositionMarker m = new PositionMarker();
m.c_pos = mPosition;
m.currentStackSize = stackSize;
return m;
}
}
/**
* Check address type.
*
* @param address address string without the postfix stinng type,
* such as "/TYPE=PLMN", "/TYPE=IPv6" and "/TYPE=IPv4"
* @return PDU_PHONE_NUMBER_ADDRESS_TYPE if it is phone number,
* PDU_EMAIL_ADDRESS_TYPE if it is email address,
* PDU_IPV4_ADDRESS_TYPE if it is ipv4 address,
* PDU_IPV6_ADDRESS_TYPE if it is ipv6 address,
* PDU_UNKNOWN_ADDRESS_TYPE if it is unknown.
*/
protected static int checkAddressType(String address) {
/**
* From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf, section 8.
* address = ( e-mail / device-address / alphanum-shortcode / num-shortcode)
* e-mail = mailbox; to the definition of mailbox as described in
* section 3.4 of [RFC2822], but excluding the
* obsolete definitions as indicated by the "obs-" prefix.
* device-address = ( global-phone-number "/TYPE=PLMN" )
* / ( ipv4 "/TYPE=IPv4" ) / ( ipv6 "/TYPE=IPv6" )
* / ( escaped-value "/TYPE=" address-type )
*
* global-phone-number = ["+"] 1*( DIGIT / written-sep )
* written-sep =("-"/".")
*
* ipv4 = 1*3DIGIT 3( "." 1*3DIGIT ) ; IPv4 address value
*
* ipv6 = 4HEXDIG 7( ":" 4HEXDIG ) ; IPv6 address per RFC 2373
*/
if (null == address) {
return PDU_UNKNOWN_ADDRESS_TYPE;
}
if (address.matches(REGEXP_IPV4_ADDRESS_TYPE)) {
// Ipv4 address.
return PDU_IPV4_ADDRESS_TYPE;
}else if (address.matches(REGEXP_PHONE_NUMBER_ADDRESS_TYPE)) {
// Phone number.
return PDU_PHONE_NUMBER_ADDRESS_TYPE;
} else if (address.matches(REGEXP_EMAIL_ADDRESS_TYPE)) {
// Email address.
return PDU_EMAIL_ADDRESS_TYPE;
} else if (address.matches(REGEXP_IPV6_ADDRESS_TYPE)) {
// Ipv6 address.
return PDU_IPV6_ADDRESS_TYPE;
} else {
// Unknown address.
return PDU_UNKNOWN_ADDRESS_TYPE;
}
}
}
| 38,944 | 31.864979 | 99 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/PduContentTypes.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
public class PduContentTypes {
/**
* All content types. From:
* http://www.openmobilealliance.org/tech/omna/omna-wsp-content-type.htm
*/
static final String[] contentTypes = {
"*/*", /* 0x00 */
"text/*", /* 0x01 */
"text/html", /* 0x02 */
"text/plain", /* 0x03 */
"text/x-hdml", /* 0x04 */
"text/x-ttml", /* 0x05 */
"text/x-vCalendar", /* 0x06 */
"text/x-vCard", /* 0x07 */
"text/vnd.wap.wml", /* 0x08 */
"text/vnd.wap.wmlscript", /* 0x09 */
"text/vnd.wap.wta-event", /* 0x0A */
"multipart/*", /* 0x0B */
"multipart/mixed", /* 0x0C */
"multipart/form-data", /* 0x0D */
"multipart/byterantes", /* 0x0E */
"multipart/alternative", /* 0x0F */
"application/*", /* 0x10 */
"application/java-vm", /* 0x11 */
"application/x-www-form-urlencoded", /* 0x12 */
"application/x-hdmlc", /* 0x13 */
"application/vnd.wap.wmlc", /* 0x14 */
"application/vnd.wap.wmlscriptc", /* 0x15 */
"application/vnd.wap.wta-eventc", /* 0x16 */
"application/vnd.wap.uaprof", /* 0x17 */
"application/vnd.wap.wtls-ca-certificate", /* 0x18 */
"application/vnd.wap.wtls-user-certificate", /* 0x19 */
"application/x-x509-ca-cert", /* 0x1A */
"application/x-x509-user-cert", /* 0x1B */
"image/*", /* 0x1C */
"image/gif", /* 0x1D */
"image/jpeg", /* 0x1E */
"image/tiff", /* 0x1F */
"image/png", /* 0x20 */
"image/vnd.wap.wbmp", /* 0x21 */
"application/vnd.wap.multipart.*", /* 0x22 */
"application/vnd.wap.multipart.mixed", /* 0x23 */
"application/vnd.wap.multipart.form-data", /* 0x24 */
"application/vnd.wap.multipart.byteranges", /* 0x25 */
"application/vnd.wap.multipart.alternative", /* 0x26 */
"application/xml", /* 0x27 */
"text/xml", /* 0x28 */
"application/vnd.wap.wbxml", /* 0x29 */
"application/x-x968-cross-cert", /* 0x2A */
"application/x-x968-ca-cert", /* 0x2B */
"application/x-x968-user-cert", /* 0x2C */
"text/vnd.wap.si", /* 0x2D */
"application/vnd.wap.sic", /* 0x2E */
"text/vnd.wap.sl", /* 0x2F */
"application/vnd.wap.slc", /* 0x30 */
"text/vnd.wap.co", /* 0x31 */
"application/vnd.wap.coc", /* 0x32 */
"application/vnd.wap.multipart.related", /* 0x33 */
"application/vnd.wap.sia", /* 0x34 */
"text/vnd.wap.connectivity-xml", /* 0x35 */
"application/vnd.wap.connectivity-wbxml", /* 0x36 */
"application/pkcs7-mime", /* 0x37 */
"application/vnd.wap.hashed-certificate", /* 0x38 */
"application/vnd.wap.signed-certificate", /* 0x39 */
"application/vnd.wap.cert-response", /* 0x3A */
"application/xhtml+xml", /* 0x3B */
"application/wml+xml", /* 0x3C */
"text/css", /* 0x3D */
"application/vnd.wap.mms-message", /* 0x3E */
"application/vnd.wap.rollover-certificate", /* 0x3F */
"application/vnd.wap.locc+wbxml", /* 0x40 */
"application/vnd.wap.loc+xml", /* 0x41 */
"application/vnd.syncml.dm+wbxml", /* 0x42 */
"application/vnd.syncml.dm+xml", /* 0x43 */
"application/vnd.syncml.notification", /* 0x44 */
"application/vnd.wap.xhtml+xml", /* 0x45 */
"application/vnd.wv.csp.cir", /* 0x46 */
"application/vnd.oma.dd+xml", /* 0x47 */
"application/vnd.oma.drm.message", /* 0x48 */
"application/vnd.oma.drm.content", /* 0x49 */
"application/vnd.oma.drm.rights+xml", /* 0x4A */
"application/vnd.oma.drm.rights+wbxml", /* 0x4B */
"application/vnd.wv.csp+xml", /* 0x4C */
"application/vnd.wv.csp+wbxml", /* 0x4D */
"application/vnd.syncml.ds.notification", /* 0x4E */
"audio/*", /* 0x4F */
"video/*", /* 0x50 */
"application/vnd.oma.dd2+xml", /* 0x51 */
"application/mikey" /* 0x52 */
};
}
| 6,299 | 55.756757 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/PduHeaders.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
import java.util.ArrayList;
import java.util.HashMap;
public class PduHeaders {
/**
* All pdu header fields.
*/
public static final int BCC = 0x81;
public static final int CC = 0x82;
public static final int CONTENT_LOCATION = 0x83;
public static final int CONTENT_TYPE = 0x84;
public static final int DATE = 0x85;
public static final int DELIVERY_REPORT = 0x86;
public static final int DELIVERY_TIME = 0x87;
public static final int EXPIRY = 0x88;
public static final int FROM = 0x89;
public static final int MESSAGE_CLASS = 0x8A;
public static final int MESSAGE_ID = 0x8B;
public static final int MESSAGE_TYPE = 0x8C;
public static final int MMS_VERSION = 0x8D;
public static final int MESSAGE_SIZE = 0x8E;
public static final int PRIORITY = 0x8F;
public static final int READ_REPLY = 0x90;
public static final int READ_REPORT = 0x90;
public static final int REPORT_ALLOWED = 0x91;
public static final int RESPONSE_STATUS = 0x92;
public static final int RESPONSE_TEXT = 0x93;
public static final int SENDER_VISIBILITY = 0x94;
public static final int STATUS = 0x95;
public static final int SUBJECT = 0x96;
public static final int TO = 0x97;
public static final int TRANSACTION_ID = 0x98;
public static final int RETRIEVE_STATUS = 0x99;
public static final int RETRIEVE_TEXT = 0x9A;
public static final int READ_STATUS = 0x9B;
public static final int REPLY_CHARGING = 0x9C;
public static final int REPLY_CHARGING_DEADLINE = 0x9D;
public static final int REPLY_CHARGING_ID = 0x9E;
public static final int REPLY_CHARGING_SIZE = 0x9F;
public static final int PREVIOUSLY_SENT_BY = 0xA0;
public static final int PREVIOUSLY_SENT_DATE = 0xA1;
public static final int STORE = 0xA2;
public static final int MM_STATE = 0xA3;
public static final int MM_FLAGS = 0xA4;
public static final int STORE_STATUS = 0xA5;
public static final int STORE_STATUS_TEXT = 0xA6;
public static final int STORED = 0xA7;
public static final int ATTRIBUTES = 0xA8;
public static final int TOTALS = 0xA9;
public static final int MBOX_TOTALS = 0xAA;
public static final int QUOTAS = 0xAB;
public static final int MBOX_QUOTAS = 0xAC;
public static final int MESSAGE_COUNT = 0xAD;
public static final int CONTENT = 0xAE;
public static final int START = 0xAF;
public static final int ADDITIONAL_HEADERS = 0xB0;
public static final int DISTRIBUTION_INDICATOR = 0xB1;
public static final int ELEMENT_DESCRIPTOR = 0xB2;
public static final int LIMIT = 0xB3;
public static final int RECOMMENDED_RETRIEVAL_MODE = 0xB4;
public static final int RECOMMENDED_RETRIEVAL_MODE_TEXT = 0xB5;
public static final int STATUS_TEXT = 0xB6;
public static final int APPLIC_ID = 0xB7;
public static final int REPLY_APPLIC_ID = 0xB8;
public static final int AUX_APPLIC_ID = 0xB9;
public static final int CONTENT_CLASS = 0xBA;
public static final int DRM_CONTENT = 0xBB;
public static final int ADAPTATION_ALLOWED = 0xBC;
public static final int REPLACE_ID = 0xBD;
public static final int CANCEL_ID = 0xBE;
public static final int CANCEL_STATUS = 0xBF;
/**
* X-Mms-Message-Type field types.
*/
public static final int MESSAGE_TYPE_SEND_REQ = 0x80;
public static final int MESSAGE_TYPE_SEND_CONF = 0x81;
public static final int MESSAGE_TYPE_NOTIFICATION_IND = 0x82;
public static final int MESSAGE_TYPE_NOTIFYRESP_IND = 0x83;
public static final int MESSAGE_TYPE_RETRIEVE_CONF = 0x84;
public static final int MESSAGE_TYPE_ACKNOWLEDGE_IND = 0x85;
public static final int MESSAGE_TYPE_DELIVERY_IND = 0x86;
public static final int MESSAGE_TYPE_READ_REC_IND = 0x87;
public static final int MESSAGE_TYPE_READ_ORIG_IND = 0x88;
public static final int MESSAGE_TYPE_FORWARD_REQ = 0x89;
public static final int MESSAGE_TYPE_FORWARD_CONF = 0x8A;
public static final int MESSAGE_TYPE_MBOX_STORE_REQ = 0x8B;
public static final int MESSAGE_TYPE_MBOX_STORE_CONF = 0x8C;
public static final int MESSAGE_TYPE_MBOX_VIEW_REQ = 0x8D;
public static final int MESSAGE_TYPE_MBOX_VIEW_CONF = 0x8E;
public static final int MESSAGE_TYPE_MBOX_UPLOAD_REQ = 0x8F;
public static final int MESSAGE_TYPE_MBOX_UPLOAD_CONF = 0x90;
public static final int MESSAGE_TYPE_MBOX_DELETE_REQ = 0x91;
public static final int MESSAGE_TYPE_MBOX_DELETE_CONF = 0x92;
public static final int MESSAGE_TYPE_MBOX_DESCR = 0x93;
public static final int MESSAGE_TYPE_DELETE_REQ = 0x94;
public static final int MESSAGE_TYPE_DELETE_CONF = 0x95;
public static final int MESSAGE_TYPE_CANCEL_REQ = 0x96;
public static final int MESSAGE_TYPE_CANCEL_CONF = 0x97;
/**
* X-Mms-Delivery-Report |
* X-Mms-Read-Report |
* X-Mms-Report-Allowed |
* X-Mms-Sender-Visibility |
* X-Mms-Store |
* X-Mms-Stored |
* X-Mms-Totals |
* X-Mms-Quotas |
* X-Mms-Distribution-Indicator |
* X-Mms-DRM-Content |
* X-Mms-Adaptation-Allowed |
* field types.
*/
public static final int VALUE_YES = 0x80;
public static final int VALUE_NO = 0x81;
/**
* Delivery-Time |
* Expiry and Reply-Charging-Deadline |
* field type components.
*/
public static final int VALUE_ABSOLUTE_TOKEN = 0x80;
public static final int VALUE_RELATIVE_TOKEN = 0x81;
/**
* X-Mms-MMS-Version field types.
*/
public static final int MMS_VERSION_1_3 = ((1 << 4) | 3);
public static final int MMS_VERSION_1_2 = ((1 << 4) | 2);
public static final int MMS_VERSION_1_1 = ((1 << 4) | 1);
public static final int MMS_VERSION_1_0 = ((1 << 4) | 0);
// Current version is 1.2.
public static final int CURRENT_MMS_VERSION = MMS_VERSION_1_2;
/**
* From field type components.
*/
public static final int FROM_ADDRESS_PRESENT_TOKEN = 0x80;
public static final int FROM_INSERT_ADDRESS_TOKEN = 0x81;
public static final String FROM_ADDRESS_PRESENT_TOKEN_STR = "address-present-token";
public static final String FROM_INSERT_ADDRESS_TOKEN_STR = "insert-address-token";
/**
* X-Mms-Status Field.
*/
public static final int STATUS_EXPIRED = 0x80;
public static final int STATUS_RETRIEVED = 0x81;
public static final int STATUS_REJECTED = 0x82;
public static final int STATUS_DEFERRED = 0x83;
public static final int STATUS_UNRECOGNIZED = 0x84;
public static final int STATUS_INDETERMINATE = 0x85;
public static final int STATUS_FORWARDED = 0x86;
public static final int STATUS_UNREACHABLE = 0x87;
/**
* MM-Flags field type components.
*/
public static final int MM_FLAGS_ADD_TOKEN = 0x80;
public static final int MM_FLAGS_REMOVE_TOKEN = 0x81;
public static final int MM_FLAGS_FILTER_TOKEN = 0x82;
/**
* X-Mms-Message-Class field types.
*/
public static final int MESSAGE_CLASS_PERSONAL = 0x80;
public static final int MESSAGE_CLASS_ADVERTISEMENT = 0x81;
public static final int MESSAGE_CLASS_INFORMATIONAL = 0x82;
public static final int MESSAGE_CLASS_AUTO = 0x83;
public static final String MESSAGE_CLASS_PERSONAL_STR = "personal";
public static final String MESSAGE_CLASS_ADVERTISEMENT_STR = "advertisement";
public static final String MESSAGE_CLASS_INFORMATIONAL_STR = "informational";
public static final String MESSAGE_CLASS_AUTO_STR = "auto";
/**
* X-Mms-Priority field types.
*/
public static final int PRIORITY_LOW = 0x80;
public static final int PRIORITY_NORMAL = 0x81;
public static final int PRIORITY_HIGH = 0x82;
/**
* X-Mms-Response-Status field types.
*/
public static final int RESPONSE_STATUS_OK = 0x80;
public static final int RESPONSE_STATUS_ERROR_UNSPECIFIED = 0x81;
public static final int RESPONSE_STATUS_ERROR_SERVICE_DENIED = 0x82;
public static final int RESPONSE_STATUS_ERROR_MESSAGE_FORMAT_CORRUPT = 0x83;
public static final int RESPONSE_STATUS_ERROR_SENDING_ADDRESS_UNRESOLVED = 0x84;
public static final int RESPONSE_STATUS_ERROR_MESSAGE_NOT_FOUND = 0x85;
public static final int RESPONSE_STATUS_ERROR_NETWORK_PROBLEM = 0x86;
public static final int RESPONSE_STATUS_ERROR_CONTENT_NOT_ACCEPTED = 0x87;
public static final int RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE = 0x88;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_SENDNG_ADDRESS_UNRESOLVED = 0xC1;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 0xC2;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC3;
public static final int RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS = 0xC4;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 0xE2;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED = 0xE3;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE4;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED = 0xE5;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET = 0xE6;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 0xE6;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED = 0xE8;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED = 0xE9;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_ADDRESS_HIDING_NOT_SUPPORTED = 0xEA;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID = 0xEB;
public static final int RESPONSE_STATUS_ERROR_PERMANENT_END = 0xFF;
/**
* X-Mms-Retrieve-Status field types.
*/
public static final int RETRIEVE_STATUS_OK = 0x80;
public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0;
public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 0xC1;
public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC2;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE2;
public static final int RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED = 0xE3;
public static final int RETRIEVE_STATUS_ERROR_END = 0xFF;
/**
* X-Mms-Sender-Visibility field types.
*/
public static final int SENDER_VISIBILITY_HIDE = 0x80;
public static final int SENDER_VISIBILITY_SHOW = 0x81;
/**
* X-Mms-Read-Status field types.
*/
public static final int READ_STATUS_READ = 0x80;
public static final int READ_STATUS__DELETED_WITHOUT_BEING_READ = 0x81;
/**
* X-Mms-Cancel-Status field types.
*/
public static final int CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED = 0x80;
public static final int CANCEL_STATUS_REQUEST_CORRUPTED = 0x81;
/**
* X-Mms-Reply-Charging field types.
*/
public static final int REPLY_CHARGING_REQUESTED = 0x80;
public static final int REPLY_CHARGING_REQUESTED_TEXT_ONLY = 0x81;
public static final int REPLY_CHARGING_ACCEPTED = 0x82;
public static final int REPLY_CHARGING_ACCEPTED_TEXT_ONLY = 0x83;
/**
* X-Mms-MM-State field types.
*/
public static final int MM_STATE_DRAFT = 0x80;
public static final int MM_STATE_SENT = 0x81;
public static final int MM_STATE_NEW = 0x82;
public static final int MM_STATE_RETRIEVED = 0x83;
public static final int MM_STATE_FORWARDED = 0x84;
/**
* X-Mms-Recommended-Retrieval-Mode field types.
*/
public static final int RECOMMENDED_RETRIEVAL_MODE_MANUAL = 0x80;
/**
* X-Mms-Content-Class field types.
*/
public static final int CONTENT_CLASS_TEXT = 0x80;
public static final int CONTENT_CLASS_IMAGE_BASIC = 0x81;
public static final int CONTENT_CLASS_IMAGE_RICH = 0x82;
public static final int CONTENT_CLASS_VIDEO_BASIC = 0x83;
public static final int CONTENT_CLASS_VIDEO_RICH = 0x84;
public static final int CONTENT_CLASS_MEGAPIXEL = 0x85;
public static final int CONTENT_CLASS_CONTENT_BASIC = 0x86;
public static final int CONTENT_CLASS_CONTENT_RICH = 0x87;
/**
* X-Mms-Store-Status field types.
*/
public static final int STORE_STATUS_SUCCESS = 0x80;
public static final int STORE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0;
public static final int STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC1;
public static final int STORE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0;
public static final int STORE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1;
public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 0xE2;
public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE3;
public static final int STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL = 0xE4;
public static final int STORE_STATUS_ERROR_END = 0xFF;
/**
* The map contains the value of all headers.
*/
private HashMap<Integer, Object> mHeaderMap = null;
private long messageBox;
/**
* Constructor of PduHeaders.
*/
public PduHeaders() {
mHeaderMap = new HashMap<Integer, Object>();
}
/**
* Get octet value by header field.
*
* @param field the field
* @return the octet value of the pdu header
* with specified header field. Return 0 if
* the value is not set.
*/
public int getOctet(int field) {
Integer octet = (Integer) mHeaderMap.get(field);
if (null == octet) {
return 0;
}
return octet;
}
public void setMessageBox(long messageBox) {
this.messageBox = messageBox;
}
public long getMessageBox() {
return this.messageBox;
}
/**
* Set octet value to pdu header by header field.
*
* @param value the value
* @param field the field
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setOctet(int value, int field)
throws InvalidHeaderValueException{
/**
* Check whether this field can be set for specific
* header and check validity of the field.
*/
switch (field) {
case REPORT_ALLOWED:
case ADAPTATION_ALLOWED:
case DELIVERY_REPORT:
case DRM_CONTENT:
case DISTRIBUTION_INDICATOR:
case QUOTAS:
case READ_REPORT:
case STORE:
case STORED:
case TOTALS:
case SENDER_VISIBILITY:
if ((VALUE_YES != value) && (VALUE_NO != value)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case READ_STATUS:
if ((READ_STATUS_READ != value) &&
(READ_STATUS__DELETED_WITHOUT_BEING_READ != value)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case CANCEL_STATUS:
if ((CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED != value) &&
(CANCEL_STATUS_REQUEST_CORRUPTED != value)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case PRIORITY:
if ((value < PRIORITY_LOW) || (value > PRIORITY_HIGH)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case STATUS:
// if ((value < STATUS_EXPIRED) || (value > STATUS_UNREACHABLE)) {
// // Invalid value.
// throw new InvalidHeaderValueException("Invalid Octet value!");
// }
break;
case REPLY_CHARGING:
if ((value < REPLY_CHARGING_REQUESTED)
|| (value > REPLY_CHARGING_ACCEPTED_TEXT_ONLY)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case MM_STATE:
if ((value < MM_STATE_DRAFT) || (value > MM_STATE_FORWARDED)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case RECOMMENDED_RETRIEVAL_MODE:
if (RECOMMENDED_RETRIEVAL_MODE_MANUAL != value) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case CONTENT_CLASS:
if ((value < CONTENT_CLASS_TEXT)
|| (value > CONTENT_CLASS_CONTENT_RICH)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
case RETRIEVE_STATUS:
// According to oma-ts-mms-enc-v1_3, section 7.3.50, we modify the invalid value.
if ((value > RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM) &&
(value < RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE)) {
value = RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE;
} else if ((value > RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED) &&
(value <= RETRIEVE_STATUS_ERROR_END)) {
value = RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE;
} else if ((value < RETRIEVE_STATUS_OK) ||
((value > RETRIEVE_STATUS_OK) &&
(value < RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE)) ||
(value > RETRIEVE_STATUS_ERROR_END)) {
value = RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE;
}
break;
case STORE_STATUS:
// According to oma-ts-mms-enc-v1_3, section 7.3.58, we modify the invalid value.
if ((value > STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM) &&
(value < STORE_STATUS_ERROR_PERMANENT_FAILURE)) {
value = STORE_STATUS_ERROR_TRANSIENT_FAILURE;
} else if ((value > STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL) &&
(value <= STORE_STATUS_ERROR_END)) {
value = STORE_STATUS_ERROR_PERMANENT_FAILURE;
} else if ((value < STORE_STATUS_SUCCESS) ||
((value > STORE_STATUS_SUCCESS) &&
(value < STORE_STATUS_ERROR_TRANSIENT_FAILURE)) ||
(value > STORE_STATUS_ERROR_END)) {
value = STORE_STATUS_ERROR_PERMANENT_FAILURE;
}
break;
case RESPONSE_STATUS:
// According to oma-ts-mms-enc-v1_3, section 7.3.48, we modify the invalid value.
if ((value > RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS) &&
(value < RESPONSE_STATUS_ERROR_PERMANENT_FAILURE)) {
value = RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE;
} else if (((value > RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID) &&
(value <= RESPONSE_STATUS_ERROR_PERMANENT_END)) ||
(value < RESPONSE_STATUS_OK) ||
((value > RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE) &&
(value < RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE)) ||
(value > RESPONSE_STATUS_ERROR_PERMANENT_END)) {
value = RESPONSE_STATUS_ERROR_PERMANENT_FAILURE;
}
break;
case MMS_VERSION:
if ((value < MMS_VERSION_1_0)|| (value > MMS_VERSION_1_3)) {
value = CURRENT_MMS_VERSION; // Current version is the default value.
}
break;
case MESSAGE_TYPE:
if ((value < MESSAGE_TYPE_SEND_REQ) || (value > MESSAGE_TYPE_CANCEL_CONF)) {
// Invalid value.
throw new InvalidHeaderValueException("Invalid Octet value!");
}
break;
default:
// This header value should not be Octect.
throw new RuntimeException("Invalid header field!");
}
mHeaderMap.put(field, value);
}
/**
* Get TextString value by header field.
*
* @param field the field
* @return the TextString value of the pdu header
* with specified header field
*/
public byte[] getTextString(int field) {
return (byte[]) mHeaderMap.get(field);
}
/**
* Set TextString value to pdu header by header field.
*
* @param value the value
* @param field the field
* @return the TextString value of the pdu header
* with specified header field
* @throws NullPointerException if the value is null.
*/
public void setTextString(byte[] value, int field) {
/**
* Check whether this field can be set for specific
* header and check validity of the field.
*/
if (null == value) {
throw new NullPointerException();
}
switch (field) {
case TRANSACTION_ID:
case REPLY_CHARGING_ID:
case AUX_APPLIC_ID:
case APPLIC_ID:
case REPLY_APPLIC_ID:
case MESSAGE_ID:
case REPLACE_ID:
case CANCEL_ID:
case CONTENT_LOCATION:
case MESSAGE_CLASS:
case CONTENT_TYPE:
break;
default:
// This header value should not be Text-String.
throw new RuntimeException("Invalid header field!");
}
mHeaderMap.put(field, value);
}
/**
* Get EncodedStringValue value by header field.
*
* @param field the field
* @return the EncodedStringValue value of the pdu header
* with specified header field
*/
public EncodedStringValue getEncodedStringValue(int field) {
return (EncodedStringValue) mHeaderMap.get(field);
}
/**
* Get TO, CC or BCC header value.
*
* @param field the field
* @return the EncodeStringValue array of the pdu header
* with specified header field
*/
public EncodedStringValue[] getEncodedStringValues(int field) {
ArrayList<EncodedStringValue> list =
(ArrayList<EncodedStringValue>) mHeaderMap.get(field);
if (null == list) {
return null;
}
EncodedStringValue[] values = new EncodedStringValue[list.size()];
return list.toArray(values);
}
/**
* Set EncodedStringValue value to pdu header by header field.
*
* @param value the value
* @param field the field
* @return the EncodedStringValue value of the pdu header
* with specified header field
* @throws NullPointerException if the value is null.
*/
public void setEncodedStringValue(EncodedStringValue value, int field) {
/**
* Check whether this field can be set for specific
* header and check validity of the field.
*/
if (null == value) {
throw new NullPointerException();
}
switch (field) {
case SUBJECT:
case RECOMMENDED_RETRIEVAL_MODE_TEXT:
case RETRIEVE_TEXT:
case STATUS_TEXT:
case STORE_STATUS_TEXT:
case RESPONSE_TEXT:
case FROM:
case PREVIOUSLY_SENT_BY:
case MM_FLAGS:
break;
default:
// This header value should not be Encoded-String-Value.
throw new RuntimeException("Invalid header field!");
}
mHeaderMap.put(field, value);
}
/**
* Set TO, CC or BCC header value.
*
* @param value the value
* @param field the field
* @return the EncodedStringValue value array of the pdu header
* with specified header field
* @throws NullPointerException if the value is null.
*/
protected void setEncodedStringValues(EncodedStringValue[] value, int field) {
/**
* Check whether this field can be set for specific
* header and check validity of the field.
*/
if (null == value) {
throw new NullPointerException();
}
switch (field) {
case BCC:
case CC:
case TO:
break;
default:
// This header value should not be Encoded-String-Value.
throw new RuntimeException("Invalid header field!");
}
ArrayList<EncodedStringValue> list = new ArrayList<EncodedStringValue>();
for (int i = 0; i < value.length; i++) {
list.add(value[i]);
}
mHeaderMap.put(field, list);
}
/**
* Append one EncodedStringValue to another.
*
* @param value the EncodedStringValue to append
* @param field the field
* @throws NullPointerException if the value is null.
*/
public void appendEncodedStringValue(EncodedStringValue value,
int field) {
if (null == value) {
throw new NullPointerException();
}
switch (field) {
case BCC:
case CC:
case TO:
break;
default:
throw new RuntimeException("Invalid header field!");
}
ArrayList<EncodedStringValue> list =
(ArrayList<EncodedStringValue>) mHeaderMap.get(field);
if (null == list) {
list = new ArrayList<EncodedStringValue>();
}
list.add(value);
mHeaderMap.put(field, list);
}
/**
* Get LongInteger value by header field.
*
* @param field the field
* @return the LongInteger value of the pdu header
* with specified header field. if return -1, the
* field is not existed in pdu header.
*/
public long getLongInteger(int field) {
Long longInteger = (Long) mHeaderMap.get(field);
if (null == longInteger) {
return -1;
}
return longInteger.longValue();
}
/**
* Set LongInteger value to pdu header by header field.
*
* @param value the value
* @param field the field
*/
public void setLongInteger(long value, int field) {
/**
* Check whether this field can be set for specific
* header and check validity of the field.
*/
switch (field) {
case DATE:
case REPLY_CHARGING_SIZE:
case MESSAGE_SIZE:
case MESSAGE_COUNT:
case START:
case LIMIT:
case DELIVERY_TIME:
case EXPIRY:
case REPLY_CHARGING_DEADLINE:
case PREVIOUSLY_SENT_DATE:
break;
default:
// This header value should not be LongInteger.
throw new RuntimeException("Invalid header field!");
}
mHeaderMap.put(field, value);
}
}
| 31,432 | 41.941257 | 103 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/PduParser.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import android.content.res.Resources;
import android.util.Log;
import ws.com.google.android.mms.ContentType;
import ws.com.google.android.mms.InvalidHeaderValueException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
public class PduParser {
/**
* The next are WAP values defined in WSP specification.
*/
private static final int QUOTE = 127;
private static final int LENGTH_QUOTE = 31;
private static final int TEXT_MIN = 32;
private static final int TEXT_MAX = 127;
private static final int SHORT_INTEGER_MAX = 127;
private static final int SHORT_LENGTH_MAX = 30;
private static final int LONG_INTEGER_LENGTH_MAX = 8;
private static final int QUOTED_STRING_FLAG = 34;
private static final int END_STRING_FLAG = 0x00;
//The next two are used by the interface "parseWapString" to
//distinguish Text-String and Quoted-String.
private static final int TYPE_TEXT_STRING = 0;
private static final int TYPE_QUOTED_STRING = 1;
private static final int TYPE_TOKEN_STRING = 2;
/**
* Specify the part position.
*/
private static final int THE_FIRST_PART = 0;
private static final int THE_LAST_PART = 1;
/**
* The pdu data.
*/
private ByteArrayInputStream mPduDataStream = null;
/**
* Store pdu headers
*/
private PduHeaders mHeaders = null;
/**
* Store pdu parts.
*/
private PduBody mBody = null;
/**
* Store the "type" parameter in "Content-Type" header field.
*/
private static byte[] mTypeParam = null;
/**
* Store the "start" parameter in "Content-Type" header field.
*/
private static byte[] mStartParam = null;
/**
* The log tag.
*/
private static final String LOG_TAG = "PduParser";
private static final boolean LOCAL_LOGV = true;
/**
* Constructor.
*
* @param pduDataStream pdu data to be parsed
*/
public PduParser(byte[] pduDataStream) {
mPduDataStream = new ByteArrayInputStream(pduDataStream);
}
/**
* Parse the pdu.
*
* @return the pdu structure if parsing successfully.
* null if parsing error happened or mandatory fields are not set.
*/
public GenericPdu parse(){
Log.w("PduParser", "parse() called...");
if (mPduDataStream == null) {
return null;
}
/* parse headers */
mHeaders = parseHeaders(mPduDataStream);
if (null == mHeaders) {
// Parse headers failed.
return null;
}
/* get the message type */
int messageType = mHeaders.getOctet(PduHeaders.MESSAGE_TYPE);
/* check mandatory header fields */
if (false == checkMandatoryHeader(mHeaders)) {
log("check mandatory headers failed!");
return null;
}
Log.w("PduParser", "Message Type: " + messageType);
if ((PduHeaders.MESSAGE_TYPE_SEND_REQ == messageType) ||
(PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF == messageType)) {
/* need to parse the parts */
Log.w("PduParser", "Parsing parts...");
mBody = parseParts(mPduDataStream);
if (null == mBody) {
// Parse parts failed.
return null;
}
}
switch (messageType) {
case PduHeaders.MESSAGE_TYPE_SEND_REQ:
SendReq sendReq = new SendReq(mHeaders, mBody);
return sendReq;
case PduHeaders.MESSAGE_TYPE_SEND_CONF:
SendConf sendConf = new SendConf(mHeaders);
return sendConf;
case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
NotificationInd notificationInd =
new NotificationInd(mHeaders);
return notificationInd;
case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND:
NotifyRespInd notifyRespInd =
new NotifyRespInd(mHeaders);
return notifyRespInd;
case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
RetrieveConf retrieveConf =
new RetrieveConf(mHeaders, mBody);
byte[] contentType = retrieveConf.getContentType();
if (null == contentType) {
return null;
}
String ctTypeStr = new String(contentType);
if (ctTypeStr.equals(ContentType.MULTIPART_MIXED)
|| ctTypeStr.equals(ContentType.MULTIPART_RELATED)
|| ctTypeStr.equals(ContentType.MULTIPART_ALTERNATIVE)) {
// The MMS content type must be "application/vnd.wap.multipart.mixed"
// or "application/vnd.wap.multipart.related"
// or "application/vnd.wap.multipart.alternative"
return retrieveConf;
} else if (ctTypeStr.equals(ContentType.MULTIPART_ALTERNATIVE)) {
// "application/vnd.wap.multipart.alternative"
// should take only the first part.
PduPart firstPart = mBody.getPart(0);
mBody.removeAll();
mBody.addPart(0, firstPart);
return retrieveConf;
}
return null;
case PduHeaders.MESSAGE_TYPE_DELIVERY_IND:
DeliveryInd deliveryInd =
new DeliveryInd(mHeaders);
return deliveryInd;
case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND:
AcknowledgeInd acknowledgeInd =
new AcknowledgeInd(mHeaders);
return acknowledgeInd;
case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND:
ReadOrigInd readOrigInd =
new ReadOrigInd(mHeaders);
return readOrigInd;
case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
ReadRecInd readRecInd =
new ReadRecInd(mHeaders);
return readRecInd;
default:
log("Parser doesn't support this message type in this version!");
return null;
}
}
/**
* Parse pdu headers.
*
* @param pduDataStream pdu data input stream
* @return headers in PduHeaders structure, null when parse fail
*/
protected PduHeaders parseHeaders(ByteArrayInputStream pduDataStream){
if (pduDataStream == null) {
return null;
}
boolean keepParsing = true;
PduHeaders headers = new PduHeaders();
while (keepParsing && (pduDataStream.available() > 0)) {
pduDataStream.mark(1);
int headerField = extractByteValue(pduDataStream);
/* parse custom text header */
if ((headerField >= TEXT_MIN) && (headerField <= TEXT_MAX)) {
pduDataStream.reset();
byte [] bVal = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if (LOCAL_LOGV) {
Log.v(LOG_TAG, "TextHeader: " + new String(bVal));
}
/* we should ignore it at the moment */
continue;
}
switch (headerField) {
case PduHeaders.MESSAGE_TYPE:
{
int messageType = extractByteValue(pduDataStream);
switch (messageType) {
// We don't support these kind of messages now.
case PduHeaders.MESSAGE_TYPE_FORWARD_REQ:
case PduHeaders.MESSAGE_TYPE_FORWARD_CONF:
case PduHeaders.MESSAGE_TYPE_MBOX_STORE_REQ:
case PduHeaders.MESSAGE_TYPE_MBOX_STORE_CONF:
case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_REQ:
case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_CONF:
case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_REQ:
case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_CONF:
case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_REQ:
case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_CONF:
case PduHeaders.MESSAGE_TYPE_MBOX_DESCR:
case PduHeaders.MESSAGE_TYPE_DELETE_REQ:
case PduHeaders.MESSAGE_TYPE_DELETE_CONF:
case PduHeaders.MESSAGE_TYPE_CANCEL_REQ:
case PduHeaders.MESSAGE_TYPE_CANCEL_CONF:
return null;
}
try {
headers.setOctet(messageType, headerField);
} catch(InvalidHeaderValueException e) {
log("Set invalid Octet value: " + messageType +
" into the header filed: " + headerField);
return null;
} catch(RuntimeException e) {
log(headerField + "is not Octet header field!");
return null;
}
break;
}
/* Octect value */
case PduHeaders.REPORT_ALLOWED:
case PduHeaders.ADAPTATION_ALLOWED:
case PduHeaders.DELIVERY_REPORT:
case PduHeaders.DRM_CONTENT:
case PduHeaders.DISTRIBUTION_INDICATOR:
case PduHeaders.QUOTAS:
case PduHeaders.READ_REPORT:
case PduHeaders.STORE:
case PduHeaders.STORED:
case PduHeaders.TOTALS:
case PduHeaders.SENDER_VISIBILITY:
case PduHeaders.READ_STATUS:
case PduHeaders.CANCEL_STATUS:
case PduHeaders.PRIORITY:
case PduHeaders.STATUS:
case PduHeaders.REPLY_CHARGING:
case PduHeaders.MM_STATE:
case PduHeaders.RECOMMENDED_RETRIEVAL_MODE:
case PduHeaders.CONTENT_CLASS:
case PduHeaders.RETRIEVE_STATUS:
case PduHeaders.STORE_STATUS:
/**
* The following field has a different value when
* used in the M-Mbox-Delete.conf and M-Delete.conf PDU.
* For now we ignore this fact, since we do not support these PDUs
*/
case PduHeaders.RESPONSE_STATUS:
{
int value = extractByteValue(pduDataStream);
try {
headers.setOctet(value, headerField);
} catch(InvalidHeaderValueException e) {
log("Set invalid Octet value: " + value +
" into the header filed: " + headerField);
return null;
} catch(RuntimeException e) {
log(headerField + "is not Octet header field!");
return null;
}
break;
}
/* Long-Integer */
case PduHeaders.DATE:
case PduHeaders.REPLY_CHARGING_SIZE:
case PduHeaders.MESSAGE_SIZE:
{
try {
long value = parseLongInteger(pduDataStream);
headers.setLongInteger(value, headerField);
} catch(RuntimeException e) {
log(headerField + "is not Long-Integer header field!");
return null;
}
break;
}
/* Integer-Value */
case PduHeaders.MESSAGE_COUNT:
case PduHeaders.START:
case PduHeaders.LIMIT:
{
try {
long value = parseIntegerValue(pduDataStream);
headers.setLongInteger(value, headerField);
} catch(RuntimeException e) {
log(headerField + "is not Long-Integer header field!");
return null;
}
break;
}
/* Text-String */
case PduHeaders.TRANSACTION_ID:
case PduHeaders.REPLY_CHARGING_ID:
case PduHeaders.AUX_APPLIC_ID:
case PduHeaders.APPLIC_ID:
case PduHeaders.REPLY_APPLIC_ID:
/**
* The next three header fields are email addresses
* as defined in RFC2822,
* not including the characters "<" and ">"
*/
case PduHeaders.MESSAGE_ID:
case PduHeaders.REPLACE_ID:
case PduHeaders.CANCEL_ID:
/**
* The following field has a different value when
* used in the M-Mbox-Delete.conf and M-Delete.conf PDU.
* For now we ignore this fact, since we do not support these PDUs
*/
case PduHeaders.CONTENT_LOCATION:
{
byte[] value = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if (null != value) {
try {
headers.setTextString(value, headerField);
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Text-String header field!");
return null;
}
}
break;
}
/* Encoded-string-value */
case PduHeaders.SUBJECT:
case PduHeaders.RECOMMENDED_RETRIEVAL_MODE_TEXT:
case PduHeaders.RETRIEVE_TEXT:
case PduHeaders.STATUS_TEXT:
case PduHeaders.STORE_STATUS_TEXT:
/* the next one is not support
* M-Mbox-Delete.conf and M-Delete.conf now */
case PduHeaders.RESPONSE_TEXT:
{
EncodedStringValue value =
parseEncodedStringValue(pduDataStream);
if (null != value) {
try {
headers.setEncodedStringValue(value, headerField);
} catch(NullPointerException e) {
log("null pointer error!");
} catch (RuntimeException e) {
log(headerField + "is not Encoded-String-Value header field!");
return null;
}
}
break;
}
/* Addressing model */
case PduHeaders.BCC:
case PduHeaders.CC:
case PduHeaders.TO:
{
EncodedStringValue value =
parseEncodedStringValue(pduDataStream);
if (null != value) {
byte[] address = value.getTextString();
if (null != address) {
String str = new String(address);
int endIndex = str.indexOf("/");
if (endIndex > 0) {
str = str.substring(0, endIndex);
}
try {
value.setTextString(str.getBytes());
} catch(NullPointerException e) {
log("null pointer error!");
return null;
}
}
try {
headers.appendEncodedStringValue(value, headerField);
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Encoded-String-Value header field!");
return null;
}
}
break;
}
/* Value-length
* (Absolute-token Date-value | Relative-token Delta-seconds-value) */
case PduHeaders.DELIVERY_TIME:
case PduHeaders.EXPIRY:
case PduHeaders.REPLY_CHARGING_DEADLINE:
{
/* parse Value-length */
parseValueLength(pduDataStream);
/* Absolute-token or Relative-token */
int token = extractByteValue(pduDataStream);
/* Date-value or Delta-seconds-value */
long timeValue;
try {
timeValue = parseLongInteger(pduDataStream);
} catch(RuntimeException e) {
log(headerField + "is not Long-Integer header field!");
return null;
}
if (PduHeaders.VALUE_RELATIVE_TOKEN == token) {
/* need to convert the Delta-seconds-value
* into Date-value */
timeValue = System.currentTimeMillis()/1000 + timeValue;
}
try {
headers.setLongInteger(timeValue, headerField);
} catch(RuntimeException e) {
log(headerField + "is not Long-Integer header field!");
return null;
}
break;
}
case PduHeaders.FROM: {
/* From-value =
* Value-length
* (Address-present-token Encoded-string-value | Insert-address-token)
*/
EncodedStringValue from = null;
parseValueLength(pduDataStream); /* parse value-length */
/* Address-present-token or Insert-address-token */
int fromToken = extractByteValue(pduDataStream);
/* Address-present-token or Insert-address-token */
if (PduHeaders.FROM_ADDRESS_PRESENT_TOKEN == fromToken) {
/* Encoded-string-value */
from = parseEncodedStringValue(pduDataStream);
if (null != from) {
byte[] address = from.getTextString();
if (null != address) {
String str = new String(address);
int endIndex = str.indexOf("/");
if (endIndex > 0) {
str = str.substring(0, endIndex);
}
try {
from.setTextString(str.getBytes());
} catch(NullPointerException e) {
log("null pointer error!");
return null;
}
}
}
} else {
try {
from = new EncodedStringValue(
PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes());
} catch(NullPointerException e) {
log(headerField + "is not Encoded-String-Value header field!");
return null;
}
}
try {
headers.setEncodedStringValue(from, PduHeaders.FROM);
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Encoded-String-Value header field!");
return null;
}
break;
}
case PduHeaders.MESSAGE_CLASS: {
/* Message-class-value = Class-identifier | Token-text */
pduDataStream.mark(1);
int messageClass = extractByteValue(pduDataStream);
if (messageClass >= PduHeaders.MESSAGE_CLASS_PERSONAL) {
/* Class-identifier */
try {
if (PduHeaders.MESSAGE_CLASS_PERSONAL == messageClass) {
headers.setTextString(
PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes(),
PduHeaders.MESSAGE_CLASS);
} else if (PduHeaders.MESSAGE_CLASS_ADVERTISEMENT == messageClass) {
headers.setTextString(
PduHeaders.MESSAGE_CLASS_ADVERTISEMENT_STR.getBytes(),
PduHeaders.MESSAGE_CLASS);
} else if (PduHeaders.MESSAGE_CLASS_INFORMATIONAL == messageClass) {
headers.setTextString(
PduHeaders.MESSAGE_CLASS_INFORMATIONAL_STR.getBytes(),
PduHeaders.MESSAGE_CLASS);
} else if (PduHeaders.MESSAGE_CLASS_AUTO == messageClass) {
headers.setTextString(
PduHeaders.MESSAGE_CLASS_AUTO_STR.getBytes(),
PduHeaders.MESSAGE_CLASS);
}
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Text-String header field!");
return null;
}
} else {
/* Token-text */
pduDataStream.reset();
byte[] messageClassString = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if (null != messageClassString) {
try {
headers.setTextString(messageClassString, PduHeaders.MESSAGE_CLASS);
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Text-String header field!");
return null;
}
}
}
break;
}
case PduHeaders.MMS_VERSION: {
int version = parseShortInteger(pduDataStream);
try {
headers.setOctet(version, PduHeaders.MMS_VERSION);
} catch(InvalidHeaderValueException e) {
log("Set invalid Octet value: " + version +
" into the header filed: " + headerField);
return null;
} catch(RuntimeException e) {
log(headerField + "is not Octet header field!");
return null;
}
break;
}
case PduHeaders.PREVIOUSLY_SENT_BY: {
/* Previously-sent-by-value =
* Value-length Forwarded-count-value Encoded-string-value */
/* parse value-length */
parseValueLength(pduDataStream);
/* parse Forwarded-count-value */
try {
parseIntegerValue(pduDataStream);
} catch(RuntimeException e) {
log(headerField + " is not Integer-Value");
return null;
}
/* parse Encoded-string-value */
EncodedStringValue previouslySentBy =
parseEncodedStringValue(pduDataStream);
if (null != previouslySentBy) {
try {
headers.setEncodedStringValue(previouslySentBy,
PduHeaders.PREVIOUSLY_SENT_BY);
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Encoded-String-Value header field!");
return null;
}
}
break;
}
case PduHeaders.PREVIOUSLY_SENT_DATE: {
/* Previously-sent-date-value =
* Value-length Forwarded-count-value Date-value */
/* parse value-length */
parseValueLength(pduDataStream);
/* parse Forwarded-count-value */
try {
parseIntegerValue(pduDataStream);
} catch(RuntimeException e) {
log(headerField + " is not Integer-Value");
return null;
}
/* Date-value */
try {
long perviouslySentDate = parseLongInteger(pduDataStream);
headers.setLongInteger(perviouslySentDate,
PduHeaders.PREVIOUSLY_SENT_DATE);
} catch(RuntimeException e) {
log(headerField + "is not Long-Integer header field!");
return null;
}
break;
}
case PduHeaders.MM_FLAGS: {
/* MM-flags-value =
* Value-length
* ( Add-token | Remove-token | Filter-token )
* Encoded-string-value
*/
/* parse Value-length */
parseValueLength(pduDataStream);
/* Add-token | Remove-token | Filter-token */
extractByteValue(pduDataStream);
/* Encoded-string-value */
parseEncodedStringValue(pduDataStream);
/* not store this header filed in "headers",
* because now PduHeaders doesn't support it */
break;
}
/* Value-length
* (Message-total-token | Size-total-token) Integer-Value */
case PduHeaders.MBOX_TOTALS:
case PduHeaders.MBOX_QUOTAS:
{
/* Value-length */
parseValueLength(pduDataStream);
/* Message-total-token | Size-total-token */
extractByteValue(pduDataStream);
/*Integer-Value*/
try {
parseIntegerValue(pduDataStream);
} catch(RuntimeException e) {
log(headerField + " is not Integer-Value");
return null;
}
/* not store these headers filed in "headers",
because now PduHeaders doesn't support them */
break;
}
case PduHeaders.ELEMENT_DESCRIPTOR: {
parseContentType(pduDataStream, null);
/* not store this header filed in "headers",
because now PduHeaders doesn't support it */
break;
}
case PduHeaders.CONTENT_TYPE: {
HashMap<Integer, Object> map =
new HashMap<Integer, Object>();
byte[] contentType =
parseContentType(pduDataStream, map);
if (null != contentType) {
try {
headers.setTextString(contentType, PduHeaders.CONTENT_TYPE);
} catch(NullPointerException e) {
log("null pointer error!");
} catch(RuntimeException e) {
log(headerField + "is not Text-String header field!");
return null;
}
}
/* get start parameter */
mStartParam = (byte[]) map.get(PduPart.P_START);
/* get charset parameter */
mTypeParam= (byte[]) map.get(PduPart.P_TYPE);
keepParsing = false;
break;
}
case PduHeaders.CONTENT:
case PduHeaders.ADDITIONAL_HEADERS:
case PduHeaders.ATTRIBUTES:
default: {
log("Unknown header");
}
}
}
return headers;
}
/**
* Parse pdu parts.
*
* @param pduDataStream pdu data input stream
* @return parts in PduBody structure
*/
protected static PduBody parseParts(ByteArrayInputStream pduDataStream) {
if (pduDataStream == null) {
return null;
}
int count = parseUnsignedInt(pduDataStream); // get the number of parts
PduBody body = new PduBody();
for (int i = 0 ; i < count ; i++) {
int headerLength = parseUnsignedInt(pduDataStream);
int dataLength = parseUnsignedInt(pduDataStream);
PduPart part = new PduPart();
int startPos = pduDataStream.available();
if (startPos <= 0) {
// Invalid part.
return null;
}
/* parse part's content-type */
HashMap<Integer, Object> map = new HashMap<Integer, Object>();
byte[] contentType = parseContentType(pduDataStream, map);
if (null != contentType) {
part.setContentType(contentType);
} else {
part.setContentType((PduContentTypes.contentTypes[0]).getBytes()); //"*/*"
}
/* get name parameter */
byte[] name = (byte[]) map.get(PduPart.P_NAME);
if (null != name) {
part.setName(name);
}
/* get charset parameter */
Integer charset = (Integer) map.get(PduPart.P_CHARSET);
if (null != charset) {
part.setCharset(charset);
}
/* parse part's headers */
int endPos = pduDataStream.available();
int partHeaderLen = headerLength - (startPos - endPos);
if (partHeaderLen > 0) {
if (false == parsePartHeaders(pduDataStream, part, partHeaderLen)) {
// Parse part header faild.
return null;
}
} else if (partHeaderLen < 0) {
// Invalid length of content-type.
return null;
}
/* FIXME: check content-id, name, filename and content location,
* if not set anyone of them, generate a default content-location
*/
if ((null == part.getContentLocation())
&& (null == part.getName())
&& (null == part.getFilename())
&& (null == part.getContentId())) {
part.setContentLocation(Long.toOctalString(
System.currentTimeMillis()).getBytes());
}
/* get part's data */
if (dataLength > 0) {
byte[] partData = new byte[dataLength];
String partContentType = new String(part.getContentType());
pduDataStream.read(partData, 0, dataLength);
if (partContentType.equalsIgnoreCase(ContentType.MULTIPART_ALTERNATIVE)) {
// parse "multipart/vnd.wap.multipart.alternative".
PduBody childBody = parseParts(new ByteArrayInputStream(partData));
// take the first part of children.
part = childBody.getPart(0);
} else {
// Check Content-Transfer-Encoding.
byte[] partDataEncoding = part.getContentTransferEncoding();
if (null != partDataEncoding) {
String encoding = new String(partDataEncoding);
if (encoding.equalsIgnoreCase(PduPart.P_BASE64)) {
// Decode "base64" into "binary".
partData = Base64.decodeBase64(partData);
} else if (encoding.equalsIgnoreCase(PduPart.P_QUOTED_PRINTABLE)) {
// Decode "quoted-printable" into "binary".
partData = QuotedPrintable.decodeQuotedPrintable(partData);
} else {
// "binary" is the default encoding.
}
}
if (null == partData) {
log("Decode part data error!");
return null;
}
part.setData(partData);
}
}
/* add this part to body */
if (THE_FIRST_PART == checkPartPosition(part)) {
/* this is the first part */
body.addPart(0, part);
} else {
/* add the part to the end */
body.addPart(part);
}
}
return body;
}
/**
* Log status.
*
* @param text log information
*/
private static void log(String text) {
if (LOCAL_LOGV) {
Log.v(LOG_TAG, text);
}
}
/**
* Parse unsigned integer.
*
* @param pduDataStream pdu data input stream
* @return the integer, -1 when failed
*/
protected static int parseUnsignedInt(ByteArrayInputStream pduDataStream) {
/**
* From wap-230-wsp-20010705-a.pdf
* The maximum size of a uintvar is 32 bits.
* So it will be encoded in no more than 5 octets.
*/
assert(null != pduDataStream);
int result = 0;
int temp = pduDataStream.read();
if (temp == -1) {
return temp;
}
while((temp & 0x80) != 0) {
result = result << 7;
result |= temp & 0x7F;
temp = pduDataStream.read();
if (temp == -1) {
return temp;
}
}
result = result << 7;
result |= temp & 0x7F;
return result;
}
/**
* Parse value length.
*
* @param pduDataStream pdu data input stream
* @return the integer
*/
protected static int parseValueLength(ByteArrayInputStream pduDataStream) {
/**
* From wap-230-wsp-20010705-a.pdf
* Value-length = Short-length | (Length-quote Length)
* Short-length = <Any octet 0-30>
* Length-quote = <Octet 31>
* Length = Uintvar-integer
* Uintvar-integer = 1*5 OCTET
*/
assert(null != pduDataStream);
int temp = pduDataStream.read();
assert(-1 != temp);
int first = temp & 0xFF;
if (first <= SHORT_LENGTH_MAX) {
return first;
} else if (first == LENGTH_QUOTE) {
return parseUnsignedInt(pduDataStream);
}
throw new RuntimeException ("Value length > LENGTH_QUOTE!");
}
/**
* Parse encoded string value.
*
* @param pduDataStream pdu data input stream
* @return the EncodedStringValue
*/
protected static EncodedStringValue parseEncodedStringValue(ByteArrayInputStream pduDataStream){
/**
* From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf
* Encoded-string-value = Text-string | Value-length Char-set Text-string
*/
assert(null != pduDataStream);
pduDataStream.mark(1);
EncodedStringValue returnValue = null;
int charset = 0;
int temp = pduDataStream.read();
assert(-1 != temp);
int first = temp & 0xFF;
if (first == 0) {
return null; // Blank subject, bail.
}
pduDataStream.reset();
if (first < TEXT_MIN) {
parseValueLength(pduDataStream);
charset = parseShortInteger(pduDataStream); //get the "Charset"
}
byte[] textString = parseWapString(pduDataStream, TYPE_TEXT_STRING);
try {
if (0 != charset) {
returnValue = new EncodedStringValue(charset, textString);
} else {
returnValue = new EncodedStringValue(textString);
}
} catch(Exception e) {
return null;
}
return returnValue;
}
/**
* Parse Text-String or Quoted-String.
*
* @param pduDataStream pdu data input stream
* @param stringType TYPE_TEXT_STRING or TYPE_QUOTED_STRING
* @return the string without End-of-string in byte array
*/
protected static byte[] parseWapString(ByteArrayInputStream pduDataStream,
int stringType) {
assert(null != pduDataStream);
/**
* From wap-230-wsp-20010705-a.pdf
* Text-string = [Quote] *TEXT End-of-string
* If the first character in the TEXT is in the range of 128-255,
* a Quote character must precede it.
* Otherwise the Quote character must be omitted.
* The Quote is not part of the contents.
* Quote = <Octet 127>
* End-of-string = <Octet 0>
*
* Quoted-string = <Octet 34> *TEXT End-of-string
*
* Token-text = Token End-of-string
*/
// Mark supposed beginning of Text-string
// We will have to mark again if first char is QUOTE or QUOTED_STRING_FLAG
pduDataStream.mark(1);
// Check first char
int temp = pduDataStream.read();
assert(-1 != temp);
if ((TYPE_QUOTED_STRING == stringType) &&
(QUOTED_STRING_FLAG == temp)) {
// Mark again if QUOTED_STRING_FLAG and ignore it
pduDataStream.mark(1);
} else if ((TYPE_TEXT_STRING == stringType) &&
(QUOTE == temp)) {
// Mark again if QUOTE and ignore it
pduDataStream.mark(1);
} else {
// Otherwise go back to origin
pduDataStream.reset();
}
// We are now definitely at the beginning of string
/**
* Return *TOKEN or *TEXT (Text-String without QUOTE,
* Quoted-String without QUOTED_STRING_FLAG and without End-of-string)
*/
return getWapString(pduDataStream, stringType);
}
/**
* Check TOKEN data defined in RFC2616.
* @param ch checking data
* @return true when ch is TOKEN, false when ch is not TOKEN
*/
protected static boolean isTokenCharacter(int ch) {
/**
* Token = 1*<any CHAR except CTLs or separators>
* separators = "("(40) | ")"(41) | "<"(60) | ">"(62) | "@"(64)
* | ","(44) | ";"(59) | ":"(58) | "\"(92) | <">(34)
* | "/"(47) | "["(91) | "]"(93) | "?"(63) | "="(61)
* | "{"(123) | "}"(125) | SP(32) | HT(9)
* CHAR = <any US-ASCII character (octets 0 - 127)>
* CTL = <any US-ASCII control character
* (octets 0 - 31) and DEL (127)>
* SP = <US-ASCII SP, space (32)>
* HT = <US-ASCII HT, horizontal-tab (9)>
*/
if((ch < 33) || (ch > 126)) {
return false;
}
switch(ch) {
case '"': /* '"' */
case '(': /* '(' */
case ')': /* ')' */
case ',': /* ',' */
case '/': /* '/' */
case ':': /* ':' */
case ';': /* ';' */
case '<': /* '<' */
case '=': /* '=' */
case '>': /* '>' */
case '?': /* '?' */
case '@': /* '@' */
case '[': /* '[' */
case '\\': /* '\' */
case ']': /* ']' */
case '{': /* '{' */
case '}': /* '}' */
return false;
}
return true;
}
/**
* Check TEXT data defined in RFC2616.
* @param ch checking data
* @return true when ch is TEXT, false when ch is not TEXT
*/
protected static boolean isText(int ch) {
/**
* TEXT = <any OCTET except CTLs,
* but including LWS>
* CTL = <any US-ASCII control character
* (octets 0 - 31) and DEL (127)>
* LWS = [CRLF] 1*( SP | HT )
* CRLF = CR LF
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
*/
if(((ch >= 32) && (ch <= 126)) || ((ch >= 128) && (ch <= 255))) {
return true;
}
switch(ch) {
case '\t': /* '\t' */
case '\n': /* '\n' */
case '\r': /* '\r' */
return true;
}
return false;
}
protected static byte[] getWapString(ByteArrayInputStream pduDataStream,
int stringType) {
assert(null != pduDataStream);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int temp = pduDataStream.read();
assert(-1 != temp);
while((-1 != temp) && ('\0' != temp)) {
// check each of the character
if (stringType == TYPE_TOKEN_STRING) {
if (isTokenCharacter(temp)) {
out.write(temp);
}
} else {
if (isText(temp)) {
out.write(temp);
}
}
temp = pduDataStream.read();
assert(-1 != temp);
}
if (out.size() > 0) {
return out.toByteArray();
}
return null;
}
/**
* Extract a byte value from the input stream.
*
* @param pduDataStream pdu data input stream
* @return the byte
*/
protected static int extractByteValue(ByteArrayInputStream pduDataStream) {
assert(null != pduDataStream);
int temp = pduDataStream.read();
assert(-1 != temp);
return temp & 0xFF;
}
/**
* Parse Short-Integer.
*
* @param pduDataStream pdu data input stream
* @return the byte
*/
protected static int parseShortInteger(ByteArrayInputStream pduDataStream) {
/**
* From wap-230-wsp-20010705-a.pdf
* Short-integer = OCTET
* Integers in range 0-127 shall be encoded as a one
* octet value with the most significant bit set to one (1xxx xxxx)
* and with the value in the remaining least significant bits.
*/
assert(null != pduDataStream);
int temp = pduDataStream.read();
assert(-1 != temp);
return temp & 0x7F;
}
/**
* Parse Long-Integer.
*
* @param pduDataStream pdu data input stream
* @return long integer
*/
protected static long parseLongInteger(ByteArrayInputStream pduDataStream) {
/**
* From wap-230-wsp-20010705-a.pdf
* Long-integer = Short-length Multi-octet-integer
* The Short-length indicates the length of the Multi-octet-integer
* Multi-octet-integer = 1*30 OCTET
* The content octets shall be an unsigned integer value
* with the most significant octet encoded first (big-endian representation).
* The minimum number of octets must be used to encode the value.
* Short-length = <Any octet 0-30>
*/
assert(null != pduDataStream);
int temp = pduDataStream.read();
assert(-1 != temp);
int count = temp & 0xFF;
if (count > LONG_INTEGER_LENGTH_MAX) {
throw new RuntimeException("Octet count greater than 8 and I can't represent that!");
}
long result = 0;
for (int i = 0 ; i < count ; i++) {
temp = pduDataStream.read();
assert(-1 != temp);
result <<= 8;
result += (temp & 0xFF);
}
return result;
}
/**
* Parse Integer-Value.
*
* @param pduDataStream pdu data input stream
* @return long integer
*/
protected static long parseIntegerValue(ByteArrayInputStream pduDataStream) {
/**
* From wap-230-wsp-20010705-a.pdf
* Integer-Value = Short-integer | Long-integer
*/
assert(null != pduDataStream);
pduDataStream.mark(1);
int temp = pduDataStream.read();
assert(-1 != temp);
pduDataStream.reset();
if (temp > SHORT_INTEGER_MAX) {
return parseShortInteger(pduDataStream);
} else {
return parseLongInteger(pduDataStream);
}
}
/**
* To skip length of the wap value.
*
* @param pduDataStream pdu data input stream
* @param length area size
* @return the values in this area
*/
protected static int skipWapValue(ByteArrayInputStream pduDataStream, int length) {
assert(null != pduDataStream);
byte[] area = new byte[length];
int readLen = pduDataStream.read(area, 0, length);
if (readLen < length) { //The actually read length is lower than the length
return -1;
} else {
return readLen;
}
}
/**
* Parse content type parameters. For now we just support
* four parameters used in mms: "type", "start", "name", "charset".
*
* @param pduDataStream pdu data input stream
* @param map to store parameters of Content-Type field
* @param length length of all the parameters
*/
protected static void parseContentTypeParams(ByteArrayInputStream pduDataStream,
HashMap<Integer, Object> map, Integer length) {
/**
* From wap-230-wsp-20010705-a.pdf
* Parameter = Typed-parameter | Untyped-parameter
* Typed-parameter = Well-known-parameter-token Typed-value
* the actual expected type of the value is implied by the well-known parameter
* Well-known-parameter-token = Integer-value
* the code values used for parameters are specified in the Assigned Numbers appendix
* Typed-value = Compact-value | Text-value
* In addition to the expected type, there may be no value.
* If the value cannot be encoded using the expected type, it shall be encoded as text.
* Compact-value = Integer-value |
* Date-value | Delta-seconds-value | Q-value | Version-value |
* Uri-value
* Untyped-parameter = Token-text Untyped-value
* the type of the value is unknown, but it shall be encoded as an integer,
* if that is possible.
* Untyped-value = Integer-value | Text-value
*/
assert(null != pduDataStream);
assert(length > 0);
int startPos = pduDataStream.available();
int tempPos = 0;
int lastLen = length;
while(0 < lastLen) {
int param = pduDataStream.read();
assert(-1 != param);
lastLen--;
switch (param) {
/**
* From rfc2387, chapter 3.1
* The type parameter must be specified and its value is the MIME media
* type of the "root" body part. It permits a MIME user agent to
* determine the content-type without reference to the enclosed body
* part. If the value of the type parameter and the root body part's
* content-type differ then the User Agent's behavior is undefined.
*
* From wap-230-wsp-20010705-a.pdf
* type = Constrained-encoding
* Constrained-encoding = Extension-Media | Short-integer
* Extension-media = *TEXT End-of-string
*/
case PduPart.P_TYPE:
case PduPart.P_CT_MR_TYPE:
pduDataStream.mark(1);
int first = extractByteValue(pduDataStream);
pduDataStream.reset();
if (first > TEXT_MAX) {
// Short-integer (well-known type)
int index = parseShortInteger(pduDataStream);
if (index < PduContentTypes.contentTypes.length) {
byte[] type = (PduContentTypes.contentTypes[index]).getBytes();
map.put(PduPart.P_TYPE, type);
} else {
//not support this type, ignore it.
}
} else {
// Text-String (extension-media)
byte[] type = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if ((null != type) && (null != map)) {
map.put(PduPart.P_TYPE, type);
}
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
break;
/**
* From oma-ts-mms-conf-v1_3.pdf, chapter 10.2.3.
* Start Parameter Referring to Presentation
*
* From rfc2387, chapter 3.2
* The start parameter, if given, is the content-ID of the compound
* object's "root". If not present the "root" is the first body part in
* the Multipart/Related entity. The "root" is the element the
* applications processes first.
*
* From wap-230-wsp-20010705-a.pdf
* start = Text-String
*/
case PduPart.P_START:
case PduPart.P_DEP_START:
byte[] start = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if ((null != start) && (null != map)) {
map.put(PduPart.P_START, start);
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
break;
/**
* From oma-ts-mms-conf-v1_3.pdf
* In creation, the character set SHALL be either us-ascii
* (IANA MIBenum 3) or utf-8 (IANA MIBenum 106)[Unicode].
* In retrieval, both us-ascii and utf-8 SHALL be supported.
*
* From wap-230-wsp-20010705-a.pdf
* charset = Well-known-charset|Text-String
* Well-known-charset = Any-charset | Integer-value
* Both are encoded using values from Character Set
* Assignments table in Assigned Numbers
* Any-charset = <Octet 128>
* Equivalent to the special RFC2616 charset value "*"
*/
case PduPart.P_CHARSET:
pduDataStream.mark(1);
int firstValue = extractByteValue(pduDataStream);
pduDataStream.reset();
//Check first char
if (((firstValue > TEXT_MIN) && (firstValue < TEXT_MAX)) ||
(END_STRING_FLAG == firstValue)) {
//Text-String (extension-charset)
byte[] charsetStr = parseWapString(pduDataStream, TYPE_TEXT_STRING);
try {
int charsetInt = CharacterSets.getMibEnumValue(
new String(charsetStr));
map.put(PduPart.P_CHARSET, charsetInt);
} catch (UnsupportedEncodingException e) {
// Not a well-known charset, use "*".
Log.e(LOG_TAG, Arrays.toString(charsetStr), e);
map.put(PduPart.P_CHARSET, CharacterSets.ANY_CHARSET);
}
} else {
//Well-known-charset
int charset = (int) parseIntegerValue(pduDataStream);
if (map != null) {
map.put(PduPart.P_CHARSET, charset);
}
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
break;
/**
* From oma-ts-mms-conf-v1_3.pdf
* A name for multipart object SHALL be encoded using name-parameter
* for Content-Type header in WSP multipart headers.
*
* From wap-230-wsp-20010705-a.pdf
* name = Text-String
*/
case PduPart.P_DEP_NAME:
case PduPart.P_NAME:
byte[] name = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if ((null != name) && (null != map)) {
map.put(PduPart.P_NAME, name);
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
break;
default:
if (LOCAL_LOGV) {
Log.v(LOG_TAG, "Not supported Content-Type parameter");
}
if (-1 == skipWapValue(pduDataStream, lastLen)) {
Log.e(LOG_TAG, "Corrupt Content-Type");
} else {
lastLen = 0;
}
break;
}
}
if (0 != lastLen) {
Log.e(LOG_TAG, "Corrupt Content-Type");
}
}
/**
* Parse content type.
*
* @param pduDataStream pdu data input stream
* @param map to store parameters in Content-Type header field
* @return Content-Type value
*/
protected static byte[] parseContentType(ByteArrayInputStream pduDataStream,
HashMap<Integer, Object> map) {
/**
* From wap-230-wsp-20010705-a.pdf
* Content-type-value = Constrained-media | Content-general-form
* Content-general-form = Value-length Media-type
* Media-type = (Well-known-media | Extension-Media) *(Parameter)
*/
assert(null != pduDataStream);
byte[] contentType = null;
pduDataStream.mark(1);
int temp = pduDataStream.read();
assert(-1 != temp);
pduDataStream.reset();
int cur = (temp & 0xFF);
if (cur < TEXT_MIN) {
int length = parseValueLength(pduDataStream);
int startPos = pduDataStream.available();
pduDataStream.mark(1);
temp = pduDataStream.read();
assert(-1 != temp);
pduDataStream.reset();
int first = (temp & 0xFF);
if ((first >= TEXT_MIN) && (first <= TEXT_MAX)) {
contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
} else if (first > TEXT_MAX) {
int index = parseShortInteger(pduDataStream);
if (index < PduContentTypes.contentTypes.length) { //well-known type
contentType = (PduContentTypes.contentTypes[index]).getBytes();
} else {
pduDataStream.reset();
contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
}
} else {
Log.e(LOG_TAG, "Corrupt content-type");
return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*"
}
int endPos = pduDataStream.available();
int parameterLen = length - (startPos - endPos);
if (parameterLen > 0) {//have parameters
parseContentTypeParams(pduDataStream, map, parameterLen);
}
if (parameterLen < 0) {
Log.e(LOG_TAG, "Corrupt MMS message");
return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*"
}
} else if (cur <= TEXT_MAX) {
contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
} else {
contentType =
(PduContentTypes.contentTypes[parseShortInteger(pduDataStream)]).getBytes();
}
return contentType;
}
/**
* Parse part's headers.
*
* @param pduDataStream pdu data input stream
* @param part to store the header informations of the part
* @param length length of the headers
* @return true if parse successfully, false otherwise
*/
protected static boolean parsePartHeaders(ByteArrayInputStream pduDataStream,
PduPart part, int length) {
assert(null != pduDataStream);
assert(null != part);
assert(length > 0);
/**
* From oma-ts-mms-conf-v1_3.pdf, chapter 10.2.
* A name for multipart object SHALL be encoded using name-parameter
* for Content-Type header in WSP multipart headers.
* In decoding, name-parameter of Content-Type SHALL be used if available.
* If name-parameter of Content-Type is not available,
* filename parameter of Content-Disposition header SHALL be used if available.
* If neither name-parameter of Content-Type header nor filename parameter
* of Content-Disposition header is available,
* Content-Location header SHALL be used if available.
*
* Within SMIL part the reference to the media object parts SHALL use
* either Content-ID or Content-Location mechanism [RFC2557]
* and the corresponding WSP part headers in media object parts
* contain the corresponding definitions.
*/
int startPos = pduDataStream.available();
int tempPos = 0;
int lastLen = length;
while(0 < lastLen) {
int header = pduDataStream.read();
assert(-1 != header);
lastLen--;
if (header > TEXT_MAX) {
// Number assigned headers.
switch (header) {
case PduPart.P_CONTENT_LOCATION:
/**
* From wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21
* Content-location-value = Uri-value
*/
byte[] contentLocation = parseWapString(pduDataStream, TYPE_TEXT_STRING);
if (null != contentLocation) {
part.setContentLocation(contentLocation);
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
break;
case PduPart.P_CONTENT_ID:
/**
* From wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21
* Content-ID-value = Quoted-string
*/
byte[] contentId = parseWapString(pduDataStream, TYPE_QUOTED_STRING);
if (null != contentId) {
part.setContentId(contentId);
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
break;
case PduPart.P_DEP_CONTENT_DISPOSITION:
case PduPart.P_CONTENT_DISPOSITION:
/**
* From wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21
* Content-disposition-value = Value-length Disposition *(Parameter)
* Disposition = Form-data | Attachment | Inline | Token-text
* Form-data = <Octet 128>
* Attachment = <Octet 129>
* Inline = <Octet 130>
*/
/*
* some carrier mmsc servers do not support content_disposition
* field correctly
*/
Resources resources = Resources.getSystem();
int id = resources.getIdentifier("config_mms_content_disposition_support",
"boolean", "android");
Log.w("PduParser", "config_mms_content_disposition_support ID: " + id);
boolean contentDisposition = (id != 0) && (resources.getBoolean(id));
Log.w("PduParser", "Content Disposition supported: " + contentDisposition);
if (contentDisposition) {
int len = parseValueLength(pduDataStream);
pduDataStream.mark(1);
int thisStartPos = pduDataStream.available();
int thisEndPos = 0;
int value = pduDataStream.read();
if (value == PduPart.P_DISPOSITION_FROM_DATA ) {
part.setContentDisposition(PduPart.DISPOSITION_FROM_DATA);
} else if (value == PduPart.P_DISPOSITION_ATTACHMENT) {
part.setContentDisposition(PduPart.DISPOSITION_ATTACHMENT);
} else if (value == PduPart.P_DISPOSITION_INLINE) {
part.setContentDisposition(PduPart.DISPOSITION_INLINE);
} else {
pduDataStream.reset();
/* Token-text */
part.setContentDisposition(parseWapString(pduDataStream
, TYPE_TEXT_STRING));
}
/* get filename parameter and skip other parameters */
thisEndPos = pduDataStream.available();
if (thisStartPos - thisEndPos < len) {
value = pduDataStream.read();
if (value == PduPart.P_FILENAME) { //filename is text-string
part.setFilename(parseWapString(pduDataStream
, TYPE_TEXT_STRING));
}
/* skip other parameters */
thisEndPos = pduDataStream.available();
if (thisStartPos - thisEndPos < len) {
int last = len - (thisStartPos - thisEndPos);
byte[] temp = new byte[last];
pduDataStream.read(temp, 0, last);
}
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
}
break;
default:
if (LOCAL_LOGV) {
Log.v(LOG_TAG, "Not supported Part headers: " + header);
}
if (-1 == skipWapValue(pduDataStream, lastLen)) {
Log.e(LOG_TAG, "Corrupt Part headers");
return false;
}
lastLen = 0;
break;
}
} else if ((header >= TEXT_MIN) && (header <= TEXT_MAX)) {
// Not assigned header.
byte[] tempHeader = parseWapString(pduDataStream, TYPE_TEXT_STRING);
byte[] tempValue = parseWapString(pduDataStream, TYPE_TEXT_STRING);
// Check the header whether it is "Content-Transfer-Encoding".
if (true ==
PduPart.CONTENT_TRANSFER_ENCODING.equalsIgnoreCase(new String(tempHeader))) {
part.setContentTransferEncoding(tempValue);
}
tempPos = pduDataStream.available();
lastLen = length - (startPos - tempPos);
} else {
if (LOCAL_LOGV) {
Log.v(LOG_TAG, "Not supported Part headers: " + header);
}
// Skip all headers of this part.
if (-1 == skipWapValue(pduDataStream, lastLen)) {
Log.e(LOG_TAG, "Corrupt Part headers");
return false;
}
lastLen = 0;
}
}
if (0 != lastLen) {
Log.e(LOG_TAG, "Corrupt Part headers");
return false;
}
return true;
}
/**
* Check the position of a specified part.
*
* @param part the part to be checked
* @return part position, THE_FIRST_PART when it's the
* first one, THE_LAST_PART when it's the last one.
*/
private static int checkPartPosition(PduPart part) {
assert(null != part);
if ((null == mTypeParam) &&
(null == mStartParam)) {
return THE_LAST_PART;
}
/* check part's content-id */
if (null != mStartParam) {
byte[] contentId = part.getContentId();
if (null != contentId) {
if (true == Arrays.equals(mStartParam, contentId)) {
return THE_FIRST_PART;
}
}
}
/* check part's content-type */
if (null != mTypeParam) {
byte[] contentType = part.getContentType();
if (null != contentType) {
if (true == Arrays.equals(mTypeParam, contentType)) {
return THE_FIRST_PART;
}
}
}
return THE_LAST_PART;
}
/**
* Check mandatory headers of a pdu.
*
* @param headers pdu headers
* @return true if the pdu has all of the mandatory headers, false otherwise.
*/
protected static boolean checkMandatoryHeader(PduHeaders headers) {
if (null == headers) {
return false;
}
/* get message type */
int messageType = headers.getOctet(PduHeaders.MESSAGE_TYPE);
/* check Mms-Version field */
int mmsVersion = headers.getOctet(PduHeaders.MMS_VERSION);
if (0 == mmsVersion) {
// Every message should have Mms-Version field.
return false;
}
/* check mandatory header fields */
switch (messageType) {
case PduHeaders.MESSAGE_TYPE_SEND_REQ:
// Content-Type field.
byte[] srContentType = headers.getTextString(PduHeaders.CONTENT_TYPE);
if (null == srContentType) {
return false;
}
// From field.
EncodedStringValue srFrom = headers.getEncodedStringValue(PduHeaders.FROM);
if (null == srFrom) {
return false;
}
// Transaction-Id field.
byte[] srTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID);
if (null == srTransactionId) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_SEND_CONF:
// Response-Status field.
int scResponseStatus = headers.getOctet(PduHeaders.RESPONSE_STATUS);
if (0 == scResponseStatus) {
return false;
}
// Transaction-Id field.
byte[] scTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID);
if (null == scTransactionId) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
// Content-Location field.
byte[] niContentLocation = headers.getTextString(PduHeaders.CONTENT_LOCATION);
if (null == niContentLocation) {
return false;
}
// Expiry field.
long niExpiry = headers.getLongInteger(PduHeaders.EXPIRY);
if (-1 == niExpiry) {
return false;
}
// Message-Class field.
byte[] niMessageClass = headers.getTextString(PduHeaders.MESSAGE_CLASS);
if (null == niMessageClass) {
return false;
}
// Message-Size field.
long niMessageSize = headers.getLongInteger(PduHeaders.MESSAGE_SIZE);
if (-1 == niMessageSize) {
return false;
}
// Transaction-Id field.
byte[] niTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID);
if (null == niTransactionId) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND:
// Status field.
int nriStatus = headers.getOctet(PduHeaders.STATUS);
if (0 == nriStatus) {
return false;
}
// Transaction-Id field.
byte[] nriTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID);
if (null == nriTransactionId) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
// Content-Type field.
byte[] rcContentType = headers.getTextString(PduHeaders.CONTENT_TYPE);
if (null == rcContentType) {
return false;
}
// Date field.
long rcDate = headers.getLongInteger(PduHeaders.DATE);
if (-1 == rcDate) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_DELIVERY_IND:
// Date field.
long diDate = headers.getLongInteger(PduHeaders.DATE);
if (-1 == diDate) {
return false;
}
// Message-Id field.
byte[] diMessageId = headers.getTextString(PduHeaders.MESSAGE_ID);
if (null == diMessageId) {
return false;
}
// Status field.
int diStatus = headers.getOctet(PduHeaders.STATUS);
if (0 == diStatus) {
return false;
}
// To field.
EncodedStringValue[] diTo = headers.getEncodedStringValues(PduHeaders.TO);
if (null == diTo) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND:
// Transaction-Id field.
byte[] aiTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID);
if (null == aiTransactionId) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND:
// Date field.
long roDate = headers.getLongInteger(PduHeaders.DATE);
if (-1 == roDate) {
return false;
}
// From field.
EncodedStringValue roFrom = headers.getEncodedStringValue(PduHeaders.FROM);
if (null == roFrom) {
return false;
}
// Message-Id field.
byte[] roMessageId = headers.getTextString(PduHeaders.MESSAGE_ID);
if (null == roMessageId) {
return false;
}
// Read-Status field.
int roReadStatus = headers.getOctet(PduHeaders.READ_STATUS);
if (0 == roReadStatus) {
return false;
}
// To field.
EncodedStringValue[] roTo = headers.getEncodedStringValues(PduHeaders.TO);
if (null == roTo) {
return false;
}
break;
case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
// From field.
EncodedStringValue rrFrom = headers.getEncodedStringValue(PduHeaders.FROM);
if (null == rrFrom) {
return false;
}
// Message-Id field.
byte[] rrMessageId = headers.getTextString(PduHeaders.MESSAGE_ID);
if (null == rrMessageId) {
return false;
}
// Read-Status field.
int rrReadStatus = headers.getOctet(PduHeaders.READ_STATUS);
if (0 == rrReadStatus) {
return false;
}
// To field.
EncodedStringValue[] rrTo = headers.getEncodedStringValues(PduHeaders.TO);
if (null == rrTo) {
return false;
}
break;
default:
// Parser doesn't support this message type in this version.
return false;
}
return true;
}
}
| 76,050 | 38.609896 | 100 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/PduPart.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import android.net.Uri;
import java.util.HashMap;
import java.util.Map;
/**
* The pdu part.
*/
public class PduPart {
/**
* Well-Known Parameters.
*/
public static final int P_Q = 0x80;
public static final int P_CHARSET = 0x81;
public static final int P_LEVEL = 0x82;
public static final int P_TYPE = 0x83;
public static final int P_DEP_NAME = 0x85;
public static final int P_DEP_FILENAME = 0x86;
public static final int P_DIFFERENCES = 0x87;
public static final int P_PADDING = 0x88;
// This value of "TYPE" s used with Content-Type: multipart/related
public static final int P_CT_MR_TYPE = 0x89;
public static final int P_DEP_START = 0x8A;
public static final int P_DEP_START_INFO = 0x8B;
public static final int P_DEP_COMMENT = 0x8C;
public static final int P_DEP_DOMAIN = 0x8D;
public static final int P_MAX_AGE = 0x8E;
public static final int P_DEP_PATH = 0x8F;
public static final int P_SECURE = 0x90;
public static final int P_SEC = 0x91;
public static final int P_MAC = 0x92;
public static final int P_CREATION_DATE = 0x93;
public static final int P_MODIFICATION_DATE = 0x94;
public static final int P_READ_DATE = 0x95;
public static final int P_SIZE = 0x96;
public static final int P_NAME = 0x97;
public static final int P_FILENAME = 0x98;
public static final int P_START = 0x99;
public static final int P_START_INFO = 0x9A;
public static final int P_COMMENT = 0x9B;
public static final int P_DOMAIN = 0x9C;
public static final int P_PATH = 0x9D;
/**
* Header field names.
*/
public static final int P_CONTENT_TYPE = 0x91;
public static final int P_CONTENT_LOCATION = 0x8E;
public static final int P_CONTENT_ID = 0xC0;
public static final int P_DEP_CONTENT_DISPOSITION = 0xAE;
public static final int P_CONTENT_DISPOSITION = 0xC5;
// The next header is unassigned header, use reserved header(0x48) value.
public static final int P_CONTENT_TRANSFER_ENCODING = 0xC8;
/**
* Content=Transfer-Encoding string.
*/
public static final String CONTENT_TRANSFER_ENCODING =
"Content-Transfer-Encoding";
/**
* Value of Content-Transfer-Encoding.
*/
public static final String P_BINARY = "binary";
public static final String P_7BIT = "7bit";
public static final String P_8BIT = "8bit";
public static final String P_BASE64 = "base64";
public static final String P_QUOTED_PRINTABLE = "quoted-printable";
/**
* Value of disposition can be set to PduPart when the value is octet in
* the PDU.
* "from-data" instead of Form-data<Octet 128>.
* "attachment" instead of Attachment<Octet 129>.
* "inline" instead of Inline<Octet 130>.
*/
static final byte[] DISPOSITION_FROM_DATA = "from-data".getBytes();
static final byte[] DISPOSITION_ATTACHMENT = "attachment".getBytes();
static final byte[] DISPOSITION_INLINE = "inline".getBytes();
/**
* Content-Disposition value.
*/
public static final int P_DISPOSITION_FROM_DATA = 0x80;
public static final int P_DISPOSITION_ATTACHMENT = 0x81;
public static final int P_DISPOSITION_INLINE = 0x82;
/**
* Header of part.
*/
private Map<Integer, Object> mPartHeader = null;
/**
* Data uri.
*/
private Uri mUri = null;
/**
* Part data.
*/
private byte[] mPartData = null;
private static final String TAG = "PduPart";
/**
* Empty Constructor.
*/
public PduPart() {
mPartHeader = new HashMap<Integer, Object>();
}
/**
* Set part data. The data are stored as byte array.
*
* @param data the data
*/
public void setData(byte[] data) {
if(data == null) {
return;
}
mPartData = new byte[data.length];
System.arraycopy(data, 0, mPartData, 0, data.length);
}
/**
* @return A copy of the part data or null if the data wasn't set or
* the data is stored as Uri.
* @see #getDataUri
*/
public byte[] getData() {
if(mPartData == null) {
return null;
}
byte[] byteArray = new byte[mPartData.length];
System.arraycopy(mPartData, 0, byteArray, 0, mPartData.length);
return byteArray;
}
/**
* Set data uri. The data are stored as Uri.
*
* @param uri the uri
*/
public void setDataUri(Uri uri) {
mUri = uri;
}
/**
* @return The Uri of the part data or null if the data wasn't set or
* the data is stored as byte array.
* @see #getData
*/
public Uri getDataUri() {
return mUri;
}
/**
* Set Content-id value
*
* @param contentId the content-id value
* @throws NullPointerException if the value is null.
*/
public void setContentId(byte[] contentId) {
if((contentId == null) || (contentId.length == 0)) {
throw new IllegalArgumentException(
"Content-Id may not be null or empty.");
}
if ((contentId.length > 1)
&& ((char) contentId[0] == '<')
&& ((char) contentId[contentId.length - 1] == '>')) {
mPartHeader.put(P_CONTENT_ID, contentId);
return;
}
// Insert beginning '<' and trailing '>' for Content-Id.
byte[] buffer = new byte[contentId.length + 2];
buffer[0] = (byte) (0xff & '<');
buffer[buffer.length - 1] = (byte) (0xff & '>');
System.arraycopy(contentId, 0, buffer, 1, contentId.length);
mPartHeader.put(P_CONTENT_ID, buffer);
}
/**
* Get Content-id value.
*
* @return the value
*/
public byte[] getContentId() {
return (byte[]) mPartHeader.get(P_CONTENT_ID);
}
/**
* Set Char-set value.
*
* @param charset the value
*/
public void setCharset(int charset) {
mPartHeader.put(P_CHARSET, charset);
}
/**
* Get Char-set value
*
* @return the charset value. Return 0 if charset was not set.
*/
public int getCharset() {
Integer charset = (Integer) mPartHeader.get(P_CHARSET);
if(charset == null) {
return 0;
} else {
return charset.intValue();
}
}
/**
* Set Content-Location value.
*
* @param contentLocation the value
* @throws NullPointerException if the value is null.
*/
public void setContentLocation(byte[] contentLocation) {
if(contentLocation == null) {
throw new NullPointerException("null content-location");
}
mPartHeader.put(P_CONTENT_LOCATION, contentLocation);
}
/**
* Get Content-Location value.
*
* @return the value
* return PduPart.disposition[0] instead of <Octet 128> (Form-data).
* return PduPart.disposition[1] instead of <Octet 129> (Attachment).
* return PduPart.disposition[2] instead of <Octet 130> (Inline).
*/
public byte[] getContentLocation() {
return (byte[]) mPartHeader.get(P_CONTENT_LOCATION);
}
/**
* Set Content-Disposition value.
* Use PduPart.disposition[0] instead of <Octet 128> (Form-data).
* Use PduPart.disposition[1] instead of <Octet 129> (Attachment).
* Use PduPart.disposition[2] instead of <Octet 130> (Inline).
*
* @param contentDisposition the value
* @throws NullPointerException if the value is null.
*/
public void setContentDisposition(byte[] contentDisposition) {
if(contentDisposition == null) {
throw new NullPointerException("null content-disposition");
}
mPartHeader.put(P_CONTENT_DISPOSITION, contentDisposition);
}
/**
* Get Content-Disposition value.
*
* @return the value
*/
public byte[] getContentDisposition() {
return (byte[]) mPartHeader.get(P_CONTENT_DISPOSITION);
}
/**
* Set Content-Type value.
*
* @param contentType the value
* @throws NullPointerException if the value is null.
*/
public void setContentType(byte[] contentType) {
if(contentType == null) {
throw new NullPointerException("null content-type");
}
mPartHeader.put(P_CONTENT_TYPE, contentType);
}
/**
* Get Content-Type value of part.
*
* @return the value
*/
public byte[] getContentType() {
return (byte[]) mPartHeader.get(P_CONTENT_TYPE);
}
/**
* Set Content-Transfer-Encoding value
*
* @param contentTransferEncoding the value
* @throws NullPointerException if the value is null.
*/
public void setContentTransferEncoding(byte[] contentTransferEncoding) {
if(contentTransferEncoding == null) {
throw new NullPointerException("null content-transfer-encoding");
}
mPartHeader.put(P_CONTENT_TRANSFER_ENCODING, contentTransferEncoding);
}
/**
* Get Content-Transfer-Encoding value.
*
* @return the value
*/
public byte[] getContentTransferEncoding() {
return (byte[]) mPartHeader.get(P_CONTENT_TRANSFER_ENCODING);
}
/**
* Set Content-type parameter: name.
*
* @param name the name value
* @throws NullPointerException if the value is null.
*/
public void setName(byte[] name) {
if(null == name) {
throw new NullPointerException("null content-id");
}
mPartHeader.put(P_NAME, name);
}
/**
* Get content-type parameter: name.
*
* @return the name
*/
public byte[] getName() {
return (byte[]) mPartHeader.get(P_NAME);
}
/**
* Get Content-disposition parameter: filename
*
* @param fileName the filename value
* @throws NullPointerException if the value is null.
*/
public void setFilename(byte[] fileName) {
if(null == fileName) {
throw new NullPointerException("null content-id");
}
mPartHeader.put(P_FILENAME, fileName);
}
/**
* Set Content-disposition parameter: filename
*
* @return the filename
*/
public byte[] getFilename() {
return (byte[]) mPartHeader.get(P_FILENAME);
}
public String generateLocation() {
// Assumption: At least one of the content-location / name / filename
// or content-id should be set. This is guaranteed by the PduParser
// for incoming messages and by MM composer for outgoing messages.
byte[] location = (byte[]) mPartHeader.get(P_NAME);
if(null == location) {
location = (byte[]) mPartHeader.get(P_FILENAME);
if (null == location) {
location = (byte[]) mPartHeader.get(P_CONTENT_LOCATION);
}
}
if (null == location) {
byte[] contentId = (byte[]) mPartHeader.get(P_CONTENT_ID);
return "cid:" + new String(contentId);
} else {
return new String(location);
}
}
}
| 12,504 | 30.029777 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/QuotedPrintable.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import java.io.ByteArrayOutputStream;
public class QuotedPrintable {
private static byte ESCAPE_CHAR = '=';
/**
* Decodes an array quoted-printable characters into an array of original bytes.
* Escaped characters are converted back to their original representation.
*
* <p>
* This function implements a subset of
* quoted-printable encoding specification (rule #1 and rule #2)
* as defined in RFC 1521.
* </p>
*
* @param bytes array of quoted-printable characters
* @return array of original bytes,
* null if quoted-printable decoding is unsuccessful.
*/
public static final byte[] decodeQuotedPrintable(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i];
if (b == ESCAPE_CHAR) {
try {
if('\r' == (char)bytes[i + 1] &&
'\n' == (char)bytes[i + 2]) {
i += 2;
continue;
}
int u = Character.digit((char) bytes[++i], 16);
int l = Character.digit((char) bytes[++i], 16);
if (u == -1 || l == -1) {
return null;
}
buffer.write((char) ((u << 4) + l));
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
} else {
buffer.write(b);
}
}
return buffer.toByteArray();
}
}
| 2,404 | 33.855072 | 84 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/ReadOrigInd.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class ReadOrigInd extends GenericPdu {
/**
* Empty constructor.
* Since the Pdu corresponding to this class is constructed
* by the Proxy-Relay server, this class is only instantiated
* by the Pdu Parser.
*
* @throws InvalidHeaderValueException if error occurs.
*/
public ReadOrigInd() throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_READ_ORIG_IND);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
ReadOrigInd(PduHeaders headers) {
super(headers);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
/**
* Get From value.
* From-value = Value-length
* (Address-present-token Encoded-string-value | Insert-address-token)
*
* @return the value
*/
public EncodedStringValue getFrom() {
return mPduHeaders.getEncodedStringValue(PduHeaders.FROM);
}
/**
* Set From value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setFrom(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get X-MMS-Read-status value.
*
* @return the value
*/
public int getReadStatus() {
return mPduHeaders.getOctet(PduHeaders.READ_STATUS);
}
/**
* Set X-MMS-Read-status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_STATUS);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* Set To value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*/
}
| 4,088 | 25.551948 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/ReadRecInd.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class ReadRecInd extends GenericPdu {
/**
* Constructor, used when composing a M-ReadRec.ind pdu.
*
* @param from the from value
* @param messageId the message ID value
* @param mmsVersion current viersion of mms
* @param readStatus the read status value
* @param to the to value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if messageId or to is null.
*/
public ReadRecInd(EncodedStringValue from,
byte[] messageId,
int mmsVersion,
int readStatus,
EncodedStringValue[] to) throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_READ_REC_IND);
setFrom(from);
setMessageId(messageId);
setMmsVersion(mmsVersion);
setTo(to);
setReadStatus(readStatus);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
ReadRecInd(PduHeaders headers) {
super(headers);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* Set To value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/**
* Get X-MMS-Read-status value.
*
* @return the value
*/
public int getReadStatus() {
return mPduHeaders.getOctet(PduHeaders.READ_STATUS);
}
/**
* Set X-MMS-Read-status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_STATUS);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*/
}
| 4,014 | 26.689655 | 83 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/RetrieveConf.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
/**
* M-Retrive.conf Pdu.
*/
public class RetrieveConf extends MultimediaMessagePdu {
/**
* Empty constructor.
* Since the Pdu corresponding to this class is constructed
* by the Proxy-Relay server, this class is only instantiated
* by the Pdu Parser.
*
* @throws InvalidHeaderValueException if error occurs.
*/
public RetrieveConf() throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
RetrieveConf(PduHeaders headers) {
super(headers);
}
/**
* Constructor with given headers and body
*
* @param headers Headers for this PDU.
* @param body Body of this PDu.
*/
public RetrieveConf(PduHeaders headers, PduBody body) {
super(headers, body);
}
/**
* Get CC value.
*
* @return the value
*/
public EncodedStringValue[] getCc() {
return mPduHeaders.getEncodedStringValues(PduHeaders.CC);
}
/**
* Add a "CC" value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void addCc(EncodedStringValue value) {
mPduHeaders.appendEncodedStringValue(value, PduHeaders.CC);
}
/**
* Get Content-type value.
*
* @return the value
*/
public byte[] getContentType() {
return mPduHeaders.getTextString(PduHeaders.CONTENT_TYPE);
}
/**
* Set Content-type value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setContentType(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.CONTENT_TYPE);
}
/**
* Get X-Mms-Delivery-Report value.
*
* @return the value
*/
public int getDeliveryReport() {
return mPduHeaders.getOctet(PduHeaders.DELIVERY_REPORT);
}
/**
* Set X-Mms-Delivery-Report value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setDeliveryReport(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.DELIVERY_REPORT);
}
/**
* Get From value.
* From-value = Value-length
* (Address-present-token Encoded-string-value | Insert-address-token)
*
* @return the value
*/
public EncodedStringValue getFrom() {
return mPduHeaders.getEncodedStringValue(PduHeaders.FROM);
}
/**
* Set From value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setFrom(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM);
}
/**
* Get X-Mms-Message-Class value.
* Message-class-value = Class-identifier | Token-text
* Class-identifier = Personal | Advertisement | Informational | Auto
*
* @return the value
*/
public byte[] getMessageClass() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_CLASS);
}
/**
* Set X-Mms-Message-Class value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageClass(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_CLASS);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get X-Mms-Read-Report value.
*
* @return the value
*/
public int getReadReport() {
return mPduHeaders.getOctet(PduHeaders.READ_REPORT);
}
/**
* Set X-Mms-Read-Report value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadReport(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_REPORT);
}
/**
* Get X-Mms-Retrieve-Status value.
*
* @return the value
*/
public int getRetrieveStatus() {
return mPduHeaders.getOctet(PduHeaders.RETRIEVE_STATUS);
}
/**
* Set X-Mms-Retrieve-Status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setRetrieveStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.RETRIEVE_STATUS);
}
/**
* Get X-Mms-Retrieve-Text value.
*
* @return the value
*/
public EncodedStringValue getRetrieveText() {
return mPduHeaders.getEncodedStringValue(PduHeaders.RETRIEVE_TEXT);
}
/**
* Set X-Mms-Retrieve-Text value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setRetrieveText(EncodedStringValue value) {
mPduHeaders.setEncodedStringValue(value, PduHeaders.RETRIEVE_TEXT);
}
/**
* Get X-Mms-Transaction-Id.
*
* @return the value
*/
public byte[] getTransactionId() {
return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID);
}
/**
* Set X-Mms-Transaction-Id.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTransactionId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte getContentClass() {return 0x00;}
* public void setApplicId(byte value) {}
*
* public byte getDrmContent() {return 0x00;}
* public void setDrmContent(byte value) {}
*
* public byte getDistributionIndicator() {return 0x00;}
* public void setDistributionIndicator(byte value) {}
*
* public PreviouslySentByValue getPreviouslySentBy() {return null;}
* public void setPreviouslySentBy(PreviouslySentByValue value) {}
*
* public PreviouslySentDateValue getPreviouslySentDate() {}
* public void setPreviouslySentDate(PreviouslySentDateValue value) {}
*
* public MmFlagsValue getMmFlags() {return null;}
* public void setMmFlags(MmFlagsValue value) {}
*
* public MmStateValue getMmState() {return null;}
* public void getMmState(MmStateValue value) {}
*
* public byte[] getReplaceId() {return 0x00;}
* public void setReplaceId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*
* public byte getReplyCharging() {return 0x00;}
* public void setReplyCharging(byte value) {}
*
* public byte getReplyChargingDeadline() {return 0x00;}
* public void setReplyChargingDeadline(byte value) {}
*
* public byte[] getReplyChargingId() {return 0x00;}
* public void setReplyChargingId(byte[] value) {}
*
* public long getReplyChargingSize() {return 0;}
* public void setReplyChargingSize(long value) {}
*/
}
| 8,635 | 27.69103 | 81 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/ws/com/google/android/mms/pdu/SendConf.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class SendConf extends GenericPdu {
/**
* Empty constructor.
* Since the Pdu corresponding to this class is constructed
* by the Proxy-Relay server, this class is only instantiated
* by the Pdu Parser.
*
* @throws InvalidHeaderValueException if error occurs.
*/
public SendConf() throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_SEND_CONF);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
SendConf(PduHeaders headers) {
super(headers);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get X-Mms-Response-Status.
*
* @return the value
*/
public int getResponseStatus() {
return mPduHeaders.getOctet(PduHeaders.RESPONSE_STATUS);
}
/**
* Set X-Mms-Response-Status.
*
* @param value the values
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setResponseStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.RESPONSE_STATUS);
}
/**
* Get X-Mms-Transaction-Id field value.
*
* @return the X-Mms-Report-Allowed value
*/
public byte[] getTransactionId() {
return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID);
}
/**
* Set X-Mms-Transaction-Id field value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTransactionId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID);
}
/*
* Optional, not supported header fields:
*
* public byte[] getContentLocation() {return null;}
* public void setContentLocation(byte[] value) {}
*
* public EncodedStringValue getResponseText() {return null;}
* public void setResponseText(EncodedStringValue value) {}
*
* public byte getStoreStatus() {return 0x00;}
* public void setStoreStatus(byte value) {}
*
* public byte[] getStoreStatusText() {return null;}
* public void setStoreStatusText(byte[] value) {}
*/
}
| 3,406 | 27.872881 | 81 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.