Beispiel #1
0
  /**
   * Creates an instance of JDO from a JNDI reference.
   *
   * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name,
   *     javax.naming.Context, java.util.Hashtable)
   */
  public Object getObjectInstance(Object refObj, Name name, Context nameCtx, Hashtable env)
      throws NamingException {
    Reference ref;

    // Can only reconstruct from a reference.
    if (refObj instanceof Reference) {
      ref = (Reference) refObj;
      // Make sure reference is of datasource class.
      if (!ref.getClassName().equals(getClass().getName())) {
        throw new NamingException("Reference not constructed from class " + getClass().getName());
      }

      JDO jdo;
      RefAddr addr;

      try {
        jdo = (JDO) Class.forName(ref.getClassName()).newInstance();
      } catch (Exception except) {
        throw new NamingException(except.toString());
      }
      addr = ref.get("description");
      if (addr != null) jdo._description = (String) addr.getContent();
      addr = ref.get("databaseName");
      if (addr != null) jdo._dbName = (String) addr.getContent();
      addr = ref.get("configuration");
      if (addr != null) jdo._jdoConfURI = (String) addr.getContent();
      addr = ref.get("lockTimeout");
      if (addr != null) jdo._lockTimeout = Integer.parseInt((String) addr.getContent());
      return jdo;

    } else if (refObj instanceof Remote) return refObj;
    else return null;
  }
  private Map<String, String[]> getConfigurationMap(Reference ref) {
    Map<String, String[]> configMap = new HashMap<String, String[]>();

    String separatorChars = ",";
    RefAddr separatorCharsRefAddr = ref.get("separatorChars");
    if (separatorCharsRefAddr != null) {
      String value = (String) separatorCharsRefAddr.getContent();
      if (value != null && !"".equals(value)) {
        separatorChars = value.trim();
      }
    }

    Enumeration addrs = ref.getAll();

    while (addrs.hasMoreElements()) {
      RefAddr addr = (RefAddr) addrs.nextElement();
      String type = addr.getType();
      String value = (String) addr.getContent();

      String[] valueArray = StringUtils.splitPreserveAllTokens(value, separatorChars);

      for (int i = 0; i < valueArray.length; i++) {
        valueArray[i] = valueArray[i].trim();
      }

      configMap.put(type, valueArray);
    }

    return configMap;
  }
Beispiel #3
0
  /**
   * @return an instance of a proxy (an EJB) that handle local calls.
   * @param obj the reference containing data to build instance
   * @param name Name of context, relative to ctx, or null.
   * @param nameCtx Context relative to which 'name' is named.
   * @param environment Environment to use when creating the context *
   * @throws Exception if this object factory encountered an exception while attempting to create an
   *     object, and no other object factories are to be tried.
   */
  public Object getObjectInstance(
      final Object obj, final Name name, final Context nameCtx, final Hashtable<?, ?> environment)
      throws Exception {
    if (obj instanceof Reference) {
      Reference ref = (Reference) obj;

      // get the embeddedID, getContainerId(), getFactoryName()
      RefAddr containerIDAddr = ref.get(AbsCallRef.CONTAINER_ID);
      RefAddr factoryNameAddr = ref.get(AbsCallRef.FACTORY_NAME);
      RefAddr itfClassNameAddr = ref.get(AbsCallRef.INTERFACE_NAME);
      RefAddr useIDAddr = ref.get(AbsCallRef.USE_ID);

      String containerID = (String) containerIDAddr.getContent();
      String factoryName = (String) factoryNameAddr.getContent();
      String itfClassName = (String) itfClassNameAddr.getContent();
      boolean useID = Boolean.valueOf((String) useIDAddr.getContent()).booleanValue();

      // Build new Handler
      ClientRPCInvocationHandler handler = buildRemoteHandler(containerID, factoryName, useID);
      // Set the environment used by client to do the lookup.
      handler.setRMIEnv(environment);

      // Get current classloader
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

      // load class
      Class<?> clz = null;
      try {
        clz = classLoader.loadClass(itfClassName);
      } catch (ClassNotFoundException e) {
        throw new EZBContainerException(
            "Cannot find the class '" + itfClassName + "' in Classloader '" + classLoader + "'.",
            e);
      }

      // set the interface class
      handler.setInterfaceClass(clz);

      // build the proxy
      Object proxy = Proxy.newProxyInstance(classLoader, new Class[] {clz}, handler);

      // Stateful case ? needs to invoke a remote method in order to
      // initialize the ID as the ID needs to be present when the client
      // performs the lookup.
      if (useID) {
        proxy.toString();
      }

      // return the object built.
      return proxy;
    }
    throw new IllegalStateException("Can only build object with a reference");
  }
 public Object getObjectInstance(
     Object paramObject, Name paramName, Context paramContext, Hashtable paramHashtable)
     throws Exception {
   if (!(paramObject instanceof Reference)) return null;
   Reference localReference = (Reference) paramObject;
   String str1 = localReference.getClassName();
   if (("org.hsqldb.jdbc.JDBCDataSource".equals(str1))
       || ("org.hsqldb.jdbc.JDBCPool".equals(str1))
       || ("org.hsqldb.jdbc.pool.JDBCPooledDataSource".equals(str1))
       || ("org.hsqldb.jdbc.pool.JDBCXADataSource".equals(str1))) {
     JDBCCommonDataSource localJDBCCommonDataSource =
         (JDBCCommonDataSource) Class.forName(str1).newInstance();
     RefAddr localRefAddr = localReference.get("database");
     if (localRefAddr == null) throw new Exception(str1 + ": RefAddr not set: database");
     Object localObject = localRefAddr.getContent();
     if (!(localObject instanceof String))
       throw new Exception(str1 + ": invalid RefAddr: database");
     localJDBCCommonDataSource.setDatabase((String) localObject);
     localRefAddr = localReference.get("user");
     if (localRefAddr == null) throw new Exception(str1 + ": RefAddr not set: user");
     localObject = localReference.get("user").getContent();
     if (!(localObject instanceof String)) throw new Exception(str1 + ": invalid RefAddr: user");
     localJDBCCommonDataSource.setUser((String) localObject);
     localRefAddr = localReference.get("password");
     if (localRefAddr == null) {
       localObject = "";
     } else {
       localObject = localReference.get("password").getContent();
       if (!(localObject instanceof String))
         throw new Exception(str1 + ": invalid RefAddr: password");
     }
     localJDBCCommonDataSource.setPassword((String) localObject);
     localRefAddr = localReference.get("loginTimeout");
     if (localRefAddr != null) {
       localObject = localRefAddr.getContent();
       if ((localObject instanceof String)) {
         String str2 = ((String) localObject).trim();
         if (str2.length() > 0)
           try {
             localJDBCCommonDataSource.setLoginTimeout(Integer.parseInt(str2));
           } catch (NumberFormatException localNumberFormatException) {
           }
       }
     }
     return localJDBCCommonDataSource;
   }
   return null;
 }
  private String nullSafeRefAddrStringGet(String referenceName, Reference ref) {
    RefAddr refAddr = ref.get(referenceName);

    String asString = refAddr != null ? (String) refAddr.getContent() : null;

    return asString;
  }
  /**
   * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name,
   *     javax.naming.Context, java.util.Hashtable)
   */
  public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment)
      throws Exception {
    Object ret = null;
    if (obj instanceof Reference) {
      Reference ref = (Reference) obj;
      RefAddr ra = ref.get("com.atomikos.serializable");
      if (ra != null) {
        byte[] bytes = (byte[]) ra.getContent();
        ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
        ObjectInputStream in =
            new ObjectInputStream(bin) {
              protected Class resolveClass(ObjectStreamClass desc)
                  throws IOException, ClassNotFoundException {
                try {
                  // try default class loading
                  return super.resolveClass(desc);
                } catch (ClassNotFoundException ex) {
                  // try the context class loader - happens in OSGi?
                  return Thread.currentThread().getContextClassLoader().loadClass(desc.getName());
                }
              }
            };
        ret = in.readObject();
        in.close();
      }
    }

    return ret;
  }
  /** JNDI object factory so the proxy can be used as a resource. */
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;

    String api = null;
    String url = null;
    String user = null;
    String password = null;

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);

      String type = addr.getType();
      String value = (String) addr.getContent();

      if (type.equals("type")) api = value;
      else if (type.equals("url")) url = value;
      else if (type.equals("user")) setUser(value);
      else if (type.equals("password")) setPassword(value);
    }

    if (url == null) throw new NamingException("`url' must be configured for HessianProxyFactory.");
    // XXX: could use meta protocol to grab this
    if (api == null)
      throw new NamingException("`type' must be configured for HessianProxyFactory.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class apiClass = Class.forName(api, false, loader);

    return create(apiClass, url);
  }
  /**
   * Create and return a new <code>BasicDataSource</code> instance. If no instance can be created,
   * return <code>null</code> instead.
   *
   * @param obj The possibly null object containing location or reference information that can be
   *     used in creating an object
   * @param name The name of this object relative to <code>nameCtx</code>
   * @param nameCtx The context relative to which the <code>name</code> parameter is specified, or
   *     <code>null</code> if <code>name</code> is relative to the default initial context
   * @param environment The possibly null environment that is used in creating this object
   * @exception Exception if an exception occurs creating the instance
   */
  public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment)
      throws Exception {

    // We only know how to deal with <code>javax.naming.Reference</code>s
    // that specify a class name of "javax.sql.DataSource"
    if ((obj == null) || !(obj instanceof Reference)) {
      return null;
    }
    Reference ref = (Reference) obj;
    if (!"javax.sql.DataSource".equals(ref.getClassName())) {
      return null;
    }

    Properties properties = new Properties();
    for (int i = 0; i < ALL_PROPERTIES.length; i++) {
      String propertyName = ALL_PROPERTIES[i];
      RefAddr ra = ref.get(propertyName);
      if (ra != null) {
        String propertyValue = ra.getContent().toString();
        properties.setProperty(propertyName, propertyValue);
      }
    }

    return createDataSource(properties);
  }
Beispiel #9
0
  @Test
  public void testGetObjectInstance() throws Exception {
    config.setAcquireIncrement(5);
    config.setMinConnectionsPerPartition(30);
    config.setMaxConnectionsPerPartition(100);
    config.setPartitionCount(1);

    Reference mockRef = createNiceMock(Reference.class);
    Enumeration<RefAddr> mockEnum = createNiceMock(Enumeration.class);
    RefAddr mockRefAddr = createNiceMock(RefAddr.class);
    expect(mockRef.getAll()).andReturn(mockEnum).anyTimes();
    expect(mockEnum.hasMoreElements()).andReturn(true).times(2);

    expect(mockEnum.nextElement()).andReturn(mockRefAddr).anyTimes();
    expect(mockRefAddr.getType())
        .andReturn("driverClassName")
        .once()
        .andReturn("password")
        .times(2);
    expect(mockRefAddr.getContent())
        .andReturn("com.jolbox.bonecp.MockJDBCDriver")
        .once()
        .andReturn("abcdefgh")
        .once();
    replay(mockRef, mockEnum, mockRefAddr);
    BoneCPDataSource dsb = new BoneCPDataSource();
    BoneCPDataSource result = (BoneCPDataSource) dsb.getObjectInstance(mockRef, null, null, null);
    assertEquals("abcdefgh", result.getPassword());
    verify(mockRef, mockEnum, mockRefAddr);
  }
    public Object getObjectInstance(Object arg0, Name arg1, Context arg2, Hashtable arg3)
        throws Exception {
      Reference ref = (Reference) arg0;

      RefAddr refAddr = ref.get(0);
      String valueName = refAddr.getType();
      if (!valueName.equalsIgnoreCase("val"))
        throw new RuntimeException("Unrecognized refaddr type = " + valueName);

      String value = (String) refAddr.getContent();

      return new SomeObject(Integer.parseInt(value.trim()));
    }
  /**
   * Crete a new Resource env instance.
   *
   * @param obj The reference object describing the DataSource
   */
  public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment)
      throws Exception {

    if (obj instanceof ResourceEnvRef) {
      Reference ref = (Reference) obj;
      ObjectFactory factory = null;
      RefAddr factoryRefAddr = ref.get(Constants.FACTORY);
      if (factoryRefAddr != null) {
        // Using the specified factory
        String factoryClassName = factoryRefAddr.getContent().toString();
        // Loading factory
        ClassLoader tcl = Thread.currentThread().getContextClassLoader();
        Class factoryClass = null;
        if (tcl != null) {
          try {
            factoryClass = tcl.loadClass(factoryClassName);
          } catch (ClassNotFoundException e) {
            NamingException ex = new NamingException("Could not load resource factory class");
            ex.initCause(e);
            throw ex;
          }
        } else {
          try {
            factoryClass = Class.forName(factoryClassName);
          } catch (ClassNotFoundException e) {
            NamingException ex = new NamingException("Could not load resource factory class");
            ex.initCause(e);
            throw ex;
          }
        }
        if (factoryClass != null) {
          try {
            factory = (ObjectFactory) factoryClass.newInstance();
          } catch (Throwable t) {
            if (t instanceof NamingException) throw (NamingException) t;
            NamingException ex = new NamingException("Could not create resource factory instance");
            ex.initCause(t);
            throw ex;
          }
        }
      }
      // Note: No defaults here
      if (factory != null) {
        return factory.getObjectInstance(obj, name, nameCtx, environment);
      } else {
        throw new NamingException("Cannot create resource instance");
      }
    }

    return null;
  }
Beispiel #12
0
  /*
   * Ref has no factory.  For each address of type "URL", try its URL
   * context factory.  Returns null if unsuccessful in creating and
   * invoking a factory.
   */
  static Object processURLAddrs(
      Reference ref, Name name, Context nameCtx, Hashtable<?, ?> environment)
      throws NamingException {

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);
      if (addr instanceof StringRefAddr && addr.getType().equalsIgnoreCase("URL")) {

        String url = (String) addr.getContent();
        Object answer = processURL(url, name, nameCtx, environment);
        if (answer != null) {
          return answer;
        }
      }
    }
    return null;
  }
  /**
   * Create and return a new <code>BasicDataSource</code> instance. If no instance can be created,
   * return <code>null</code> instead.
   *
   * @param obj The possibly null object containing location or reference information that can be
   *     used in creating an object
   * @param name The name of this object relative to <code>nameCtx</code>
   * @param nameCtx The context relative to which the <code>name</code> parameter is specified, or
   *     <code>null</code> if <code>name</code> is relative to the default initial context
   * @param environment The possibly null environment that is used in creating this object
   * @exception Exception if an exception occurs creating the instance
   */
  @Override
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {

    // We only know how to deal with <code>javax.naming.Reference</code>s
    // that specify a class name of "javax.sql.DataSource"
    if ((obj == null) || !(obj instanceof Reference)) {
      return null;
    }
    Reference ref = (Reference) obj;
    boolean XA = false;
    boolean ok = false;
    if ("javax.sql.DataSource".equals(ref.getClassName())) {
      ok = true;
    }
    if ("javax.sql.XADataSource".equals(ref.getClassName())) {
      ok = true;
      XA = true;
    }
    if (org.apache.tomcat.jdbc.pool.DataSource.class.getName().equals(ref.getClassName())) {
      ok = true;
    }

    if (!ok) {
      log.warn(ref.getClassName() + " is not a valid class name/type for this JNDI factory.");
      return null;
    }

    Properties properties = new Properties();
    for (int i = 0; i < ALL_PROPERTIES.length; i++) {
      String propertyName = ALL_PROPERTIES[i];
      RefAddr ra = ref.get(propertyName);
      if (ra != null) {
        String propertyValue = ra.getContent().toString();
        properties.setProperty(propertyName, propertyValue);
      }
    }

    return createDataSource(properties, nameCtx, XA);
  }
  /** Return a String rendering of this object. */
  @Override
  public String toString() {

    StringBuilder sb = new StringBuilder("HandlerRef[");
    sb.append("className=");
    sb.append(getClassName());
    sb.append(",factoryClassLocation=");
    sb.append(getFactoryClassLocation());
    sb.append(",factoryClassName=");
    sb.append(getFactoryClassName());
    Enumeration<RefAddr> refAddrs = getAll();
    while (refAddrs.hasMoreElements()) {
      RefAddr refAddr = refAddrs.nextElement();
      sb.append(",{type=");
      sb.append(refAddr.getType());
      sb.append(",content=");
      sb.append(refAddr.getContent());
      sb.append("}");
    }
    sb.append("]");
    return (sb.toString());
  }
  public Object lookup(String name) throws NamingException {
    name = trimSlashes(name);
    int i = name.indexOf("/");
    String tok = i == -1 ? name : name.substring(0, i);
    Object value = map.get(tok);
    if (value == null) {
      throw new NameNotFoundException("Name not found: " + tok);
    }
    if (value instanceof InVMContext && i != -1) {
      return ((InVMContext) value).lookup(name.substring(i));
    }
    if (value instanceof Reference) {
      Reference ref = (Reference) value;
      RefAddr refAddr = ref.get("nns");

      // we only deal with references create by NonSerializableFactory
      String key = (String) refAddr.getContent();
      return NonSerializableFactory.lookup(key);
    } else {
      return value;
    }
  }
Beispiel #16
0
  /**
   * Create a new Bean instance.
   *
   * @param obj The reference object describing the Bean
   */
  @Override
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws NamingException {

    if (obj instanceof ResourceRef) {

      try {

        Reference ref = (Reference) obj;
        String beanClassName = ref.getClassName();
        Class<?> beanClass = null;
        ClassLoader tcl = Thread.currentThread().getContextClassLoader();
        if (tcl != null) {
          try {
            beanClass = tcl.loadClass(beanClassName);
          } catch (ClassNotFoundException e) {
          }
        } else {
          try {
            beanClass = Class.forName(beanClassName);
          } catch (ClassNotFoundException e) {
            e.printStackTrace();
          }
        }
        if (beanClass == null) {
          throw new NamingException("Class not found: " + beanClassName);
        }

        BeanInfo bi = Introspector.getBeanInfo(beanClass);
        PropertyDescriptor[] pda = bi.getPropertyDescriptors();

        Object bean = beanClass.newInstance();

        /* Look for properties with explicitly configured setter */
        RefAddr ra = ref.get("forceString");
        Map<String, Method> forced = new HashMap<String, Method>();
        String value;

        if (ra != null) {
          value = (String) ra.getContent();
          Class<?> paramTypes[] = new Class[1];
          paramTypes[0] = String.class;
          String setterName;
          int index;

          /* Items are given as comma separated list */
          for (String param : value.split(",")) {
            param = param.trim();
            /* A single item can either be of the form name=method
             * or just a property name (and we will use a standard
             * setter) */
            index = param.indexOf('=');
            if (index >= 0) {
              setterName = param.substring(index + 1).trim();
              param = param.substring(0, index).trim();
            } else {
              setterName =
                  "set" + param.substring(0, 1).toUpperCase(Locale.ENGLISH) + param.substring(1);
            }
            try {
              forced.put(param, beanClass.getMethod(setterName, paramTypes));
            } catch (NoSuchMethodException ex) {
              throw new NamingException(
                  "Forced String setter " + setterName + " not found for property " + param);
            } catch (SecurityException ex) {
              throw new NamingException(
                  "Forced String setter " + setterName + " not allowed for property " + param);
            }
          }
        }

        Enumeration<RefAddr> e = ref.getAll();

        while (e.hasMoreElements()) {

          ra = e.nextElement();
          String propName = ra.getType();

          if (propName.equals(Constants.FACTORY)
              || propName.equals("scope")
              || propName.equals("auth")
              || propName.equals("forceString")
              || propName.equals("singleton")) {
            continue;
          }

          value = (String) ra.getContent();

          Object[] valueArray = new Object[1];

          /* Shortcut for properties with explicitly configured setter */
          Method method = forced.get(propName);
          if (method != null) {
            valueArray[0] = value;
            try {
              method.invoke(bean, valueArray);
            } catch (IllegalAccessException ex) {
              throw new NamingException(
                  "Forced String setter "
                      + method.getName()
                      + " threw IllegalAccessException for property "
                      + propName);
            } catch (IllegalArgumentException ex) {
              throw new NamingException(
                  "Forced String setter "
                      + method.getName()
                      + " threw IllegalArgumentException for property "
                      + propName);
            } catch (InvocationTargetException ex) {
              throw new NamingException(
                  "Forced String setter "
                      + method.getName()
                      + " threw InvocationTargetException for property "
                      + propName);
            }
            continue;
          }

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

            if (pda[i].getName().equals(propName)) {

              Class<?> propType = pda[i].getPropertyType();

              if (propType.equals(String.class)) {
                valueArray[0] = value;
              } else if (propType.equals(Character.class) || propType.equals(char.class)) {
                valueArray[0] = Character.valueOf(value.charAt(0));
              } else if (propType.equals(Byte.class) || propType.equals(byte.class)) {
                valueArray[0] = Byte.valueOf(value);
              } else if (propType.equals(Short.class) || propType.equals(short.class)) {
                valueArray[0] = Short.valueOf(value);
              } else if (propType.equals(Integer.class) || propType.equals(int.class)) {
                valueArray[0] = Integer.valueOf(value);
              } else if (propType.equals(Long.class) || propType.equals(long.class)) {
                valueArray[0] = Long.valueOf(value);
              } else if (propType.equals(Float.class) || propType.equals(float.class)) {
                valueArray[0] = Float.valueOf(value);
              } else if (propType.equals(Double.class) || propType.equals(double.class)) {
                valueArray[0] = Double.valueOf(value);
              } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) {
                valueArray[0] = Boolean.valueOf(value);
              } else {
                throw new NamingException(
                    "String conversion for property "
                        + propName
                        + " of type '"
                        + propType.getName()
                        + "' not available");
              }

              Method setProp = pda[i].getWriteMethod();
              if (setProp != null) {
                setProp.invoke(bean, valueArray);
              } else {
                throw new NamingException("Write not allowed for property: " + propName);
              }

              break;
            }
          }

          if (i == pda.length) {
            throw new NamingException("No set method found for property: " + propName);
          }
        }

        return bean;

      } catch (java.beans.IntrospectionException ie) {
        NamingException ne = new NamingException(ie.getMessage());
        ne.setRootCause(ie);
        throw ne;
      } catch (java.lang.IllegalAccessException iae) {
        NamingException ne = new NamingException(iae.getMessage());
        ne.setRootCause(iae);
        throw ne;
      } catch (java.lang.InstantiationException ie2) {
        NamingException ne = new NamingException(ie2.getMessage());
        ne.setRootCause(ie2);
        throw ne;
      } catch (java.lang.reflect.InvocationTargetException ite) {
        Throwable cause = ite.getCause();
        if (cause instanceof ThreadDeath) {
          throw (ThreadDeath) cause;
        }
        if (cause instanceof VirtualMachineError) {
          throw (VirtualMachineError) cause;
        }
        NamingException ne = new NamingException(ite.getMessage());
        ne.setRootCause(ite);
        throw ne;
      }

    } else {
      return null;
    }
  }
  /** implements ObjectFactory to create an instance of this class */
  public Object getObjectInstance(Object refObj, Name name, Context context, Hashtable env)
      throws Exception {
    // The spec says to return null if we can't create an instance
    // of the reference
    Jdbc2PoolDataSource ds = null;
    if (refObj instanceof Reference) {
      Reference ref = (Reference) refObj;

      if (ref.getClassName().equals(getClass().getName())) {
        RefAddr ra = ref.get("isNew");
        if (ra != null && ra.getContent() != null) {
          isNew = Boolean.valueOf(ra.getContent().toString()).booleanValue();
        }

        ra = ref.get("instanceKey");
        if (ra != null && ra.getContent() != null) {
          instanceKey = new Integer(ra.getContent().toString());
        }

        ra = ref.get("dataSourceName");
        if (ra != null && ra.getContent() != null) {
          setDataSourceName(ra.getContent().toString());
        }

        ra = ref.get("defaultAutoCommit");
        if (ra != null && ra.getContent() != null) {
          setDefaultAutoCommit(Boolean.valueOf(ra.getContent().toString()).booleanValue());
        }

        ra = ref.get("defaultMaxActive");
        if (ra != null && ra.getContent() != null) {
          setDefaultMaxActive(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("defaultMaxIdle");
        if (ra != null && ra.getContent() != null) {
          setDefaultMaxIdle(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("defaultMaxWait");
        if (ra != null && ra.getContent() != null) {
          setDefaultMaxWait(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("defaultReadOnly");
        if (ra != null && ra.getContent() != null) {
          setDefaultReadOnly(Boolean.valueOf(ra.getContent().toString()).booleanValue());
        }

        ra = ref.get("description");
        if (ra != null && ra.getContent() != null) {
          setDescription(ra.getContent().toString());
        }

        ra = ref.get("jndiEnvironment");
        if (ra != null && ra.getContent() != null) {
          byte[] serialized = (byte[]) ra.getContent();
          jndiEnvironment = (Properties) deserialize(serialized);
        }

        ra = ref.get("loginTimeout");
        if (ra != null && ra.getContent() != null) {
          setLoginTimeout(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("perUserDefaultAutoCommit");
        if (ra != null && ra.getContent() != null) {
          byte[] serialized = (byte[]) ra.getContent();
          perUserDefaultAutoCommit = (Map) deserialize(serialized);
        }

        ra = ref.get("perUserMaxActive");
        if (ra != null && ra.getContent() != null) {
          byte[] serialized = (byte[]) ra.getContent();
          perUserMaxActive = (Map) deserialize(serialized);
        }

        ra = ref.get("perUserMaxIdle");
        if (ra != null && ra.getContent() != null) {
          byte[] serialized = (byte[]) ra.getContent();
          perUserMaxIdle = (Map) deserialize(serialized);
        }

        ra = ref.get("perUserMaxWait");
        if (ra != null && ra.getContent() != null) {
          byte[] serialized = (byte[]) ra.getContent();
          perUserMaxWait = (Map) deserialize(serialized);
        }

        ra = ref.get("perUserDefaultReadOnly");
        if (ra != null && ra.getContent() != null) {
          byte[] serialized = (byte[]) ra.getContent();
          perUserDefaultReadOnly = (Map) deserialize(serialized);
        }

        ra = ref.get("testOnBorrow");
        if (ra != null && ra.getContent() != null) {
          setTestOnBorrow(Boolean.valueOf(ra.getContent().toString()).booleanValue());
        }

        ra = ref.get("testOnReturn");
        if (ra != null && ra.getContent() != null) {
          setTestOnReturn(Boolean.valueOf(ra.getContent().toString()).booleanValue());
        }

        ra = ref.get("timeBetweenEvictionRunsMillis");
        if (ra != null && ra.getContent() != null) {
          setTimeBetweenEvictionRunsMillis(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("numTestsPerEvictionRun");
        if (ra != null && ra.getContent() != null) {
          setNumTestsPerEvictionRun(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("minEvictableIdleTimeMillis");
        if (ra != null && ra.getContent() != null) {
          setMinEvictableIdleTimeMillis(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("testWhileIdle");
        if (ra != null && ra.getContent() != null) {
          setTestWhileIdle(Boolean.valueOf(ra.getContent().toString()).booleanValue());
        }

        ra = ref.get("validationQuery");
        if (ra != null && ra.getContent() != null) {
          setValidationQuery(ra.getContent().toString());
        }
        ds = this;
      }
    }
    return ds;
  }
Beispiel #18
0
  /**
   * Create a new Bean instance.
   *
   * @param obj The reference object describing the Bean
   */
  @Override
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws NamingException {

    if (obj instanceof ResourceRef) {

      try {

        Reference ref = (Reference) obj;
        String beanClassName = ref.getClassName();
        Class<?> beanClass = null;
        ClassLoader tcl = Thread.currentThread().getContextClassLoader();
        if (tcl != null) {
          try {
            beanClass = tcl.loadClass(beanClassName);
          } catch (ClassNotFoundException e) {
          }
        } else {
          try {
            beanClass = Class.forName(beanClassName);
          } catch (ClassNotFoundException e) {
            e.printStackTrace();
          }
        }
        if (beanClass == null) {
          throw new NamingException("Class not found: " + beanClassName);
        }

        BeanInfo bi = Introspector.getBeanInfo(beanClass);
        PropertyDescriptor[] pda = bi.getPropertyDescriptors();

        Object bean = beanClass.newInstance();

        Enumeration<RefAddr> e = ref.getAll();
        while (e.hasMoreElements()) {

          RefAddr ra = e.nextElement();
          String propName = ra.getType();

          if (propName.equals(Constants.FACTORY)
              || propName.equals("scope")
              || propName.equals("auth")
              || propName.equals("singleton")) {
            continue;
          }

          String value = (String) ra.getContent();

          Object[] valueArray = new Object[1];

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

            if (pda[i].getName().equals(propName)) {

              Class<?> propType = pda[i].getPropertyType();

              if (propType.equals(String.class)) {
                valueArray[0] = value;
              } else if (propType.equals(Character.class) || propType.equals(char.class)) {
                valueArray[0] = Character.valueOf(value.charAt(0));
              } else if (propType.equals(Byte.class) || propType.equals(byte.class)) {
                valueArray[0] = new Byte(value);
              } else if (propType.equals(Short.class) || propType.equals(short.class)) {
                valueArray[0] = new Short(value);
              } else if (propType.equals(Integer.class) || propType.equals(int.class)) {
                valueArray[0] = new Integer(value);
              } else if (propType.equals(Long.class) || propType.equals(long.class)) {
                valueArray[0] = new Long(value);
              } else if (propType.equals(Float.class) || propType.equals(float.class)) {
                valueArray[0] = new Float(value);
              } else if (propType.equals(Double.class) || propType.equals(double.class)) {
                valueArray[0] = new Double(value);
              } else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) {
                valueArray[0] = Boolean.valueOf(value);
              } else {
                throw new NamingException(
                    "String conversion for property type '"
                        + propType.getName()
                        + "' not available");
              }

              Method setProp = pda[i].getWriteMethod();
              if (setProp != null) {
                setProp.invoke(bean, valueArray);
              } else {
                throw new NamingException("Write not allowed for property: " + propName);
              }

              break;
            }
          }

          if (i == pda.length) {
            throw new NamingException("No set method found for property: " + propName);
          }
        }

        return bean;

      } catch (java.beans.IntrospectionException ie) {
        NamingException ne = new NamingException(ie.getMessage());
        ne.setRootCause(ie);
        throw ne;
      } catch (java.lang.IllegalAccessException iae) {
        NamingException ne = new NamingException(iae.getMessage());
        ne.setRootCause(iae);
        throw ne;
      } catch (java.lang.InstantiationException ie2) {
        NamingException ne = new NamingException(ie2.getMessage());
        ne.setRootCause(ie2);
        throw ne;
      } catch (java.lang.reflect.InvocationTargetException ite) {
        NamingException ne = new NamingException(ite.getMessage());
        ne.setRootCause(ite);
        throw ne;
      }

    } else {
      return null;
    }
  }
  /** implements ObjectFactory to create an instance of this class */
  public Object getObjectInstance(Object refObj, Name name, Context context, Hashtable env)
      throws Exception {
    // The spec says to return null if we can't create an instance
    // of the reference
    DriverAdapterCPDS cpds = null;
    if (refObj instanceof Reference) {
      Reference ref = (Reference) refObj;
      if (ref.getClassName().equals(getClass().getName())) {
        RefAddr ra = ref.get("description");
        if (ra != null && ra.getContent() != null) {
          setDescription(ra.getContent().toString());
        }

        ra = ref.get("driver");
        if (ra != null && ra.getContent() != null) {
          setDriver(ra.getContent().toString());
        }
        ra = ref.get("url");
        if (ra != null && ra.getContent() != null) {
          setUrl(ra.getContent().toString());
        }
        ra = ref.get("user");
        if (ra != null && ra.getContent() != null) {
          setUser(ra.getContent().toString());
        }
        ra = ref.get("password");
        if (ra != null && ra.getContent() != null) {
          setPassword(ra.getContent().toString());
        }

        ra = ref.get("poolPreparedStatements");
        if (ra != null && ra.getContent() != null) {
          setPoolPreparedStatements(Boolean.valueOf(ra.getContent().toString()).booleanValue());
        }
        ra = ref.get("maxActive");
        if (ra != null && ra.getContent() != null) {
          setMaxActive(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("maxIdle");
        if (ra != null && ra.getContent() != null) {
          setMaxIdle(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("timeBetweenEvictionRunsMillis");
        if (ra != null && ra.getContent() != null) {
          setTimeBetweenEvictionRunsMillis(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("numTestsPerEvictionRun");
        if (ra != null && ra.getContent() != null) {
          setNumTestsPerEvictionRun(Integer.parseInt(ra.getContent().toString()));
        }

        ra = ref.get("minEvictableIdleTimeMillis");
        if (ra != null && ra.getContent() != null) {
          setMinEvictableIdleTimeMillis(Integer.parseInt(ra.getContent().toString()));
        }
        ra = ref.get("maxPreparedStatements");
        if (ra != null && ra.getContent() != null) {
          setMaxPreparedStatements(Integer.parseInt(ra.getContent().toString()));
        }

        cpds = this;
      }
    }
    return cpds;
  }