Example usage for javax.naming Reference Reference

List of usage examples for javax.naming Reference Reference

Introduction

In this page you can find the example usage for javax.naming Reference Reference.

Prototype

public Reference(String className, String factory, String factoryLocation) 

Source Link

Document

Constructs a new reference for an object with class name 'className', and the class name and location of the object's factory.

Usage

From source file:com.caricah.iotracah.datastore.IotDataSource.java

public void setupDatasource(String driver, String dbUrl, String username, String password)
        throws NamingException {

    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    System.setProperty(Context.PROVIDER_URL, "file:////tmp");

    Context ctx = new InitialContext();

    // Construct DriverAdapterCPDS reference
    Reference cpdsRef = new Reference("org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS",
            "org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS", null);
    cpdsRef.add(new StringRefAddr("driver", driver));
    cpdsRef.add(new StringRefAddr("url", dbUrl));
    cpdsRef.add(new StringRefAddr("user", username));
    cpdsRef.add(new StringRefAddr("password", password));
    ctx.rebind("jdbc_cpds", cpdsRef);

    Reference ref = new Reference("org.apache.commons.dbcp2.datasources.SharedPoolDataSource",
            "org.apache.commons.dbcp2.datasources.SharedPoolDataSourceFactory", null);
    ref.add(new StringRefAddr("dataSourceName", "jdbc_cpds"));
    ref.add(new StringRefAddr("defaultMaxTotal", "100"));
    ref.add(new StringRefAddr("defaultMaxIdle", "30"));
    ref.add(new StringRefAddr("defaultMaxWaitMillis", "10000"));

    ctx.rebind("jdbc_commonpool", ref);

}

From source file:marshalsec.gadgets.C3P0WrapperConnPool.java

public static String makeC3P0UserOverridesString(String codebase, String clazz)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException,
        InvocationTargetException, IOException {

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try (ObjectOutputStream oos = new ObjectOutputStream(b)) {
        Class<?> refclz = Class.forName("com.mchange.v2.naming.ReferenceIndirector$ReferenceSerialized"); //$NON-NLS-1$
        Constructor<?> con = refclz.getDeclaredConstructor(Reference.class, Name.class, Name.class,
                Hashtable.class);
        con.setAccessible(true);//from  w  w w.j  a va  2s  .  c o m
        Reference jndiref = new Reference("Foo", clazz, codebase);
        Object ref = con.newInstance(jndiref, null, null, null);
        oos.writeObject(ref);
    }

    return "HexAsciiSerializedMap:" + Hex.encodeHexString(b.toByteArray()) + ";"; //$NON-NLS-1$
}

From source file:com.stratelia.silverpeas.versioning.jcr.impl.AbstractJcrTestCase.java

@Resource
public void setDataSource(DataSource datasource) {
    this.datasource = datasource;
    try {/* ww w .  ja  v a 2  s  .  co m*/
        prepareJndi();
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
        InitialContext ic = new InitialContext(env);
        Properties properties = new Properties();
        properties.load(PathTestUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        // Construct BasicDataSource reference
        Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
                null);
        ref.add(new StringRefAddr("driverClassName",
                properties.getProperty("driverClassName", "org.postgresql.Driver")));
        ref.add(new StringRefAddr("url",
                properties.getProperty("url", "jdbc:postgresql://localhost:5432/postgres")));
        ref.add(new StringRefAddr("username", properties.getProperty("username", "postgres")));
        ref.add(new StringRefAddr("password", properties.getProperty("password", "postgres")));
        ref.add(new StringRefAddr("maxActive", "4"));
        ref.add(new StringRefAddr("maxWait", "5000"));
        ref.add(new StringRefAddr("removeAbandoned", "true"));
        ref.add(new StringRefAddr("removeAbandonedTimeout", "5000"));
        rebind(ic, JNDINames.DATABASE_DATASOURCE, ref);
        rebind(ic, JNDINames.ADMIN_DATASOURCE, ref);
    } catch (NamingException nex) {
        nex.printStackTrace();
    } catch (IOException nex) {
        nex.printStackTrace();
    }
}

From source file:com.alibaba.wasp.jdbcx.JdbcDataSource.java

/**
 * Get a new reference for this object, using the current settings.
 * //www .  j a v  a 2 s.  c o  m
 * @return the new reference
 */
public Reference getReference() {
    String factoryClassName = JdbcDataSourceFactory.class.getName();
    Reference ref = new Reference(getClass().getName(), factoryClassName, null);
    ref.add(new StringRefAddr("url", url));
    ref.add(new StringRefAddr("user", userName));
    ref.add(new StringRefAddr("password", convertToString(passwordChars)));
    ref.add(new StringRefAddr("loginTimeout", String.valueOf(loginTimeout)));
    ref.add(new StringRefAddr("description", description));
    return ref;
}

From source file:com.frameworkset.commons.dbcp2.datasources.PerUserPoolDataSource.java

/**
 * Returns a <code>PerUserPoolDataSource</code> {@link Reference}.
 *///from  ww w. jav a2 s  .com
@Override
public Reference getReference() throws NamingException {
    Reference ref = new Reference(getClass().getName(), PerUserPoolDataSourceFactory.class.getName(), null);
    ref.add(new StringRefAddr("instanceKey", getInstanceKey()));
    return ref;
}

From source file:org.apache.synapse.commons.datasource.JNDIBasedDataSourceRepository.java

/**
 * Register a DataSource in the JNDI tree
 *
 * @see DataSourceRepository#register(DataSourceInformation)
 *//*from w  w w .  j a  v a  2s .c o  m*/
public void register(DataSourceInformation information) {

    validateInitialized();
    String dataSourceName = information.getDatasourceName();
    validateDSName(dataSourceName);
    Properties properties = information.getProperties();

    InitialContext context = null;
    Properties jndiEvn = null;

    if (properties == null || properties.isEmpty()) {
        if (initialContext != null) {
            context = initialContext;
            if (log.isDebugEnabled()) {
                log.debug("Empty JNDI properties for datasource " + dataSourceName);
                log.debug("Using system-wide jndi properties : " + jndiProperties);
            }

            jndiEvn = jndiProperties;
        }
    }

    if (context == null) {

        jndiEvn = createJNDIEnvironment(properties, information.getAlias());
        context = createInitialContext(jndiEvn);

        if (context == null) {

            validateInitialContext(initialContext);
            context = initialContext;

            if (log.isDebugEnabled()) {
                log.debug("Cannot create a name context with provided jndi properties : " + jndiEvn);
                log.debug("Using system-wide JNDI properties : " + jndiProperties);
            }

            jndiEvn = jndiProperties;
        } else {
            perDataSourceICMap.put(dataSourceName, context);
        }
    }

    String dsType = information.getType();
    String driver = information.getDriver();
    String url = information.getUrl();

    String user = information.getSecretInformation().getUser();
    String password = information.getSecretInformation().getResolvedSecret();

    String maxActive = String.valueOf(information.getMaxActive());
    String maxIdle = String.valueOf(information.getMaxIdle());
    String maxWait = String.valueOf(information.getMaxWait());

    //populates context tree
    populateContextTree(context, dataSourceName);

    if (DataSourceInformation.BASIC_DATA_SOURCE.equals(dsType)) {

        Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
                null);

        ref.add(new StringRefAddr(DataSourceConstants.PROP_DRIVER_CLS_NAME, driver));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_URL, url));
        ref.add(new StringRefAddr(SecurityConstants.PROP_USER_NAME, user));
        ref.add(new StringRefAddr(SecurityConstants.PROP_PASSWORD, password));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_MAX_ACTIVE, maxActive));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_MAX_IDLE, maxIdle));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_MAX_WAIT, maxWait));

        // set BasicDataSource specific parameters
        setBasicDataSourceParameters(ref, information);
        //set default jndiProperties for reference
        setCommonParameters(ref, information);

        try {

            if (log.isDebugEnabled()) {
                log.debug("Registering a DataSource with name : " + dataSourceName
                        + " in the JNDI tree with jndiProperties : " + jndiEvn);
            }

            context.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = " Error binding name ' " + dataSourceName + " ' to "
                    + "the DataSource(BasicDataSource) reference";
            throw new SynapseCommonsException(msg, e, log);
        }

    } else if (DataSourceInformation.PER_USER_POOL_DATA_SOURCE.equals(dsType)) {

        // Construct DriverAdapterCPDS reference
        String className = (String) information.getParameter(DataSourceConstants.PROP_CPDS_ADAPTER
                + DataSourceConstants.DOT_STRING + DataSourceConstants.PROP_CPDS_CLASS_NAME);
        String factory = (String) information.getParameter(DataSourceConstants.PROP_CPDS_ADAPTER
                + DataSourceConstants.DOT_STRING + DataSourceConstants.PROP_CPDS_FACTORY);
        String name = (String) information.getParameter(DataSourceConstants.PROP_CPDS_ADAPTER
                + DataSourceConstants.DOT_STRING + DataSourceConstants.PROP_CPDS_NAME);

        Reference cpdsRef = new Reference(className, factory, null);

        cpdsRef.add(new StringRefAddr(DataSourceConstants.PROP_DRIVER, driver));
        cpdsRef.add(new StringRefAddr(DataSourceConstants.PROP_URL, url));
        cpdsRef.add(new StringRefAddr(DataSourceConstants.PROP_USER, user));
        cpdsRef.add(new StringRefAddr(SecurityConstants.PROP_PASSWORD, password));

        try {
            context.rebind(name, cpdsRef);
        } catch (NamingException e) {
            String msg = "Error binding name '" + name + "' to " + "the DriverAdapterCPDS reference";
            throw new SynapseCommonsException(msg, e, log);
        }

        // Construct PerUserPoolDataSource reference
        Reference ref = new Reference("org.apache.commons.dbcp.datasources.PerUserPoolDataSource",
                "org.apache.commons.dbcp.datasources.PerUserPoolDataSourceFactory", null);

        ref.add(new BinaryRefAddr(DataSourceConstants.PROP_JNDI_ENV, MiscellaneousUtil.serialize(jndiEvn)));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DATA_SOURCE_NAME, name));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DEFAULT_MAX_ACTIVE, maxActive));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DEFAULT_MAX_IDLE, maxIdle));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DEFAULT_MAX_WAIT, maxWait));

        //set default jndiProperties for reference
        setCommonParameters(ref, information);

        try {

            if (log.isDebugEnabled()) {
                log.debug("Registering a DataSource with name : " + dataSourceName
                        + " in the JNDI tree with jndiProperties : " + jndiEvn);
            }

            context.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = "Error binding name ' " + dataSourceName + " ' to "
                    + "the PerUserPoolDataSource reference";
            throw new SynapseCommonsException(msg, e, log);
        }

    } else {
        throw new SynapseCommonsException("Unsupported data source type : " + dsType, log);
    }
    cachedNameList.add(dataSourceName);
}

From source file:org.apache.synapse.util.DataSourceRegistrar.java

/**
 * Helper method to register a single data source .The given data source name is used ,
 * if there is no property with name dsName ,when,data source is binding to the initial context,
 *
 * @param dsName         The name of the data source
 * @param dsProperties   The property bag
 * @param initialContext The initial context instance
 * @param jndiEnv        The JNDI environment properties
 *///from  ww  w  . j a va 2s  . co m
private static void registerDataSource(String dsName, Properties dsProperties, InitialContext initialContext,
        Properties jndiEnv) {

    if (dsName == null || "".equals(dsName)) {
        if (log.isDebugEnabled()) {
            log.debug("DataSource name is either empty or null, ignoring..");
        }
        return;
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append(SynapseConstants.SYNAPSE_DATASOURCES);
    buffer.append(DOT_STRING);
    buffer.append(dsName);
    buffer.append(DOT_STRING);

    // Prefix for getting particular data source's properties
    String prefix = buffer.toString();

    String driver = getProperty(dsProperties, prefix + PROP_DRIVER_CLS_NAME, null);
    if (driver == null) {
        handleException(prefix + PROP_DRIVER_CLS_NAME + " cannot be found.");
    }

    String url = getProperty(dsProperties, prefix + PROP_URL, null);
    if (url == null) {
        handleException(prefix + PROP_URL + " cannot be found.");
    }

    // get other required properties
    String user = getProperty(dsProperties, prefix + PROP_USER_NAME, "synapse");
    String password = getProperty(dsProperties, prefix + PROP_PASSWORD, "synapse");
    String dataSourceName = getProperty(dsProperties, prefix + PROP_DSNAME, dsName);

    //populates context tree
    populateContextTree(initialContext, dataSourceName);

    String dsType = getProperty(dsProperties, prefix + "type", "BasicDataSource");

    String maxActive = getProperty(dsProperties, prefix + PROP_MAXACTIVE,
            String.valueOf(GenericObjectPool.DEFAULT_MAX_ACTIVE));
    String maxIdle = getProperty(dsProperties, prefix + PROP_MAXIDLE,
            String.valueOf(GenericObjectPool.DEFAULT_MAX_IDLE));
    String maxWait = getProperty(dsProperties, prefix + PROP_MAXWAIT,
            String.valueOf(GenericObjectPool.DEFAULT_MAX_WAIT));

    if ("BasicDataSource".equals(dsType)) {

        Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
                null);

        ref.add(new StringRefAddr(PROP_DRIVER_CLS_NAME, driver));
        ref.add(new StringRefAddr(PROP_URL, url));
        ref.add(new StringRefAddr(PROP_USER_NAME, user));
        ref.add(new StringRefAddr(PROP_PASSWORD, password));
        ref.add(new StringRefAddr(PROP_MAXACTIVE, maxActive));
        ref.add(new StringRefAddr(PROP_MAXIDLE, maxIdle));
        ref.add(new StringRefAddr(PROP_MAXWAIT, maxWait));

        //set BasicDataSource specific parameters
        setBasicDataSourceParameters(ref, dsProperties, prefix);
        //set default properties for reference
        setCommonParameters(ref, dsProperties, prefix);

        try {
            initialContext.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = " Error binding name ' " + dataSourceName + " ' to "
                    + "the DataSource(BasicDataSource) reference";
            handleException(msg, e);
        }

    } else if ("PerUserPoolDataSource".equals(dsType)) {

        // Construct DriverAdapterCPDS reference
        String className = getProperty(dsProperties, prefix + PROP_CPDSADAPTER + DOT_STRING + "className",
                "org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS");
        String factory = getProperty(dsProperties, prefix + PROP_CPDSADAPTER + DOT_STRING + "factory",
                "org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS");
        String name = getProperty(dsProperties, prefix + PROP_CPDSADAPTER + DOT_STRING + "name", "cpds");

        Reference cpdsRef = new Reference(className, factory, null);

        cpdsRef.add(new StringRefAddr(PROP_DRIVER, driver));
        cpdsRef.add(new StringRefAddr(PROP_URL, url));
        cpdsRef.add(new StringRefAddr(PROP_USER, user));
        cpdsRef.add(new StringRefAddr(PROP_PASSWORD, password));

        try {
            initialContext.rebind(name, cpdsRef);
        } catch (NamingException e) {
            String msg = "Error binding name '" + name + "' to " + "the DriverAdapterCPDS reference";
            handleException(msg, e);
        }

        // Construct PerUserPoolDataSource reference
        Reference ref = new Reference("org.apache.commons.dbcp.datasources.PerUserPoolDataSource",
                "org.apache.commons.dbcp.datasources.PerUserPoolDataSourceFactory", null);

        ref.add(new BinaryRefAddr(PROP_JNDI_ENV, serialize(jndiEnv)));
        ref.add(new StringRefAddr(PROP_DATA_SOURCE_NAME, name));
        ref.add(new StringRefAddr(PROP_DEFAULTMAXACTIVE, maxActive));
        ref.add(new StringRefAddr(PROP_DEFAULTMAXIDLE, maxIdle));
        ref.add(new StringRefAddr(PROP_DEFAULTMAXWAIT, maxWait));

        //set default properties for reference
        setCommonParameters(ref, dsProperties, prefix);

        try {
            initialContext.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = "Error binding name ' " + dataSourceName + " ' to "
                    + "the PerUserPoolDataSource reference";
            handleException(msg, e);
        }

    } else {
        handleException("Unsupported data source type : " + dsType);
    }
}

From source file:org.enhydra.jdbc.standard.StandardDataSource.java

/**
 * Methods inherited from referenceable//from  w w w  . j  a v  a2  s.  c o  m
 */
public Reference getReference() throws NamingException {
    // Note that we use getClass().getName() to provide the factory
    // class name. It is assumed that this class, and all of its
    // descendants are their own factories.

    Reference ref = new Reference(getClass().getName(), getClass().getName(), null);
    ref.add(new StringRefAddr("driverName", getDriverName()));
    ref.add(new StringRefAddr("url", getUrl()));
    ref.add(new StringRefAddr("user", getUser()));
    ref.add(new StringRefAddr("password", getPassword()));
    ref.add(new StringRefAddr("description", getDescription()));
    ref.add(new StringRefAddr("loginTimeout", Integer.toString(getLoginTimeout())));
    ref.add(new StringRefAddr("transIsolation", Integer.toString(getTransactionIsolation())));
    log.debug("StandardDataSource:getReference object returned");
    return ref;
}

From source file:org.exoplatform.services.jcr.impl.storage.JDBCWDCTest.java

@Override
protected void setUp() throws Exception {

    RepositoryEntry repositoryEntry = new RepositoryEntry();
    config = new WorkspaceEntry();
    config.setName("test");
    ContainerEntry containerEntry = new ContainerEntry();
    List params = new ArrayList();
    params.add(new SimpleParameterEntry("sourceName", sourceName));
    params.add(new SimpleParameterEntry("db-structure-type", "multi"));
    containerEntry.setParameters(params);
    config.setContainer(containerEntry);

    // Construct BasicDataSource reference
    Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
            null);//from  w  w  w  . j a  v a  2 s.  c  o m

    // Reference ref = new Reference("org.hsqldb.jdbc.jdbcDataSource",
    // "org.hsqldb.jdbc.jdbcDataSourceFactory", null);

    ref.add(new StringRefAddr("driverClassName", "org.hsqldb.jdbcDriver"));

    ref.add(new StringRefAddr("url", "jdbc:hsqldb:file:target/data/test"));
    // ref.add(new StringRefAddr("url", "jdbc:hsqldb:mem:aname"));

    ref.add(new StringRefAddr("username", "sa"));
    ref.add(new StringRefAddr("password", ""));

    FileCleanerHolder cleanerHolder = new FileCleanerHolder();

    container = new JDBCWorkspaceDataContainer(config, repositoryEntry, null,
            new StandaloneStoragePluginProvider(config, cleanerHolder), null, cleanerHolder);

    Properties logProps = new Properties();
    logProps.put("org.apache.commons.logging.simplelog.defaultlog", "debug");

    new LogConfigurationInitializer("org.exoplatform.services.log.impl.BufferedSimpleLog",
            "org.exoplatform.services.log.impl.SimpleLogConfigurator", logProps);

}

From source file:org.jresearch.gossip.listeners.ContextListener.java

public void contextInitialized(ServletContextEvent evt) {
    boolean useDatasource = Boolean.valueOf(evt.getServletContext().getInitParameter("useDatasource"))
            .booleanValue();/* w  w  w  .  j  ava 2 s  . com*/
    String datasourceName = evt.getServletContext().getInitParameter("datasourceName");

    InitialContext ic;
    try {
        ic = new InitialContext();
        if (useDatasource) {
            if (datasourceName == null)
                throw new RuntimeException(
                        "Using datasource is enabled but datasourceName parameter is not specified.");

            DataSource dataSource = (DataSource) PortableRemoteObject.narrow(ic.lookup(datasourceName),
                    javax.sql.DataSource.class);
            ic.rebind("jgossip_db", dataSource);

        } else {
            Properties dbconf = new Properties();
            dbconf.load(evt.getServletContext()
                    .getResourceAsStream("/WEB-INF/classes/org/jresearch/gossip/resources/db.properties"));
            // Construct BasicDataSource reference
            Reference ref = new Reference("javax.sql.DataSource",
                    "org.apache.commons.dbcp.BasicDataSourceFactory", null);
            ref.add(new StringRefAddr("driverClassName", dbconf.getProperty("driverClassName")));
            ref.add(new StringRefAddr("url", dbconf.getProperty("url")));
            ref.add(new StringRefAddr("password", dbconf.getProperty("password")));
            ref.add(new StringRefAddr("username", dbconf.getProperty("username")));
            ref.add(new StringRefAddr("maxActive", dbconf.getProperty("maxActive")));
            ref.add(new StringRefAddr("maxWait", dbconf.getProperty("maxWait")));
            ref.add(new StringRefAddr("initialSize", dbconf.getProperty("initialSize")));
            ref.add(new StringRefAddr("defaultAutoCommit", dbconf.getProperty("defaultAutoCommit")));
            ref.add(new StringRefAddr("defaultReadOnly", dbconf.getProperty("defaultReadOnly")));
            ref.add(new StringRefAddr("poolPreparedStatements", dbconf.getProperty("poolPreparedStatements")));
            ref.add(new StringRefAddr("maxOpenPreparedStatements",
                    dbconf.getProperty("maxOpenPreparedStatements")));

            ic.rebind("jgossip_db", ref);
        }

    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}