下面列出了怎么用javax.naming.spi.ObjectFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Resolve a Remote Object: If this object is a reference return the
* reference
* @param o the object to resolve
* @param n the name of this object
* @return a <code>Referenceable</code> if o is a Reference and the
* inititial object o if else
*/
private Object resolveObject(Object o, Name name) {
try {
if (o instanceof Reference) {
// build of the Referenceable object with is Reference
Reference objRef = (Reference) o;
ObjectFactory objFact = (ObjectFactory) (Thread.currentThread().getContextClassLoader()
.loadClass(objRef.getFactoryClassName())).newInstance();
return objFact.getObjectInstance(objRef, name, this, this.getEnvironment());
} else {
return o;
}
} catch (Exception e) {
TraceCarol.error("LmiInitialContext.resolveObject()", e);
return o;
}
}
/**
* Resolve a Remote Object: If this object is a reference return the
* reference
* @param o the object to resolve
* @param n the name of this object
* @return a <code>Referenceable</code> if o is a Reference and the
* inititial object o if else
*/
private Object resolveObject(Object o, Name name) {
try {
if (o instanceof Reference) {
// build of the Referenceable object with is Reference
Reference objRef = (Reference) o;
ObjectFactory objFact = (ObjectFactory) (Thread.currentThread().getContextClassLoader()
.loadClass(objRef.getFactoryClassName())).newInstance();
return objFact.getObjectInstance(objRef, name, this, this.getEnvironment());
} else {
return o;
}
} catch (Exception e) {
TraceCarol.error("LmiInitialContext.resolveObject()", e);
return o;
}
}
protected Object federate(final String compositName) throws NamingException {
final ObjectFactory[] factories = getFederatedFactories();
for (final ObjectFactory factory : factories) {
try {
final CompositeName name = new CompositeName(compositName);
final Object obj = factory.getObjectInstance(null, name, null, null);
if (obj instanceof Context) {
return ((Context) obj).lookup(compositName);
} else if (obj != null) {
return obj;
}
} catch (final Exception doNothing) {
// no-op
}
}
throw new NameNotFoundException("Name \"" + compositName + "\" not found.");
}
@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);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
@Test(timeout = 60000)
public void testBindable() throws Exception {
JmsPoolXAConnectionFactory pcf = createXAPooledConnectionFactory();
assertTrue(pcf instanceof ObjectFactory);
assertTrue(((ObjectFactory)pcf).getObjectInstance(null, null, null, null) instanceof JmsPoolXAConnectionFactory);
assertTrue(pcf.isTmFromJndi());
pcf.stop();
}
@Test(timeout = 60000)
public void testBindableEnvOverrides() throws Exception {
JmsPoolXAConnectionFactory pcf = createXAPooledConnectionFactory();
assertTrue(pcf instanceof ObjectFactory);
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put("tmFromJndi", String.valueOf(Boolean.FALSE));
assertTrue(((ObjectFactory) pcf).getObjectInstance(null, null, null, environment) instanceof JmsPoolXAConnectionFactory);
assertFalse(pcf.isTmFromJndi());
pcf.stop();
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
/**
* Make sure it is possible to create a new data source using
* <code>Referencable</code>, that the new instance has the correct
* default values set for the bean properties and finally that the
* data source can be serialized/deserialized.
*
* @param dsDesc data source descriptor
* @param className data source class name
* @throws Exception on a wide variety of error conditions...
*/
private void assertDataSourceReferenceEmpty(DataSourceDescriptor dsDesc,
String className)
throws Exception {
println("Testing recreated empty data source.");
// Create an empty data source.
Object ds = Class.forName(className).newInstance();
Referenceable refDs = (Referenceable)ds;
Reference dsAsReference = refDs.getReference();
String factoryClassName = dsAsReference.getFactoryClassName();
ObjectFactory factory =
(ObjectFactory)Class.forName(factoryClassName).newInstance();
Object recreatedDs =
factory.getObjectInstance(dsAsReference, null, null, null);
// Empty, recreated data source should not be the same as the one we
// created earlier on.
assertNotNull("Recreated datasource is <null>", recreatedDs);
assertNotSame(recreatedDs, ds);
compareDataSources(dsDesc, ds, recreatedDs, true);
// Serialize and recreate data source with default values.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(ds);
oos.flush();
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
recreatedDs = ois.readObject();
compareDataSources(dsDesc, ds, recreatedDs, true);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
/**
* Make sure it is possible to create a new data source using
* <code>Referencable</code>, that the new instance has the correct
* default values set for the bean properties and finally that the
* data source can be serialized/deserialized.
*
* @param dsDesc data source descriptor
* @param className data source class name
* @throws Exception on a wide variety of error conditions...
*/
private void assertDataSourceReferenceEmpty(DataSourceDescriptor dsDesc,
String className)
throws Exception {
println("Testing recreated empty data source.");
// Create an empty data source.
Object ds = Class.forName(className).newInstance();
Referenceable refDs = (Referenceable)ds;
Reference dsAsReference = refDs.getReference();
String factoryClassName = dsAsReference.getFactoryClassName();
ObjectFactory factory =
(ObjectFactory)Class.forName(factoryClassName).newInstance();
Object recreatedDs =
factory.getObjectInstance(dsAsReference, null, null, null);
// Empty, recreated data source should not be the same as the one we
// created earlier on.
assertNotNull("Recreated datasource is <null>", recreatedDs);
assertNotSame(recreatedDs, ds);
compareDataSources(dsDesc, ds, recreatedDs, true);
// Serialize and recreate data source with default values.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(ds);
oos.flush();
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
recreatedDs = ois.readObject();
compareDataSources(dsDesc, ds, recreatedDs, true);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
public Object getObjectInstance(Object ref, Name name, Context nameCtx,
Hashtable<?,?> env) throws Exception {
if (!isLdapRef(ref)) {
return null;
}
ObjectFactory factory = new ldapURLContextFactory();
String[] urls = getURLs((Reference)ref);
return factory.getObjectInstance(urls, name, nameCtx, env);
}
@Test
public void testReference() throws Exception {
ActiveMQDestination queue = (ActiveMQDestination) ActiveMQJMSClient.createQueue(RandomUtil.randomString());
Reference reference = queue.getReference();
String factoryName = reference.getFactoryClassName();
Class<?> factoryClass = Class.forName(factoryName);
ObjectFactory factory = (ObjectFactory) factoryClass.newInstance();
Object object = factory.getObjectInstance(reference, null, null, null);
Assert.assertNotNull(object);
Assert.assertTrue(object instanceof ActiveMQDestination);
Assert.assertEquals(queue, object);
}
private <T> T getObject(Reference reference, Class<T> tClass) throws Exception {
String factoryName = reference.getFactoryClassName();
Class<?> factoryClass = Class.forName(factoryName);
ObjectFactory factory = (ObjectFactory) factoryClass.newInstance();
Object o = factory.getObjectInstance(reference, null, null, null);
if (tClass.isAssignableFrom(tClass)) {
return tClass.cast(o);
} else {
throw new IllegalStateException("Expected class, " + tClass.getName());
}
}
public Object create() throws NamingException {
final TomcatWebAppBuilder.ContextInfo info = ((TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class))
.getContextInfo(appName);
if (info == null || info.standardContext == null) {
return null;
}
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
final ClassLoader tccl = info.standardContext.getLoader().getClassLoader();
Thread.currentThread().setContextClassLoader(tccl);
try {
// lookup can't work because of the lifecycle
// return new InitialContext().lookup(jndiName);
if (factory != null) {
final Class<?> clazz = tccl.loadClass(factory);
final Object instance = clazz.newInstance();
if (instance instanceof ObjectFactory) {
// not really used as expected but it matches a bit more than before
// context is null since it can't be used at this moment (see TomcatWebAppBuilder lifecycle)
return ((ObjectFactory) instance).getObjectInstance(reference, name, null, null);
}
}
if (reference != null) {
return NamingManager.getObjectInstance(reference, name, null, null);
}
throw new IllegalStateException("nothing to create the resource " + jndiName);
} catch (final Exception e) {
LOGGER.error("Can't create resource " + jndiName, e);
} finally {
Thread.currentThread().setContextClassLoader(loader);
}
return null;
}
public static ObjectFactory[] getFederatedFactories() throws NamingException {
if (federatedFactories == null) {
final Set<ObjectFactory> factories = new HashSet<>();
final String urlPackagePrefixes = getUrlPackagePrefixes();
if (urlPackagePrefixes == null) {
return new ObjectFactory[0];
}
for (final StringTokenizer tokenizer = new StringTokenizer(urlPackagePrefixes, ":"); tokenizer.hasMoreTokens(); ) {
final String urlPackagePrefix = tokenizer.nextToken();
final String className = urlPackagePrefix + ".java.javaURLContextFactory";
if (className.equals("org.apache.openejb.core.ivm.naming.java.javaURLContextFactory")) {
continue;
}
try {
final ClassLoader cl = ClassLoaderUtil.getContextClassLoader();
final Class factoryClass = Class.forName(className, true, cl);
final ObjectFactory factoryInstance = (ObjectFactory) factoryClass.newInstance();
factories.add(factoryInstance);
} catch (final ClassNotFoundException cnfe) {
// no-op
} catch (final Throwable e) {
final NamingException ne = new NamingException("Federation failed: Cannot instantiate " + className);
ne.setRootCause(e);
throw ne;
}
}
final Object[] temp = factories.toArray();
federatedFactories = new ObjectFactory[temp.length];
System.arraycopy(temp, 0, federatedFactories, 0, federatedFactories.length);
}
return federatedFactories;
}
/**
* Make sure it is possible to create a new data source using
* <code>Referencable</code>, that the new instance has the correct
* default values set for the bean properties and finally that the
* data source can be serialized/deserialized.
*
* @param dsDesc data source descriptor
* @param className data source class name
* @throws Exception on a wide variety of error conditions...
*/
private void assertDataSourceReferenceEmpty(DataSourceDescriptor dsDesc,
String className)
throws Exception {
println("Testing recreated empty data source.");
// Create an empty data source.
Object ds = Class.forName(className).newInstance();
Referenceable refDs = (Referenceable)ds;
Reference dsAsReference = refDs.getReference();
String factoryClassName = dsAsReference.getFactoryClassName();
ObjectFactory factory =
(ObjectFactory)Class.forName(factoryClassName).newInstance();
Object recreatedDs =
factory.getObjectInstance(dsAsReference, null, null, null);
// Empty, recreated data source should not be the same as the one we
// created earlier on.
assertNotNull("Recreated datasource is <null>", recreatedDs);
assertNotSame(recreatedDs, ds);
compareDataSources(dsDesc, ds, recreatedDs, true);
// Serialize and recreate data source with default values.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(ds);
oos.flush();
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
recreatedDs = ois.readObject();
compareDataSources(dsDesc, ds, recreatedDs, true);
}
@Override
protected ObjectFactory getDefaultFactory(Reference ref) {
// No default factory supported.
return null;
}
@Override
protected ObjectFactory getDefaultFactory(Reference ref) {
// No default factory supported.
return null;
}
/**
* Make sure it is possible to recreate and serialize/deserialize a
* populated data source.
* <p>
* Populated means the various bean properties have non-default
* values set.
*
* @param dsDesc data source descriptor
* @param className data source class name
* @throws Exception on a wide variety of error conditions...
*/
private void assertDataSourceReferencePopulated(
DataSourceDescriptor dsDesc,
String className)
throws Exception {
println("Testing recreated populated data source.");
Object ds = Class.forName(className).newInstance();
// Populate the data source.
Iterator propIter = dsDesc.getPropertyIterator();
while (propIter.hasNext()) {
String property = (String)propIter.next();
String value = dsDesc.getPropertyValue(property);
Method getMethod = getGet(property, ds);
Method setMethod = getSet(getMethod, ds);
Class paramType = getMethod.getReturnType();
if (paramType.equals(Integer.TYPE)) {
setMethod.invoke(ds, new Object[] {Integer.valueOf(value)});
} else if (paramType.equals(String.class)) {
setMethod.invoke(ds, new Object[] {value});
} else if (paramType.equals(Boolean.TYPE)) {
setMethod.invoke(ds, new Object[] {Boolean.valueOf(value)});
} else if (paramType.equals(Short.TYPE)) {
setMethod.invoke(ds, new Object[] {Short.valueOf(value)});
} else if (paramType.equals(Long.TYPE)) {
setMethod.invoke(ds, new Object[] {Long.valueOf(value)});
} else {
fail("'" + property + "' not settable - update test!!");
}
}
Referenceable refDs = (Referenceable)ds;
Reference dsAsReference = refDs.getReference();
String factoryClassName = dsAsReference.getFactoryClassName();
ObjectFactory factory =
(ObjectFactory)Class.forName(factoryClassName).newInstance();
Object recreatedDs =
factory.getObjectInstance(dsAsReference, null, null, null);
// Recreated should not be same instance as original.
assertNotSame(recreatedDs, ds);
compareDataSources(dsDesc, ds, recreatedDs, false);
// Serialize and recreate.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(ds);
oos.flush();
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
recreatedDs = ois.readObject();
compareDataSources(dsDesc, ds, recreatedDs, false);
}
/**
* Make sure it is possible to recreate and serialize/deserialize a
* populated data source.
* <p>
* Populated means the various bean properties have non-default
* values set.
*
* @param dsDesc data source descriptor
* @param className data source class name
* @throws Exception on a wide variety of error conditions...
*/
private void assertDataSourceReferencePopulated(
DataSourceDescriptor dsDesc,
String className)
throws Exception {
println("Testing recreated populated data source.");
Object ds = Class.forName(className).newInstance();
// Populate the data source.
Iterator propIter = dsDesc.getPropertyIterator();
while (propIter.hasNext()) {
String property = (String)propIter.next();
String value = dsDesc.getPropertyValue(property);
Method getMethod = getGet(property, ds);
Method setMethod = getSet(getMethod, ds);
Class paramType = getMethod.getReturnType();
if (paramType.equals(Integer.TYPE)) {
setMethod.invoke(ds, new Object[] {Integer.valueOf(value)});
} else if (paramType.equals(String.class)) {
setMethod.invoke(ds, new Object[] {value});
} else if (paramType.equals(Boolean.TYPE)) {
setMethod.invoke(ds, new Object[] {Boolean.valueOf(value)});
} else if (paramType.equals(Short.TYPE)) {
setMethod.invoke(ds, new Object[] {Short.valueOf(value)});
} else if (paramType.equals(Long.TYPE)) {
setMethod.invoke(ds, new Object[] {Long.valueOf(value)});
} else {
fail("'" + property + "' not settable - update test!!");
}
}
Referenceable refDs = (Referenceable)ds;
Reference dsAsReference = refDs.getReference();
String factoryClassName = dsAsReference.getFactoryClassName();
ObjectFactory factory =
(ObjectFactory)Class.forName(factoryClassName).newInstance();
Object recreatedDs =
factory.getObjectInstance(dsAsReference, null, null, null);
// Recreated should not be same instance as original.
assertNotSame(recreatedDs, ds);
compareDataSources(dsDesc, ds, recreatedDs, false);
// Serialize and recreate.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(ds);
oos.flush();
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
recreatedDs = ois.readObject();
compareDataSources(dsDesc, ds, recreatedDs, false);
}