Example usage for java.lang String contentEquals

List of usage examples for java.lang String contentEquals

Introduction

In this page you can find the example usage for java.lang String contentEquals.

Prototype

public boolean contentEquals(CharSequence cs) 

Source Link

Document

Compares this string to the specified CharSequence .

Usage

From source file:com.homeworkreminder.Main.java

private void showDialogForNewSubject() {
    // TODO Auto-generated method stub
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("Create a new subject");
    alertDialog.setMessage("Name the your subject");
    final EditText input = new EditText(context);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(10, 0, 10, 0);//from  ww  w  .  j  av a  2 s.  c  o  m
    input.setLayoutParams(lp);
    alertDialog.setView(input);
    alertDialog.setPositiveButton("Create", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            String subject = input.getText().toString();
            if (subject.contentEquals("")) {
                Toast.makeText(context, "Subject name cannot be empty", Toast.LENGTH_LONG).show();
                return;
            }
            if (!(subjectArray.contains(subject))) {
                addSubject(subject);
                dialog.dismiss();
            } else if (subject.contentEquals(ADD_SUBJECT)) {
                Toast.makeText(context, "Cannot use this name", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            } else {
                Toast.makeText(context, "Subject already exists", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

        }
    });
    // Setting Negative Button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after
            // dialog
            dialog.cancel();
        }
    });
    alertDialog.show();
}

From source file:com.android.mail.utils.NotificationUtils.java

/**
 * Configure the notification for one conversation.  When there are multiple conversations,
 * this method is used to configure bundled notification for Android Wear.
 *///from   w ww.j a  va 2s .  com
private static ConfigResult configureNotifForOneConversation(Context context, Account account,
        FolderPreferences folderPreferences, NotificationCompat.Builder notificationBuilder,
        NotificationCompat.WearableExtender wearExtender, Cursor conversationCursor, Intent notificationIntent,
        Folder folder, long when, Resources res, boolean isInbox, String notificationLabelName,
        int notificationId, final ContactFetcher contactFetcher) {

    final ConfigResult result = new ConfigResult();

    final Conversation conversation = new Conversation(conversationCursor);

    // Set of all unique senders for unseen messages
    final HashSet<String> senderAddressesSet = new HashSet<String>();
    Cursor cursor = null;
    MessageCursor messageCursor = null;
    boolean multipleUnseenThread = false;
    String from = null;
    try {
        final Uri uri = conversation.messageListUri.buildUpon()
                .appendQueryParameter(UIProvider.LABEL_QUERY_PARAMETER, folder.persistentId).build();
        cursor = context.getContentResolver().query(uri, UIProvider.MESSAGE_PROJECTION, null, null, null);
        messageCursor = new MessageCursor(cursor);
        // Use the information from the last sender in the conversation that triggered
        // this notification.

        String fromAddress = "";
        if (messageCursor.moveToPosition(messageCursor.getCount() - 1)) {
            final Message message = messageCursor.getMessage();
            fromAddress = message.getFrom();
            if (fromAddress == null) {
                // No sender. Go back to default value.
                LogUtils.e(LOG_TAG, "No sender found for message: %d", message.getId());
                fromAddress = "";
            }
            from = getDisplayableSender(fromAddress);
            result.contactIconInfo = getContactIcon(context, account.getAccountManagerAccount().name, from,
                    getSenderAddress(fromAddress), folder, contactFetcher);
            addEmailAddressToSet(fromAddress, senderAddressesSet);
            notificationBuilder.setLargeIcon(result.contactIconInfo.icon);
        }

        // Assume that the last message in this conversation is unread
        int firstUnseenMessagePos = messageCursor.getPosition();
        while (messageCursor.moveToPosition(messageCursor.getPosition() - 1)) {
            final Message message = messageCursor.getMessage();
            final boolean unseen = !message.seen;
            if (unseen) {
                firstUnseenMessagePos = messageCursor.getPosition();
                addEmailAddressToSet(message.getFrom(), senderAddressesSet);
                if (!multipleUnseenThread && !fromAddress.contentEquals(message.getFrom())) {
                    multipleUnseenThread = true;
                }
            }
        }

        final String subject = ConversationItemView.filterTag(context, conversation.subject);

        // TODO(skennedy) Can we remove this check?
        if (Utils.isRunningJellybeanOrLater()) {
            // For a new-style notification

            if (multipleUnseenThread) {
                // The title of a single conversation is the list of senders.
                int sendersLength = res.getInteger(R.integer.swipe_senders_length);

                final SpannableStringBuilder sendersBuilder = getStyledSenders(context, conversationCursor,
                        sendersLength, account);

                notificationBuilder.setContentTitle(sendersBuilder);
                // For a single new conversation, the ticker is based on the sender's name.
                result.notificationTicker = sendersBuilder.toString();
            } else {
                from = getWrappedFromString(from);
                // The title of a single message the sender.
                notificationBuilder.setContentTitle(from);
                // For a single new conversation, the ticker is based on the sender's name.
                result.notificationTicker = from;
            }

            // The notification content will be the subject of the conversation.
            notificationBuilder.setContentText(getSingleMessageLittleText(context, subject));

            // The notification subtext will be the subject of the conversation for inbox
            // notifications, or will based on the the label name for user label
            // notifications.
            notificationBuilder.setSubText(isInbox ? account.getDisplayName() : notificationLabelName);

            final NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(
                    notificationBuilder);

            // Seek the message cursor to the first unread message
            final Message message;
            if (messageCursor.moveToPosition(firstUnseenMessagePos)) {
                message = messageCursor.getMessage();
                bigText.bigText(getSingleMessageBigText(context, subject, message));
            } else {
                LogUtils.e(LOG_TAG, "Failed to load message");
                message = null;
            }

            if (message != null) {
                final Set<String> notificationActions = folderPreferences.getNotificationActions(account);

                NotificationActionUtils.addNotificationActions(context, notificationIntent, notificationBuilder,
                        wearExtender, account, conversation, message, folder, notificationId, when,
                        notificationActions);
            }
        } else {
            // For an old-style notification

            // The title of a single conversation notification is built from both the sender
            // and subject of the new message.
            notificationBuilder.setContentTitle(getSingleMessageNotificationTitle(context, from, subject));

            // The notification content will be the subject of the conversation for inbox
            // notifications, or will based on the the label name for user label
            // notifications.
            notificationBuilder.setContentText(isInbox ? account.getDisplayName() : notificationLabelName);

            // For a single new conversation, the ticker is based on the sender's name.
            result.notificationTicker = from;
        }

        tagNotificationsWithPeople(notificationBuilder, senderAddressesSet);
    } finally {
        if (messageCursor != null) {
            messageCursor.close();
        }
        if (cursor != null) {
            cursor.close();
        }
    }
    return result;
}

From source file:com.nuvolect.securesuite.data.SqlCipher.java

/**
 * Look for issues with group membership.
 * //FUTURE fix problems with groups during import
 * The problem has to do with remapping groups IDs during import.
 * Each group ID is associated with an account, ie., can only be used by contacts in that account.
 * Each contact ID is associated with an account.  There is an error when contacts are associated
 * with groups in a different account.  Validate groups detects the erroronous groups and can also delete them.
 *//* ww  w.j a v  a2  s.c  o  m*/
public static int validateGroups(Context ctx, boolean fix_errors) {

    int successCount = 0;
    int failCount = 0;
    int contactCount = 0;
    int fixCount = 0;

    String[] accounts = MyAccounts.getAccounts();

    for (String contact_account : accounts) {

        long[] contacts = getContactIds(contact_account);

        for (long contact_id : contacts) {

            int[] groups = MyGroups.getGroups(contact_id);

            for (int group_id : groups) {

                // Check that the contact and group are on the same account
                String group_account = MyGroups.mGroupAccount.get(group_id);

                if (group_account != null && group_account.contentEquals(contact_account))
                    ++successCount;
                else {

                    if (fix_errors) {

                        MyGroups.deleteGroupRecords(ctx, contact_id, group_id, false);
                        ++fixCount;

                        String display_name = get(contact_id, ATab.display_name);
                        logError(ctx, LogType.SQLCIPHER,
                                DETAIL_TABLE + " fixed by delete, group_id: " + group_id + " display_name: "
                                        + display_name + " for contact_id: " + contact_id);
                    } else {

                        String display_name = get(contact_id, ATab.display_name);
                        logError(ctx, LogType.SQLCIPHER,
                                DETAIL_TABLE
                                        + " ERROR contact and group do not have same account.  group account: "
                                        + group_account + " contact account: " + contact_account);
                        logError(ctx, LogType.SQLCIPHER, DETAIL_TABLE + " group_id: " + group_id
                                + " display_name: " + display_name + " for contact_id: " + contact_id);
                        ++failCount;
                    }
                }
            }
            if (++contactCount % 200 == 0)
                logError(ctx, LogType.SQLCIPHER, "Progress: " + contactCount);
        }
    }
    logError(ctx, LogType.SQLCIPHER, "validateDbGroups complete, success: " + successCount + ", fail: "
            + failCount + ", fixed: " + fixCount);
    return failCount;
}

From source file:com.nuvolect.securesuite.data.SqlCipher.java

/**
 * Replace select password data including the history and password gen parameters
 * Note that this will destroy the existing data.
 * @param accountCryp Array of objects containing row data
 * @return ArrayList of source _id processed
 *///from ww w  . j  a va2  s  .co  m
public static ArrayList<Integer> replaceCrypData(JSONArray accountCryp) {

    ArrayList<Integer> source_id_processed = new ArrayList<Integer>();
    try {

        for (int i = 0; i < accountCryp.length(); i++) {

            JSONObject cryp = accountCryp.getJSONObject(i);
            int _id = cryp.getInt(ACTab._id.toString());
            String key = decodeBase64(cryp, ACTab.key.toString());
            String value = decodeBase64(cryp, ACTab.value.toString());

            if (key.contentEquals(Passphrase.PASSWORD_GEN_HISTORY))
                Cryp.put(Passphrase.PASSWORD_GEN_HISTORY, value);
            if (key.contentEquals(Passphrase.PASSWORD_TARGET))
                Cryp.put(Passphrase.PASSWORD_TARGET, value);
            if (key.contentEquals(Passphrase.PASSWORD_LENGTH))
                Cryp.put(Passphrase.PASSWORD_LENGTH, value);
            if (key.contentEquals(Passphrase.PASSWORD_GEN_MODE))
                Cryp.put(Passphrase.PASSWORD_GEN_MODE, value);
            source_id_processed.add(_id);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return source_id_processed;
}

From source file:com.tct.mail.utils.NotificationUtils.java

/**
 * Configure the notification for one conversation.  When there are multiple conversations,
 * this method is used to configure bundled notification for Android Wear.
 *///from  w  w  w.j av a2 s.  c o m
private static ConfigResult configureNotifForOneConversation(Context context, Account account,
        FolderPreferences folderPreferences, NotificationCompat.Builder notification,
        NotificationCompat.WearableExtender wearExtender, Cursor conversationCursor, Intent notificationIntent,
        Folder folder, long when, Resources res, String notificationAccountDisplayName,
        String notificationAccountEmail, boolean isInbox, String notificationLabelName, int notificationId,
        final ContactPhotoFetcher photoFetcher) {

    final ConfigResult result = new ConfigResult();

    final Conversation conversation = new Conversation(conversationCursor);

    Cursor cursor = null;
    MessageCursor messageCursor = null;
    boolean multipleUnseenThread = false;
    String from = null;
    try {
        final Uri uri = conversation.messageListUri.buildUpon()
                .appendQueryParameter(UIProvider.LABEL_QUERY_PARAMETER, folder.persistentId).build();
        cursor = context.getContentResolver().query(uri, UIProvider.MESSAGE_PROJECTION, null, null, null);
        messageCursor = new MessageCursor(cursor);
        // Use the information from the last sender in the conversation that triggered
        // this notification.

        String fromAddress = "";
        if (messageCursor.moveToPosition(messageCursor.getCount() - 1)) {
            final Message message = messageCursor.getMessage();
            fromAddress = message.getFrom();
            if (fromAddress == null) {
                // No sender. Go back to default value.
                LogUtils.e(LOG_TAG, "No sender found for message: %d", message.getId());
                fromAddress = "";
            }
            from = getDisplayableSender(fromAddress);
            result.contactIconInfo = getContactIcon(context, account.getAccountManagerAccount().name, from,
                    getSenderAddress(fromAddress), folder, photoFetcher);
            notification.setLargeIcon(result.contactIconInfo.icon);
        }

        // Assume that the last message in this conversation is unread
        int firstUnseenMessagePos = messageCursor.getPosition();
        while (messageCursor.moveToPosition(messageCursor.getPosition() - 1)) {
            final Message message = messageCursor.getMessage();
            final boolean unseen = !message.seen;
            if (unseen) {
                firstUnseenMessagePos = messageCursor.getPosition();
                if (!multipleUnseenThread && !fromAddress.contentEquals(message.getFrom())) {
                    multipleUnseenThread = true;
                }
            }
        }

        final String subject = ConversationItemView.filterTag(context, conversation.subject);

        // TODO(skennedy) Can we remove this check?
        if (Utils.isRunningJellybeanOrLater()) {
            // For a new-style notification

            if (multipleUnseenThread) {
                // The title of a single conversation is the list of senders.
                int sendersLength = res.getInteger(R.integer.swipe_senders_length);

                final SpannableStringBuilder sendersBuilder = getStyledSenders(context, conversationCursor,
                        sendersLength, notificationAccountEmail);

                from = sendersBuilder.toString();
                notification.setContentText(sendersBuilder);
                // For a single new conversation, the ticker is based on the sender's name.
                result.notificationTicker = sendersBuilder.toString();
            } else {
                from = getWrappedFromString(from);
                // The title of a single message the sender.
                notification.setContentText(from);
                // For a single new conversation, the ticker is based on the sender's name.
                result.notificationTicker = from;
            }

            // The notification content will be the subject of the conversation.

            /*TS: linzhou 2016-01-06 EMAIL 1271037 DEL_S*/
            notification.setContentTitle(getSingleMessageLittleText(context, subject));
            /*TS: linzhou 2016-01-06 EMAIL 1271037 DEL_S*/

            // The notification subtext will be the subject of the conversation for inbox
            // notifications, or will based on the the label name for user label
            // notifications.
            notification.setSubText(isInbox ? notificationAccountDisplayName : notificationLabelName);

            if (multipleUnseenThread) {
                notification.setLargeIcon(getDefaultNotificationIcon(context, folder, true));
            }
            final NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(notification);

            // Seek the message cursor to the first unread message
            final Message message;
            if (messageCursor.moveToPosition(firstUnseenMessagePos)) {
                message = messageCursor.getMessage();
                bigText.bigText(getSingleMessageBigText(context, message, from));
            } else {
                LogUtils.e(LOG_TAG, "Failed to load message");
                message = null;
            }

            if (message != null) {
                // TS: zhaotianyong 2015-05-1003318 EMAIL BUGFIX_1003318 MOD_S
                final Set<String> notificationActions = folderPreferences.getNotificationActions(account,
                        message);
                // TS: zhaotianyong 2015-05-1003318 EMAIL BUGFIX_1003318 MOD_E

                NotificationActionUtils.addNotificationActions(context, notificationIntent, notification,
                        wearExtender, account, conversation, message, folder, notificationId, when,
                        notificationActions);
            }
        } else {
            // For an old-style notification

            // The title of a single conversation notification is built from both the sender
            // and subject of the new message.
            notification.setContentTitle(getSingleMessageNotificationTitle(context, from, subject));

            // The notification content will be the subject of the conversation for inbox
            // notifications, or will based on the the label name for user label
            // notifications.
            notification.setContentText(isInbox ? notificationAccountDisplayName : notificationLabelName);

            // For a single new conversation, the ticker is based on the sender's name.
            result.notificationTicker = from;
        }
    } finally {
        if (messageCursor != null) {
            messageCursor.close();
        }
        if (cursor != null) {
            cursor.close();
        }
    }
    return result;
}

From source file:com.nuvolect.securesuite.data.SqlCipher.java

/**<pre>
 * contact_id = testIdTestVersion( account, cloud_c_id, cloud_version)
 * Return  0: cloud_c_id is current version, no update required
 * Return >0: cloud_c_id does not exists or is newer, update required
 * Return Long.MIN_VALUE, cloud_c_id is older than local version, no update required
 *
 * Assumes setupImport() is called prior to calling this method.
 *
 * 1. Search cloud_c_id in field cloud_c_id, get contact_id, loc_version, loc_account
 *
 * 2. count == 0/* ww  w . java2s .c  om*/
 * a. The loc_contact_id does not exist
 * a. loc_contact_id is clear
 * a. No contact_id collision, no remapping required
 * a. import this contact
 * a. return cloud_c_id (== cloud_id)
 *
 * 3. count > 0,
 * a. && no account match
 * a. cloud_c_id for this account is not in local database
 * a. there is a contact_id collision, remapping is required
 * a. import this contact
 * a. return next open new_contact_id
 *
 * 4. count > 0
 * b. && account match
 * b. cloud_c_id for this account is in local database
 * b. We don't know if contact_id is remapped
 *
 * b.1. cloud_version > loc_version
 * b.1. cloud version is newer
 * b.1. import this contact
 * b.1. if remapped, remapped value is in contact_id
 * b.1. return contact_id
 *
 * b.2. cloud_version = local_version
 * b.2. cloud version is the same
 * b.2. do not import this contact
 * b.2. return 0 (it exists, same version)
 *
 * b.3. cloud_version < local_version
 * b.3. The local version is newer than the cloud version
 * b.3. do not import this contact
 * b.3. return Long.MIN_VALUE
 *
 * Test data:
 * account   cloud_c_id  contact_id  loc_ver  _id
 * jack      1           1           1        1
 * grandma   1           1001        1        2
 * jack      2           2           1        3
 * jack      3           3           2        4
 * grandma   3           1002        2        4
 *
 * Test cases:
 * account   cloud_c_id  cloud_ver  result
 * jack      1           1          _id 1, b.2, return 0
 * jack      2           2          _id 3, b.1, return 2
 * grandma   1           1          _id 2, b.2, return 0
 * grandma   1           2          _id 2, b.1, return 1001
 * grandma   3           1          _id 4, b.3, return Long.MIN_VALUE
 * grandma   2           1          _id x, a., return 1003 (next open id)
 *</pre>
 */
public static synchronized long testIdTestVersion(String cloud_account, long cloud_c_id, int cloud_version) {

    String[] projection = { ATab.account_name.toString(), ATab.contact_id.toString(),
            ATab.cloud_version.toString() };

    String where = ATab.cloud_c_id + "=?";
    String[] args = new String[] { String.valueOf(cloud_c_id) };

    Cursor c = account_db.query(ACCOUNT_TABLE, projection, where, args, null, null, null);

    int count = c.getCount();
    if (DEBUG_IMPORT)
        LogUtil.log("testIdTestVersion count: " + count + ", cloud_account: " + cloud_account + ", cloud_c_id: "
                + cloud_c_id + ", cloud_version: " + cloud_version);

    if (count == 0) {
        c.close();
        if (DEBUG_IMPORT)
            LogUtil.log("case 2, cloud_c_id: " + cloud_c_id);
        return cloud_c_id; //case 2
    }

    boolean accountMatch = false;
    int loc_version = 0;
    long contact_id = 0;
    String account = "";

    while (c.moveToNext()) {

        account = c.getString(c.getColumnIndex(ATab.account_name.toString()));

        if (account.contentEquals(cloud_account)) {
            accountMatch = true;
            loc_version = c.getInt(c.getColumnIndex(ATab.cloud_version.toString()));
            contact_id = c.getLong(c.getColumnIndex(ATab.contact_id.toString()));
            break;
        }
    }
    c.close();

    if (!accountMatch) { //case 3

        long remapId = getNextUnusedContactID();
        mCloudRemapContactId.put(cloud_c_id, remapId);
        if (DEBUG_IMPORT)
            LogUtil.log("case 3, return remapId: " + remapId);
        return remapId;

    } else { // Case 4

        if (cloud_version > loc_version) {//case 4.b.1

            if (DEBUG_IMPORT)
                LogUtil.log("case 4, > loc_version: " + loc_version + ", return contact_id: " + contact_id);
            return contact_id;
        } else {
            if (cloud_version == loc_version) {//case 4.b.2

                if (DEBUG_IMPORT)
                    LogUtil.log("case 4, = loc_version: " + loc_version + ", return 0");
                return 0L;
            } else {// case 4.b.3

                if (DEBUG_IMPORT)
                    LogUtil.log("case 4, < loc_version: " + loc_version + ", return " + Long.MIN_VALUE);
                return Long.MIN_VALUE;
            }
        }
    }
}

From source file:marytts.tools.voiceimport.HTKLabeler.java

/** Translation table for labels which are incompatible with HTK or shell filenames
 * See common_routines.pl in HTS training.
 * In this function the phones as used internally in HTSEngine are changed
 * back to the Mary TTS set, this function is necessary when correcting the 
 * actual durations of AcousticPhonemes.
 * @param lab/*  w  w w  . j  a  v  a  2  s . c o  m*/
 * @return String
 */
public String replaceBackTrickyPhones(String lab) {
    String s = lab;
    /** DE (replacements in German phone set) */
    if (lab.contentEquals("ER6"))
        s = "6";
    else if (lab.contentEquals("ER66")) /* CHECK ??? */
        s = "=6";
    else if (lab.contentEquals("EU2"))
        s = "2";
    else if (lab.contentEquals("EU22"))
        s = "2:";
    else if (lab.contentEquals("EU9"))
        s = "9";
    else if (lab.contentEquals("UM9"))
        s = "9~";
    else if (lab.contentEquals("IMe"))
        s = "e~";
    else if (lab.contentEquals("ANa"))
        s = "a~";
    else if (lab.contentEquals("ONo"))
        s = "o~";
    else if (lab.contentEquals("gstop"))
        s = "?";
    /** EN (replacements in English phone set) */
    //else if (lab.contentEquals("rr") )
    //    s = "r="; 

    //System.out.println("LAB=" + s);

    return s;

}

From source file:com.nuvolect.securesuite.webserver.CrypServer.java

@Override
public Response serve(IHTTPSession session) {

    if (!m_serverEnabled) {

        return null;
    }//from ww w.  j a  va2s  . com

    Map<String, List<String>> paramsMultiple = session.getParameters();

    m_session = session;

    CookieHandler cookies = session.getCookies();
    Map<String, String> headers = session.getHeaders();
    String uniqueId = cookies.read(CConst.UNIQUE_ID);

    if (uniqueId == null) {

        if (embedded_header_value.isEmpty())
            embedded_header_value = WebUtil.getServerUrl(m_ctx);

        for (Map.Entry<String, String> entry : headers.entrySet()) {

            if (entry.getKey().startsWith(EMBEDDED_HEADER_KEY)
                    && entry.getValue().contains(embedded_header_value)) {
                uniqueId = CConst.EMBEDDED_USER;
                break;
            }
        }
        if (DEBUG && uniqueId == null) {

            LogUtil.log(LogUtil.LogType.CRYP_SERVER, "header value mismatch: " + embedded_header_value);
            for (Map.Entry<String, String> entry : headers.entrySet()) {

                LogUtil.log(LogUtil.LogType.CRYP_SERVER,
                        "header: " + entry.getKey() + ":::" + entry.getValue());
            }
        }
    }

    if (uniqueId == null) {

        uniqueId = String.valueOf(System.currentTimeMillis());
        cookies.set(CConst.UNIQUE_ID, uniqueId, 30);
    }
    /**
     * Session is authenticated when authentication is wide open or
     * session has been previously authenticated.
     */
    mAuthenticated = Cryp.getLockCode(m_ctx).isEmpty() || uniqueId.contentEquals(CConst.EMBEDDED_USER)
            || get(uniqueId, CConst.AUTHENTICATED, "0").contentEquals("1");

    Method method = session.getMethod();
    Map<String, String> params = new HashMap<String, String>();

    /**
     * Get files associated with a POST method
     */
    Map<String, String> files = new HashMap<String, String>();
    try {
        session.parseBody(files);
    } catch (ResponseException e) {
        LogUtil.logException(CrypServer.class, e);
    } catch (IOException e) {
        LogUtil.logException(CrypServer.class, e);
    }
    /**
     * {
     *    "data": {
     *        "EventID": 0,
     *        "StartAt": "2017/04/13 12:00 AM",
     *        "EndAt": "2017/04/14 12:00 AM",
     *        "IsFullDay": false,
     *        "Title ": "Sample title",
     *        "Description": "Something about the event"
     *    }
     * }
     */
    if (method.equals(Method.POST) && files.size() > 0) {

        if (files.containsKey("postData")) {

            try {
                JSONObject postData = new JSONObject(files.get("postData"));
                JSONObject data = postData.getJSONObject("data");
                params.put("data", data.toString());

                Iterator<String> keys = data.keys();

                while (keys.hasNext()) {

                    String key = keys.next();
                    String value = data.getString(key);
                    params.put(key, value);
                }
            } catch (JSONException e) {
                LogUtil.logException(CrypServer.class, e);
            }
        }
    }

    /**
     * Parameters can now have multiple values for a single key.
     * Iterate over params and copy to a HashMap<String, String>.
     * This "old way" is simple and compatible with code base.
     * Duplicate keys are made unique { key, key_2, key_3, .. key_n }
     */
    Set<String> keySet = paramsMultiple.keySet();
    for (String key : keySet) {
        List<String> values = paramsMultiple.get(key);
        int n = 0;
        for (String value : values) {
            if (++n == 1) {
                params.put(key, value);
            } else {
                params.put(key + "_" + n, value);
            }
        }
    }

    String uri = session.getUri();
    params.put(CConst.URI, uri);
    params.put(CConst.URL, m_serverUrl);
    params.put("queryParameterStrings", session.getQueryParameterString());

    params.put(CConst.UNIQUE_ID, uniqueId);

    log(LogUtil.LogType.CRYP_SERVER, method + " '" + uri + "' " + params.toString());

    InputStream is = null;
    EXT ext = null;

    String fileExtension = FilenameUtils.getExtension(uri).toLowerCase(US);
    if (fileExtension.isEmpty()) {
        if (uri.contentEquals("/")) {
            ext = EXT.htm;
            if (mAuthenticated)
                uri = "/list.htm";
            else
                uri = "/login.htm";
        } else {
            ext = determineServiceEnum(uri);
        }
    } else {
        try {
            ext = EXT.valueOf(fileExtension);
        } catch (IllegalArgumentException e) {
            log(LogUtil.LogType.CRYP_SERVER, "ERROR invalid extension " + uri + fileExtension);
            ext = EXT.invalid;
        }
    }

    try {

        if (uri == null)
            return null;

        switch (ext) {

        case js:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MimeUtil.MIME_JS, is, -1);
        case css:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MimeUtil.MIME_CSS, is, -1);
        case map:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_JSON, is, -1);
        case png:
            if (uri.startsWith("/img") || uri.startsWith("/css") || uri.startsWith("/elFinder")) {

                is = m_ctx.getAssets().open(uri.substring(1));
                return new Response(Status.OK, MIME_PNG, is, -1);
            } else if (uri.startsWith("/files/")) {
                String fileName = FilenameUtils.getName(uri);
                File file = new File(m_ctx.getFilesDir() + "/" + fileName);
                is = new FileInputStream(file);
                return new Response(Status.OK, MIME_PNG, is, -1);
            }
            log(LogUtil.LogType.CRYP_SERVER, "ERROR not found: " + uri);
            return new Response(Status.NOT_FOUND, MIME_PLAINTEXT, "Not found: " + uri);
        case jpg:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_JPG, is, -1);
        case gif:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_GIF, is, -1);
        case ico:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_ICO, is, -1);
        case ttf:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_TTF, is, -1);
        case wav:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_WAV, is, -1);
        case woff:
        case woff2:
            is = m_ctx.getAssets().open(uri.substring(1));
            return new Response(Status.OK, MIME_WOFF, is, -1);
        case htm:
        case html: {
            if (uri.contentEquals("/login.htm")) {
                log(LogUtil.LogType.CRYP_SERVER, "Serving login.htm");
                is = m_ctx.getAssets().open("login.htm");
                return new Response(Status.OK, MimeUtil.MIME_HTML, is, -1);
            }
            if (uri.contentEquals("/footer.htm")) {
                log(LogUtil.LogType.CRYP_SERVER, "Serving footer.htm");
                is = m_ctx.getAssets().open("footer.htm");
                return new Response(Status.OK, MimeUtil.MIME_HTML, is, -1);
            }
            if (mAuthenticated) {

                return serveAuthenticatedHtml(uri, uniqueId, params);
            } else {
                return new Response(Status.UNAUTHORIZED, MIME_PLAINTEXT, "Invalid authentication: " + uri);
            }
        }
        case omni: {
            String mime = "";
            OmniFile omniFile = new OmniFile(uri);
            if (omniFile.getPath().startsWith(CConst.TMB_FOLDER)) {
                /**
                 * Request for a thumbnail file.
                 * The file name is hashed and mime type is png.
                 */
                mime = MIME_PNG;
            } else
                mime = omniFile.getMime();

            is = omniFile.getFileInputStream();
            return new Response(Status.OK, mime, is, -1);
        }
        case admin: {
            /**
             * GET/POST /admin?cmd=login works with or without validation.
             * All other REST services require authentication.
             */
            if (params.containsKey("cmd") && params.get("cmd").contentEquals("login")) {

                is = AdminCmd.process(m_ctx, params);
                return new Response(Status.OK, MIME_JSON, is, -1);
            }
        }
        case calendar:
        case connector:
        case sync: {
            if (passSecurityCheck(uri, headers)) {

                switch (ext) {
                case admin:
                    is = AdminCmd.process(m_ctx, params);
                    return new Response(Status.OK, MIME_JSON, is, -1);
                case calendar: {
                    String json = CalendarRest.process(m_ctx, params);
                    return new Response(Status.OK, MIME_JSON, json);
                }
                case connector: {

                    String mime = MIME_JSON;
                    if (params.get("cmd").contentEquals("upload")) {
                        loadUploadParams(files, params);
                    } else if (params.get("cmd").contentEquals("file")) {
                        OmniFile omniFile = new OmniFile(params.get("target"));
                        mime = omniFile.getMime();
                    }

                    ServeCmd serveCmd = new ServeCmd(m_ctx, params);

                    boolean zipDl = params.get("cmd").equals("zipdl") && params.containsKey("download")
                            && params.get("download").equals("1");
                    if (zipDl) {
                        zipDownloadFileHash = params.get("targets[]_2");
                        mime = MIME_ZIP;
                    }
                    Response response = new Response(Status.OK, mime, serveCmd.process(), -1);
                    if (zipDl) {
                        response.addHeader("Content-disposition", "attachment;filename=\"Archive.zip\"");
                    }
                    return response;
                }
                case sync:
                    String json = SyncRest.process(m_ctx, params);
                    return new Response(Status.OK, MIME_PLAINTEXT, json);
                }
            } else {
                /**
                 * The security token can be temporarily disabled during companion pairing.
                 */
                boolean hostVerifierDisabled = !WebUtil.NullHostNameVerifier
                        .getInstance().m_hostVerifierEnabled;
                if (ext == EXT.sync && hostVerifierDisabled && params.containsKey(CConst.CMD) && (params
                        .get(CConst.CMD).contentEquals(SyncRest.CMD.register_companion_device.toString())
                        || params.get(CConst.CMD).contentEquals(SyncRest.CMD.companion_ip_test.toString()))) {

                    log(LogUtil.LogType.CRYP_SERVER, "sec_tok test skipped");
                    String json = SyncRest.process(m_ctx, params);
                    return new Response(Status.OK, MIME_PLAINTEXT, json);
                } else {

                    log(LogUtil.LogType.CRYP_SERVER, "Authentication ERROR: " + params);
                    return new Response(Status.UNAUTHORIZED, MIME_PLAINTEXT, "Authentication error: " + uri);
                }
            }
        }
        case invalid:
            log(LogUtil.LogType.CRYP_SERVER, "ERROR invalid extension " + uri);
            return new Response(Status.NOT_ACCEPTABLE, MIME_PLAINTEXT, "Invalid request " + uri);
        default:
            log(LogUtil.LogType.CRYP_SERVER, "ERROR unmanaged extension " + ext);
            return new Response(Status.NOT_FOUND, MIME_PLAINTEXT, "Not found: " + uri);
        }

    } catch (Exception e) {
        log(LogUtil.LogType.CRYP_SERVER, "ERROR exception " + uri);
        LogUtil.logException(CrypServer.class, e);
    }
    return new Response(Status.NOT_FOUND, MIME_PLAINTEXT, "Unmanaged request: " + uri);
}

From source file:com.nuvolect.securesuite.data.SqlCipher.java

/**
 * Iterate through and test all the accounts, contacts and groups of contacts.
 * Tests are performed on the raw database tables and does not use any in-memory data.
 * 1. For each contact, confirm there is exactly one account and detail record
 * When the user is part of a group://www .  j  a v  a 2  s.  c  om
 * 2. Confirm group_id > 0, not -2, -1 or 0
 * 3. Confirm user is in the group a single time, not zero or multiple times in the same group
 * 4. Confirm group has a single title record
 * 5. Confirm detail table key value items are valid JSON
 * //FUTURE Check for unused/rogue group records.
 * //FUTURE Check for unused/rogue group title records
 //FUTURE cleanup any rogue group data records: records not associated with any contacts
 //FUTURE cleanup any rogue group title records: records with no associated group data, not My Contacts, not Trash
 * @param ctx
 * @return
 */
public static synchronized int validateFixDb(Context ctx, boolean fixErrors) {

    int successCount = 0;
    int failCount = 0;
    int fixCount = 0;
    int contactCount = 0;
    logError(ctx, LogType.SQLCIPHER, "validateDbCounts starting ");

    String[] accountProjection = { ATab.contact_id.toString(), //0
            ATab.display_name.toString(), //1
            ATab.last_name.toString(), //2
            ATab.account_name.toString(), //3
    };

    Cursor ac = account_db.query(ACCOUNT_TABLE, accountProjection, null, null, null, null, null);

    while (ac.moveToNext()) {

        long contact_id = ac.getLong(0);
        String display_name = ac.getString(1);
        String contact_account = ac.getString(3);

        /**
         * Check account records for complete names
         */
        String last_name = ac.getString(2);

        if (last_name == null) {

            logError(ctx, LogType.SQLCIPHER,
                    ACCOUNT_TABLE + " ERROR last_name null or empty: " + display_name + ", " + contact_id);
            ++failCount;
        } else
            ++successCount;

        String[] detailProjection = { DTab.contact_id.toString(), };
        String where = DTab.contact_id + "=?";
        String[] args = new String[] { String.valueOf(contact_id) };

        // Cursor is from detail db, test to see if it matches accouts db
        Cursor dc = detail_db.query(DETAIL_TABLE, detailProjection, where, args, null, null, null);
        int dCount = dc.getCount();
        dc.close();

        if (dCount != 1) {

            logError(ctx, LogType.SQLCIPHER,
                    ACCOUNT_TABLE + " ERROR count: " + dCount + " != 1 for contact_id: " + contact_id);
            ++failCount;
        } else
            ++successCount;

        /**
         * 5. Confirm that detail table key value items are valid JSON
         */
        boolean jsonTest = true;
        try {
            String kvString = get(contact_id, DTab.kv);
            JSONObject kvJobj = new JSONObject(kvString);
        } catch (JSONException e) {
            logError(ctx, LogType.SQLCIPHER, "Invalid JSON DTab.kv for ID: " + contact_id);
            jsonTest = false;
        } catch (RuntimeException e) {
            logError(ctx, LogType.SQLCIPHER, "RuntimeException test 5. for ID: " + contact_id);
            ++failCount;
        }
        if (jsonTest)
            ++successCount;
        else
            ++failCount;

        // See if the user is part of any groups
        int[] groups = MyGroups.getGroups(contact_id);

        for (int group_id : groups) {

            // Test that group is > 0
            if (group_id <= 0) {

                logError(ctx, LogType.SQLCIPHER, ACCOUNT_TABLE + " ERROR group_id: " + group_id
                        + " <= 0 in group for contact_id: " + contact_id);
                ++failCount;
                if (fixErrors) {

                    int rows = MyGroups.deleteGroupForce(ctx, group_id, false);// don't sync
                    if (rows > 0) {
                        logError(ctx, LogType.SQLCIPHER, ACCOUNT_TABLE + " DB Fix group_id: " + group_id
                                + " <= 0, group deleted for contact_id: " + contact_id);
                        ++fixCount;
                    }
                }
                continue;
            } else
                ++successCount;

            // Test to find contact in groups
            int foundContact = 0;

            long[] contacts_in_group = MyGroups.getContacts(group_id);

            for (long c_id : contacts_in_group) {

                if (c_id == contact_id) {
                    ++foundContact;
                }
            }

            if (foundContact == 0) {

                logError(ctx, LogType.SQLCIPHER, DETAIL_TABLE + " ERROR group_id: " + group_id
                        + " zero times in group for contact_id: " + contact_id);
                ++failCount;
            } else if (foundContact > 1) {

                logError(ctx, LogType.SQLCIPHER, DETAIL_TABLE + " ERROR group_id: " + group_id
                        + " > 1 times in group for contact_id: " + contact_id);
                ++failCount;
            } else
                ++successCount;

            // Check that the group has exactly one group title record

            String title = MyGroups.getGroupTitle(group_id);

            if (title == null || title.isEmpty()) {

                logError(ctx, LogType.SQLCIPHER, DETAIL_TABLE + " ERROR title missing group_id: " + group_id
                        + " for contact_id: " + contact_id);
                ++failCount;
            }
            ++successCount;

            // Check that the contact and group are on the same account
            String group_account = MyGroups.mGroupAccount.get(group_id);

            if (group_account != null && group_account.contentEquals(contact_account))
                ++successCount;
            else {

                logError(ctx, LogType.SQLCIPHER,
                        DETAIL_TABLE + " ERROR contact and group do not have same account.  group account: "
                                + group_account + " contact account: " + contact_account);
                logError(ctx, LogType.SQLCIPHER, DETAIL_TABLE + " group_id: " + group_id + " display_name: "
                        + display_name + " for contact_id: " + contact_id);
                ++failCount;
            }
        }
        if (++contactCount % 200 == 0)
            logError(ctx, LogType.SQLCIPHER, "Progress: " + contactCount);
    }
    ac.close();

    logError(ctx, LogType.SQLCIPHER, "validateDbCounts complete, success: " + successCount + ", fail: "
            + failCount + ", fixed: " + fixCount);

    return failCount;
}

From source file:marytts.tools.voiceimport.HTKLabeler.java

/** Translation table for labels which are incompatible with HTK or shell filenames
 * See common_routines.pl in HTS training.
 * @param lab//from  w  ww.  j  a v  a2s . c o  m
 * @return String
 */
public String replaceTrickyPhones(String lab) {
    String s = lab;

    /** the replace is done for the labels: phone, prev_phone and next_phone */

    /** DE (replacements in German phone set) */
    if (lab.contentEquals("6"))
        s = "ER6";
    else if (lab.contentEquals("=6"))
        s = "ER66";
    else if (lab.contentEquals("2:"))
        s = "EU22";
    else if (lab.contentEquals("2"))
        s = "EU2";
    else if (lab.contentEquals("9"))
        s = "EU9";
    else if (lab.contentEquals("9~"))
        s = "UM9";
    else if (lab.contentEquals("e~"))
        s = "IMe";
    else if (lab.contentEquals("a~"))
        s = "ANa";
    else if (lab.contentEquals("o~"))
        s = "ONo";
    else if (lab.contentEquals("?"))
        s = "gstop";
    /** EN (replacements in English phone set) */
    //else if (lab.contentEquals("r=") )
    //    s = "rr"; 

    return s;

}