Android Open Source - CampusUB1 Directory Manager






From Project

Back to project page CampusUB1.

License

The source code is released under:

Apache License

If you think the Android project CampusUB1 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * Copyright (C) 2013 CampusUB1 Development Team
 */*from www.  j  ava2  s .  c  o  m*/
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dev.campus.directory;

import java.io.IOException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.dev.campus.CampusUB1App;
import com.dev.campus.directory.Contact.ContactType;
import com.unboundid.ldap.sdk.Control;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPConnectionPool;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldap.sdk.controls.SimplePagedResultsControl;

/**
 * Class responsible for managing contact search queries
 * @author CampusUB1 Development Team
 *
 */
public class DirectoryManager {

  // LaBRI directory
  private ArrayList<Contact> mLabriDirectory;
  
  // LDAP connection parameters
  private final int NUM_CONNECTIONS = 10;
  private final int MAX_PAGE_SIZE = 10;
  private final int UB1_LDAP_PORT = 389;
  private final String UB1_BASE_DN = "ou=people,dc=u-bordeaux1,dc=fr";
  private final String UB1_LDAP_HOST = "carnet.u-bordeaux1.fr";
  
  // LDAP search attributes
  private final String ATTR_MAIL = "mail";
  private final String ATTR_TEL = "telephoneNumber";
  private final String ATTR_NAME = "givenName";
  private final String ATTR_SURNAME = "sn";
  private final String[] LDAPSearchAttributes = {ATTR_MAIL, ATTR_TEL, ATTR_NAME, ATTR_SURNAME};

  // LDAP connections
  private LDAPConnection LDAP;
  private LDAPConnectionPool mConnectionPool;
  
  /**
   * Entry point for searching a contact in subscribed establishments
   * @param firstName first name of the contact to search
   * @param lastName last name of the contact to search
   * @return list of all contacts matching the search query
   * @throws LDAPException
   * @throws IOException
   */
  public List<Contact> searchContact(String firstName, String lastName) throws LDAPException, IOException {
    ArrayList<Contact> searchResult = new ArrayList<Contact>();
    if (CampusUB1App.persistence.isSubscribedUB1()) 
      searchResult.addAll(searchUB1(firstName, lastName));

    if (CampusUB1App.persistence.isSubscribedLabri()) {
      if (mLabriDirectory == null || mLabriDirectory.size() == 0) {
        parseLabriDirectory();
      }
      searchResult.addAll(filterLabriResults(firstName, lastName));
    }
    return searchResult;
  }

  /**
   * Searches a contact in the LDAP directory of UB1
   * @param firstName first name of the contact to search
   * @param lastName last name of the contact to search
   * @return list of all contacts matching the search query
   * @throws LDAPException
   */
  public List<Contact> searchUB1(String firstName, String lastName) throws LDAPException {
    if (LDAP == null || mConnectionPool == null) {
      LDAP = new LDAPConnection(UB1_LDAP_HOST, UB1_LDAP_PORT);
      mConnectionPool = new LDAPConnectionPool(LDAP, NUM_CONNECTIONS);
    }
    
    ArrayList<Contact> contacts = new ArrayList<Contact>();
    Filter f = Filter.create("(&(" + ATTR_NAME + "=" + firstName + "*)("
                     + ATTR_SURNAME + "=" + lastName + "*))");
    
    SearchRequest searchRequest = new SearchRequest(UB1_BASE_DN, SearchScope.SUB, f, LDAPSearchAttributes);
    searchRequest.setControls(new Control[] { new SimplePagedResultsControl(MAX_PAGE_SIZE, null)});
    SearchResult searchResult = mConnectionPool.search(searchRequest);
    int entryCount = searchResult.getEntryCount();
    
    // Create Contact objects with the entries that are returned.
    for (int i = 0; i < entryCount; i++) {
      SearchResultEntry entry = searchResult.getSearchEntries().get(i);
      Contact contact = new Contact();
      
      if ((entry.getAttributeValue(ATTR_MAIL) != null) && !entry.getAttributeValue(ATTR_MAIL).equals(""))
        contact.setEmail(entry.getAttributeValue(ATTR_MAIL));
      if ((entry.getAttributeValue(ATTR_TEL) != null) && !entry.getAttributeValue(ATTR_TEL).equals("Non renseigne"))
        contact.setTel(entry.getAttributeValue(ATTR_TEL));
      contact.setFirstName(entry.getAttributeValue(ATTR_NAME));
      contact.setLastName(entry.getAttributeValue(ATTR_SURNAME));
      contact.setType(ContactType.UB1_CONTACT);
      contacts.add(contact);
    }

    return contacts;
  }


  /**
   * Looks up a contact in the LaBRI directory
   * @param firstName first name of the contact to search
   * @param lastName last name of the contact to search
   * @return list of all contacts matching the search query
   */
  public List<Contact> filterLabriResults(String firstName, String lastName){
    ArrayList<Contact> matchingContacts = new ArrayList<Contact>();
    if (firstName == null)
      firstName = "";
    if (lastName == null)
      lastName = "";
    firstName = reformatString(firstName);
    lastName = reformatString(lastName);

    for (Contact c : mLabriDirectory) {
      if (reformatString(c.getFirstName()).contains(firstName)
       && reformatString(c.getLastName()).contains(lastName)) {
        matchingContacts.add(c);
      }
    }
    return matchingContacts;
  }

  /**
   * Parses the HTML page corresponding to the directory of LaBRI
   * @throws IOException
   */
  public void parseLabriDirectory() throws IOException {
    ArrayList<Contact> allContacts = new ArrayList<Contact>();
    Document doc;

    try {
      doc = Jsoup.connect("http://www.labri.fr/index.php?n=Annuaires.Noms&initiale=tout").get();
    } catch (Exception e) {
      //Either java.net.SocketTimeoutException or org.jsoup.HttpStatusException
      CampusUB1App.LogD("Failed to retrieve LaBRI contacts");
      mLabriDirectory = allContacts;
      return;
    }

    Elements tables = doc.select("table[border=1][cellpadding=4][cellspacing=0][width=100%]");
    Element table = tables.first();

    int i = 1;
    String buffer;
    Contact contact = new Contact();

    Elements tds = table.getElementsByTag("td");
    for (Element td : tds) {
      buffer = td.text();

      if (i > 8) {
        if (i % 8 == 1) { // Name
          String name = buffer;
          int offset = name.lastIndexOf (" "); // Split first name/last name with last space
          if (offset != -1) {
            String lastName = name.substring(0, offset);
            String firstName = name.substring(offset+1, name.length());
            contact.setFirstName(firstName);
            contact.setLastName(lastName);
            contact.setType(ContactType.LABRI_CONTACT);
          }
        }
        else if(i % 8 == 2) { // Email
          String email = td.getElementsByTag("a").attr("href");
          email = email.substring(7); // remove: "mailto:"
          if (!email.equals(""))
            contact.setEmail(email);
        }
        else if (i % 8 == 3) { // Telephone
          String tel = buffer;
          if (!tel.equals("+33 (0)5 40 00")) { // Default value: "+33 (0)5 40 00 "
            tel = tel.replaceAll("\\(0\\)", "");
            contact.setTel(tel);
          }
        }
        else if (i % 8 == 7) { // Website
          contact.setWebsite(td.getElementsByTag("a").attr("href"));
        }
        else if (i % 8 == 0 && i > 0) {
          allContacts.add(contact);
          contact = new Contact();
        }
      }
      i++;
    }

    mLabriDirectory = allContacts;
  }

  /**
   * Strips diacritics from argument string and sets it to lower case
   * @param str the string to reformat
   * @return 
   */
  public String reformatString(String str) {
    str = Normalizer.normalize(str, Normalizer.Form.NFD);
    str = str.replaceAll("[^\\p{ASCII}]", "");
    return str.toLowerCase();
  }
}




Java Source Code List

android.UnusedStub.java
com.dev.campus.CampusUB1App.java
com.dev.campus.LauncherActivity.java
com.dev.campus.SettingsActivity.java
com.dev.campus.directory.Contact.java
com.dev.campus.directory.DirectoryActivity.java
com.dev.campus.directory.DirectoryAdapter.java
com.dev.campus.directory.DirectoryManager.java
com.dev.campus.event.Category.java
com.dev.campus.event.EventAdapter.java
com.dev.campus.event.EventFragment.java
com.dev.campus.event.EventMultiChoiceModeListener.java
com.dev.campus.event.EventPagerAdapter.java
com.dev.campus.event.EventParser.java
com.dev.campus.event.EventViewActivity.java
com.dev.campus.event.Event.java
com.dev.campus.event.EventsActivity.java
com.dev.campus.event.Feed.java
com.dev.campus.home.HomeActivity.java
com.dev.campus.home.HomeAdapter.java
com.dev.campus.home.HomeEntryItem.java
com.dev.campus.home.HomeItem.java
com.dev.campus.home.HomeSeparatorItem.java
com.dev.campus.map.MapActivity.java
com.dev.campus.map.Position.java
com.dev.campus.schedule.Group.java
com.dev.campus.schedule.ScheduleActivity.java
com.dev.campus.schedule.ScheduleAdapter.java
com.dev.campus.schedule.ScheduleImportService.java
com.dev.campus.schedule.ScheduleParser.java
com.dev.campus.util.AboutDialog.java
com.dev.campus.util.FilterDialog.java
com.dev.campus.util.Persistence.java
com.dev.campus.util.PrefFragment.java
com.dev.campus.util.SubscribeDialog.java
com.dev.campus.util.TimeExtractor.java
com.dev.campus.util.UpcomingEventsDialog.java
com.slidingmenu.lib.CanvasTransformerBuilder.java
com.slidingmenu.lib.CustomViewAbove.java
com.slidingmenu.lib.CustomViewBehind.java
com.slidingmenu.lib.MenuInterface.java
com.slidingmenu.lib.SlidingMenu.java
com.slidingmenu.lib.app.SlidingActivityBase.java
com.slidingmenu.lib.app.SlidingActivityHelper.java
com.slidingmenu.lib.app.SlidingActivity.java
com.slidingmenu.lib.app.SlidingFragmentActivity.java
com.slidingmenu.lib.app.SlidingListActivity.java
com.slidingmenu.lib.app.SlidingMapActivity.java
com.slidingmenu.lib.app.SlidingPreferenceActivity.java