下面列出了怎么用javax.naming.Reference的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a new DataSource instance.
*
* @param obj The reference object describing the DataSource
*/
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment)
throws NamingException {
Object result = super.getObjectInstance(obj, name, nameCtx, environment);
// Can we process this request?
if (result!=null) {
Reference ref = (Reference) obj;
RefAddr userAttr = ref.get("username");
RefAddr passAttr = ref.get("password");
if (userAttr.getContent()!=null && passAttr.getContent()!=null) {
result = wrapDataSource(result,userAttr.getContent().toString(), passAttr.getContent().toString());
}
}
return result;
}
/**
* 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;
}
protected void storeToRef(Reference ref) throws SQLException {
int numPropertiesToSet = PROPERTY_LIST.size();
for (int i = 0; i < numPropertiesToSet; i++) {
java.lang.reflect.Field propertyField = PROPERTY_LIST.get(i);
try {
ConnectionProperty propToStore = (ConnectionProperty) propertyField.get(this);
if (ref != null) {
propToStore.storeTo(ref);
}
} catch (IllegalAccessException iae) {
throw SQLError.createSQLException(Messages.getString("ConnectionProperties.errorNotExpected"), getExceptionInterceptor());
}
}
}
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
if (!(object instanceof Reference)) {
return null;
}
final Reference reference = ((Reference) object);
final String jndiName = NamingUtil.getProperty(reference, NamingUtil.JNDI_NAME);
if (jndiName == null) {
return null;
}
try {
return context.lookup(jndiName.replaceFirst("^java:", ""));
} catch (final NameNotFoundException e) {
return new InitialContext().lookup(jndiName);
}
}
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
// ignore non resource-refs
if (!(object instanceof ResourceRef)) {
return null;
}
final Reference ref = (Reference) object;
final Object value;
if (getProperty(ref, JNDI_NAME) != null) {
// lookup the value in JNDI
value = super.getObjectInstance(object, name, context, environment);
} else {
// value is hard hard coded in the properties
value = getStaticValue(ref);
}
return value;
}
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment)
throws ViburDBCPException {
Reference reference = (Reference) obj;
Enumeration<RefAddr> enumeration = reference.getAll();
Properties props = new Properties();
while (enumeration.hasMoreElements()) {
RefAddr refAddr = enumeration.nextElement();
String pName = refAddr.getType();
String pValue = (String) refAddr.getContent();
props.setProperty(pName, pValue);
}
ViburDBCPDataSource dataSource = new ViburDBCPDataSource(props);
dataSource.start();
return dataSource;
}
@Test(timeout = 10000)
public void testActiveMQConnectionFactoryFromPropertiesJNDI() throws Exception {
Properties properties = new Properties();
properties.setProperty(TYPE, ActiveMQConnectionFactory.class.getName());
properties.setProperty(FACTORY, JNDIReferenceFactory.class.getName());
String brokerURL = "vm://0";
String connectionTTL = "1000";
String preAcknowledge = "true";
properties.setProperty("brokerURL", brokerURL);
properties.setProperty("connectionTTL", connectionTTL);
properties.setProperty("preAcknowledge", preAcknowledge);
Reference reference = from(properties);
ActiveMQConnectionFactory object = getObject(reference, ActiveMQConnectionFactory.class);
assertEquals(Long.parseLong(connectionTTL), object.getConnectionTTL());
assertEquals(Boolean.parseBoolean(preAcknowledge), object.isPreAcknowledge());
}
/**
* Create a new DataSource instance.
*
* @param obj The reference object describing the DataSource
*/
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?,?> environment)
throws NamingException {
Object result = super.getObjectInstance(obj, name, nameCtx, environment);
// Can we process this request?
if (result!=null) {
Reference ref = (Reference) obj;
RefAddr userAttr = ref.get("username");
RefAddr passAttr = ref.get("password");
if (userAttr.getContent()!=null && passAttr.getContent()!=null) {
result = wrapDataSource(result,userAttr.getContent().toString(), passAttr.getContent().toString());
}
}
return result;
}
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception
{
String url = null;
if (obj instanceof Reference)
{
Reference resource = (Reference) obj;
if (resource.get("URL") != null)
{
url = (String) resource.get("URL").getContent();
}
}
else if (environment.containsKey("URL"))
{
url = (String) environment.get("URL");
}
if (url == null)
{
throw new NamingException("Resource does not have a valid URL parameter");
}
return new URL(url);
}
@Override
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 InVMNamingContext && i != -1) {
return ((InVMNamingContext) 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;
}
}
@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();
}
}
/**
* Tests reconstruction of a {@link FBConnectionPoolDataSource} using a reference.
* <p>
* This test is done with a selection of properties set through the {@link FBConnectionPoolDataSource#setNonStandardProperty(String)} methods. It tests
* <ol>
* <li>If the reference returned has the right factory name</li>
* <li>If the reference returned has the right classname</li>
* <li>If the object returned by the factory is a distinct new instance</li>
* <li>If all the properties set on the original are also set on the new instance</li>
* <li>If an unset property is handled correctly</li>
* </ol>
* </p>
*/
@Test
public void testBuildFBConnectionPoolDataSource_nonStandardProperties() throws Exception {
final FBConnectionPoolDataSource originalDS = new FBConnectionPoolDataSource();
originalDS.setNonStandardProperty("buffersNumber=127"); // note number of buffers is apparently byte, so using higher values can give weird results
originalDS.setNonStandardProperty("defaultTransactionIsolation", Integer.toString(Connection.TRANSACTION_SERIALIZABLE));
originalDS.setNonStandardProperty("madeUpProperty", "madeUpValue");
Reference ref = originalDS.getReference();
FBConnectionPoolDataSource newDS = (FBConnectionPoolDataSource)new DataSourceFactory().getObjectInstance(ref, null, null, null);
assertEquals("127", newDS.getNonStandardProperty("buffersNumber"));
assertEquals(Integer.toString(Connection.TRANSACTION_SERIALIZABLE), newDS.getNonStandardProperty("defaultTransactionIsolation"));
assertEquals("madeUpValue", newDS.getNonStandardProperty("madeUpProperty"));
assertNull(newDS.getDescription());
}
/**
* 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;
}
}
private static JndiBinding createJndiBinding(String path, Binding binding) {
final String name = getBindingName(path, binding);
final String className = binding.getClassName();
final Object object = binding.getObject();
final String contextPath;
final String value;
if (object instanceof Context
// "javax.naming.Context".equals(className) nécessaire pour le path "comp" dans JBoss 6.0
|| "javax.naming.Context".equals(className)
// pour jetty :
|| object instanceof Reference
&& "javax.naming.Context".equals(((Reference) object).getClassName())) {
if (!path.isEmpty()) {
contextPath = path + '/' + name;
} else {
// nécessaire pour jonas 5.1.0
contextPath = name;
}
value = null;
} else {
contextPath = null;
value = formatValue(object);
}
return new JndiBinding(name, className, contextPath, value);
}
/**
* 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);
}
/**
* @param ois
* @param out
* @throws IOException
* @throws ClassNotFoundException
* @throws NamingException
*/
private boolean handleRMI ( ObjectInputStream ois, DataOutputStream out ) throws Exception {
int method = ois.readInt(); // method
ois.readLong(); // hash
if ( method != 2 ) { // lookup
return false;
}
String object = (String) ois.readObject();
System.err.println("Is RMI.lookup call for " + object + " " + method);
out.writeByte(TransportConstants.Return);// transport op
try ( ObjectOutputStream oos = new MarshalOutputStream(out, this.classpathUrl) ) {
oos.writeByte(TransportConstants.NormalReturn);
new UID().write(oos);
System.err.println(
String.format(
"Sending remote classloading stub targeting %s",
new URL(this.classpathUrl, this.classpathUrl.getRef().replace('.', '/').concat(".class"))));
ReferenceWrapper rw = Reflections.createWithoutConstructor(ReferenceWrapper.class);
Reflections.setFieldValue(rw, "wrappee", new Reference("Foo", this.classpathUrl.getRef(), this.classpathUrl.toString()));
Field refF = RemoteObject.class.getDeclaredField("ref");
refF.setAccessible(true);
refF.set(rw, new UnicastServerRef(12345));
oos.writeObject(rw);
oos.flush();
out.flush();
}
return true;
}
/**
* Initializes driver properties that come from a JNDI reference (in the
* case of a javax.sql.DataSource bound into some name service that doesn't
* handle Java objects directly).
*
* @param ref
* The JNDI Reference that holds RefAddrs for all properties
* @throws SQLException
* if error occurs
*/
public void setPropertiesViaRef(Reference ref) throws SQLException {
for (PropertyKey propKey : PropertyDefinitions.PROPERTY_KEY_TO_PROPERTY_DEFINITION.keySet()) {
RuntimeProperty<?> propToSet = getProperty(propKey);
if (ref != null) {
propToSet.initializeFrom(ref, null);
}
}
postInitialization();
}
@SuppressWarnings({"unchecked"})
public static <T> T getStaticValue(final Reference ref, String name) {
name = name != null ? "-" + name : "";
final String token = getProperty(ref, "static-token" + name);
if (token == null) {
return null;
}
final T object = (T) REGISTRY.get(token);
return object;
}
private void removeFromRef(Reference ref, String key) {
int size = ref.size();
for (int i = 0; i < size; i++) {
RefAddr refAddr = ref.get(i);
if (refAddr.getType().equals(key)) {
ref.remove(i);
break;
}
}
}
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception
{
Reference resource = (Reference) obj;
if (resource.get("STRING") != null)
{
String res = (String) resource.get("STRING").getContent();
return res;
}
else
{
throw new NamingException("Resource does not have a valid STRING parameter");
}
}
/**
* Serialize and write data sources to file.
*
* @param versionString Derby version string (i.e. 10.3.2.1)
* @param buildNumber Derby build number (svn)
* @param dataSourceClasses list of data source class names
* @return The number of data sources serialized and written to file.
*
* @throws ClassNotFoundException required class is not on the classpath
* @throws InstantiationException if instantiating data source class fails
* @throws IllegalAccessException if instantiating data source class fails
* @throws IOException if writing to file fails
* @throws NamingException if creating a naming reference for the data
* source fails
*/
private static int serializeDataSources(String versionString,
String buildNumber,
String[] dataSourceClasses)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IOException, NamingException {
String modifiedVersionString = versionString.replaceAll("\\.", "_");
int dsCount = 0;
for (String dsClassName : dataSourceClasses) {
Class dsClass;
// Try to load the class.
try {
dsClass = Class.forName(dsClassName);
} catch (ClassNotFoundException cnfe) {
// Print error message, but keep going.
System.out.println("\tcouldn't load " + dsClassName);
continue;
}
// Create new instance.
DataSource ds = (DataSource)dsClass.newInstance();
// Generate file name.
File serialized = new File(dsClass.getSimpleName() + "-" +
modifiedVersionString + ".ser");
System.out.println("\twriting " + serialized.getName());
OutputStream os = new FileOutputStream(serialized);
ObjectOutputStream oos = new ObjectOutputStream(os);
// Wrote version string, build number, the data source object and finally
// a {@link javax.naming.Reference} for the data source.
oos.writeUTF(versionString);
oos.writeUTF(buildNumber);
oos.writeObject(ds);
Reference dsRef = ((Referenceable)ds).getReference();
oos.writeObject(dsRef);
oos.flush();
oos.close();
dsCount++;
}
return dsCount;
}
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment)
throws Exception {
Reference ref = (Reference) obj;
RefAddr addr = ref.get("configPath");
return buildClient(addr.getContent().toString());
}
@Test
public void testInstanceOfReferencable() throws Exception {
assertTrue("Instance of Referenceable", cf instanceof Referenceable);
assertNull("No ref set", cf.getReference());
Reference ref = EasyMock.createMock(Reference.class);
cf.setReference(ref);
assertEquals("Got back what was set", ref, cf.getReference());
}
@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);
}
/**
* Wrap an Object : If the object is a reference wrap it into a Reference
* Wrapper Object here the good way is to contact the carol configuration to
* get the portable remote object
* @param o the object to encode
* @param name of the object
* @param replace if the object need to be replaced
* @return a <code>Remote JNDIRemoteReference Object</code> if o is a
* resource o if else
* @throws NamingException if object cannot be wrapped
*/
protected Object wrapObject(Object o, Name name, boolean replace) throws NamingException {
try {
// Add wrapper for the two first cases. Then it will use PortableRemoteObject instead of UnicastRemoteObject
// and when fixing JRMP exported objects port, it use JRMPProdelegate which is OK.
if ((!(o instanceof Remote)) && (o instanceof Referenceable)) {
return new UnicastJNDIReferenceWrapper(((Referenceable) o).getReference(), getObjectPort());
} else if ((!(o instanceof Remote)) && (o instanceof Reference)) {
return new UnicastJNDIReferenceWrapper((Reference) o, getObjectPort());
} else if ((!(o instanceof Remote)) && (!(o instanceof Referenceable)) && (!(o instanceof Reference))
&& (o instanceof Serializable)) {
// Only Serializable (not implementing Remote or Referenceable or
// Reference)
JNDIResourceWrapper irw = new JNDIResourceWrapper((Serializable) o);
PortableRemoteObjectDelegate proDelegate = ConfigurationRepository.getCurrentConfiguration().getProtocol().getPortableRemoteObject();
proDelegate.exportObject(irw);
Remote oldObj = (Remote) addToExported(name, irw);
if (oldObj != null) {
if (replace) {
proDelegate.unexportObject(oldObj);
} else {
proDelegate.unexportObject(irw);
addToExported(name, oldObj);
throw new NamingException("Object '" + o + "' with name '" + name + "' is already bind");
}
}
return irw;
} else {
return o;
}
} catch (Exception e) {
throw NamingExceptionHelper.create("Cannot wrap object '" + o + "' with name '" + name + "' : "
+ e.getMessage(), e);
}
}
@Override
protected String buildJndiName(final Reference reference) throws NamingException {
final String jndiName;// get and verify deploymentId
final String deploymentId = NamingUtil.getProperty(reference, NamingUtil.DEPLOYMENT_ID);
if (deploymentId == null) {
throw new NamingException("ejb-ref deploymentId is null");
}
// get and verify interface type
InterfaceType type = InterfaceType.BUSINESS_REMOTE;
String interfaceType = NamingUtil.getProperty(reference, NamingUtil.REMOTE);
if (interfaceType == null) {
type = InterfaceType.LOCALBEAN;
interfaceType = NamingUtil.getProperty(reference, NamingUtil.LOCALBEAN);
}
if (interfaceType == null) {
type = InterfaceType.BUSINESS_LOCAL;
interfaceType = NamingUtil.getProperty(reference, NamingUtil.LOCAL);
}
if (interfaceType == null) {
throw new NamingException("ejb-ref interface type is null");
}
// build jndi name using the deploymentId and interface type
jndiName = "java:openejb/Deployment/" + JndiBuilder.format(deploymentId, interfaceType, type);
return jndiName;
}
/**
* 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 BurlapProxyFactory.");
// XXX: could use meta protocol to grab this
if (api == null)
throw new NamingException("`type' must be configured for BurlapProxyFactory.");
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class apiClass = Class.forName(api, false, loader);
return create(apiClass, url);
}
/**
* Set the naming reference
*
* @param reference The reference
*/
@Override
public void setReference(final Reference reference) {
if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
ActiveMQRALogger.LOGGER.trace("setReference(" + reference + ")");
}
this.reference = reference;
}
private static ReferenceWrapper makeReference ( String codebase, String clazz ) throws Exception {
Reference ref = new Reference("Foo", clazz, codebase);
ReferenceWrapper wrapper = Reflections.createWithoutConstructor(ReferenceWrapper.class);
Reflections.setFieldValue(wrapper, "wrappee", ref);
Reflections.setFieldValue(wrapper, "ref", Reflections.createWithoutConstructor(sun.rmi.server.UnicastServerRef.class));
return wrapper;
}
private Reference createTestReference(String className, String addressType, Object content) {
Reference mockReference = mock(Reference.class);
when(mockReference.getClassName()).thenReturn(className);
RefAddr mockRefAddr = mock(StringRefAddr.class);
when(mockRefAddr.getType()).thenReturn(addressType);
when(mockRefAddr.getContent()).thenReturn(content);
RefAddrTestEnumeration testEnumeration = new RefAddrTestEnumeration(mockRefAddr);
when(mockReference.getAll()).thenReturn(testEnumeration);
return mockReference;
}