Search in sources :

Example 76 with Context

use of javax.naming.Context in project hibernate-orm by hibernate.

the class JndiServiceImpl method bind.

private void bind(Name name, Object value, Context context) {
    try {
        LOG.tracef("Binding : %s", name);
        context.rebind(name, value);
    } catch (Exception initialException) {
        // We had problems doing a simple bind operation.
        if (name.size() == 1) {
            // if the jndi name had only 1 component there is nothing more we can do...
            throw new JndiException("Error performing bind [" + name + "]", initialException);
        }
        // Otherwise, there is a good chance this may have been caused by missing intermediate contexts.  So we
        // attempt to create those missing intermediate contexts and bind again
        Context intermediateContextBase = context;
        while (name.size() > 1) {
            final String intermediateContextName = name.get(0);
            Context intermediateContext = null;
            try {
                LOG.tracev("Intermediate lookup: {0}", intermediateContextName);
                intermediateContext = (Context) intermediateContextBase.lookup(intermediateContextName);
            } catch (NameNotFoundException handledBelow) {
            // ok as we will create it below if not found
            } catch (NamingException e) {
                throw new JndiException("Unanticipated error doing intermediate lookup", e);
            }
            if (intermediateContext != null) {
                LOG.tracev("Found intermediate context: {0}", intermediateContextName);
            } else {
                LOG.tracev("Creating sub-context: {0}", intermediateContextName);
                try {
                    intermediateContext = intermediateContextBase.createSubcontext(intermediateContextName);
                } catch (NamingException e) {
                    throw new JndiException("Error creating intermediate context [" + intermediateContextName + "]", e);
                }
            }
            intermediateContextBase = intermediateContext;
            name = name.getSuffix(1);
        }
        LOG.tracev("Binding : {0}", name);
        try {
            intermediateContextBase.rebind(name, value);
        } catch (NamingException e) {
            throw new JndiException("Error performing intermediate bind [" + name + "]", e);
        }
    }
    LOG.debugf("Bound name: %s", name);
}
Also used : InitialContext(javax.naming.InitialContext) EventContext(javax.naming.event.EventContext) Context(javax.naming.Context) NameNotFoundException(javax.naming.NameNotFoundException) JndiException(org.hibernate.engine.jndi.JndiException) NamingException(javax.naming.NamingException) NamingException(javax.naming.NamingException) JndiException(org.hibernate.engine.jndi.JndiException) JndiNameException(org.hibernate.engine.jndi.JndiNameException) InvalidNameException(javax.naming.InvalidNameException) NameNotFoundException(javax.naming.NameNotFoundException)

Example 77 with Context

use of javax.naming.Context in project jdk8u_jdk by JetBrains.

the class IPv6NameserverPlatformParsingTest method main.

public static void main(String[] args) {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.dns.DnsContextFactory.class.getName());
    String[] servers;
    try {
        Context ctx = NamingManager.getInitialContext(env);
        if (!com.sun.jndi.dns.DnsContextFactory.platformServersAvailable()) {
            throw new RuntimeException("FAIL: no platform servers available, test does not make sense");
        }
        DnsContext context = (DnsContext) ctx;
        servers = getServersFromContext(context);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    for (String server : servers) {
        System.out.println("DEBUG: 'nameserver = " + server + "'");
        if (server.indexOf(':') >= 0 && server.indexOf('.') < 0) {
            System.out.println("DEBUG: ==> Found IPv6 address in servers list: " + server);
            foundIPv6 = true;
        }
    }
    try {
        new com.sun.jndi.dns.DnsClient(servers, 100, 1);
    } catch (NumberFormatException e) {
        throw new RuntimeException("FAIL: Tried to parse non-[]-encapsulated IPv6 address.", e);
    } catch (Exception e) {
        throw new RuntimeException("ERROR: Something unexpected happened.");
    }
    if (!foundIPv6) {
        // platforms. See comment as to how to run this test.
        throw new RuntimeException("ERROR: No IPv6 address returned from platform.");
    }
    System.out.println("PASS: Found IPv6 address and DnsClient parsed it correctly.");
}
Also used : Context(javax.naming.Context) DnsContext(com.sun.jndi.dns.DnsContext) Hashtable(java.util.Hashtable) DnsContext(com.sun.jndi.dns.DnsContext) NamingException(javax.naming.NamingException) NamingException(javax.naming.NamingException)

Example 78 with Context

use of javax.naming.Context in project jdk8u_jdk by JetBrains.

the class HelloClient method executeRmiClientCall.

public static void executeRmiClientCall() throws Exception {
    Context ic;
    Object objref;
    HelloInterface helloSvc;
    String response;
    int retryCount = 0;
    Test test = new Test();
    System.out.println("HelloClient.main: enter ...");
    while (retryCount < MAX_RETRY) {
        try {
            ic = new InitialContext();
            System.out.println("HelloClient.main: HelloService lookup ...");
            // STEP 1: Get the Object reference from the Name Service
            // using JNDI call.
            objref = ic.lookup("HelloService");
            System.out.println("HelloClient: Obtained a ref. to Hello server.");
            // STEP 2: Narrow the object reference to the concrete type and
            // invoke the method.
            helloSvc = (HelloInterface) PortableRemoteObject.narrow(objref, HelloInterface.class);
            System.out.println("HelloClient: Invoking on remote server with ConcurrentHashMap parameter");
            ConcurrentHashMap<String, String> testConcurrentHashMap = new ConcurrentHashMap<String, String>();
            response = helloSvc.sayHelloWithHashMap(testConcurrentHashMap);
            System.out.println("HelloClient: Server says:  " + response);
            if (!response.contains("Hello with hashMapSize ==")) {
                System.out.println("HelloClient: expected response not received");
                throw new RuntimeException("Expected Response Hello with hashMapSize == 0 not received");
            }
            responseReceived = true;
            break;
        } catch (NameNotFoundException nnfEx) {
            System.err.println("NameNotFoundException Caught  .... try again");
            retryCount++;
            try {
                Thread.sleep(ONE_SECOND);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            continue;
        } catch (Exception e) {
            System.err.println("Exception " + e + "Caught");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    System.err.println("HelloClient terminating ");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) NameNotFoundException(javax.naming.NameNotFoundException) InitialContext(javax.naming.InitialContext) MalformedURLException(java.net.MalformedURLException) NamingException(javax.naming.NamingException) RemoteException(java.rmi.RemoteException) NotBoundException(java.rmi.NotBoundException) NameNotFoundException(javax.naming.NameNotFoundException) PortableRemoteObject(javax.rmi.PortableRemoteObject) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 79 with Context

use of javax.naming.Context in project OpenClinica by OpenClinica.

the class SessionManager method setupDataSource.

public void setupDataSource() {
    // end remove later
    try {
        Context ctx = new InitialContext();
        Context env = (Context) ctx.lookup("java:comp/env");
        dbName = CoreResources.getField("dataBase");
        if ("oracle".equals(dbName)) {
            logger.debug("looking up oracle...");
            ds = (DataSource) env.lookup("SQLOracle");
        } else if ("postgres".equals(dbName)) {
            // logger.info("looking up postgres...");
            ds = (DataSource) env.lookup("SQLPostgres");
        }
    } catch (NamingException ne) {
        ne.printStackTrace();
        logger.warn("This is :" + ne.getMessage() + " when we tried to get the connection");
    }
}
Also used : InitialContext(javax.naming.InitialContext) ApplicationContext(org.springframework.context.ApplicationContext) Context(javax.naming.Context) NamingException(javax.naming.NamingException) InitialContext(javax.naming.InitialContext) OracleDataSource(oracle.jdbc.pool.OracleDataSource) DataSource(javax.sql.DataSource)

Example 80 with Context

use of javax.naming.Context in project OpenAM by OpenRock.

the class JdbcSimpleUserDao method initialize.

/**
     * This class must be called before using the methods since the datasource
     * must be set up.
     * This version of initialize is used when connections are retreived using
     * a Java EE datasource resource which is configured through the application
     * server. For example if you use your server's ability to configure and
     * pool connections. This also requires a java:comp/env resource-ref
     * in web.xml
     *
     * @throws java.lang.InstantiationException when not able to instantiate
     *      this class, for example if parameters are bad or null or can not
     *      make a connection to datasource.
     */
public void initialize(String jndiName, String userDataBaseTableName, String membershipDataBaseTableName, Debug idRepoDebugLog) throws java.lang.InstantiationException {
    useJNDI = true;
    //validate input parameters
    if (jndiName == null || jndiName.trim().length() == 0 || userDataBaseTableName == null || userDataBaseTableName.trim().length() == 0 || idRepoDebugLog == null || membershipDataBaseTableName == null) {
        String msg = "JdbcSimpleUserDao.initialize" + " validation failed to make and make a new instance" + " with paramaters: jndiName=" + jndiName + " userDataBaseTableName=" + userDataBaseTableName + " membershipDataBaseTableName=" + membershipDataBaseTableName + " debug=" + idRepoDebugLog == null ? null : idRepoDebugLog.getName();
        if (idRepoDebugLog != null && idRepoDebugLog.messageEnabled()) {
            idRepoDebugLog.message(msg);
        }
        throw new java.lang.InstantiationException(msg);
    }
    //set class fields to input paramater
    debug = idRepoDebugLog;
    datasourceName = jndiName.trim();
    userTableName = userDataBaseTableName.trim();
    //input value for membership table can be empty, but null is not allowed
    if (membershipDataBaseTableName != null) {
        membershipTableName = membershipDataBaseTableName.trim();
    }
    //set the datasource class field
    try {
        Context ctx = new InitialContext();
        //java:comp/env requires a resource-ref in web.xml
        datasource = (DataSource) ctx.lookup(datasourceName);
    } catch (Exception ex) {
        String msg = "JdbcSimpleUserDao.getInstance:" + " Not able to initialize the datasource through JNDI" + " for datasourceName=" + datasourceName;
        if (debug.errorEnabled()) {
            debug.error(msg + " exception =" + ex);
        }
        //reset to un-initialized state
        datasourceName = null;
        datasource = null;
        userTableName = null;
        debug = null;
        throw new java.lang.InstantiationException(msg + ex.getMessage());
    }
    Connection con = null;
    try {
        //test out and log database info to debug log
        con = getConnection();
        DatabaseMetaData dbmd = con.getMetaData();
        if (debug.messageEnabled()) {
            debug.message("JdbcSimpleUserDao.initialize: DB Meta Data:" + " name=" + (dbmd == null ? "Not Available" : dbmd.getUserName()) + " url=" + (dbmd == null ? "Not Available" : dbmd.getURL()));
        }
        databaseURL = (dbmd == null ? null : dbmd.getURL());
        isMySQL = isMySQL(databaseURL);
    } catch (Exception ex) {
        String msg = "JdbcSimpleUserDao.getInstance:" + " Not able to connect the datasource and get the meta" + " data such as DB url";
        if (debug.errorEnabled()) {
            debug.error(msg + " exception =" + ex);
        }
        //reset to un-initialized state
        datasourceName = null;
        datasource = null;
        userTableName = null;
        membershipTableName = null;
        throw new java.lang.InstantiationException(msg + ex.getMessage());
    } finally {
        closeConnection(con);
        //reset to un-initialized state
        if (datasourceName == null) {
            debug = null;
        }
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData) InitialContext(javax.naming.InitialContext) IdRepoUnsupportedOpException(com.sun.identity.idm.IdRepoUnsupportedOpException) SQLException(java.sql.SQLException)

Aggregations

Context (javax.naming.Context)507 InitialContext (javax.naming.InitialContext)250 Test (org.junit.Test)173 NamingException (javax.naming.NamingException)156 DataSource (javax.sql.DataSource)72 Properties (java.util.Properties)67 Connection (java.sql.Connection)62 NameNotFoundException (javax.naming.NameNotFoundException)52 UserTransaction (javax.transaction.UserTransaction)48 SQLException (java.sql.SQLException)46 IOException (java.io.IOException)44 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)44 Statement (java.sql.Statement)42 Name (javax.naming.Name)38 Hashtable (java.util.Hashtable)35 NameAlreadyBoundException (javax.naming.NameAlreadyBoundException)27 BeanContext (org.apache.openejb.BeanContext)27 Binding (javax.naming.Binding)25 Reference (javax.naming.Reference)25 NotContextException (javax.naming.NotContextException)23