jndi-1.0.5

16:37:56.540 INFO  jd.cli.Main - Decompiling jndi-1.0.5.jar
package net.winstone.jndi;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.naming.Binding;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.spi.NamingManager;

public class Bindings
  implements NamingEnumeration<Binding>
{
  private Iterator<Map.Entry<String, Object>> iterator;
  private Context context;
  private Hashtable<String, Object> environnement;
  
  public Bindings(Context context, Hashtable<String, Object> environnement, Map<String, Object> bindings)
  {
    this.context = context;
    this.environnement = environnement;
    iterator = bindings.entrySet().iterator();
  }
  
  public void close()
    throws NamingException
  {
    context = null;
    environnement = null;
    iterator = null;
  }
  
  public boolean hasMore()
    throws NamingException
  {
    if (iterator == null) {
      throw new NamingException("Enumeration has already been closed");
    }
    return iterator.hasNext();
  }
  
  public Binding next()
    throws NamingException
  {
    if (hasMore())
    {
      Map.Entry<String, Object> entry = (Map.Entry)iterator.next();
      
      String name = (String)entry.getKey();
      Object value = entry.getValue();
      try
      {
        value = NamingManager.getObjectInstance(value, new CompositeName().add(name), context, environnement);
      }
      catch (Throwable err)
      {
        NamingException errNaming = new NamingException("Failed To Get Instance ");
        errNaming.setRootCause(err);
        throw errNaming;
      }
      return new Binding(name, value);
    }
    throw new NoSuchElementException();
  }
  
  public boolean hasMoreElements()
  {
    try
    {
      return hasMore();
    }
    catch (NamingException err) {}
    return Boolean.FALSE.booleanValue();
  }
  
  public Binding nextElement()
  {
    try
    {
      return next();
    }
    catch (NamingException namingException)
    {
      throw new NoSuchElementException();
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.Bindings
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi;

import net.winstone.jndi.resources.SimpleDatasource;

class JndiManager$1
  implements Runnable
{
  JndiManager$1(JndiManager paramJndiManager, SimpleDatasource paramSimpleDatasource) {}
  
  public void run()
  {
    val$dataSource.keepAlive();
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.JndiManager.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi;

import net.winstone.jndi.resources.SimpleDatasource;

class JndiManager$2
  implements Runnable
{
  JndiManager$2(JndiManager paramJndiManager, SimpleDatasource paramSimpleDatasource) {}
  
  public void run()
  {
    val$dataSource.drain();
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.JndiManager.2
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import net.winstone.jndi.resources.DataSourceConfig;
import net.winstone.jndi.resources.SimpleDatasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JndiManager
{
  protected Logger logger = LoggerFactory.getLogger(getClass());
  protected InitialContext initialContext;
  protected ScheduledExecutorService scheduler;
  
  public void initialize()
  {
    scheduler = Executors.newScheduledThreadPool(1);
    
    Hashtable<Object, Object> env = new Hashtable();
    env.put("java.naming.factory.initial", "net.winstone.jndi.url.java.javaURLContextFactory");
    env.put("java.naming.factory.url.pkgs", "net.winstone.jndi.url");
    try
    {
      initialContext = new InitialContext(env);
    }
    catch (NamingException e)
    {
      throw new IllegalStateException(e);
    }
    logger.info("jndi context initialized");
  }
  
  public void destroy()
  {
    if (initialContext != null)
    {
      try
      {
        Context jdbc = (Context)initialContext.lookup("java:/comp/env/jdbc");
        NamingEnumeration<NameClassPair> names = jdbc.list("");
        while (names.hasMore()) {
          try
          {
            NameClassPair pair = (NameClassPair)names.next();
            Object object = jdbc.lookup(pair.getName());
            if ((object instanceof SimpleDatasource)) {
              ((SimpleDatasource)object).close();
            }
            jdbc.unbind(pair.getName());
          }
          catch (NamingException e) {}
        }
      }
      catch (NamingException e)
      {
        throw new IllegalStateException(e);
      }
      try
      {
        initialContext.close();
        initialContext = null;
      }
      catch (NamingException e) {}
    }
    if (!scheduler.isShutdown()) {
      scheduler.shutdownNow();
    }
    logger.info("jndi context destroyed");
  }
  
  public void bind(DataSourceConfig dataSourceConfig)
    throws IllegalStateException, NamingException
  {
    final SimpleDatasource dataSource = new SimpleDatasource(dataSourceConfig);
    String jndiName = dataSource.getName();
    if (jndiName.startsWith("jdbc/")) {
      jndiName = "java:/comp/env/" + jndiName;
    }
    bind(jndiName, dataSource);
    if (dataSourceConfig.getKeepAlivePeriod() > 0) {
      scheduler.scheduleWithFixedDelay(new Runnable()
      {
        public void run()
        {
          dataSource.keepAlive();
        }
      }, dataSourceConfig.getKeepAlivePeriod(), dataSourceConfig.getKeepAlivePeriod(), TimeUnit.MINUTES);
    }
    if (dataSourceConfig.getKillInactivePeriod() > 0) {
      scheduler.scheduleWithFixedDelay(new Runnable()
      {
        public void run()
        {
          dataSource.drain();
        }
      }, dataSourceConfig.getKillInactivePeriod(), dataSourceConfig.getKillInactivePeriod(), TimeUnit.MINUTES);
    }
  }
  
  public void bindSmtpSession(String name, Properties properties, ClassLoader loader)
    throws IllegalStateException, NamingException
  {
    try
    {
      Class<?> smtpClass = Class.forName("javax.mail.Session", Boolean.TRUE.booleanValue(), loader);
      Method smtpMethod = smtpClass.getMethod("getInstance", new Class[] { Properties.class, Class.forName("javax.mail.Authenticator") });
      
      Object object = smtpMethod.invoke(null, new Object[] { properties, null });
      String jndiName = name;
      if (name.startsWith("mail/")) {
        jndiName = "java:comp/env/" + name;
      }
      bind(jndiName, object);
    }
    catch (ClassNotFoundException e)
    {
      throw new IllegalStateException(e);
    }
    catch (SecurityException e)
    {
      throw new IllegalStateException(e);
    }
    catch (NoSuchMethodException e)
    {
      throw new IllegalStateException(e);
    }
    catch (IllegalArgumentException e)
    {
      throw new IllegalStateException(e);
    }
    catch (IllegalAccessException e)
    {
      throw new IllegalStateException(e);
    }
    catch (InvocationTargetException e)
    {
      throw new IllegalStateException(e);
    }
  }
  
  public void bind(String name, String className, String value, ClassLoader loader)
    throws IllegalStateException, NamingException
  {
    if (value != null) {
      try
      {
        Class<?> objClass = Class.forName(className.trim(), Boolean.TRUE.booleanValue(), loader);
        
        Constructor<?> objConstr = objClass.getConstructor(new Class[] { String.class });
        
        Object object = objConstr.newInstance(new Object[] { value });
        
        bind(name, object);
      }
      catch (ClassNotFoundException e)
      {
        throw new IllegalStateException(e);
      }
      catch (IllegalArgumentException e)
      {
        throw new IllegalStateException(e);
      }
      catch (InstantiationException e)
      {
        throw new IllegalStateException(e);
      }
      catch (IllegalAccessException e)
      {
        throw new IllegalStateException(e);
      }
      catch (InvocationTargetException e)
      {
        throw new IllegalStateException(e);
      }
      catch (SecurityException e)
      {
        throw new IllegalStateException(e);
      }
      catch (NoSuchMethodException e)
      {
        throw new IllegalStateException(e);
      }
    }
  }
  
  public void unbind(String name)
    throws IllegalStateException, NamingException
  {
    if (name != null)
    {
      String jndiName = name;
      if (!jndiName.startsWith("java:/comp/env/")) {
        jndiName = "java:/comp/env/" + jndiName;
      }
      try
      {
        initialContext.unbind(jndiName);
      }
      catch (IllegalArgumentException e)
      {
        throw new IllegalStateException(e);
      }
      catch (SecurityException e)
      {
        throw new IllegalStateException(e);
      }
    }
  }
  
  public InitialContext getInitialContext()
  {
    return initialContext;
  }
  
  private void bind(String name, Object object)
    throws IllegalStateException, NamingException
  {
    if (initialContext == null) {
      throw new IllegalStateException("Initial Context is closed");
    }
    String jndiName = name;
    if (!jndiName.startsWith("java:/comp/env/")) {
      jndiName = "java:/comp/env/" + jndiName;
    }
    Name fullName = new CompositeName(jndiName);
    Context currentContext = initialContext;
    while (fullName.size() > 1)
    {
      try
      {
        currentContext = currentContext.createSubcontext(fullName.get(0));
      }
      catch (NamingException err)
      {
        currentContext = (Context)currentContext.lookup(fullName.get(0));
      }
      fullName = fullName.getSuffix(1);
    }
    initialContext.bind(name, object);
    logger.info("bind " + jndiName + " to " + object);
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.JndiManager
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

public class Names
  implements NamingEnumeration<NameClassPair>
{
  private Iterator<Map.Entry<String, Object>> iterator;
  
  public Names(Map<String, Object> bindings)
  {
    iterator = bindings.entrySet().iterator();
  }
  
  public void close()
    throws NamingException
  {
    iterator = null;
  }
  
  public boolean hasMore()
    throws NamingException
  {
    if (iterator == null) {
      throw new NamingException("Enumeration has already been closed");
    }
    return iterator.hasNext();
  }
  
  public NameClassPair next()
    throws NamingException
  {
    if (hasMore())
    {
      Map.Entry<String, Object> entry = (Map.Entry)iterator.next();
      return new NameClassPair((String)entry.getKey(), entry.getValue().getClass().getName());
    }
    throw new NoSuchElementException();
  }
  
  public boolean hasMoreElements()
  {
    try
    {
      return hasMore();
    }
    catch (NamingException err) {}
    return Boolean.FALSE.booleanValue();
  }
  
  public NameClassPair nextElement()
  {
    try
    {
      return next();
    }
    catch (NamingException namingException)
    {
      throw new NoSuchElementException();
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.Names
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi;

import java.util.Hashtable;
import javax.naming.Binding;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NotContextException;
import javax.naming.OperationNotSupportedException;
import javax.naming.spi.NamingManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NamingContext
  implements Context
{
  protected Logger logger = LoggerFactory.getLogger(getClass());
  private static final transient String PREFIX = "java:";
  private static final transient String FIRST_CHILD = "comp";
  private static final transient String BODGED_PREFIX = "java:comp";
  protected static final transient NameParser nameParser = new SimpleNameParser();
  protected Hashtable<String, Object> environnement;
  protected final Hashtable<String, Object> bindings;
  protected final NamingContext parent;
  protected final String myAtomicName;
  
  public NamingContext(Hashtable<String, Object> environnement)
  {
    this(null, environnement);
  }
  
  public NamingContext(String name, Hashtable<String, Object> environnement)
  {
    this(null, name, environnement, null);
  }
  
  protected NamingContext(NamingContext parent, String name, Hashtable<String, Object> environnement, Hashtable<String, Object> bindings)
  {
    this.parent = parent;
    myAtomicName = name;
    if (environnement != null)
    {
      this.environnement = new Hashtable();
      this.environnement.putAll(environnement);
    }
    this.bindings = new Hashtable();
    if (bindings != null) {
      this.bindings.putAll(bindings);
    }
  }
  
  private Name validateName(Name name)
    throws NamingException
  {
    if (name.isEmpty()) {
      return name;
    }
    if (name.get(0).equals("java:comp"))
    {
      Name newName = name.getSuffix(1).add(0, "comp").add(0, "java:");
      return validateName(newName);
    }
    if (name.get(0).equals("java:"))
    {
      String nameInNamespace = getNameInNamespace();
      String stringName = name.toString();
      if (stringName.equals(nameInNamespace)) {
        return nameParser.parse("");
      }
      if (nameInNamespace.equals("")) {
        return nameParser.parse(stringName);
      }
      if (stringName.startsWith(nameInNamespace)) {
        return nameParser.parse(stringName.substring(nameInNamespace.length() + 1));
      }
      if (parent != null) {
        return null;
      }
      throw new NameNotFoundException("Name '" + name.toString() + "' Not Found");
    }
    if ((name instanceof CompositeName)) {
      return nameParser.parse(name.toString());
    }
    return name;
  }
  
  public Object lookup(String name)
    throws NamingException
  {
    logger.trace("lookup {}", name);
    return lookup(new CompositeName(name));
  }
  
  public Object lookup(Name name)
    throws NamingException
  {
    Name searchName = validateName(name);
    if (searchName == null)
    {
      logger.debug("lookup parent for {}", name);
      return parent.lookup(name);
    }
    if (searchName.isEmpty()) {
      return new NamingContext(parent, myAtomicName, environnement, bindings);
    }
    Name nm = searchName;
    String atom = nm.get(0);
    Object inter = bindings.get(atom);
    if (nm.size() == 1)
    {
      if (inter == null)
      {
        logger.debug("{} not found", name);
        throw new NameNotFoundException(name + " not found");
      }
      try
      {
        return NamingManager.getObjectInstance(inter, new CompositeName().add(atom), this, environnement);
      }
      catch (Exception e)
      {
        logger.debug("getObjectInstance failed for {} ", atom);
        NamingException ne = new NamingException("getObjectInstance failed");
        ne.setRootCause(e);
        throw ne;
      }
    }
    if (!(inter instanceof Context))
    {
      logger.debug("{} does not name a context", atom);
      throw new NotContextException(atom + " does not name a context");
    }
    return ((Context)inter).lookup(nm.getSuffix(1));
  }
  
  public void bind(String name, Object obj)
    throws NamingException
  {
    bind(new CompositeName(name), obj);
  }
  
  public void bind(Name name, Object obj)
    throws NamingException
  {
    Name bindName = validateName(name);
    if (bindName == null) {
      parent.bind(name, obj);
    }
    if (bindName.isEmpty()) {
      throw new InvalidNameException("Cannot rebind an empty name");
    }
    Name nm = bindName;
    String atom = nm.get(0);
    Object inter = bindings.get(atom);
    if (nm.size() == 1)
    {
      if (inter != null) {
        throw new NameAlreadyBoundException("Use rebind to override");
      }
      Object result = NamingManager.getStateToBind(obj, new CompositeName().add(atom), this, environnement);
      
      bindings.put(atom, result);
    }
    else
    {
      if (!(inter instanceof Context)) {
        throw new NotContextException(atom + " does not name a context");
      }
      ((Context)inter).bind(nm.getSuffix(1), obj);
    }
  }
  
  public void rebind(String name, Object obj)
    throws NamingException
  {
    rebind(new CompositeName(name), obj);
  }
  
  public void rebind(Name name, Object obj)
    throws NamingException
  {
    Name bindName = validateName(name);
    if (bindName == null) {
      parent.bind(name, obj);
    }
    if (bindName.isEmpty()) {
      throw new InvalidNameException("Cannot rebind an empty name");
    }
    Name nm = bindName;
    String atom = nm.get(0);
    if (nm.size() == 1)
    {
      Object result = NamingManager.getStateToBind(obj, new CompositeName().add(atom), this, environnement);
      
      bindings.put(atom, result);
    }
    else
    {
      Object inter = bindings.get(atom);
      if (!(inter instanceof Context)) {
        throw new NotContextException(atom + " does not name a context");
      }
      ((Context)inter).rebind(nm.getSuffix(1), obj);
    }
  }
  
  public void unbind(String name)
    throws NamingException
  {
    unbind(new CompositeName(name));
  }
  
  public void unbind(Name name)
    throws NamingException
  {
    Name unbindName = validateName(name);
    if (unbindName == null) {
      parent.unbind(name);
    } else if (unbindName.isEmpty()) {
      throw new InvalidNameException("Cannot unbind empty name");
    }
    Name nm = unbindName;
    String atom = nm.get(0);
    if (nm.size() == 1)
    {
      bindings.remove(atom);
    }
    else
    {
      Object inter = bindings.get(atom);
      if (!(inter instanceof Context)) {
        throw new NotContextException(atom + " does not name a context");
      }
      ((Context)inter).unbind(nm.getSuffix(1));
    }
  }
  
  public void rename(String oldname, String newname)
    throws NamingException
  {
    rename(new CompositeName(oldname), new CompositeName(newname));
  }
  
  public void rename(Name oldname, Name newname)
    throws NamingException
  {
    if ((oldname.isEmpty()) || (newname.isEmpty())) {
      throw new InvalidNameException("Cannot rename empty name");
    }
    Name oldnm = validateName(oldname);
    Name newnm = validateName(newname);
    if (oldnm == null) {
      parent.rename(oldname, newname);
    } else if (oldname.isEmpty()) {
      throw new InvalidNameException("Cannot rename from an empty name");
    }
    if (oldnm.size() != newnm.size()) {
      throw new OperationNotSupportedException("Do not support rename across different contexts");
    }
    String oldatom = oldnm.get(0);
    String newatom = newnm.get(0);
    if (oldnm.size() == 1)
    {
      if (bindings.get(newatom) != null) {
        throw new NameAlreadyBoundException(newname.toString() + " is already bound");
      }
      Object oldBinding = bindings.remove(oldatom);
      if (oldBinding == null) {
        throw new NameNotFoundException(oldname.toString() + " not bound");
      }
      bindings.put(newatom, oldBinding);
    }
    else
    {
      if (!oldatom.equals(newatom)) {
        throw new OperationNotSupportedException("Do not support rename across different contexts");
      }
      Object inter = bindings.get(oldatom);
      if (!(inter instanceof Context)) {
        throw new NotContextException(oldatom + " does not name a context");
      }
      ((Context)inter).rename(oldnm.getSuffix(1), newnm.getSuffix(1));
    }
  }
  
  public NamingEnumeration<NameClassPair> list(String name)
    throws NamingException
  {
    return list(new CompositeName(name));
  }
  
  public NamingEnumeration<NameClassPair> list(Name name)
    throws NamingException
  {
    Name searchName = validateName(name);
    if (searchName == null) {
      return parent.list(name);
    }
    if (searchName.isEmpty()) {
      return new Names(bindings);
    }
    Object target = lookup(name);
    if ((target instanceof Context)) {
      return ((Context)target).list("");
    }
    throw new NotContextException(name + " cannot be listed");
  }
  
  public NamingEnumeration<Binding> listBindings(String name)
    throws NamingException
  {
    return listBindings(new CompositeName(name));
  }
  
  public NamingEnumeration<Binding> listBindings(Name name)
    throws NamingException
  {
    Name searchName = validateName(name);
    if (searchName == null) {
      return parent.listBindings(name);
    }
    if (searchName.isEmpty()) {
      return new Bindings(this, environnement, bindings);
    }
    Object target = lookup(name);
    if ((target instanceof Context)) {
      return ((Context)target).listBindings("");
    }
    throw new NotContextException(name + " cannot be listed");
  }
  
  public void destroySubcontext(String name)
    throws NamingException
  {
    destroySubcontext(new CompositeName(name));
  }
  
  public void destroySubcontext(Name name)
    throws NamingException
  {
    Name childName = validateName(name);
    if (childName == null) {
      parent.destroySubcontext(name);
    }
    if (childName.isEmpty())
    {
      if ((!name.isEmpty()) && (name.size() > 1))
      {
        parent.destroySubcontext(name.getSuffix(name.size() - 2));
        return;
      }
      throw new InvalidNameException("Cannot destroy context using empty name");
    }
    unbind(name);
  }
  
  public Context createSubcontext(String name)
    throws NamingException
  {
    return createSubcontext(new CompositeName(name));
  }
  
  public Context createSubcontext(Name name)
    throws NamingException
  {
    Name childName = validateName(name);
    if (childName == null) {
      return parent.createSubcontext(name);
    }
    if (childName.isEmpty()) {
      throw new InvalidNameException("Cannot bind empty name");
    }
    Name nm = childName;
    String atom = nm.get(0);
    Object inter = bindings.get(atom);
    if (nm.size() == 1)
    {
      if (inter != null) {
        throw new NameAlreadyBoundException("Use rebind to override");
      }
      Context child = new NamingContext(this, atom, environnement, null);
      
      bindings.put(atom, child);
      return child;
    }
    if (!(inter instanceof Context)) {
      throw new NotContextException(atom + " does not name a context");
    }
    return ((Context)inter).createSubcontext(nm.getSuffix(1));
  }
  
  public Object lookupLink(String name)
    throws NamingException
  {
    return lookupLink(new CompositeName(name));
  }
  
  public Object lookupLink(Name name)
    throws NamingException
  {
    Object result = lookup(name);
    if ((result instanceof LinkRef))
    {
      LinkRef ref = (LinkRef)result;
      String link = ref.getLinkName();
      if (link.startsWith("./")) {
        return lookup(link.substring(2));
      }
      return lookupLink(link);
    }
    return result;
  }
  
  public NameParser getNameParser(String name)
    throws NamingException
  {
    return getNameParser(new CompositeName(name));
  }
  
  public NameParser getNameParser(Name name)
    throws NamingException
  {
    Object obj = lookup(name);
    if ((obj instanceof Context)) {
      ((Context)obj).close();
    }
    return nameParser;
  }
  
  public String composeName(String name, String prefix)
    throws NamingException
  {
    Name result = composeName(new CompositeName(name), new CompositeName(prefix));
    return result.toString();
  }
  
  public Name composeName(Name name, Name prefix)
    throws NamingException
  {
    if ((!(name instanceof CompositeName)) && (!(prefix instanceof CompositeName)))
    {
      Name result = (Name)prefix.clone();
      result.addAll(name);
      return new CompositeName().add(result.toString());
    }
    throw new OperationNotSupportedException("Do not support composing composite names");
  }
  
  public Object addToEnvironment(String propName, Object propVal)
    throws NamingException
  {
    if (environnement == null) {
      environnement = new Hashtable();
    }
    return environnement.put(propName, propVal);
  }
  
  public Object removeFromEnvironment(String propName)
    throws NamingException
  {
    if (environnement == null) {
      return null;
    }
    return environnement.remove(propName);
  }
  
  public Hashtable<String, Object> getEnvironment()
    throws NamingException
  {
    Hashtable<String, Object> result = new Hashtable();
    if (environnement != null) {
      result.putAll(environnement);
    }
    return result;
  }
  
  public String getNameInNamespace()
    throws NamingException
  {
    NamingContext ancestor = parent;
    if (ancestor == null) {
      return "";
    }
    Name name = nameParser.parse("");
    name.add(myAtomicName);
    while ((ancestor != null) && (myAtomicName != null))
    {
      name.add(0, myAtomicName);
      ancestor = parent;
    }
    return name.toString();
  }
  
  public String toString()
  {
    if (myAtomicName != null) {
      return myAtomicName;
    }
    return "ROOT CONTEXT";
  }
  
  public void close()
    throws NamingException
  {}
}

/* Location:
 * Qualified Name:     net.winstone.jndi.NamingContext
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi.resources;

import java.io.Serializable;

public class DataSourceConfig
  implements Serializable
{
  private static final long serialVersionUID = -4762104837042371012L;
  private String name = null;
  private String url = null;
  private String driverClassName = null;
  private String username = null;
  private String password = null;
  private int maxActive = 20;
  private int maxIdle = 10;
  private int minIdle = 1;
  private int maxWait = 10000;
  private String validationQuery = null;
  private int validationTimeOut = 1000;
  private String keepAliveSQL = null;
  private int keepAlivePeriod = 1;
  private int keepAliveTimeOut = 1000;
  private int killInactivePeriod = -1;
  
  public String getName()
  {
    return name;
  }
  
  public void setName(String name)
  {
    this.name = name;
  }
  
  public String getUrl()
  {
    return url;
  }
  
  public void setUrl(String url)
  {
    this.url = url;
  }
  
  public String getDriverClassName()
  {
    return driverClassName;
  }
  
  public void setDriverClassName(String driverClassName)
  {
    this.driverClassName = driverClassName;
  }
  
  public String getUsername()
  {
    return username;
  }
  
  public void setUsername(String username)
  {
    this.username = username;
  }
  
  public String getPassword()
  {
    return password;
  }
  
  public void setPassword(String password)
  {
    this.password = password;
  }
  
  public int getMaxActive()
  {
    return maxActive;
  }
  
  public void setMaxActive(int maxActive)
  {
    this.maxActive = maxActive;
  }
  
  public int getMaxIdle()
  {
    return maxIdle;
  }
  
  public void setMaxIdle(int maxIdle)
  {
    this.maxIdle = maxIdle;
  }
  
  public int getMinIdle()
  {
    return minIdle;
  }
  
  public void setMinIdle(int minIdle)
  {
    this.minIdle = minIdle;
  }
  
  public int getMaxWait()
  {
    return maxWait;
  }
  
  public void setMaxWait(int maxWait)
  {
    this.maxWait = maxWait;
  }
  
  public String getValidationQuery()
  {
    return validationQuery;
  }
  
  public void setValidationQuery(String validationQuery)
  {
    this.validationQuery = validationQuery;
  }
  
  public int getValidationTimeOut()
  {
    return validationTimeOut;
  }
  
  public void setValidationTimeOut(int validationTimeOut)
  {
    this.validationTimeOut = validationTimeOut;
  }
  
  public String getKeepAliveSQL()
  {
    return keepAliveSQL;
  }
  
  public void setKeepAliveSQL(String keepAliveSQL)
  {
    this.keepAliveSQL = keepAliveSQL;
  }
  
  public int getKeepAlivePeriod()
  {
    return keepAlivePeriod;
  }
  
  public void setKeepAlivePeriod(int keepAlivePeriod)
  {
    this.keepAlivePeriod = keepAlivePeriod;
  }
  
  public int getKeepAliveTimeOut()
  {
    return keepAliveTimeOut;
  }
  
  public void setKeepAliveTimeOut(int keepAliveTimeOut)
  {
    this.keepAliveTimeOut = keepAliveTimeOut;
  }
  
  public int getKillInactivePeriod()
  {
    return killInactivePeriod;
  }
  
  public void setKillInactivePeriod(int killInactivePeriod)
  {
    this.killInactivePeriod = killInactivePeriod;
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.resources.DataSourceConfig
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi.resources;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import net.winstone.pool.Function;
import net.winstone.pool.SimplePool;

class SimpleDatasource$1
  implements Function<Void, Connection>
{
  SimpleDatasource$1(SimpleDatasource paramSimpleDatasource) {}
  
  public Void apply(Connection connection)
  {
    PreparedStatement keepAliveQuery = null;
    try
    {
      keepAliveQuery = connection.prepareStatement(SimpleDatasource.access$000(this$0));
      keepAliveQuery.execute();
      
      return null;
    }
    catch (SQLException err)
    {
      SimpleDatasource.access$200(this$0, "Keep alive failed for %s, invalidate connection", err, new Object[] { SimpleDatasource.access$100(this$0) });
      SimpleDatasource.access$300(this$0).invalidate(connection);
    }
    finally
    {
      if (keepAliveQuery != null) {
        try
        {
          keepAliveQuery.close();
        }
        catch (SQLException e) {}
      }
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.resources.SimpleDatasource.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi.resources;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

class SimpleDatasource$2
  implements Runnable
{
  SimpleDatasource$2(SimpleDatasource paramSimpleDatasource, Connection paramConnection) {}
  
  public void run()
  {
    Statement statement = null;
    try
    {
      statement = val$connection.createStatement();
      statement.execute(SimpleDatasource.access$400(this$0)); return;
    }
    catch (SQLException e)
    {
      throw new IllegalStateException("ValidationFailure");
    }
    finally
    {
      if (statement != null) {
        try
        {
          statement.close();
        }
        catch (SQLException e) {}
      }
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.resources.SimpleDatasource.2
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi.resources;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import net.winstone.pool.SimplePool;

class SimpleDatasource$ConnectionWrapperInvocationHandler
  implements InvocationHandler
{
  private final Connection connection;
  
  protected SimpleDatasource$ConnectionWrapperInvocationHandler(SimpleDatasource paramSimpleDatasource, Connection connection)
  {
    this.connection = connection;
  }
  
  public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable
  {
    if (connection == null) {
      throw new SQLException("The connection is closed");
    }
    if (method.getName().equals("close"))
    {
      if (connection.getAutoCommit() == Boolean.FALSE.booleanValue()) {
        try
        {
          connection.rollback();
        }
        catch (SQLException se) {}
      }
      SimpleDatasource.access$300(this$0).release(connection);
      return null;
    }
    if (method.getName().equals("unwrap")) {
      return connection;
    }
    if (method.getName().equals("isWrapperFor")) {
      return Boolean.valueOf(((Class)args[0]).isInstance(connection));
    }
    if (method.getName().equals("equals")) {
      return Boolean.valueOf(proxy == args[0]);
    }
    try
    {
      return method.invoke(connection, args);
    }
    catch (InvocationTargetException exception)
    {
      Throwable cause = exception.getCause();
      try
      {
        if ((cause instanceof SQLException)) {
          SimpleDatasource.access$300(this$0).invalidate(connection);
        }
      }
      catch (Throwable e) {}
      throw exception.getCause();
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.jndi.resources.SimpleDatasource.ConnectionWrapperInvocationHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.jndi.resources;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import javax.sql.DataSource;
import net.winstone.pool.Function;
import net.winstone.pool.ResourceFactory;
import net.winstone.pool.SimplePool;

public class SimpleDatasource
  implements DataSource, ResourceFactory<Connection>
{
  private final SimplePool<Connection> pool;
  private final String name;
  private final String url;
  private final Driver driver;
  private final Properties connectionProperties;
  private PrintWriter logWriter;
  private final String validationQuery;
  private final int validationTimeOut;
  private final boolean validated;
  private final String keepAliveSQL;
  private final int keepAliveTimeOut;
  
  public SimpleDatasource(DataSourceConfig config)
    throws IllegalArgumentException, IllegalStateException
  {
    logWriter = null;
    
    name = (config.getName() != null ? config.getName() : config.getUrl());
    
    connectionProperties = new Properties();
    if (config.getUsername() != null) {
      connectionProperties.setProperty("user", config.getUsername());
    }
    if (config.getPassword() != null) {
      connectionProperties.setProperty("password", config.getPassword());
    }
    url = config.getUrl();
    if ((url == null) || (url.isEmpty())) {
      throw new IllegalArgumentException(String.format("Can't create database %s connection : url not provided", new Object[] { config.getName() }));
    }
    validationQuery = config.getValidationQuery();
    validated = ((config.getValidationQuery() != null) && (config.getValidationQuery().length() > 0));
    validationTimeOut = config.getValidationTimeOut();
    if (validationTimeOut <= 0) {
      throw new IllegalArgumentException(String.format("Database %s: validation TimeOut must be > 0", new Object[] { config.getName() }));
    }
    keepAliveSQL = config.getKeepAliveSQL();
    keepAliveTimeOut = config.getKeepAliveTimeOut();
    if (keepAliveTimeOut <= 0) {
      throw new IllegalArgumentException(String.format("Database %s: Keep Alive TimeOut must be > 0", new Object[] { config.getName() }));
    }
    try
    {
      if (config.getDriverClassName() != null)
      {
        Class<?> driverClass = Class.forName(config.getDriverClassName().trim());
        driver = ((Driver)driverClass.newInstance());
      }
      else
      {
        driver = DriverManager.getDriver(config.getUrl());
      }
    }
    catch (Throwable err)
    {
      throw new IllegalStateException(String.format("Can't load database driver for %s connection", new Object[] { config.getName() }), err);
    }
    pool = new SimplePool(this, config.getMaxActive(), config.getMaxWait(), config.getMinIdle());
    log("Database %s Initialized: %s", null, new Object[] { name, pool.toString() });
  }
  
  public void close()
  {
    log("Closing %s", null, new Object[] { name });
    pool.close();
  }
  
  public Connection getConnection()
    throws SQLException
  {
    Connection connection = null;
    if (!validated)
    {
      connection = (Connection)pool.acquire();
    }
    else
    {
      int retry = 0;
      do
      {
        Connection result = (Connection)pool.acquire();
        if (validate(result)) {
          connection = result;
        }
        retry++;
        pool.invalidate(result);
      } while (retry <= pool.getCapacity());
      if (connection == null) {
        throw new IllegalStateException("Unable to obtain a validated connection %s");
      }
    }
    if (connection == null) {
      throw new SQLException("Connection unavailable - pool limit exceeded : " + pool.toString());
    }
    return (Connection)Proxy.newProxyInstance(connection.getClass().getClassLoader(), new Class[] { Connection.class }, new ConnectionWrapperInvocationHandler(connection));
  }
  
  public Connection getConnection(String username, String password)
    throws SQLException
  {
    connectionProperties.setProperty("user", username);
    connectionProperties.setProperty("password", password);
    return getConnection();
  }
  
  public int getLoginTimeout()
    throws SQLException
  {
    return pool.getTimeout() / 1000;
  }
  
  public PrintWriter getLogWriter()
    throws SQLException
  {
    return logWriter;
  }
  
  public void setLogWriter(PrintWriter out)
    throws SQLException
  {
    logWriter = out;
  }
  
  public void setLoginTimeout(int seconds)
    throws SQLException
  {
    log("LoginTimeout cannot be modified at runtime for %s%n", null, new Object[] { name });
  }
  
  public boolean isWrapperFor(Class<?> iface)
    throws SQLException
  {
    return DataSource.class.equals(iface);
  }
  
  public <T> T unwrap(Class<T> iface)
    throws SQLException
  {
    if (isWrapperFor(iface)) {
      return this;
    }
    return null;
  }
  
  public Connection create()
  {
    try
    {
      return driver.connect(url, connectionProperties);
    }
    catch (SQLException e)
    {
      log("Can't create connection %s for %s%n", e, new Object[] { name, url });
      throw new IllegalStateException("Can't create connection, check connection parameters and class path for JDBC driver", e);
    }
  }
  
  public void destroy(Connection resource)
  {
    try
    {
      if (resource != null) {
        resource.close();
      }
    }
    catch (SQLException err)
    {
      log("Error when closing %s connection ", err, new Object[] { name });
    }
  }
  
  public int drain()
  {
    try
    {
      return pool.drain();
    }
    catch (Throwable e)
    {
      log("Drain error on Datasource %s:", e, new Object[] { name });
    }
    return -1;
  }
  
  public void keepAlive()
  {
    if ((keepAliveSQL != null) && (!keepAliveSQL.isEmpty())) {
      try
      {
        
1 2

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd