Java Code Examples for javax.naming.Reference#add()

The following examples show how to use javax.naming.Reference#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DriverAdapterCPDS.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
/**
 * Implements {@link Referenceable}.
 */
@Override
public Reference getReference() throws NamingException {
    // this class implements its own factory
    final String factory = getClass().getName();

    final Reference ref = new Reference(getClass().getName(), factory, null);

    ref.add(new StringRefAddr("description", getDescription()));
    ref.add(new StringRefAddr("driver", getDriver()));
    ref.add(new StringRefAddr("loginTimeout", String.valueOf(getLoginTimeout())));
    ref.add(new StringRefAddr(KEY_PASSWORD, getPassword()));
    ref.add(new StringRefAddr(KEY_USER, getUser()));
    ref.add(new StringRefAddr("url", getUrl()));

    ref.add(new StringRefAddr("poolPreparedStatements", String.valueOf(isPoolPreparedStatements())));
    ref.add(new StringRefAddr("maxIdle", String.valueOf(getMaxIdle())));
    ref.add(new StringRefAddr("timeBetweenEvictionRunsMillis", String.valueOf(getTimeBetweenEvictionRunsMillis())));
    ref.add(new StringRefAddr("numTestsPerEvictionRun", String.valueOf(getNumTestsPerEvictionRun())));
    ref.add(new StringRefAddr("minEvictableIdleTimeMillis", String.valueOf(getMinEvictableIdleTimeMillis())));
    ref.add(new StringRefAddr("maxPreparedStatements", String.valueOf(getMaxPreparedStatements())));

    return ref;
}
 
Example 2
Source File: TestBasicDataSourceFactory.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateProperties() throws Exception {
    try {
        StackMessageLog.lock();
        StackMessageLog.clear();
        final Reference ref = new Reference("javax.sql.DataSource", BasicDataSourceFactory.class.getName(), null);
        ref.add(new StringRefAddr("foo", "bar")); // Unknown
        ref.add(new StringRefAddr("maxWait", "100")); // Changed
        ref.add(new StringRefAddr("driverClassName", "org.apache.commons.dbcp2.TesterDriver")); // OK
        final BasicDataSourceFactory basicDataSourceFactory = new BasicDataSourceFactory();
        basicDataSourceFactory.getObjectInstance(ref, null, null, null);
        final List<String> messages = StackMessageLog.getAll();
        assertEquals(2, messages.size(), messages.toString());
        for (final String message : messages) {
            if (message.contains("maxWait")) {
                assertTrue(message.contains("use maxWaitMillis"));
            } else {
                assertTrue(message.contains("foo"));
                assertTrue(message.contains("Ignoring unknown property"));
            }
        }
    } finally {
        StackMessageLog.clear();
        StackMessageLog.unLock();
    }
}
 
Example 3
Source File: TestFactory.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testJNDI2Pools() throws Exception {
    final Reference refObj = new Reference(SharedPoolDataSource.class.getName());
    refObj.add(new StringRefAddr("dataSourceName","java:comp/env/jdbc/bookstoreCPDS"));
    final Context context = new InitialContext();
    final Hashtable<?, ?> env = new Hashtable<>();

    final ObjectFactory factory = new SharedPoolDataSourceFactory();

    final Name name = new CompositeName("myDB");
    final Object obj = factory.getObjectInstance(refObj, name, context, env);
    assertNotNull(obj);

    final Name name2 = new CompositeName("myDB2");
    final Object obj2 = factory.getObjectInstance(refObj, name2, context, env);
    assertNotNull(obj2);
}
 
Example 4
Source File: TestBasicDataSourceFactory.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllProperties() throws Exception {
    try {
        StackMessageLog.lock();
        StackMessageLog.clear();
        final Reference ref = new Reference("javax.sql.DataSource",
                                      BasicDataSourceFactory.class.getName(), null);
        final Properties properties = getTestProperties();
        for (final Entry<Object, Object> entry : properties.entrySet()) {
            ref.add(new StringRefAddr((String) entry.getKey(), (String) entry.getValue()));
        }
        final BasicDataSourceFactory basicDataSourceFactory = new BasicDataSourceFactory();
        final BasicDataSource ds = (BasicDataSource) basicDataSourceFactory.getObjectInstance(ref, null, null, null);
        checkDataSourceProperties(ds);
        checkConnectionPoolProperties(ds.getConnectionPool());
        final List<String> messages = StackMessageLog.getAll();
        assertEquals(0,messages.size());
    } finally {
        StackMessageLog.clear();
        StackMessageLog.unLock();
    }
}
 
Example 5
Source File: MysqlDataSource.java    From r-course with MIT License 6 votes vote down vote up
/**
 * Required method to support this class as a <CODE>Referenceable</CODE>.
 * 
 * @return a Reference to this data source
 * 
 * @throws NamingException
 *             if a JNDI error occurs
 */
public Reference getReference() throws NamingException {
    String factoryName = "com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory";
    Reference ref = new Reference(getClass().getName(), factoryName, null);
    ref.add(new StringRefAddr(NonRegisteringDriver.USER_PROPERTY_KEY, getUser()));
    ref.add(new StringRefAddr(NonRegisteringDriver.PASSWORD_PROPERTY_KEY, this.password));
    ref.add(new StringRefAddr("serverName", getServerName()));
    ref.add(new StringRefAddr("port", "" + getPort()));
    ref.add(new StringRefAddr("databaseName", getDatabaseName()));
    ref.add(new StringRefAddr("url", getUrl()));
    ref.add(new StringRefAddr("explicitUrl", String.valueOf(this.explicitUrl)));

    //
    // Now store all of the 'non-standard' properties...
    //
    try {
        storeToRef(ref);
    } catch (SQLException sqlEx) {
        throw new NamingException(sqlEx.getMessage());
    }

    return ref;
}
 
Example 6
Source File: JDBCPool.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the Reference of this object.
 *
 * @return The non-null Reference of this object.
 * @exception NamingException If a naming exception was encountered
 *          while retrieving the reference.
 */
public Reference getReference() throws NamingException {
    String    cname = "org.hsqldb.jdbc.JDBCDataSourceFactory";
    Reference ref   = new Reference(getClass().getName(), cname, null);

    ref.add(new StringRefAddr("database", source.getDatabase()));
    ref.add(new StringRefAddr("user", source.getUser()));
    ref.add(new StringRefAddr("password", source.password));
    ref.add(new StringRefAddr("loginTimeout",
                              Integer.toString(source.loginTimeout)));
    ref.add(new StringRefAddr("poolSize", Integer.toString(connections.length)));

    return ref;
}
 
Example 7
Source File: SharedPoolDataSource.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Returns a <code>SharedPoolDataSource</code> {@link Reference}.
 */
@Override
public Reference getReference() throws NamingException {
    final Reference ref = new Reference(getClass().getName(), SharedPoolDataSourceFactory.class.getName(), null);
    ref.add(new StringRefAddr("instanceKey", getInstanceKey()));
    return ref;
}
 
Example 8
Source File: MysqlDataSource.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Required method to support this class as a <CODE>Referenceable</CODE>.
 * 
 * @return a Reference to this data source
 * 
 * @throws NamingException
 *             if a JNDI error occurs
 */
@Override
public Reference getReference() throws NamingException {
    String factoryName = MysqlDataSourceFactory.class.getName();
    Reference ref = new Reference(getClass().getName(), factoryName, null);
    ref.add(new StringRefAddr(PropertyKey.USER.getKeyName(), getUser()));
    ref.add(new StringRefAddr(PropertyKey.PASSWORD.getKeyName(), this.password));
    ref.add(new StringRefAddr("serverName", getServerName()));
    ref.add(new StringRefAddr("port", "" + getPort()));
    ref.add(new StringRefAddr("databaseName", getDatabaseName()));
    ref.add(new StringRefAddr("url", getUrl()));
    ref.add(new StringRefAddr("explicitUrl", String.valueOf(this.explicitUrl)));

    //
    // Now store all of the 'non-standard' properties...
    //
    for (PropertyKey propKey : PropertyDefinitions.PROPERTY_KEY_TO_PROPERTY_DEFINITION.keySet()) {
        RuntimeProperty<?> propToStore = getProperty(propKey);

        String val = propToStore.getStringValue();
        if (val != null) {
            ref.add(new StringRefAddr(propToStore.getPropertyDefinition().getName(), val));
        }

    }

    return ref;
}
 
Example 9
Source File: JDBCPooledDataSource.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the Reference of this object.
 *
 * @return The non-null javax.naming.Reference of this object.
 * @exception NamingException If a naming exception was encountered
 *          while retrieving the reference.
 */
public Reference getReference() throws NamingException {

    String    cname = "org.hsqldb.jdbc.JDBCDataSourceFactory";
    Reference ref   = new Reference(getClass().getName(), cname, null);

    ref.add(new StringRefAddr("database", getDatabase()));
    ref.add(new StringRefAddr("user", getUser()));
    ref.add(new StringRefAddr("password", password));
    ref.add(new StringRefAddr("loginTimeout",
                              Integer.toString(loginTimeout)));

    return ref;
}
 
Example 10
Source File: PerUserPoolDataSource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a <code>PerUserPoolDataSource</code> {@link Reference}.
 */
@Override
public Reference getReference() throws NamingException {
    final Reference ref = new Reference(getClass().getName(), PerUserPoolDataSourceFactory.class.getName(), null);
    ref.add(new StringRefAddr("instanceKey", getInstanceKey()));
    return ref;
}
 
Example 11
Source File: ElasticSearchDruidDataSource.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
public Reference getReference() throws NamingException {
    final String className = getClass().getName();
    final String factoryName = className + "Factory"; // XXX: not robust
    Reference ref = new Reference(className, factoryName, null);
    ref.add(new StringRefAddr("instanceKey", instanceKey));
    ref.add(new StringRefAddr("url", this.getUrl()));
    ref.add(new StringRefAddr("username", this.getUsername()));
    ref.add(new StringRefAddr("password", this.getPassword()));
    // TODO ADD OTHER PROPERTIES
    return ref;
}
 
Example 12
Source File: NamingContextListener.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Set the specified resource link in the naming context.
 *
 * @param resourceLink the resource link
 */
public void addResourceLink(ContextResourceLink resourceLink) {

    // Create a reference to the resource.
    Reference ref = new ResourceLinkRef
        (resourceLink.getType(), resourceLink.getGlobal(), resourceLink.getFactory(), null);
    Iterator<String> i = resourceLink.listProperties();
    while (i.hasNext()) {
        String key = i.next();
        Object val = resourceLink.getProperty(key);
        if (val!=null) {
            StringRefAddr refAddr = new StringRefAddr(key, val.toString());
            ref.add(refAddr);
        }
    }
    javax.naming.Context ctx =
        "UserTransaction".equals(resourceLink.getName())
        ? compCtx : envCtx;
    try {
        if (log.isDebugEnabled())
            log.debug("  Adding resource link " + resourceLink.getName());
        createSubcontexts(envCtx, resourceLink.getName());
        ctx.bind(resourceLink.getName(), ref);
    } catch (NamingException e) {
        log.error(sm.getString("naming.bindFailed", e));
    }

    ResourceLinkFactory.registerGlobalResourceAccess(
            getGlobalNamingContext(), resourceLink.getName(), resourceLink.getGlobal());
}
 
Example 13
Source File: SharedPoolDataSource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a <code>SharedPoolDataSource</code> {@link Reference}.
 */
@Override
public Reference getReference() throws NamingException {
    final Reference ref = new Reference(getClass().getName(), SharedPoolDataSourceFactory.class.getName(), null);
    ref.add(new StringRefAddr("instanceKey", getInstanceKey()));
    return ref;
}
 
Example 14
Source File: JNPStrategy.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void bind(String jndiName, Object o) throws NamingException
{
   if (jndiName == null)
      throw new NamingException();

   if (o == null)
      throw new NamingException();

   Context context = createContext();
   try
   {
      String className = o.getClass().getName();

      if (trace)
         log.trace("Binding " + className + " under " + jndiName);

      Reference ref = new Reference(className,
                                    new StringRefAddr("class", className),
                                    JNPStrategy.class.getName(),
                                    null);
      ref.add(new StringRefAddr("name", jndiName));

      if (objs.putIfAbsent(qualifiedName(jndiName, className), o) != null)
      {
         throw new NamingException(bundle.deploymentFailedSinceJndiNameHasDeployed(className, jndiName));
      }

      if (o instanceof Referenceable)
      {
         Referenceable referenceable = (Referenceable)o;
         referenceable.setReference(ref);
      }
         
      Util.bind(context, jndiName, o);

      if (log.isDebugEnabled())
         log.debug("Bound " + className + " under " + jndiName);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }
}
 
Example 15
Source File: JndiBinder.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Bind
 * @exception Throwable Thrown in case of an error
 */
public void bind() throws Throwable
{
   if (name == null)
      throw new IllegalArgumentException("Name is null");

   if (obj == null)
      throw new IllegalArgumentException("Obj is null");

   if (trace)
      log.trace("Binding " + obj.getClass().getName() + " under " + name);

   Properties properties = new Properties();
   properties.setProperty(Context.PROVIDER_URL, jndiProtocol + "://" + jndiHost + ":" + jndiPort);
   Context context = new InitialContext(properties);

   try
   {
      String className = obj.getClass().getName();
      Reference ref = new Reference(className,
                                    new StringRefAddr("class", className),
                                    JndiBinder.class.getName(),
                                    null);
      ref.add(new StringRefAddr("name", name));

      objs.put(name, obj);

      Util.bind(context, name, ref);

      if (log.isDebugEnabled())
         log.debug("Bound " + obj.getClass().getName() + " under " + name);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }
}
 
Example 16
Source File: SimpleJndiStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String[] bindAdminObjects(String deployment, Object[] aos, String[] jndis) throws Throwable
{
   if (deployment == null)
      throw new IllegalArgumentException("Deployment is null");

   if (deployment.trim().equals(""))
      throw new IllegalArgumentException("Deployment is empty");

   if (aos == null)
      throw new IllegalArgumentException("AOS is null");

   if (aos.length == 0)
      throw new IllegalArgumentException("AOS is empty");

   if (aos.length > 1)
      throw new IllegalArgumentException("SimpleJndiStrategy only support " + 
                                         "a single admin object per deployment");
   if (jndis == null)
      throw new IllegalArgumentException("JNDIs is null");

   if (jndis.length == 0)
      throw new IllegalArgumentException("JNDIs is empty");

   if (jndis.length > 1)
      throw new IllegalArgumentException("SimpleJndiStrategy only support " + 
                                         "a single JNDI name per deployment");

   String jndiName = jndis[0];
   Object ao = aos[0];

   if (log.isTraceEnabled())
      log.tracef("Binding %s under %s", ao.getClass().getName(), jndiName);
   
   if (ao == null)
      throw new IllegalArgumentException("Admin object is null");
   
   if (jndiName == null)
      throw new IllegalArgumentException("JNDI name is null");

   Context context = new InitialContext();
   try
   {
      if (ao instanceof Referenceable)
      {
         String className = ao.getClass().getName();
         Reference ref = new Reference(className,
                                       new StringRefAddr("class", className),
                                       SimpleJndiStrategy.class.getName(),
                                       null);
         ref.add(new StringRefAddr("name", jndiName));

         if (objs.putIfAbsent(qualifiedName(jndiName, className), ao) != null)
            throw new Exception(bundle.deploymentFailedSinceJndiNameHasDeployed(className, jndiName));

         Referenceable referenceable = (Referenceable)ao;
         referenceable.setReference(ref);
      }

      Util.bind(context, jndiName, ao);

      if (log.isDebugEnabled())
         log.debug("Bound " + ao.getClass().getName() + " under " + jndiName);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }

   return new String[] {jndiName};
}
 
Example 17
Source File: JndiBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bind
 * @exception Throwable Thrown in case of an error
 */
public void bind() throws Throwable
{
   if (name == null)
      throw new IllegalArgumentException("Name is null");

   if (obj == null)
      throw new IllegalArgumentException("Obj is null");

   if (log.isTraceEnabled())
      log.tracef("Binding %s under %s", obj.getClass().getName(), name);

   Context context = new InitialContext();
   try
   {
      String className = obj.getClass().getName();
      Reference ref = new Reference(className,
                                    new StringRefAddr("class", className),
                                    JndiBinder.class.getName(),
                                    null);
      ref.add(new StringRefAddr("name", name));

      objs.put(name, obj);

      Util.bind(context, name, ref);

      if (log.isDebugEnabled())
         log.debug("Bound " + obj.getClass().getName() + " under " + name);
   }
   finally
   {
      if (context != null)
      {
         try
         {
            context.close();
         }
         catch (NamingException ne)
         {
            // Ignore
         }
      }
   }
}
 
Example 18
Source File: DecryptingDataSourceFactory.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private void replace( final int idx, final String refType, final String newValue, final Reference ref ) {
  ref.remove( idx );
  ref.add( idx, new StringRefAddr( refType, newValue ) );
}
 
Example 19
Source File: ClientBaseDataSource.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
     * Add Java Bean properties to the reference using
     * StringRefAddr for each property. List of bean properties
     * is defined from the public getXXX() methods on this object
     * that take no arguments and return short, int, boolean or String.
     * The StringRefAddr has a key of the Java bean property name,
     * converted from the method name. E.g. traceDirectory for
     * traceDirectory.
     * 
      */
    private void addBeanProperties(Reference ref)
    {
        // Look for all the getXXX methods in the class that take no arguments.
        Method[] methods = this.getClass().getMethods();
        
        for (int i = 0; i < methods.length; i++) {

            Method m = methods[i];

            // only look for simple getter methods.
            if (m.getParameterTypes().length != 0)
                continue;

            // only non-static methods
            if (Modifier.isStatic(m.getModifiers()))
                continue;

            // Only getXXX methods
            String methodName = m.getName();
            if ((methodName.length() < 5) || !methodName.startsWith("get"))
                continue;

            Class returnType = m.getReturnType();

            if (Integer.TYPE.equals(returnType)
                    || Short.TYPE.equals(returnType)
                    || String.class.equals(returnType)
                    || Boolean.TYPE.equals(returnType)) {

                // setSomeProperty
                // 01234

                String propertyName = methodName.substring(3, 4).toLowerCase(
                        java.util.Locale.ENGLISH).concat(
                        methodName.substring(4));

                try {
// GemStone changes BEGIN
                    Object ov = m.invoke(this, (Object[])null);
                    /* (original code)
                    Object ov = m.invoke(this, null);
                    */
// GemStone changes END
                    String value = ov == null ? null : ov.toString();
                    ref.add(new StringRefAddr(propertyName, value));
                } catch (IllegalAccessException iae) {
                } catch (InvocationTargetException ite) {
                }

            }
        }
    }
 
Example 20
Source File: ReferenceableDataSource.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
	Referenceable method.

	@exception NamingException cannot find named object
 */
public final Reference getReference() throws NamingException 
{
	// These fields will be set by the JNDI server when it decides to
	// materialize a data source.
	Reference ref = new Reference(this.getClass().getName(),
								  "com.pivotal.gemfirexd.internal.jdbc.ReferenceableDataSource",
								  null);


	// Look for all the getXXX methods in the class that take no arguments.
	Method[] methods = this.getClass().getMethods();

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

		Method m = methods[i];

		// only look for simple getter methods.
		if (m.getParameterTypes().length != 0)
			continue;

		// only non-static methods
		if (Modifier.isStatic(m.getModifiers()))
			continue;

		// Only getXXX methods
		String methodName = m.getName();
		if ((methodName.length() < 5) || !methodName.startsWith("get"))
			continue;



		Class returnType = m.getReturnType();

		if (Integer.TYPE.equals(returnType) || STRING_ARG[0].equals(returnType) || Boolean.TYPE.equals(returnType)) {

			// setSomeProperty
			// 01234

			String propertyName = methodName.substring(3,4).toLowerCase(java.util.Locale.ENGLISH).concat(methodName.substring(4));

			try {
				Object ov = m.invoke(this, (Object[])null);

				//Need to check for nullability for all the properties, otherwise
				//rather than null, "null" string gets stored in jndi.
				if (ov != null) {
					ref.add(new StringRefAddr(propertyName, ov.toString()));
				}
			} catch (IllegalAccessException iae) {
			} catch (InvocationTargetException ite) {
			}


		}
	}

	return ref;
}