Example usage for org.apache.commons.lang StringUtils left

List of usage examples for org.apache.commons.lang StringUtils left

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils left.

Prototype

public static String left(String str, int len) 

Source Link

Document

Gets the leftmost len characters of a String.

Usage

From source file:com.funambol.foundation.items.dao.PIMNoteDAOTest.java

/**
 * Check truncateTextField./*from   www. j  ava2  s.c  o  m*/
 * 
 * 0 if truncationSize < textField size then text field is not truncated
 * 1 if truncationSize = textField size then text field is not truncated
 * 2 if truncationSize > textField size then text field is truncated at truncationSize
 */
public void testTruncate() throws Throwable {

    String truncatedTextField = null;
    int truncationSize = 2;

    String[][] tests = { new String[] { "a", "a" }, // 0
            new String[] { "aa", "aa" }, // 1
            new String[] { "aabbbb", "aa" }, // 2
    };

    for (String[] test : tests) {
        truncatedTextField = StringUtils.left(test[0], truncationSize);
        assertEquals(test[1], truncatedTextField);
    }
}

From source file:adalid.commons.velocity.Writer.java

private boolean isAbsolutePath(String string) {
    String trimmed = StringUtils.trimToNull(string);
    if (trimmed == null) {
        return false;
    }/*from   ww  w.j  a  v a 2 s .c  o  m*/
    if (WINDOWS) {
        String left = StringUtils.left(trimmed, 2);
        return left.matches("[a-zA-Z]\\:");
    } else {
        return StringUtils.startsWithAny(trimmed, FILE_SEPARATOR_STRINGS);
    }
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Updates a contact./*from   w w  w . ja  v a  2  s  .c  o m*/
 *
 * @param cw as a ContactWrapper object. If its last update time is null,
 *           then it's set to the current time.
 * @return the UID of the contact
 * @throws DAOException
 *
 * @see ContactWrapper
 */
public String updateItem(ContactWrapper cw) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatement ps1 = null;
    ResultSet rs = null;

    int type = 0;

    PersonalDetail personalDetail = null;
    BusinessDetail businessDetail = null;
    Address homeAddressBook = null;
    Address workAddressBook = null;
    Address otherAddressBook = null;

    Name name = null;
    Phone phone = null;
    Email email = null;
    WebPage webPage = null;

    List<WebPage> webPages = new ArrayList<WebPage>();
    List<Email> emails = new ArrayList<Email>();
    List<Phone> phones = new ArrayList<Phone>();
    List<String[]> labels = new ArrayList<String[]>();

    String phoneType = null;
    String webPageType = null;

    StringBuffer queryUpdateFunPimContact = null;

    Short importance = null;
    Short sensitivity = null;
    String mileage = null;
    String subject = null;
    String folder = null;
    String anniversary = null;
    String firstName = null;
    String middleName = null;
    String lastName = null;
    String displayName = null;
    String birthday = null;
    String note = null;
    String categories = null;
    String hobbies = null;
    String gender = null;
    String initials = null;
    String languages = null;
    String nickName = null;
    String spouse = null;
    String suffix = null;
    String assistant = null;
    String company = null;
    String companies = null;
    String department = null;
    String jobTitle = null;
    String manager = null;
    String city = null;
    String state = null;
    String role = null;
    String children = null;
    String salutation = null;
    String officeLocation = null;
    String street = null;
    String postalCode = null;
    String country = null;
    String postOfficeAddress = null;
    String extendedAddress = null;

    String[] addressFields = null;

    boolean findRecord = false;
    boolean emptyAddress = false;

    short photoType = ContactWrapper.EMPTY_PHOTO;
    boolean photoToRemove = false;
    boolean photoToSet = false;
    boolean photoNothingToDo = false;

    StringBuffer sqlUpdateFunPimAddress = null;

    try {

        Timestamp lastUpdate = (cw.getLastUpdate() == null) ? new Timestamp(System.currentTimeMillis())
                : cw.getLastUpdate();

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        Contact c = cw.getContact();

        personalDetail = c.getPersonalDetail();
        businessDetail = c.getBusinessDetail();
        name = c.getName();
        importance = c.getImportance();
        sensitivity = c.getSensitivity();
        mileage = c.getMileage();
        subject = c.getSubject();
        languages = c.getLanguages();
        folder = c.getFolder();
        categories = Property.stringFrom(c.getCategories());

        if (personalDetail != null) {

            homeAddressBook = personalDetail.getAddress();
            otherAddressBook = personalDetail.getOtherAddress();
            anniversary = personalDetail.getAnniversary();
            birthday = personalDetail.getBirthday();
            children = personalDetail.getChildren();
            spouse = personalDetail.getSpouse();
            hobbies = personalDetail.getHobbies();
            gender = personalDetail.getGender();
            webPages.addAll(personalDetail.getWebPages());
            emails.addAll(personalDetail.getEmails());
            phones.addAll(personalDetail.getPhones());
        }

        if (businessDetail != null) {

            assistant = businessDetail.getAssistant();
            manager = businessDetail.getManager();
            workAddressBook = businessDetail.getAddress();
            companies = businessDetail.getCompanies();
            company = Property.stringFrom(businessDetail.getCompany());
            department = Property.stringFrom(businessDetail.getDepartment());
            role = Property.stringFrom(businessDetail.getRole());
            officeLocation = businessDetail.getOfficeLocation();
            webPages.addAll(businessDetail.getWebPages());
            emails.addAll(businessDetail.getEmails());
            phones.addAll(businessDetail.getPhones());
        }

        if (name != null) {
            firstName = Property.stringFrom(name.getFirstName());
            middleName = Property.stringFrom(name.getMiddleName());
            lastName = Property.stringFrom(name.getLastName());
            displayName = Property.stringFrom(name.getDisplayName());
            initials = Property.stringFrom(name.getInitials());
            nickName = Property.stringFrom(name.getNickname());
            suffix = Property.stringFrom(name.getSuffix());
            salutation = Property.stringFrom(name.getSalutation());
        }

        if (c.getNotes() != null && c.getNotes().size() > 0) {
            note = ((Note) c.getNotes().get(0)).getPropertyValueAsString();
        } else {
            note = null;
        }

        if (businessDetail.getTitles() != null && businessDetail.getTitles().size() > 0) {
            jobTitle = ((Title) businessDetail.getTitles().get(0)).getPropertyValueAsString();
        } else {
            jobTitle = null;
        }

        queryUpdateFunPimContact = new StringBuffer();

        queryUpdateFunPimContact.append(
                SQL_UPDATE_FNBL_PIM_CONTACT_BEGIN + SQL_FIELD_LAST_UPDATE + SQL_EQUALS_QUESTIONMARK_COMMA);

        //
        // Updating photo:
        // 1. if the contact doesn't have a photo (photo null),
        //    nothing should be done (If there is a photo in the db this will
        //    be kept)
        // 2. if the contact has a photo (image or url) it must be inserted
        //    in the db
        // 3. if the photo has a photo but the image and the url are null,
        //    the one in the db must be removed
        //
        Photo photo = personalDetail.getPhotoObject();
        if (photo == null) {
            //
            // nothing to do
            //
            photoNothingToDo = true;
        } else {
            if (photo.getImage() != null) {
                photoType = ContactWrapper.PHOTO_IMAGE;
                photoToSet = true;
            } else if (photo.getUrl() != null) {
                photoType = ContactWrapper.PHOTO_URL;
                photoToSet = true;
            } else {
                photoToRemove = true;
                photoType = ContactWrapper.EMPTY_PHOTO;
            }
            queryUpdateFunPimContact.append(SQL_FIELD_PHOTO_TYPE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        if (importance != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_IMPORTANCE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (sensitivity != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SENSITIVITY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (subject != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SUBJECT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (folder != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_FOLDER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (anniversary != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_ANNIVERSARY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (firstName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_FIRST_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (middleName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_MIDDLE_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (lastName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_LAST_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (displayName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_DISPLAY_NAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (birthday != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_BIRTHDAY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (note != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_BODY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (categories != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_CATEGORIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (children != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_CHILDREN + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (hobbies != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_HOBBIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (initials != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_INITIALS + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (languages != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_LANGUAGES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (nickName != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_NICKNAME + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (spouse != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SPOUSE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (suffix != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_SUFFIX + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (salutation != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_TITLE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (assistant != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_ASSISTANT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (company != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_COMPANY + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (department != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_DEPARTMENT + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (jobTitle != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_JOB_TITLE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (manager != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_MANAGER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (mileage != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_MILEAGE + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (officeLocation != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_OFFICE_LOCATION + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (role != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_PROFESSION + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (companies != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_COMPANIES + SQL_EQUALS_QUESTIONMARK_COMMA);
        }
        if (gender != null) {
            queryUpdateFunPimContact.append(SQL_FIELD_GENDER + SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        queryUpdateFunPimContact
                .append(SQL_FIELD_STATUS + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_CONTACT_END);

        ps = con.prepareStatement(queryUpdateFunPimContact.toString());

        int k = 1;

        //
        // GENERAL
        //
        ps.setLong(k++, lastUpdate.getTime());

        //
        // PHOTO TYPE
        //
        if (!photoNothingToDo) {
            ps.setShort(k++, photoType);
        }

        //
        // CONTACT DETAILS
        //
        if (importance != null) {
            ps.setShort(k++, importance.shortValue());
        }
        if (sensitivity != null) {
            ps.setShort(k++, sensitivity.shortValue());
        }

        if (subject != null) {
            if (subject.length() > SQL_SUBJECT_DIM) {
                subject = subject.substring(0, SQL_SUBJECT_DIM);
            }
            ps.setString(k++, subject);
        }
        //
        // folder
        //
        if (folder != null) {
            if (folder.length() > SQL_FOLDER_DIM) {
                folder = folder.substring(0, SQL_FOLDER_DIM);
            }
            ps.setString(k++, folder);
        }

        //
        // PERSONAL DETAILS
        //

        //
        // anniversary
        //
        if (anniversary != null) {
            if (anniversary.length() > SQL_ANNIVERSARY_DIM) {
                anniversary = anniversary.substring(0, SQL_ANNIVERSARY_DIM);
            }
            ps.setString(k++, anniversary);
        }
        //
        // firstName
        //
        if (firstName != null) {
            if (firstName.length() > SQL_FIRSTNAME_DIM) {
                firstName = firstName.substring(0, SQL_FIRSTNAME_DIM);
            }
            ps.setString(k++, firstName);
        }
        //
        // middleName
        //
        if (middleName != null) {
            if (middleName.length() > SQL_MIDDLENAME_DIM) {
                middleName = middleName.substring(0, SQL_MIDDLENAME_DIM);
            }
            ps.setString(k++, middleName);
        }
        //
        // lastName
        //
        if (lastName != null) {
            if (lastName.length() > SQL_LASTNAME_DIM) {
                lastName = lastName.substring(0, SQL_LASTNAME_DIM);
            }
            ps.setString(k++, lastName);
        }
        //
        // displayName
        //
        if (displayName != null) {
            if (displayName.length() > SQL_DISPLAYNAME_DIM) {
                displayName = displayName.substring(0, SQL_DISPLAYNAME_DIM);
            }
            ps.setString(k++, displayName);
        }
        //
        // birthday
        //
        if (birthday != null) {
            if (birthday.length() > SQL_BIRTHDAY_DIM) {
                birthday = birthday.substring(0, SQL_BIRTHDAY_DIM);
            }
            ps.setString(k++, birthday);
        }
        //
        // note
        //
        if (note != null) {
            if (note.length() > SQL_NOTE_DIM) {
                note = note.substring(0, SQL_NOTE_DIM);
            }
            ps.setString(k++, note);
        }
        //
        // categories
        //
        if (categories != null) {
            if (categories.length() > SQL_CATEGORIES_DIM) {
                categories = categories.substring(0, SQL_CATEGORIES_DIM);
            }
            ps.setString(k++, categories);
        }
        //
        // children
        //
        if (children != null) {
            if (children.length() > SQL_CHILDREN_DIM) {
                children = children.substring(0, SQL_CHILDREN_DIM);
            }
            ps.setString(k++, children);
        }
        //
        // hobbies
        //
        if (hobbies != null) {
            if (hobbies.length() > SQL_HOBBIES_DIM) {
                hobbies = hobbies.substring(0, SQL_HOBBIES_DIM);
            }
            ps.setString(k++, hobbies);
        }
        //
        // initials
        //
        if (initials != null) {
            if (initials.length() > SQL_INITIALS_DIM) {
                initials = initials.substring(0, SQL_INITIALS_DIM);
            }
            ps.setString(k++, initials);
        }
        //
        // languages
        //
        if (languages != null) {
            if (languages.length() > SQL_LANGUAGES_DIM) {
                languages = initials.substring(0, SQL_LANGUAGES_DIM);
            }
            ps.setString(k++, languages);
        }
        //
        // nickName
        //
        if (nickName != null) {
            if (nickName.length() > SQL_NICKNAME_DIM) {
                nickName = nickName.substring(0, SQL_NICKNAME_DIM);
            }
            ps.setString(k++, nickName);
        }
        //
        // spouse
        //
        if (spouse != null) {
            if (spouse.length() > SQL_SPOUSE_DIM) {
                spouse = spouse.substring(0, SQL_SPOUSE_DIM);
            }
            ps.setString(k++, spouse);
        }
        //
        // suffix
        //
        if (suffix != null) {
            if (suffix.length() > SQL_SUFFIX_DIM) {
                suffix = suffix.substring(0, SQL_SUFFIX_DIM);
            }
            ps.setString(k++, suffix);
        }
        //
        // salutation
        //
        if (salutation != null) {
            if (salutation.length() > SQL_SALUTATION_DIM) {
                salutation = salutation.substring(0, SQL_SALUTATION_DIM);
            }
            ps.setString(k++, salutation);
        }
        //
        // assistant
        //
        if (assistant != null) {
            if (assistant.length() > SQL_ASSISTANT_DIM) {
                assistant = assistant.substring(0, SQL_ASSISTANT_DIM);
            }
            ps.setString(k++, assistant);
        }
        //
        // company
        //
        if (company != null) {
            if (company.length() > SQL_COMPANY_DIM) {
                company = company.substring(0, SQL_COMPANY_DIM);
            }
            ps.setString(k++, company);
        }
        //
        // department
        //
        if (department != null) {
            if (department.length() > SQL_DEPARTMENT_DIM) {
                department = department.substring(0, SQL_DEPARTMENT_DIM);
            }
            ps.setString(k++, department);
        }
        //
        // jobTitle
        //
        if (jobTitle != null) {
            if (jobTitle.length() > SQL_TITLE_DIM) {
                jobTitle = jobTitle.substring(0, SQL_TITLE_DIM);
            }
            ps.setString(k++, jobTitle);
        }
        //
        // manager
        //
        if (manager != null) {
            if (manager.length() > SQL_MANAGER_DIM) {
                manager = manager.substring(0, SQL_MANAGER_DIM);
            }
            ps.setString(k++, manager);
        }
        //
        // mileage
        //
        if (mileage != null) {
            if (mileage.length() > SQL_MILEAGE_DIM) {
                mileage = mileage.substring(0, SQL_MILEAGE_DIM);
            }
            ps.setString(k++, mileage);
        }
        if (officeLocation != null) {
            if (officeLocation.length() > SQL_OFFICELOCATION_DIM) {
                officeLocation = officeLocation.substring(0, SQL_OFFICELOCATION_DIM);
            }
            ps.setString(k++, officeLocation);
        }
        //
        // role
        //
        if (role != null) {
            if (role.length() > SQL_ROLE_DIM) {
                role = role.substring(0, SQL_ROLE_DIM);
            }
            ps.setString(k++, role);
        }

        //
        // companies
        //
        if (companies != null) {
            if (companies.length() > SQL_COMPANIES_DIM) {
                companies = companies.substring(0, SQL_COMPANIES_DIM);
            }
            ps.setString(k++, companies);
        }

        //
        // gender
        //
        if (gender != null) {
            if (gender.length() > SQL_GENDER_DIM) {
                gender = gender.substring(0, SQL_GENDER_DIM);
            }
            ps.setString(k++, gender);
        }

        //
        // status
        //
        ps.setString(k++, String.valueOf('U'));
        //
        // id
        //
        ps.setLong(k++, Long.parseLong(cw.getId()));
        //
        // userId
        //
        ps.setString(k++, userId);

        ps.executeUpdate();

        DBTools.close(null, ps, null);

        //
        // emails
        //
        if (!emails.isEmpty()) {
            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = emails.size(); i < l; i++) {

                email = emails.get(i);

                if ((FIELD_EMAIL_1_ADDRESS).equals(email.getEmailType())) {
                    type = TYPE_EMAIL_1_ADDRESS;
                } else if ((FIELD_EMAIL_2_ADDRESS).equals(email.getEmailType())) {
                    type = TYPE_EMAIL_2_ADDRESS;
                } else if ((FIELD_EMAIL_3_ADDRESS).equals(email.getEmailType())) {
                    type = TYPE_EMAIL_3_ADDRESS;
                } else if ((FIELD_INSTANT_MESSENGER).equals(email.getEmailType())) {
                    type = TYPE_INSTANT_MESSENGER;
                } else {
                    //
                    // no save unknown property
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                rs.close();
                rs = null;

                String emailValue = email.getPropertyValueAsString();

                emailValue = StringUtils.left(emailValue, SQL_EMAIL_DIM);

                if (!findRecord) {

                    if (emailValue != null && emailValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, emailValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (emailValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, emailValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);

                    } else {

                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);

                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }
            }

            DBTools.close(null, ps1, null);

        }

        //
        // phones
        //
        if (!phones.isEmpty()) {

            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = phones.size(); i < l; i++) {

                phone = phones.get(i);

                phoneType = phone.getPhoneType();

                if ((FIELD_HOME_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_HOME_TELEPHONE_NUMBER;
                } else if ((FIELD_HOME_2_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_HOME_2_TELEPHONE_NUMBER;
                } else if ((FIELD_HOME_FAX_NUMBER).equals(phoneType)) {
                    type = TYPE_HOME_FAX_NUMBER;
                } else if ((FIELD_MOBILE_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_MOBILE_TELEPHONE_NUMBER;
                } else if ((FIELD_CAR_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_CAR_TELEPHONE_NUMBER;
                } else if ((FIELD_OTHER_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_OTHER_TELEPHONE_NUMBER;
                } else if ((FIELD_OTHER_FAX_NUMBER).equals(phoneType)) {
                    type = TYPE_OTHER_FAX_NUMBER;
                } else if ((FIELD_PRIMARY_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_PRIMARY_TELEPHONE_NUMBER;
                } else if ((FIELD_BUSINESS_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_BUSINESS_TELEPHONE_NUMBER;
                } else if ((FIELD_BUSINESS_2_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_BUSINESS_2_TELEPHONE_NUMBER;
                } else if ((FIELD_BUSINESS_FAX_NUMBER).equals(phoneType)) {
                    type = TYPE_BUSINESS_FAX_NUMBER;
                } else if ((FIELD_COMPANY_MAIN_TELEPHONE_NUMBER).equals(phoneType)) {
                    type = TYPE_COMPANY_MAIN_TELEPHONE_NUMBER;
                } else if ((FIELD_PAGER_NUMBER).equals(phoneType)) {
                    type = TYPE_PAGER_NUMBER;
                } else if ((FIELD_ASSISTANT_NUMBER).equals(phoneType)) {
                    type = TYPE_ASSISTANT_NUMBER;
                } else if ((FIELD_CALLBACK_NUMBER).equals(phoneType)) {
                    type = TYPE_CALLBACK_NUMBER;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                String phoneValue = phone.getPropertyValueAsString();
                phoneValue = StringUtils.left(phoneValue, SQL_EMAIL_DIM);

                if (!findRecord) {
                    if (phoneValue != null && phoneValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, phoneValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (phoneValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, phoneValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);

                    } else {
                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

                DBTools.close(null, null, rs);

            }

            DBTools.close(null, ps1, null);

        }

        //
        // web pages
        //
        if (!webPages.isEmpty()) {

            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = webPages.size(); i < l; i++) {

                webPage = webPages.get(i);

                webPageType = webPage.getWebPageType();

                if ((FIELD_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_WEB_PAGE;
                } else if ((FIELD_HOME_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_HOME_WEB_PAGE;
                } else if ((FIELD_BUSINESS_WEB_PAGE).equals(webPageType)) {
                    type = TYPE_BUSINESS_WEB_PAGE;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                String webPageValue = webPage.getPropertyValueAsString();
                webPageValue = StringUtils.left(webPageValue, SQL_WEBPAGE_DIM);

                if (!findRecord) {

                    if (webPageValue != null && webPageValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, webPageValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (webPageValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, webPageValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);
                    } else {
                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

                DBTools.close(null, null, rs);

            }

            DBTools.close(null, ps1, null);

        }

        //
        // home address
        //
        if (homeAddressBook != null) {

            ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS);

            ps.setLong(1, Long.parseLong(cw.getId()));
            ps.setInt(2, ADDRESS_TYPE_HOME);

            rs = ps.executeQuery();

            findRecord = rs.next();

            DBTools.close(null, ps, rs);

            street = Property.stringFrom(homeAddressBook.getStreet());
            city = Property.stringFrom(homeAddressBook.getCity());
            postalCode = Property.stringFrom(homeAddressBook.getPostalCode());
            state = Property.stringFrom(homeAddressBook.getState());
            country = Property.stringFrom(homeAddressBook.getCountry());
            postOfficeAddress = Property.stringFrom(homeAddressBook.getPostOfficeAddress());
            extendedAddress = Property.stringFrom(homeAddressBook.getExtendedAddress());

            street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM));
            city = StringUtils.left(city, SQL_CITY_DIM);
            state = StringUtils.left(state, SQL_STATE_DIM);
            postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM);
            country = StringUtils.left(country, SQL_COUNTRY_DIM);
            postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM);
            extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM);

            String homeLabel = Property.stringFrom(homeAddressBook.getLabel());
            if (homeLabel != null) {
                String[] label = { homeLabel, FIELD_HOME_LABEL };
                labels.add(label);
            }

            addressFields = new String[] { street, city, postalCode, country, state, postOfficeAddress,
                    extendedAddress };

            emptyAddress = hasOnlyNullContent(addressFields);

            if (!emptyAddress) {

                if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)) {
                    ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                    ps.setLong(1, Long.parseLong(cw.getId()));
                    ps.setInt(2, ADDRESS_TYPE_HOME);
                    ps.setString(3, street);
                    ps.setString(4, city);
                    ps.setString(5, state);
                    ps.setString(6, postalCode);
                    ps.setString(7, country);
                    ps.setString(8, postOfficeAddress);
                    ps.setString(9, extendedAddress);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                } else {

                    sqlUpdateFunPimAddress = new StringBuffer();

                    sqlUpdateFunPimAddress.append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN);

                    if (street != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (city != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (state != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postalCode != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (country != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postOfficeAddress != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (extendedAddress != null) {
                        sqlUpdateFunPimAddress
                                .append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }

                    sqlUpdateFunPimAddress
                            .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END);

                    ps = con.prepareStatement(sqlUpdateFunPimAddress.toString());

                    k = 1;

                    if (street != null) {
                        ps.setString(k++, street);
                    }
                    if (city != null) {
                        ps.setString(k++, city);
                    }
                    if (state != null) {
                        ps.setString(k++, state);
                    }
                    if (postalCode != null) {
                        ps.setString(k++, postalCode);
                    }
                    if (country != null) {
                        ps.setString(k++, country);
                    }
                    if (postOfficeAddress != null) {
                        ps.setString(k++, postOfficeAddress);
                    }
                    if (extendedAddress != null) {
                        ps.setString(k++, extendedAddress);
                    }

                    ps.setInt(k++, ADDRESS_TYPE_HOME);
                    ps.setLong(k++, Long.parseLong(cw.getId()));
                    ps.setInt(k++, ADDRESS_TYPE_HOME);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

            }

        }

        //
        // other address
        //
        if (otherAddressBook != null) {

            ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS);

            ps.setLong(1, Long.parseLong(cw.getId()));
            ps.setInt(2, ADDRESS_TYPE_OTHER);

            rs = ps.executeQuery();

            findRecord = rs.next();

            DBTools.close(null, ps, rs);

            street = Property.stringFrom(otherAddressBook.getStreet());
            city = Property.stringFrom(otherAddressBook.getCity());
            postalCode = Property.stringFrom(otherAddressBook.getPostalCode());
            state = Property.stringFrom(otherAddressBook.getState());
            country = Property.stringFrom(otherAddressBook.getCountry());
            postOfficeAddress = Property.stringFrom(otherAddressBook.getPostOfficeAddress());
            extendedAddress = Property.stringFrom(otherAddressBook.getExtendedAddress());

            street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM));
            city = StringUtils.left(city, SQL_CITY_DIM);
            state = StringUtils.left(state, SQL_STATE_DIM);
            postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM);
            country = StringUtils.left(country, SQL_COUNTRY_DIM);
            postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM);
            extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM);

            addressFields = new String[] { street, city, postalCode, country, state, postOfficeAddress,
                    extendedAddress };

            String otherLabel = Property.stringFrom(otherAddressBook.getLabel());
            if (otherLabel != null) {
                String[] label = { otherLabel, FIELD_OTHER_LABEL };
                labels.add(label);
            }

            emptyAddress = hasOnlyNullContent(addressFields);

            if (!emptyAddress) {

                if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)) {

                    ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                    ps.setLong(1, Long.parseLong(cw.getId()));
                    ps.setInt(2, ADDRESS_TYPE_OTHER);
                    ps.setString(3, street);
                    ps.setString(4, city);
                    ps.setString(5, state);
                    ps.setString(6, postalCode);
                    ps.setString(7, country);
                    ps.setString(8, postOfficeAddress);
                    ps.setString(9, extendedAddress);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                } else {

                    sqlUpdateFunPimAddress = new StringBuffer();

                    sqlUpdateFunPimAddress.append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN);

                    if (street != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (city != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (state != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postalCode != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (country != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postOfficeAddress != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (extendedAddress != null) {
                        sqlUpdateFunPimAddress
                                .append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }

                    sqlUpdateFunPimAddress
                            .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END);

                    ps = con.prepareStatement(sqlUpdateFunPimAddress.toString());

                    k = 1;

                    if (street != null) {
                        ps.setString(k++, street);
                    }
                    if (city != null) {
                        ps.setString(k++, city);
                    }
                    if (state != null) {
                        ps.setString(k++, state);
                    }
                    if (postalCode != null) {
                        ps.setString(k++, postalCode);
                    }
                    if (country != null) {
                        ps.setString(k++, country);
                    }
                    if (postOfficeAddress != null) {
                        ps.setString(k++, postOfficeAddress);
                    }
                    if (extendedAddress != null) {
                        ps.setString(k++, extendedAddress);
                    }

                    ps.setInt(k++, ADDRESS_TYPE_OTHER);
                    ps.setLong(k++, Long.parseLong(cw.getId()));
                    ps.setInt(k++, ADDRESS_TYPE_OTHER);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                }

            }

        }

        //
        // work address
        //
        if (workAddressBook != null) {

            ps = con.prepareStatement(SQL_SELECT_FROM_FNBL_PIM_ADDRESS);

            ps.setLong(1, Long.parseLong(cw.getId()));
            ps.setInt(2, ADDRESS_TYPE_WORK);

            rs = ps.executeQuery();

            findRecord = rs.next();

            DBTools.close(null, ps, rs);

            street = Property.stringFrom(workAddressBook.getStreet());
            city = Property.stringFrom(workAddressBook.getCity());
            postalCode = Property.stringFrom(workAddressBook.getPostalCode());
            state = Property.stringFrom(workAddressBook.getState());
            country = Property.stringFrom(workAddressBook.getCountry());
            postOfficeAddress = Property.stringFrom(workAddressBook.getPostOfficeAddress());
            extendedAddress = Property.stringFrom(workAddressBook.getExtendedAddress());

            street = replaceNewLine(StringUtils.left(street, SQL_STREET_DIM));
            city = StringUtils.left(city, SQL_CITY_DIM);
            state = StringUtils.left(state, SQL_STATE_DIM);
            postalCode = StringUtils.left(postalCode, SQL_POSTALCODE_DIM);
            country = StringUtils.left(country, SQL_COUNTRY_DIM);
            postOfficeAddress = StringUtils.left(postOfficeAddress, SQL_POSTALOFFICEADDRESS_DIM);
            extendedAddress = StringUtils.left(extendedAddress, SQL_EXTENDEDADDRESS_DIM);

            String workLabel = Property.stringFrom(workAddressBook.getLabel());
            if (workLabel != null) {
                String[] label = { workLabel, FIELD_BUSINESS_LABEL };
                labels.add(label);
            }

            addressFields = new String[] { street, city, postalCode, country, state, postOfficeAddress,
                    extendedAddress };

            emptyAddress = hasOnlyNullContent(addressFields);

            if (!emptyAddress) {

                if (!findRecord && !hasOnlyEmptyOrNullContent(addressFields)) {

                    ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_ADDRESS);

                    ps.setLong(1, Long.parseLong(cw.getId()));
                    ps.setInt(2, ADDRESS_TYPE_WORK);
                    ps.setString(3, street);
                    ps.setString(4, city);
                    ps.setString(5, state);
                    ps.setString(6, postalCode);
                    ps.setString(7, country);
                    ps.setString(8, postOfficeAddress);
                    ps.setString(9, extendedAddress);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                } else {

                    sqlUpdateFunPimAddress = new StringBuffer();

                    sqlUpdateFunPimAddress.append(SQL_UPDATE_FNBL_PIM_ADDRESS_BEGIN);

                    if (street != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STREET + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (city != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_CITY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (state != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_STATE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postalCode != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_POSTAL_CODE + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (country != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_COUNTRY + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (postOfficeAddress != null) {
                        sqlUpdateFunPimAddress.append(SQL_FIELD_PO_BOX + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }
                    if (extendedAddress != null) {
                        sqlUpdateFunPimAddress
                                .append(SQL_FIELD_EXTENDED_ADDRESS + SQL_EQUALS_QUESTIONMARK_COMMA);
                    }

                    sqlUpdateFunPimAddress
                            .append(SQL_FIELD_TYPE + SQL_EQUALS_QUESTIONMARK + SQL_UPDATE_FNBL_PIM_ADDRESS_END);

                    ps = con.prepareStatement(sqlUpdateFunPimAddress.toString());

                    k = 1;

                    if (street != null) {
                        ps.setString(k++, street);
                    }
                    if (city != null) {
                        ps.setString(k++, city);
                    }
                    if (state != null) {
                        ps.setString(k++, state);
                    }
                    if (postalCode != null) {
                        ps.setString(k++, postalCode);
                    }
                    if (country != null) {
                        ps.setString(k++, country);
                    }
                    if (postOfficeAddress != null) {
                        ps.setString(k++, postOfficeAddress);
                    }
                    if (extendedAddress != null) {
                        ps.setString(k++, extendedAddress);
                    }

                    ps.setInt(k++, ADDRESS_TYPE_WORK);
                    ps.setLong(k++, Long.parseLong(cw.getId()));
                    ps.setInt(k++, ADDRESS_TYPE_WORK);

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);

                }

            }

        }

        //
        // labels
        //
        if (!labels.isEmpty()) {

            ps1 = con.prepareStatement(SQL_CHECK_IF_IN_FNBL_PIM_CONTACT_ITEM);

            for (int i = 0, l = labels.size(); i < l; i++) {

                String[] label = labels.get(i);

                String labelType = label[1];

                if ((FIELD_HOME_LABEL).equals(labelType)) {
                    type = TYPE_HOME_LABEL;
                } else if ((FIELD_BUSINESS_LABEL).equals(labelType)) {
                    type = TYPE_BUSINESS_LABEL;
                } else if ((FIELD_OTHER_LABEL).equals(labelType)) {
                    type = TYPE_OTHER_LABEL;
                } else {
                    //
                    // Unknown property: saves nothing
                    //
                    continue;
                }

                ps1.setLong(1, Long.parseLong(cw.getId()));
                ps1.setInt(2, type);

                rs = ps1.executeQuery();

                findRecord = rs.next();

                String labelValue = StringUtils.left(label[0], SQL_LABEL_DIM);

                if (!findRecord) {

                    if (labelValue != null && labelValue.length() != 0) {
                        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                        ps.setString(3, labelValue);

                        ps.executeUpdate();

                        DBTools.close(null, ps, null);
                    }

                } else {

                    if (labelValue != null) {
                        ps = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_ITEM);

                        ps.setString(1, labelValue);
                        ps.setLong(2, Long.parseLong(cw.getId()));
                        ps.setInt(3, type);
                    } else {
                        ps = con.prepareStatement(SQL_DELETE_FNBL_PIM_CONTACT_ITEM);

                        ps.setLong(1, Long.parseLong(cw.getId()));
                        ps.setInt(2, type);
                    }

                    ps.executeUpdate();

                    DBTools.close(null, ps, null);
                }

                DBTools.close(null, null, rs);

            }

            DBTools.close(null, ps1, null);

        }
        if (photoToSet) {
            setPhoto(con, Long.parseLong(cw.getId()), photo);
        } else if (photoToRemove) {
            deletePhoto(con, Long.parseLong(cw.getId()));
        }

    } catch (Exception e) {
        throw new DAOException("Error updating contact.", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return cw.getId();
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Retrieves the UID list of the contacts considered to be "twins" of a
 * given contact.//from   w  w w .j  av a 2 s.c  o  m
 *
 * @param c the Contact object representing the contact whose twins
 *          need to be found.
 * @return a List of UIDs (as String objects) that may be empty but not null
 * @throws DAOException if an error occurs
 */
public List<String> getTwinItems(Contact c) throws DAOException {
    if (log.isTraceEnabled()) {
        log.trace("Retrieving twin items for the given contact...");
    }

    List<String> twins = new ArrayList<String>();
    Map<Long, Map<Integer, String>> twinsFound = new HashMap<Long, Map<Integer, String>>();

    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    if (!isTwinSearchAppliableOn(c)) {
        if (log.isTraceEnabled()) {
            log.trace("Item with no email addresses, company name, first, "
                    + "last and display names: twin search skipped.");
        }
        return twins;
    }

    try {

        String firstName = c.getName().getFirstName().getPropertyValueAsString();
        String lastName = c.getName().getLastName().getPropertyValueAsString();
        String displayName = c.getName().getDisplayName().getPropertyValueAsString();
        String companyName = null;
        if (c.getBusinessDetail().getCompany() != null) {
            companyName = c.getBusinessDetail().getCompany().getPropertyValueAsString();
        }

        firstName = StringUtils.left(firstName, SQL_FIRSTNAME_DIM);
        lastName = StringUtils.left(lastName, SQL_LASTNAME_DIM);
        displayName = StringUtils.left(displayName, SQL_DISPLAYNAME_DIM);
        companyName = StringUtils.left(companyName, SQL_COMPANY_DIM);
        firstName = normalizeField(firstName);
        lastName = normalizeField(lastName);
        displayName = normalizeField(displayName);
        companyName = normalizeField(companyName);

        StringBuilder query = new StringBuilder(SQL_GET_POTENTIAL_TWINS);
        List<String> params = new ArrayList<String>();

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);
        con.setReadOnly(true);

        //
        // If Funambol is not in the debug mode is not possible to print the
        // contact because it contains sensitive data.
        //
        if (Configuration.getConfiguration().isDebugMode()) {
            if (log.isTraceEnabled()) {
                StringBuilder sb = new StringBuilder(100);
                sb.append("Looking for items having: ").append("\n> first name   : '")
                        .append(toPrintableString(firstName)).append('\'').append("\n> last  name   : '")
                        .append(toPrintableString(lastName)).append('\'').append("\n> display name : '")
                        .append(toPrintableString(displayName)).append('\'').append("\n> company name : '")
                        .append(toPrintableString(companyName)).append('\'');

                log.trace(sb.toString());
            }
        }

        boolean isUnnamedContact = StringUtils.isEmpty(firstName) && StringUtils.isEmpty(lastName)
                && StringUtils.isEmpty(displayName) && StringUtils.isEmpty(companyName);

        if (isUnnamedContact) {

            if (unnamedContacts == null) {

                query.append(SQL_UNNAMED_WHERE_CLAUSES);
                query.append(SQL_STATUS_NOT_D);
                query.append(SQL_ORDER_BY_ID);

                params.add(userId);
                params.add(firstName);
                params.add(lastName);
                params.add(companyName);
                params.add(displayName);

                ps = con.prepareStatement(query.toString());

                int cont = 1;
                for (String param : params) {
                    ps.setString(cont++, param);
                }

                rs = ps.executeQuery();

                //slipts query result in a better organized data structure
                //-contact id
                //  -item type, item value
                //  -item type, item value
                //  -...
                //-contact id
                //  -...
                unnamedContacts = getTwinsItemsFromRecordset(rs);

                if (log.isTraceEnabled()) {
                    log.trace(
                            "Found '" + unnamedContacts.size() + "' potential twin unnamed contacts with ids '"
                                    + unnamedContacts.keySet().toString() + "'");
                }
                DBTools.close(null, null, rs);
            }

            // returns only the twin items
            twinsFound = retrievePotentialTwinsComparingEmailsAndPhoneNumbers(c, unnamedContacts,
                    isUnnamedContact);

        } else {

            params.add(userId);

            query.append(" AND (");
            if ("".equals(firstName)) {
                query.append(" (c.first_name is null) OR ");
            }
            query.append(" (lower(c.first_name) = ?) ");
            params.add(firstName.toLowerCase());
            query.append(" )");

            query.append(" AND (");
            if ("".equals(lastName)) {
                query.append(" (c.last_name is null) OR ");
            }
            query.append(" (lower(c.last_name) = ?) ");
            params.add(lastName.toLowerCase());
            query.append(" )");
            //
            // Only if the first name and last name are empty,
            // the company is used in the research of twin items.
            //                
            if ("".equals(firstName) && "".equals(lastName)) {

                query.append(" AND (");

                if ("".equals(companyName)) {
                    query.append(" (c.company is null) OR ");
                }
                query.append(" (lower(c.company) = ?) ");
                params.add(companyName.toLowerCase());
                query.append(" )");

                //
                // Only if the first name, last name and company are empty,
                // the display name is used in the research of twin items.
                //
                if ("".equals(companyName)) {

                    query.append(" AND (");
                    if ("".equals(displayName)) {
                        query.append(" (c.display_name is null) OR ");
                    }
                    query.append(" (lower(c.display_name) = ?) ");
                    params.add(displayName.toLowerCase());
                    query.append(" ) ");
                }
            }

            query.append(SQL_STATUS_NOT_D);
            query.append(SQL_ORDER_BY_ID);

            ps = con.prepareStatement(query.toString());

            int cont = 1;
            for (String param : params) {
                ps.setString(cont++, param);
            }

            rs = ps.executeQuery();

            //slipts query result in a better organized data structure
            //-contact id
            //  -item type, item value
            //  -item type, item value
            //  -...
            //-contact id
            //  -...
            Map<Long, Map<Integer, String>> twinsInfo = getTwinsItemsFromRecordset(rs);

            if (log.isTraceEnabled()) {
                log.trace("Found '" + twinsInfo.size() + "' potential twin contacts with ids '"
                        + twinsInfo.keySet().toString() + "'");
            }
            DBTools.close(null, null, rs);

            //returns only the twin items
            twinsFound = retrievePotentialTwinsComparingEmailsAndPhoneNumbers(c, twinsInfo, isUnnamedContact);
        }

        for (Long twinId : twinsFound.keySet()) {
            if (log.isTraceEnabled()) {
                log.trace("Found twin '" + twinId + "'");
            }
            twins.add(Long.toString(twinId));
        }

    } catch (Exception e) {
        throw new DAOException("Error retrieving contact twin items", e);
    } finally {
        DBTools.close(con, ps, rs);
    }

    return twins;
}

From source file:edu.bu.kuali.kra.award.sapintegration.SapIntegrationServiceImpl.java

private String convertLeadUnitToBusinessArea(String leadUnitNumber, Award award) {
    String firstDigit = StringUtils.left(leadUnitNumber, 1);
    String returnValue = getParameterService().getSubParameterValueAsString(AwardDocument.class,
            BUConstants.LEAD_UNIT_MAPPING, firstDigit);
    if (StringUtils.isEmpty(returnValue)) {
        throw new IllegalArgumentException(
                "Failed to convert lead unit, given lead unit value was not understood: " + leadUnitNumber
                        + " awardNumber was: " + award.getAwardNumber() + "\n" + award.toString());
    }// w  ww  . j a v a2 s .c om
    return returnValue;
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Analyzes raw list of twins for a contact and returns only the items that
 * satisfies the condition on emails and phone numbers.
 *
 * @param contact the contact to check twins
 * @param twinsInfo the information about potential twins to check
 * @param isUnnamedContact true id the contact is unnamed, false otherwise
 * @return a Map of twin items/*from  w w  w. j a  v a  2  s.  c  om*/
 */
private Map<Long, Map<Integer, String>> retrievePotentialTwinsComparingEmailsAndPhoneNumbers(Contact contact,
        Map<Long, Map<Integer, String>> twinsInfo, boolean isUnnamedContact) {

    Map<Long, Map<Integer, String>> twinsFound = new HashMap<Long, Map<Integer, String>>();

    if (twinsInfo.isEmpty())
        return twinsFound;

    //get emails from contact
    List<Email> contactEmails = getContactPropertiesRemovingNullOrEmptyValues(
            contact.getPersonalDetail().getEmails(), contact.getBusinessDetail().getEmails());
    List<Email> contactEmailsAux = new ArrayList<Email>();
    for (Email index : contactEmails) {
        index.setPropertyValue(StringUtils.left(index.getPropertyValueAsString(), SQL_EMAIL_DIM));
        contactEmailsAux.add(index);
    }
    contactEmails = contactEmailsAux;

    //get phone numbers from contact
    List<Phone> contactPhones = getContactPropertiesRemovingNullOrEmptyValues(
            contact.getPersonalDetail().getPhones(), contact.getBusinessDetail().getPhones());

    for (Long twinId : twinsInfo.keySet()) {

        Map<Integer, String> twinValues = twinsInfo.get(twinId);

        //get emails for the potential twin
        Map<Integer, String> twinEmails = getPropertiesWithValidValues(twinValues, TYPE_EMAIL_1_ADDRESS,
                TYPE_EMAIL_2_ADDRESS, TYPE_EMAIL_3_ADDRESS);
        //get phone numbers for the potential twin
        Map<Integer, String> twinPhones = getPropertiesWithValidValues(twinValues, TYPE_ASSISTANT_NUMBER,
                TYPE_BUSINESS_2_TELEPHONE_NUMBER, TYPE_BUSINESS_FAX_NUMBER, TYPE_BUSINESS_TELEPHONE_NUMBER,
                TYPE_CALLBACK_NUMBER, TYPE_CAR_TELEPHONE_NUMBER, TYPE_COMPANY_MAIN_TELEPHONE_NUMBER,
                TYPE_HOME_2_TELEPHONE_NUMBER, TYPE_HOME_FAX_NUMBER, TYPE_HOME_TELEPHONE_NUMBER,
                TYPE_MOBILE_TELEPHONE_NUMBER, TYPE_OTHER_FAX_NUMBER, TYPE_OTHER_TELEPHONE_NUMBER,
                TYPE_PAGER_NUMBER, TYPE_PRIMARY_TELEPHONE_NUMBER, TYPE_RADIO_TELEPHONE_NUMBER,
                TYPE_TELEX_NUMBER);

        boolean areTwins = false;

        //manages the conditions that make the potential twins true twins
        //(inclusion cases)
        if (!isUnnamedContact) {
            //case
            //- if both contact and twins haven't email addresses and phone
            //  numbers, they must be considered twins
            if (!areTwins) {
                areTwins = contactEmails.isEmpty() && contactPhones.isEmpty() && twinEmails.isEmpty()
                        && twinPhones.isEmpty();
            }
            //case
            //- if the contact contains no fields other than name
            //  (first/last/display/company) and the twin contains name
            //  plus other fields (or viceversa), they must be considered
            // twins
            if (!areTwins) {
                areTwins = contactOrTwinHasNoFieldsWhileTheOtherHas(contactEmails, contactPhones, twinEmails,
                        twinPhones);
            }
        }

        //case
        //- If they contain at least one identical email address in any
        //  of the address fields
        if (!areTwins) {
            areTwins = haveContactAndTwinEmailsInCommon(contactEmails, twinEmails);
        }
        //case
        //- If they contain at least one identical phone number in any of
        //  the phone number fields
        if (!areTwins) {
            areTwins = haveContactAndTwinPhoneNumbersInCommon(contactPhones, twinPhones);
        }

        //manages the conditions that make the true twins not twins anymore
        //(exclusion cases)

        //manage the case
        //- If the contacts don't have different phone numbers/email
        //  addresses/ in the same corresponding field (e.g. 2 different
        //  phone numbers in the same HOME phone # fields of the contacts)
        if (areTwins) {
            areTwins = haveContactAndTwinSameEmailsInSamePosition(contactEmails, twinEmails);
        }
        if (areTwins) {
            areTwins = haveContactAndTwinSamePhonesInSamePosition(contactPhones, twinPhones);
        }

        if (areTwins) {
            twinsFound.put(twinId, twinValues);
        }
    }

    return twinsFound;
}

From source file:nl.nn.adapterframework.extensions.svn.ScanTibcoSolutionPipe.java

private String skipLastCharacter(String str) {
    return StringUtils.left(str, str.length() - 1);
}

From source file:org.apache.cocoon.components.language.markup.xsp.XSPExpressionFilter.java

/**
 * Start a new element. If attribute value templates are enabled and the element has attributes
 * with templates, these are replaced by xsp:attribute tags.
 *
 * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
 *      java.lang.String, org.xml.sax.Attributes)
 *///from  w  w w. ja  v a 2s.  c  o m
public void startElement(String namespaceURI, String localName, String qName, Attributes attribs)
        throws SAXException {
    expressionParser.flush(locator, "...<" + qName + ">");

    // Check template for interpolation flags
    attribs = pushInterpolationStack(attribs);

    if (getInterpolationSettings().attrInterpolation) {
        // Attribute value templates enabled => process attributes
        AttributesImpl staticAttribs = new AttributesImpl();
        AttributesImpl dynamicAttribs = new AttributesImpl();

        // Gather attributes with and without templates separately
        for (int i = 0; i < attribs.getLength(); ++i) {
            String value = attribs.getValue(i);

            if (value.indexOf("{#") != -1) {
                // The attribute contains templates
                dynamicAttribs.addAttribute(attribs.getURI(i), attribs.getLocalName(i), attribs.getQName(i),
                        attribs.getType(i), value);
            } else {
                // The attribute does not contain templates
                staticAttribs.addAttribute(attribs.getURI(i), attribs.getLocalName(i), attribs.getQName(i),
                        attribs.getType(i), value);
            }
        }

        // Start the element with template-free attributes
        super.startElement(namespaceURI, localName, qName, staticAttribs);

        // Generate xsp:attribute elements for the attributes containing templates
        for (int i = 0; i < dynamicAttribs.getLength(); ++i) {
            AttributesImpl elemAttribs = new AttributesImpl();
            addAttribute(elemAttribs, "uri", dynamicAttribs.getURI(i));

            String qname = dynamicAttribs.getQName(i);

            if (qname != null) {
                addAttribute(elemAttribs, "prefix", StringUtils.left(qname, qname.indexOf(':')));
            }

            String attrName = dynamicAttribs.getLocalName(i);
            addAttribute(elemAttribs, "name", attrName);

            super.startElement(markupURI, "attribute", markupPrefix + ":attribute", elemAttribs);
            expressionParser.consume(dynamicAttribs.getValue(i));
            expressionParser.flush(locator, "<" + qName + " " + attrName + "=\"...\">");
            super.endElement(markupURI, "attribute", markupPrefix + ":attribute");
        }
    } else {
        // Attribute value templates disabled => pass through element
        super.startElement(namespaceURI, localName, qName, attribs);
    }
}

From source file:org.apache.cocoon.util.log.ExtensiblePatternFormatter.java

/**
 * Utility to append a string to buffer given certain constraints.
 *
 * @param sb the StringBuffer/*w  w w .  j a  v  a  2  s  .co  m*/
 * @param minSize the minimum size of output (0 to ignore)
 * @param maxSize the maximum size of output (0 to ignore)
 * @param rightJustify true if the string is to be right justified in it's box.
 * @param output the input string
 */
protected void append(final StringBuffer sb, final int minSize, final int maxSize, final boolean rightJustify,
        final String output) {
    if (output.length() < minSize) {
        if (rightJustify) {
            sb.append(StringUtils.leftPad(output, minSize));
        } else {
            sb.append(StringUtils.rightPad(output, minSize));
        }
    } else if (maxSize > 0) {
        if (rightJustify) {
            sb.append(StringUtils.right(output, maxSize));
        } else {
            sb.append(StringUtils.left(output, maxSize));
        }
    } else {
        sb.append(output);
    }
}

From source file:org.apache.ofbiz.accounting.thirdparty.verisign.PayflowPro.java

private static void addCartDetails(Map<String, String> parameterMap, ShoppingCart cart)
        throws GenericEntityException {
    parameterMap.put("CURRENCY", cart.getCurrency());
    int line = 0;
    for (ShoppingCartItem item : cart.items()) {
        //paramMap.put("L_NUMBER" + line, item.getProductId());
        parameterMap.put("L_NAME" + line, item.getName());
        parameterMap.put("L_DESC" + line, item.getDescription());
        parameterMap.put("L_AMT" + line, item.getBasePrice().setScale(2).toPlainString());
        parameterMap.put("L_QTY" + line, item.getQuantity().toBigInteger().toString());
        line++;/*from   w ww.  ja v  a 2s  .c  o  m*/
        BigDecimal otherAdjustments = item.getOtherAdjustments();
        if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
            parameterMap.put("L_NAME" + line, item.getName() + " Adjustments");
            parameterMap.put("L_DESC" + line, "Adjustments for item: " + item.getName());
            parameterMap.put("L_AMT" + line, otherAdjustments.setScale(2).toPlainString());
            parameterMap.put("L_QTY" + line, "1");
            line++;
        }
    }
    BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
    if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
        parameterMap.put("L_NAME" + line, "Order Adjustments");
        parameterMap.put("L_AMT" + line, otherAdjustments.setScale(2).toPlainString());
        parameterMap.put("L_QTY" + line, "1");
        line++;
    }
    parameterMap.put("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    parameterMap.put("TAXAMT", cart.getTotalSalesTax().setScale(2).toPlainString());
    parameterMap.put("FREIGHTAMT", cart.getTotalShipping().setScale(2).toPlainString());
    parameterMap.put("AMT", cart.getGrandTotal().setScale(2).toPlainString());

    if (!cart.shippingApplies()) {
        parameterMap.put("NOSHIPPING", "1");
    } else {
        GenericValue shippingAddress = cart.getShippingAddress();
        parameterMap.put("ADDROVERRIDE", "1");
        parameterMap.put("SHIPTOSTREET", StringUtils.left(shippingAddress.getString("address1"), 30));
        parameterMap.put("SHIPTOSTREET2", StringUtils.left(shippingAddress.getString("address2"), 30));
        parameterMap.put("SHIPTOCITY", StringUtils.left(shippingAddress.getString("city"), 40));
        if (shippingAddress.getString("stateProvinceGeoId") != null
                && !"_NA_".equals(shippingAddress.getString("stateProvinceGeoId"))) {
            GenericValue stateProvinceGeo = shippingAddress.getRelatedOne("StateProvinceGeo", false);
            parameterMap.put("SHIPTOSTATE", StringUtils.left(stateProvinceGeo.getString("geoCode"), 40));
        }
        parameterMap.put("SHIPTOZIP", StringUtils.left(shippingAddress.getString("postalCode"), 16));
        GenericValue countryGeo = shippingAddress.getRelatedOne("CountryGeo", false);
        parameterMap.put("SHIPTOCOUNTRY", StringUtils.left(countryGeo.getString("geoCode"), 2));
    }
}