javax.naming.Reference Java Examples

The following examples show how to use javax.naming.Reference. 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: ViburDBCPObjectFactory.java    From vibur-dbcp with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: JndiBinding.java    From javamelody with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: right_LmiInitialContext_1.6.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #4
Source File: TestDataSourceFactory.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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());
}
 
Example #5
Source File: InVMNamingContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@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;
   }
}
 
Example #6
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 #7
Source File: DriverAdapterCPDS.java    From Tomcat8-Source-Read with MIT License 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 #8
Source File: UrlFactory.java    From jqm with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: DataSourceLinkFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: ConnectionPropertiesImpl.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
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());
        }
    }
}
 
Example #11
Source File: DataSourceLinkFactory.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: StringRefAddrReferenceTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@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());

}
 
Example #13
Source File: LookupFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #14
Source File: PersistenceUnitFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: TestDataSourceFactory.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testBuildFBSimpleDataSource() throws Exception {
    final FBSimpleDataSource originalDS = new FBSimpleDataSource();
    originalDS.setDescription(DESCRIPTION);
    originalDS.setType(TYPE);
    final String database = String.format("//%s:%d/%s", SERVER_NAME, PORT_NUMBER, DATABASE_NAME);
    originalDS.setDatabase(database);
    originalDS.setUserName(USER);
    originalDS.setPassword(PASSWORD);
    originalDS.setEncoding(ENCODING);
    originalDS.setLoginTimeout(LOGIN_TIMEOUT);
    originalDS.setRoleName(ROLE_NAME);
    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();

    assertEquals("Unexpected factory name", DataSourceFactory.class.getName(), ref.getFactoryClassName());
    assertEquals("Unexpected class name", FBSimpleDataSource.class.getName(), ref.getClassName());

    FBSimpleDataSource newDS =
            (FBSimpleDataSource) new DataSourceFactory().getObjectInstance(ref, null, null, null);

    assertEquals(DESCRIPTION, newDS.getDescription());
    assertEquals(TYPE, newDS.getType());
    assertEquals(database, newDS.getDatabase());
    assertEquals(USER, newDS.getUserName());
    assertEquals(PASSWORD, newDS.getPassword());
    assertEquals(ENCODING, newDS.getEncoding());
    assertEquals(LOGIN_TIMEOUT, newDS.getLoginTimeout());
    assertEquals(ROLE_NAME, newDS.getRoleName());
    assertEquals("127", newDS.getNonStandardProperty("buffersNumber"));
    assertEquals(Integer.toString(Connection.TRANSACTION_SERIALIZABLE), newDS.getNonStandardProperty("defaultTransactionIsolation"));
    assertEquals("madeUpValue", newDS.getNonStandardProperty("madeUpProperty"));
}
 
Example #16
Source File: OpenEjbFactory.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new EJB instance using OpenEJB.
 * 
 * @param obj The reference object describing the DataSource
 */
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
                                Hashtable<?,?> environment)
    throws Exception {

    Object beanObj = null;

    if (obj instanceof EjbRef) {

        Reference ref = (Reference) obj;

        String factory = DEFAULT_OPENEJB_FACTORY;
        RefAddr factoryRefAddr = ref.get("openejb.factory");
        if (factoryRefAddr != null) {
            // Retrieving the OpenEJB factory
            factory = factoryRefAddr.getContent().toString();
        }

        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);

        RefAddr linkRefAddr = ref.get("openejb.link");
        if (linkRefAddr != null) {
            String ejbLink = linkRefAddr.getContent().toString();
            beanObj = (new InitialContext(env)).lookup(ejbLink);
        }

    }

    return beanObj;

}
 
Example #17
Source File: JDKUtil.java    From marshalsec with MIT License 5 votes vote down vote up
public static DirContext makeContinuationContext ( String codebase, String clazz ) throws Exception {
    Class<?> ccCl = Class.forName("javax.naming.spi.ContinuationDirContext"); //$NON-NLS-1$
    Constructor<?> ccCons = ccCl.getDeclaredConstructor(CannotProceedException.class, Hashtable.class);
    ccCons.setAccessible(true);
    CannotProceedException cpe = new CannotProceedException();
    Reflections.setFieldValue(cpe, "stackTrace", new StackTraceElement[0]);
    cpe.setResolvedObj(new Reference("Foo", clazz, codebase));
    return (DirContext) ccCons.newInstance(cpe, null);
}
 
Example #18
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 #19
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 #20
Source File: NamingContextListener.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Set the specified resource link in the naming context.
 */
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().toString();
        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 (logger.isDebugEnabled())
            log.debug("  Adding resource link " + resourceLink.getName());
        createSubcontexts(envCtx, resourceLink.getName());
        ctx.bind(resourceLink.getName(), ref);
    } catch (NamingException e) {
        logger.error(sm.getString("naming.bindFailed", e));
    }

}
 
Example #21
Source File: left_CmiContext_1.2.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
}
 
Example #22
Source File: RMIRefServer.java    From marshalsec with MIT License 5 votes vote down vote up
/**
 * @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;
}
 
Example #23
Source File: JNDIReferenceFactoryTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: NonSerializableFactory.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public Object getObjectInstance(final Object obj,
                                final Name name,
                                final Context nameCtx,
                                final Hashtable<?, ?> env) throws Exception {
   Reference ref = (Reference) obj;
   RefAddr addr = ref.get("nns");
   String key = (String) addr.getContent();
   return NonSerializableFactory.getWrapperMap().get(key);
}
 
Example #25
Source File: JDKUtil.java    From learnjavabug with MIT License 5 votes vote down vote up
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;
}
 
Example #26
Source File: ActiveMQRASessionFactoryImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: DataSourceRegressionTest.java    From r-course with MIT License 5 votes vote down vote up
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;
        }
    }
}
 
Example #28
Source File: BurlapProxyFactory.java    From sofa-hessian with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #29
Source File: EjbFactory.java    From tomee with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: ConnectionPropertiesImpl.java    From r-course with MIT License 5 votes vote down vote up
void initializeFrom(Reference ref, ExceptionInterceptor exceptionInterceptor) throws SQLException {
    RefAddr refAddr = ref.get(getPropertyName());

    if (refAddr != null) {
        String refContentAsString = (String) refAddr.getContent();

        initializeFrom(refContentAsString, exceptionInterceptor);
    }
}