james-server-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From charl...@apache.org
Subject cvs commit: jakarta-james/src/org/apache/james/util CharTerminatedInputStream.java InternetPrintWriter.java Lock.java LockException.java RFC822DateFormat.java
Date Fri, 11 May 2001 09:52:35 GMT
charlesb    01/05/11 02:52:34

  Added:       src/java/org/apache/james/userrepository
                        UsersFileRepository.java UsersLDAPRepository.java
                        UsersTownRepository.java
               src/java/org/apache/james/util
                        CharTerminatedInputStream.java
                        InternetPrintWriter.java Lock.java
                        LockException.java RFC822DateFormat.java
  Removed:     src/org/apache/james/userrepository UsersFileRepository.java
                        UsersLDAPRepository.java UsersTownRepository.java
               src/org/apache/james/util CharTerminatedInputStream.java
                        InternetPrintWriter.java Lock.java
                        LockException.java RFC822DateFormat.java
  Log:
  Moving from src/org to src/java/org
  
  Revision  Changes    Path
  1.1                  jakarta-james/src/java/org/apache/james/userrepository/UsersFileRepository.java
  
  Index: UsersFileRepository.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.userrepository;
  
  import java.io.File;
  import java.util.Iterator;
  import org.apache.avalon.framework.activity.Initializable;
  import org.apache.avalon.framework.component.Component;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.component.Composable;
  import org.apache.avalon.framework.configuration.Configurable;
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.avalon.framework.configuration.DefaultConfiguration;
  import org.apache.avalon.framework.logger.AbstractLoggable;
  import org.apache.avalon.cornerstone.services.store.ObjectRepository;
  import org.apache.avalon.cornerstone.services.store.Store;
  import org.apache.avalon.excalibur.concurrent.Lock;
  import org.apache.james.services.UsersRepository;
  
  /**
   * Implementation of a Repository to store users on the File System.
   *
   * Requires a configuration element in the .conf.xml file of the form:
   *  <repository destinationURL="file://path-to-root-dir-for-repository"
   *              type="USERS"
   *              model="SYNCHRONOUS"/>
   * Requires a logger called UsersRepository.
   *
   * @version 1.0.0, 24/04/1999
   * @author  Federico Barbieri <scoobie@pop.systemy.it>
   * @author Charles Benett <charles@benett1.demon.co.uk>
   */
  public class UsersFileRepository
      extends AbstractLoggable
      implements UsersRepository, Component, Configurable, Composable, Initializable {
  
      private static final String TYPE = "USERS";
  
      private Store store;
      private ObjectRepository or;
      private String destination;
      private Lock lock  = new Lock();
  
      public void configure( final Configuration configuration )
          throws ConfigurationException {
  
          destination = configuration.getChild( "destination" ).getAttribute( "URL" );
  
          if (!destination.endsWith(File.separator)) {
              destination += File.separator;
          }
      }
  
      public void compose( final ComponentManager componentManager )
          throws ComponentException {
  
          store = (Store)componentManager.
              lookup( "org.apache.avalon.cornerstone.services.store.Store" );
      }
  
      public void initialize()
          throws Exception {
  
          try {
              //prepare Configurations for object and stream repositories
              final DefaultConfiguration objectConfiguration
                  = new DefaultConfiguration( "repository",
                                              "generated:UsersFileRepository.compose()" );
  
              objectConfiguration.addAttribute( "destinationURL", destination );
              objectConfiguration.addAttribute( "type", "OBJECT" );
              objectConfiguration.addAttribute( "model", "SYNCHRONOUS" );
  
              or = (ObjectRepository)store.select( objectConfiguration );
  
          } catch (Exception e) {
              getLogger().error("Failed to retrieve Store component:" + e.getMessage(), e
);
              throw e;
          }
      }
  
      public Iterator list() {
          return or.list();
      }
  
      public synchronized void addUser(String name, Object attributes) {
          try {
              or.put(name, attributes);
          } catch (Exception e) {
              throw new RuntimeException("Exception caught while storing user: " + e );
          }
      }
  
      public synchronized Object getAttributes(String name) {
          try {
              return or.get(name);
          } catch (Exception e) {
              throw new RuntimeException("Exception while retrieving user: " + e.getMessage());
          }
      }
  
      public synchronized void removeUser(String name) {
          or.remove(name);
      }
  
      public boolean contains(String name) {
          return or.containsKey(name);
      }
  
      public boolean test(String name, Object attributes) {
          try {
              return attributes.equals(or.get(name));
          } catch (Exception e) {
              return false;
          }
      }
  
      public int countUsers() {
          int count = 0;
          for (Iterator it = list(); it.hasNext(); it.next()) {
              count++;
          }
          return count;
      }
  
  }
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/userrepository/UsersLDAPRepository.java
  
  Index: UsersLDAPRepository.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.userrepository;
  
  import java.io.*;
  import java.util.*;
  import javax.naming.*;
  import javax.naming.directory.*;
  import org.apache.avalon.framework.activity.Initializable;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.component.Composable;
  import org.apache.avalon.framework.configuration.Configurable;
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.avalon.framework.context.Context;
  import org.apache.avalon.framework.context.ContextException;
  import org.apache.avalon.framework.context.Contextualizable;
  import org.apache.avalon.framework.logger.Loggable;
  import org.apache.james.Constants;
  import org.apache.james.services.UsersRepository;
  import org.apache.log.Logger;
  
  /**
   * Implementation of a Repository to store users.
   * @version 1.0.0, 24/04/1999
   * @author  Charles Bennett
   */
  public class UsersLDAPRepository
      implements UsersRepository, Loggable, Configurable, Contextualizable, Initializable{
  
      private ComponentManager comp;
  
      private Logger logger;
      private String path;
      private String name;
      private String destination;
      private String type;
      private String model;
      private DirContext ctx;
  
      private String LDAPHost;
      private String rootNodeDN;
      private String rootURL;
      private String serverRDN;
      private String baseNodeDN;
      private String baseURL;
      private String mailAddressAttr;
      private String identAttr;
      private String authType;
      private String principal;
      private String password;
      private String usersDomain;
      private String membersAttr;
      private boolean manageGroupAttr;
      private String groupAttr;
      private boolean managePasswordAttr;
      private String passwordAttr;
  
  
      public void setLogger(final Logger a_Logger) {
          logger = a_Logger;
      }
  
      public void configure(Configuration conf)
          throws ConfigurationException {
  
          LDAPHost = conf.getChild("LDAPServer").getValue();
          rootNodeDN = conf.getChild("LDAPRoot").getValue();
          serverRDN = conf.getChild("ThisServerRDN").getValue();
          mailAddressAttr
              = conf.getChild("MailAddressAttribute").getValue();
          identAttr = conf.getChild("IdentityAttribute").getValue();
          authType = conf.getChild("AuthenticationType").getValue();
          principal = conf.getChild("Principal").getValue();
          password = conf.getChild("Password").getValue();
  
          membersAttr = conf.getChild("MembersAttribute").getValue();
          manageGroupAttr
              = conf.getChild("ManageGroupAttribute").getValue().equals("TRUE");
          groupAttr = conf.getChild("GroupAttribute").getValue();
          managePasswordAttr = conf.getChild("ManagePasswordAttribute").getValue().equals("TRUE");
          passwordAttr = conf.getChild("PasswordAttribute").getValue();
      }
  
      public void compose(ComponentManager compMgr) {
          this.comp = comp;
      }
  
      public void contextualize(Context context) 
          throws ContextException {
          Collection serverNames
              = (Collection)context.get(Constants.SERVER_NAMES);
          usersDomain = (String)serverNames.iterator().next();
      }
  
      public void setServerRoot() {
          this.setBase(serverRDN +", " + rootNodeDN);
      }
  
      public void setBase(String base) {
          baseNodeDN = base;
      }
  
      public void initialize() throws Exception {
          //setServerRoot();
          rootURL = LDAPHost + "/" + rootNodeDN;
          baseURL = LDAPHost + "/" + baseNodeDN;
  
          logger.info("Creating initial context from " + baseURL);
          //System.out.println("Creating initial context from " + baseURL);
  
          Hashtable env = new Hashtable();
          env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                  "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(javax.naming.Context.PROVIDER_URL, baseURL);
  
          try {
              ctx = new InitialDirContext(env); // Could throw a NamingExcpetion
          } catch (Exception e) {
              e.getMessage();
              e.printStackTrace();
          }
  
  
          logger.info("Initial context initialised from " + baseURL);
      }
  
  
  
      public String getChildDestination(String childName) {
  
          String destination = null;
          String filter = "cn=" + childName;
          SearchControls ctls = new SearchControls();
  
          try {
  
              NamingEnumeration result  = ctx.search("", filter, ctls);
  
              if (result.hasMore()) {
                  destination = "cn=" + childName + ", " + baseNodeDN;
                  logger.info("Pre-exisisting LDAP node: " + destination);
              } else {
                  Attributes attrs = new BasicAttributes(true);
                  Attribute objclass = new BasicAttribute("objectclass");
                  objclass.add("top");
                  objclass.add("rfc822MailGroup");
                  attrs.put(objclass);
                  Attribute cname = new BasicAttribute("cn");
                  cname.add(childName);
                  attrs.put(cname);
                  Attribute owner = new BasicAttribute("owner");
                  owner.add("JAMES-unassigned");
                  attrs.put(owner);
  
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, authType);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);
  
                  ctx.createSubcontext("cn="+childName, attrs);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "none");
  
                  destination = "cn=" + childName + ", " + baseNodeDN;
                  logger.info("Created new LDAP node: " + destination);
              }
          } catch (NamingException e) {
              System.out.println("Problem with child nodes " + e.getMessage());
              e.printStackTrace();
          }
  
          return destination;
      }
  
      public Iterator list() {
  
          List result = new ArrayList();
          String filter = mailAddressAttr + "=*";
          String[] attrIDs = {membersAttr};
  
          try {
              Attribute members
                  = ctx.getAttributes("", attrIDs).get(membersAttr);
              if (members != null) {
                  NamingEnumeration enum = members.getAll();
                  while (enum.hasMore()) {
                      result.add((String)enum.next());
                  }
              }
          } catch (NamingException e) {
              logger.error("Problem listing mailboxes. " + e );
  
          }
          return result.iterator();
      }
  
  
  
  
      // Methods from interface UsersRepository --------------------------
  
      /**
       * Adds userName to the MemberAttribute (specified in conf.xml) of this
       * node.
       * If ManageGroupAttribute (conf.xml) is TRUE then calls addGroupToUser.
       */
      public synchronized void addUser(String userName, Object attributes) {
  
          String[] attrIDs = {membersAttr};
  
          // First, add username to mailGroup at baseNode
  
          try {
              Attribute members = ctx.getAttributes("", attrIDs).get(membersAttr);
  
  
              if (members != null && members.contains(userName)) {//user already here
                  logger.info("Found " + userName + " already in mailGroup. " );
                  //System.out.println("Found " + userName + " already in mailGroup. ");
  
              } else {
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, authType);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);
  
                  ModificationItem[] mods = new ModificationItem[1];
                  mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(membersAttr,
userName));
  
                  ctx.modifyAttributes("", mods);
  
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "none");
                  logger.info(userName + " added to mailGroup " + baseNodeDN );
                  //System.out.println(userName + " added to mailGroup " + baseNodeDN);
              }
          } catch (NamingException e) {
              logger.error("Problem adding user " + userName + " to: " + baseNodeDN + e);
              //System.out.println("Problem adding user " + userName + " to: " + baseNodeDN);
              //System.out.println(e.getMessage());
              //e.printStackTrace();
          }
  
          // Add attributes to user objects, if necessary
  
          if (manageGroupAttr) {
              addGroupToUser(userName);
          }
  
          if (managePasswordAttr) {
              String userPassword = (String) attributes; // Not yet implemented
          }
      }
  
      private void addGroupToUser(String userName) {
          String[] attrIDs = {membersAttr};
  
          Hashtable env = new Hashtable();
          env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(javax.naming.Context.PROVIDER_URL, rootURL);
  
          try {
              DirContext rootCtx = new InitialDirContext(env);
  
              String[] returnAttrs = {groupAttr};
              SearchControls ctls = new SearchControls();
              ctls.setReturningAttributes(attrIDs);
              ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
              String filter = mailAddressAttr + "=" + userName + "@" + usersDomain;
  
              NamingEnumeration enum  = rootCtx.search("", filter, ctls);
  
              if (enum.hasMore()) { // ie User is in Directory
                  SearchResult newSr = (SearchResult)enum.next();
                  String userDN = newSr.getName();
                  Attribute servers = rootCtx.getAttributes(userDN, returnAttrs).get(groupAttr);
  
  
                  if (servers != null && servers.contains(baseNodeDN)) {//server already
registered for user
                      logger.info(baseNodeDN + " already in user's Groups. " );
                      //System.out.println(baseNodeDN + " already in user's Groups. ");
  
                  } else {
  
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION,
authType);
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
password);
  
                      rootCtx.modifyAttributes(userDN, DirContext.ADD_ATTRIBUTE, new BasicAttributes(groupAttr,
baseNodeDN, true));
  
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION,
"none");
                      logger.info(baseNodeDN + " added to user's groups ");
                      //System.out.println(baseNodeDN + " added to users' groups ");
  
                  }
  
              } else {
                  logger.info("User " + userName + " not in Directory.");
                  // System.out.println("User " + userName + " not in Directory.");
  
              }
              rootCtx.close();
  
  
  
          } catch (NamingException e) {
              logger.error("Problem adding group to user " + userName);
              //System.out.println("Problem adding group to user " + userName);
              //System.out.println(e.getMessage());
              //e.printStackTrace();
          }
  
      }
  
  
  
  
      public synchronized Object getAttributes(String name) {
          return null;
      }
  
  
      public synchronized void removeUser(String userName) {
          String[] attrIDs = {membersAttr};
  
          try {
              Attribute members = ctx.getAttributes("", attrIDs).get(membersAttr);
              if (members == null) {
                  System.out.println("UsersLDAPRepository - Null list attribute.");
  
              } else  if (!members.contains(userName)) {//user not here
                  logger.info(userName + " missing from mailGroup. ");
                  //System.out.println(userName + " missing from mailGroup. ");
  
              } else {
                  // First, remove username from mailGroup at baseNode
  
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, authType);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, password);
  
                  ModificationItem[] mods = new ModificationItem[1];
                  mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(membersAttr,
userName));
  
                  ctx.modifyAttributes("", mods);
  
  
                  ctx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION, "none");
                  logger.info(userName + " removed from mailGroup. ");
                  //System.out.println(userName + " removed from mailGroup. ");
              }
          } catch (NamingException e) {
              logger.error("Problem removing user " + userName + e);
              //System.out.println("Problem removing user " + userName);
              //System.out.println(e.getMessage());
              //e.printStackTrace();
          }
          if (manageGroupAttr) {
              removeGroupFromUser(userName);
          }
  
          if (managePasswordAttr) {
              // not yet implemented
          }
  
      }
  
      public void removeGroupFromUser(String userName) {
  
          Hashtable env = new Hashtable();
          env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(javax.naming.Context.PROVIDER_URL, rootURL);
  
  
          try {
              DirContext rootCtx = new InitialDirContext(env);
  
              // Find directory entry
              String[] returnAttrs = {groupAttr};
              SearchControls ctls = new SearchControls();
              ctls.setReturningAttributes(returnAttrs);
              ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
              String filter = mailAddressAttr + "=" + userName + "@" + usersDomain;
  
              NamingEnumeration enum  = rootCtx.search("", filter, ctls);
  
              if (enum.hasMore()) { // ie User is in Directory
                  SearchResult newSr = (SearchResult)enum.next();
                  String userDN = newSr.getName();
  
                  System.out.println("Found user entry: " + userDN);
  
                  Attribute servers = rootCtx.getAttributes(userDN, returnAttrs).get(groupAttr);
                  if (servers == null) { //should not happen
                      logger.info("GroupAttribute missing from user: " + userName);
                      // System.out.println("GroupAttribute missing from user: " + userName
);
  
                  } else if (!servers.contains(baseNodeDN)) {//server not registered for user
                      logger.info(baseNodeDN + " missing from users' Groups. " );
                      //System.out.println(baseNodeDN + " missing from users' Groups. ");
  
                  } else {
  
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION,
authType);
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, principal);
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
password);
  
                      ModificationItem[] mods = new ModificationItem[1];
                      mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(groupAttr,
baseNodeDN));
  
                      rootCtx.modifyAttributes(userDN, mods);
  
                      //rootCtx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, changes);
  
                      rootCtx.addToEnvironment(javax.naming.Context.SECURITY_AUTHENTICATION,
"none");
                      logger.info(baseNodeDN + " removed from users' groups " );
                      //System.out.println(baseNodeDN + " removed from users' groups ");
  
                  }
  
              } else {
                  logger.info("User " + userName + " not in Directory.");
                  //System.out.println("User " + userName + " not in Directory.");
  
              }
              rootCtx.close();
  
          } catch (NamingException e) {
              logger.error("Problem removing user " + userName + e);
              //System.out.println("Problem removing user " + userName);
              //System.out.println(e.getMessage());
              //e.printStackTrace();
          }
  
      }
  
  
      public boolean contains(String name) {
          boolean found = false;
          String[] attrIDs = {membersAttr};
  
          try {
              Attribute members = ctx.getAttributes("", attrIDs).get(membersAttr);
              if (members != null && members.contains(name)) {
                  found = true;
                  logger.info("Found " + name + " in mailGroup. " );
                  //System.out.println("Found " + name + " in mailGroup. ");
              }
          } catch (NamingException e) {
              logger.error("Problem finding user " + name + e);
              //System.out.println("Problem finding user " + name + " : " + e);
          }
          return found;
      }
  
  
      public boolean test(String name, Object attributes) {
          boolean result = false;
          boolean foundFlag = false;
          String testPassword = (String) attributes;
          String userDN = null;
  
          try {
              String[] returnAttrs = {identAttr, passwordAttr};
              SearchControls ctls = new SearchControls();
              ctls.setReturningAttributes(returnAttrs);
              ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
              String filter = mailAddressAttr + "=" + name + "@" + usersDomain;
  
              Hashtable env = new Hashtable();
              env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
              env.put(javax.naming.Context.PROVIDER_URL, rootURL);
              DirContext rootCtx = new InitialDirContext(env);
  
              NamingEnumeration enum  = rootCtx.search("", filter, ctls);
              if (enum.hasMore()) { // ie User is in Directory
                  SearchResult sr = (SearchResult)enum.next();
                  String userRDN = sr.getName();
                  userDN = userRDN +", " + rootNodeDN;
                  foundFlag = true;
                  //System.out.println("UserDN is : " + userDN);
              }
  
              rootCtx.close();
          } catch (Exception e) {
              logger.error("Problem finding user " + name + " for password test." +e);
              //e.getMessage();
              //e.printStackTrace();
          }
  
          if (foundFlag) { // ie User is in Directory
              Hashtable env2 = new Hashtable();
              env2.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
              env2.put(javax.naming.Context.PROVIDER_URL, rootURL);
              env2.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
              env2.put(javax.naming.Context.SECURITY_PRINCIPAL, userDN);
              env2.put(javax.naming.Context.SECURITY_CREDENTIALS, testPassword);
              //System.out.println("Creating initial context from " + baseURL);
  
              try {
                  DirContext testCtx = new InitialDirContext(env2);
                  result = true;
                  testCtx.close();
  
              } catch (AuthenticationException ae) {
                  result = false;
                  logger.error("Attempt to authenticate with incorrect password for " + name
+ " : " + ae );
                  //System.out.println("Attempt to authenticate with incorrect password for
" + name + " : " + ae);
                  //System.out.println(ae.getMessage());
                  //ae.printStackTrace();
              } catch (Exception e) {
                  logger.error("Problem checking password for " + name + " : " + e );
                  //System.out.println("Problem checking password for " + name + " : " + e);
                  //System.out.println(e.getMessage());
                  //e.printStackTrace();
              }
          }
          return result;
  
      }
  
      public int countUsers() {
  
          String[] attrIDs = {membersAttr};
          int result = -1;
  
          try {
              Attribute members = ctx.getAttributes("", attrIDs).get(membersAttr);
              if (members != null) {
                  result = members.size();
              } else {
                  result = 0;
              }
          } catch (NamingException e) {
              logger.error("Problem counting users: "  + e);
              //System.out.println("Problem counting users. ");
          }
          return result;
      }
  
      public String getDomains() {
          return usersDomain;
      }
  
      /**
       * Disposes of all open directory contexts.
       * Based on signature from interface Disposable in new Avalon
       */
      public void dispose() throws Exception {
          ctx.close();
      }
  
  }
  
  
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/userrepository/UsersTownRepository.java
  
  Index: UsersTownRepository.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.userrepository;
  
  import com.workingdogs.town.*;
  import java.io.*;
  import java.util.*;
  import org.apache.avalon.framework.component.Component;
  import org.apache.avalon.framework.configuration.Configurable;
  import org.apache.avalon.framework.configuration.Configuration;
  import org.apache.avalon.framework.configuration.ConfigurationException;
  import org.apache.avalon.framework.logger.Loggable;
  import org.apache.james.services.UsersRepository;
  import org.apache.log.LogKit;
  import org.apache.log.Logger;
  
  /**
   * Implementation of a Repository to store users in database.
   * @version 1.0.0, 10/01/2000
   * @author  Ivan Seskar, Upside Technologies <seskar@winlab.rutgers.edu>
   */
  public class UsersTownRepository implements UsersRepository, Loggable, Component, Configurable
{
  
      //private String destination;
      //private String repositoryName;
  
      private String conndefinition;
      private String tableName;
  
      //  System defined logger funtion
      //private ComponentManager comp;
      private Logger logger;
  
      // Constructor - empty
      public UsersTownRepository() {
      }
  
      public void setLogger(final Logger a_Logger) {
          logger = a_Logger;
      }
  
      public void configure(Configuration conf) throws ConfigurationException {
          //  destination = conf.getChild("destination").getAttribute("URL");
          //  repositoryName = destination.substring(destination.indexOf("//") + 2);
          conndefinition= conf.getChild("conn").getValue();
          tableName = conf.getChild("table").getValue("Users");
  
      }
  
      // Methods from interface Repository
  
      public synchronized void addUser(String strUserName, Object attributes) {
          try {
              TableDataSet MRUser = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              MRUser.setWhere("username = '" + strUserName+"'");
              Record user = null;
              if (MRUser.size() == 0) {
                  // file://Add new user
                  user = MRUser.addRecord();
                  user.setValue("username", strUserName);
                  user.setValue("password", attributes.toString());
                  user.save();
              } else {
                  // file://User already exists: reject add
                  logger.warn("User "+strUserName+" already exists.");
              }
          } catch (Exception e) {
              e.printStackTrace();
              throw new RuntimeException("Exception caught while storing user: " + e);
          }
      }
  
      public synchronized Object getAttributes(String strUserName) {
          try {
              TableDataSet MRUser = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              MRUser.setWhere("username = '" + strUserName+"'");
              if (MRUser.size() == 0) {
                  logger.warn("User "+strUserName+" could not be found while fetching password.");
                  return(null);
              } else {
                  Record user = MRUser.getRecord(0);
                  return ((Object) user.getAsString("Password"));
              }
          } catch (Exception e) {
              throw new RuntimeException("Exception while retrieving password: " + e.getMessage());
          }
      }
  
      public synchronized void removeUser(String strUserName) {
          try {
              TableDataSet MRUser = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              MRUser.setWhere("username = '" + strUserName + "'");
              if (MRUser.size() == 0) {
                  // file://User doesn't exists: reject delete
                  logger.warn("User: " + strUserName + " does not exist.  Cannot delete");
              } else {
                  Record user = MRUser.getRecord(0);
                  user.markToBeDeleted();
                  user.save();
              }
          } catch (Exception e) {
              throw new RuntimeException("Exception while deleting user: " + e.getMessage());
          }
      }
  
      public boolean contains(String strUserName) {
          try {
              TableDataSet MRUser = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              MRUser.setWhere("username = '" + strUserName + "'");
              if (MRUser.size() > 0) {
                  return true;   // User exists
              } else {
                  return false;  // User does not exist
              }
          } catch (Exception e) {
              throw new RuntimeException("Exception while retrieving user: " + e.getMessage());
          }
      }
  
      public boolean test(String strUserName, Object attributes) {
          try {
              TableDataSet MRUser = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              MRUser.setWhere("username = '" + strUserName + "'");
              if (MRUser.size() > 0) {
                  // UserName exists - check if the password is OK
                  Record user = MRUser.getRecord(0);
                  return(user.getAsString("Password").equals(attributes.toString()));
              } else {
                  // file://UserName does not exist
                  logger.warn("User "+strUserName+" doesn't exist");
                  return(false);
              }
          } catch (Exception e) {
              e.printStackTrace();
              throw new RuntimeException("Exception caught while testing UserName: " + e.getMessage());
          }
      }
  
      public int countUsers() {
          try {
              TableDataSet MRUser = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              int nSize = MRUser.size();
              return (int) nSize;
          } catch (Exception e) {
              e.printStackTrace();
              throw new RuntimeException("Exception caught while testing UserName: " + e.getMessage());
          }
      }
  
      public Iterator list() {
          List list = new ArrayList();
  
          try {
              TableDataSet users = new TableDataSet(ConnDefinition.getInstance(conndefinition),
tableName);
              for (int i = 0; i < users.size(); i++) {
                  list.add(users.getRecord(i).getAsString("username"));
              }
          } catch (Exception e) {
              logger.error("Problem listing mailboxes. " + e );
              e.printStackTrace();
              throw new RuntimeException("Exception while listing users: " + e.getMessage());
          }
          return list.iterator();
      }
  }
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/util/CharTerminatedInputStream.java
  
  Index: CharTerminatedInputStream.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.util;
  
  import java.io.IOException;
  import java.io.InputStream;
  
  /**
   * @version 1.0.0, 24/04/1999
   * @author  Federico Barbieri <scoobie@pop.systemy.it>
   */
  public class CharTerminatedInputStream
      extends InputStream {
  
      private InputStream in;
      private int match[];
      private int buffer[];
      private int pos = 0;
      private boolean endFound = false;
  
      public CharTerminatedInputStream(InputStream in, char[] terminator) {
          match = new int[terminator.length];
          buffer = new int[terminator.length];
          for (int i = 0; i < terminator.length; i++) {
              match[i] = (int)terminator[i];
              buffer[i] = (int)terminator[i];
          }
          this.in = in;
      }
  
      public int read() throws IOException {
          if (endFound) {
              //We've found the match to the terminator
              return -1;
          }
          if (pos == 0) {
              //We have no data... read in a record
              int b = in.read();
              if (b == -1) {
                  //End of stream reached
                  endFound = true;
                  return -1;
              }
              if (b != match[0]) {
                  //this char is not the first char of the match
                  return b;
              }
              //this is a match...put this in the first byte of the buffer,
              // and fall through to matching logic
              buffer[0] = b;
              pos++;
          } else {
              if (buffer[0] != match[0]) {
                  //Maybe from a previous scan, there is existing data,
                  // and the first available char does not match the
                  // beginning of the terminating string.
                  return topChar();
              }
              //we have a match... fall through to matching logic.
          }
          //MATCHING LOGIC
  
          //The first character is a match... scan for complete match,
          // reading extra chars as needed, until complete match is found
          for (int i = 0; i < match.length; i++) {
              if (i >= pos) {
                  int b = in.read();
                  if (b == -1) {
                      //end of stream found, so match cannot be fulfilled.
                      // note we don't set endFound, because otherwise
                      // remaining part of buffer won't be returned.
                      return topChar();
                  }
                  //put the read char in the buffer
                  buffer[pos] = b;
                  pos++;
              }
              if (buffer[i] != match[i]) {
                  //we did not find a match... return the top char
                  return topChar();
              }
          }
          //A complete match was made...
          endFound = true;
          return -1;
      }
  
      private int topChar() {
          int b = buffer[0];
          if (pos > 1) {
              //copy down the buffer to keep the fresh data at top
              System.arraycopy(buffer, 1, buffer, 0, pos - 1);
          }
          pos--;
          return b;
      }
  }
  
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/util/InternetPrintWriter.java
  
  Index: InternetPrintWriter.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.util;
  
  import java.io.OutputStream;
  import java.io.PrintWriter;
  import java.io.Writer;
  
  public class InternetPrintWriter
      extends PrintWriter {
  
      private static String lineSeparator = "\r\n";
  
      public InternetPrintWriter (Writer out) {
          super (out);
      }
  
      public InternetPrintWriter (Writer out, boolean autoFlush) {
          super (out, autoFlush);
      }
  
      public InternetPrintWriter (OutputStream out) {
          super (out);
      }
  
      public InternetPrintWriter (OutputStream out, boolean autoFlush) {
          super (out, autoFlush);
      }
  
      public void println () {
          print (lineSeparator);
          super.flush();
      }
  
      public void println(boolean x) {
          synchronized (lock) {
              print(x);
              println();
          }
      }
  
      public void println(char x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (int x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (long x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (float x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (double x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (char[] x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (String x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  
      public void println (Object x) {
          synchronized (lock) {
              print (x);
              println ();
          }
      }
  }
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/util/Lock.java
  
  Index: Lock.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.util;
  
  import java.util.Hashtable;
  
  /**
   * @author Federico Barbieri <fede@apache.org>
   */
  public class Lock
  {
      private Hashtable locks = new Hashtable();
  
      public boolean isLocked( final Object key )
      {
          return (locks.get(key) != null);
      }
  
      public boolean canI( final Object key )
      {
          Object o = locks.get( key );
  
          if( null == o || o == this.getCallerId() )
          {
              return true;
          }
  
          return false;
      }
  
      public boolean lock( final Object key )
      {
          Object theLock;
  
          synchronized( this )
          {
              theLock = locks.get( key );
  
              if( null == theLock )
              {
                  locks.put( key, getCallerId() );
                  return true;
              }
              else if( getCallerId() == theLock )
              {
                  return true;
              }
              else
              {
                  return false;
              }
          }
      }
  
      public boolean unlock( final Object key )
      {
          Object theLock;
          synchronized( this )
          {
              theLock = locks.get( key );
  
              if( null == theLock )
              {
                  return true;
              }
              else if( getCallerId() == theLock )
              {
                  locks.remove( key );
                  return true;
              }
              else
              {
                  return false;
              }
          }
      }
  
      private Object getCallerId()
      {
          return Thread.currentThread();
      }
  }
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/util/LockException.java
  
  Index: LockException.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.util;
  
  public class LockException extends RuntimeException
  {
      public LockException(String msg) {
          super(msg);
      }
  }
  
  
  
  1.1                  jakarta-james/src/java/org/apache/james/util/RFC822DateFormat.java
  
  Index: RFC822DateFormat.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   */
  package org.apache.james.util;
  
  import java.text.DateFormat;
  import java.text.DecimalFormat;
  import java.text.SimpleDateFormat;
  import java.util.Date;
  import java.util.Locale;
  import java.util.TimeZone;
  
  /**
   * I suppose I could access some of the special messages within Sun's implementation of
the JavaMail
   * API, but I've always been told not to do that.  This class has one static method that
takes a
   * java.util.Date object and returns a nicely formatted String version of this, formatted
as per the
   * RFC822 mail date format.
   * @author Serge Knystautas <sergek@lokitech.com>
   * @version 0.9
   */
  public class RFC822DateFormat {
      private static DateFormat df;
      private static DecimalFormat tz;
  
      /**
       * SimpleDateFormat will handle most of this for us, but the
       * timezone won't match, so we do that manually
       *
       * @return java.lang.String
       * @param d Date
       */
      public static String toString(Date d) {
          if (df == null) {
              df = new SimpleDateFormat("EE, d MMM yyyy HH:mm:ss",Locale.US);
          }
          if (tz == null) {
              tz = new DecimalFormat("00");
          }
  
          StringBuffer sb = new StringBuffer(df.format(d));
  
          sb.append(' ');
  
          int min = TimeZone.getDefault().getRawOffset() / 1000 / 60;
  
          if (min >= 0) {
              sb.append('+');
          } else {
              sb.append('-');
          }
  
          min = Math.abs(min);
  
          sb.append(tz.format(min / 60));
          sb.append(tz.format(min % 60));
  
          return sb.toString();
      }
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: james-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: james-dev-help@jakarta.apache.org


Mime
View raw message