Search in sources :

Example 81 with Context

use of javax.naming.Context in project ACS by ACS-Community.

the class TestJDAL method testListContext.

/**
	 * Listing different contexts - simple and XML contexts
	 * We shouldn't see any difference in listing just 'directory' context
	 * or listing inside a XML data
	 */
public void testListContext() throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.cosylab.cdb.jdal.JNDIContextFactory");
    env.put(Context.PROVIDER_URL, strIOR);
    Context context = null;
    context = new InitialContext(env);
    assertNotNull(context);
    // try simple listing
    String list = "";
    NamingEnumeration ne = context.list("MACI");
    while (ne.hasMore()) {
        NameClassPair pair = (NameClassPair) ne.nextElement();
        list = list + pair.getName() + " ";
    }
    // same as we did listing
    assertTrue(list.indexOf("Containers") != -1);
    assertTrue(list.indexOf("Managers") != -1);
    // try with a XML
    ne = ((Context) (((Context) context.lookup("MACI")).lookup("Managers"))).list("Manager");
    list = "";
    while (ne.hasMore()) {
        NameClassPair pair = (NameClassPair) ne.nextElement();
        list = list + pair.getName() + " ";
    //System.out.println(pair.getName() + " " + pair.getClassName());
    }
    // this should be in Manager data
    assertTrue(list.indexOf("ServiceComponents") != -1);
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Hashtable(java.util.Hashtable) NameClassPair(javax.naming.NameClassPair) NamingEnumeration(javax.naming.NamingEnumeration) InitialContext(javax.naming.InitialContext)

Example 82 with Context

use of javax.naming.Context in project ACS by ACS-Community.

the class TestJDAL method testLookupContext.

/**
	 * Test lookup functions. We can just obtain an InitialContext
	 * and then use it to get any information in the CDB
	 */
public void testLookupContext() throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.cosylab.cdb.jdal.JNDIContextFactory");
    env.put(Context.PROVIDER_URL, strIOR);
    Context context = null;
    context = new InitialContext(env);
    assertNotNull(context);
    // try simple lookup
    String list = "";
    Object ob = context.lookup("MACI");
    assertTrue(ob instanceof Context);
    // try with a value inside XML
    ob = ((Context) (((Context) (((Context) context.lookup("MACI")).lookup("Managers"))).lookup("Manager"))).lookup("ContainerPingInterval");
    assertTrue(ob instanceof String);
    double contPingInt = Double.parseDouble((String) ob);
    assertEquals(2.0, contPingInt);
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Hashtable(java.util.Hashtable) InitialContext(javax.naming.InitialContext)

Example 83 with Context

use of javax.naming.Context in project ACS by ACS-Community.

the class ManagerImpl method bind.

/**
	 * Bind object to remote directory.
	 *
	 * Use INS syntax specified in the INS specification.
	 * In short, the syntax is that components are left-to-right slash ('/') separated and case-sensitive.
	 * The id and kind of each component are separated by the period character ('.').
	 *
	 * @param	remoteDirectory	remote directory context to be used.
	 * @param	name	name of the object, code non-<code>null</code>
	 * @param	object	object to be binded
	 */
private void bind(Context remoteDirectory, String name, String type, Object object) {
    assert (name != null);
    // do not bind interdomain names
    if (name.startsWith(CURL_URI_SCHEMA))
        return;
    if (remoteDirectory != null) {
        try {
            // hierarchical name check
            int pos = name.indexOf('/');
            if (pos != -1) {
                if (pos == 0 || pos == name.length())
                    throw new IllegalArgumentException("Invalid hierarchical name '" + name + "'.");
                String parent = name.substring(0, pos);
                String child = name.substring(pos + 1);
                // lookup for subcontext, if not found create one
                Context parentContext = null;
                try {
                    parentContext = (Context) remoteDirectory.lookup(parent);
                } catch (NameNotFoundException nnfe) {
                // noop
                }
                if (parentContext == null) {
                    parentContext = remoteDirectory.createSubcontext(parent);
                /// @todo temp. commented out
                //generateHiearchyContexts(remoteDirectory, parent, parentContext);
                }
                // delegate
                bind(parentContext, child, type, object);
                return;
            }
            NameParser parser = remoteDirectory.getNameParser("");
            Name n;
            if (type != null)
                n = parser.parse(name + "." + type);
            else
                n = parser.parse(name);
            // special case
            if (name.endsWith(".D")) {
                remoteDirectory.rebind(n, object);
            /// @todo temp. commented out
            //generateHiearchyContexts(remoteDirectory, name, (Context)remoteDirectory.lookup(name));
            } else
                remoteDirectory.bind(n, object);
        } catch (NameAlreadyBoundException nabe) {
            rebind(remoteDirectory, name, type, object);
        } catch (NamingException ne) {
            CoreException ce = new CoreException("Failed to bind name '" + name + "' to the remote directory.", ne);
            logger.log(Level.FINE, ce.getMessage(), ce);
        }
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) CoreException(com.cosylab.acs.maci.CoreException) NameNotFoundException(javax.naming.NameNotFoundException) NamingException(javax.naming.NamingException) NameParser(javax.naming.NameParser) Name(javax.naming.Name)

Example 84 with Context

use of javax.naming.Context in project ACS by ACS-Community.

the class ManagerEngine method initializeManager.

/**
	 * Initialize and activate Manager.
	 */
private void initializeManager() throws Throwable {
    logger = ClientLogManager.getAcsLogManager().getLoggerForApplication("Manager", true);
    logger.info("Initializing Manager.");
    //
    // CORBA
    //
    // obtain CORBA Service
    corbaService = new DefaultCORBAService(logger);
    // get ORB
    final ORB orb = corbaService.getORB();
    if (orb == null) {
        CoreException ce = new CoreException("CORBA Service can not provide ORB.");
        throw ce;
    }
    // get RootPOA
    POA rootPOA = corbaService.getRootPOA();
    if (rootPOA == null) {
        CoreException ce = new CoreException("CORBA Service can not provide RootPOA.");
        throw ce;
    }
    //
    // Remote Directory
    //
    NamingServiceRemoteDirectory remoteDirectory = new NamingServiceRemoteDirectory(orb, logger);
    Context context = null;
    if (remoteDirectory != null)
        context = remoteDirectory.getContext();
    //
    // Initialize CORBA
    //
    // set USER_ID, PERSISTENT policies
    org.omg.CORBA.Policy[] policies = new org.omg.CORBA.Policy[2];
    /*
		// set USER_ID, PERSISTENT,BIDIRECTIONAL policies
		org.omg.CORBA.Policy [] policies = new org.omg.CORBA.Policy[3];
		*/
    policies[0] = rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID);
    policies[1] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT);
    /*
		// create BIDIRECTIONAL policy
		Any bidirValue = orb.create_any();
		BidirectionalPolicyValueHelper.insert(bidirValue, BOTH.value);
		policies[2] = orb.create_policy(BIDIRECTIONAL_POLICY_TYPE.value, bidirValue);
        */
    // create ManagerPOA
    managerPOA = rootPOA.create_POA("ManagerPOA", rootPOA.the_POAManager(), policies);
    // destroy policies
    for (int i = 0; i < policies.length; i++) policies[i].destroy();
    // initialize Manager implementation
    // allow object reference serialization 
    CORBAReferenceSerializator.setOrb(orb);
    manager = new ManagerImpl();
    manager.setDomain(MANAGER_DOMAIN);
    recoveryLocation = FileHelper.getTempFileName(null, RECOVERY_DIR_NAME);
    String readRecovery = System.getProperties().getProperty("Manager.recovery", "true");
    if (readRecovery.equalsIgnoreCase("false")) {
        // if we are not interested in recovery files just delete them
        File recoveryDir = new File(recoveryLocation);
        //recoveryDir.delete();
        File[] files = recoveryDir.listFiles();
        for (int i = 0; files != null && i < files.length; i++) files[i].delete();
        // Now check if there are log files left. Maybe user do not have enough permision
        // or we are didn't set proper permission before Manager killed.
        // That can lead to unwanted or illegal state so we will refuse to continue
        files = recoveryDir.listFiles();
        for (int i = 0; files != null && i < files.length; i++) {
            if (files[i].getName().endsWith(".commandLog"))
                throw new Exception("Some recovery files are left in recovery location probably because of permission\nUnable to start without recovery state!");
        }
    } else {
        // remove old recovery files
        RecoveryFilesRemover.removeRecoveryFiles(new File(recoveryLocation));
    }
    SnapshotPrevayler prevayler = null;
    if (isPrevaylerDisabled) {
        System.out.println("Prevayler disabled!");
    } else {
        prevayler = new SnapshotPrevayler(manager, recoveryLocation);
        if (readRecovery.equalsIgnoreCase("false")) {
            // just to invalidate prevaylers message
            System.out.println("Skipping saved manager state!");
        }
        manager = (ManagerImpl) prevayler.system();
    }
    CDBAccess cdbAccess = new CDBAccess(orb, logger);
    LogConfig logConfig = ClientLogManager.getAcsLogManager().getLogConfig();
    logConfig.setCDBLoggingConfigPath("MACI/Managers/Manager");
    logConfig.setCDB(cdbAccess.connectAndGetDAL());
    try {
        logConfig.initialize(false);
    } catch (LogConfigException ex) {
        // if the CDB can't be read, we still want to run the manager, so
        // we only log the problems
        logger.log(Level.FINE, "Failed to configure logging (default values will be used). Reason: " + ex.getMessage());
    }
    // initialize manager "mock" container services
    ManagerContainerServices managerContainerServices = new ManagerContainerServices(orb, managerPOA, cdbAccess.getDAL(), logger);
    manager.initialize(prevayler, cdbAccess, context, logger, managerContainerServices);
    manager.setShutdownImplementation(shutdownImplementation);
    // setup ORB profiling
    try {
        if (orb instanceof AcsProfilingORB) {
            AcsORBProfiler profiler = new ManagerOrbProfiler(manager, logger);
            ((AcsProfilingORB) orb).registerAcsORBProfiler(profiler);
            logger.finer("Orb profiling set up, using class " + ManagerOrbProfiler.class.getName());
        }
    } catch (Throwable th) {
        logger.log(Level.WARNING, "Failed to setup ORB profiling.", th);
    }
    if (prevayler != null) {
        FileHelper.setFileAttributes("g+w", recoveryLocation);
        // create new task for snapshoot creation,
        final long MINUTE_IN_MS = 60 * 1000;
        new RecoverySnapshotTask(prevayler, 1 * MINUTE_IN_MS, recoveryLocation, manager.getStatePersitenceFlag());
    }
    // initialize Manager CORBA Proxy (create servant)
    managerProxy = new ManagerProxyImpl(manager, logger);
    //activate object
    managerPOA.activate_object_with_id(MANAGER_ID, managerProxy);
    // get object reference from the servant
    org.omg.CORBA.Object obj = managerPOA.servant_to_reference(managerProxy);
    managerReference = ManagerHelper.narrow(obj);
    // get IOR
    String ior = orb.object_to_string(managerReference);
    // notify user
    logger.info("Manager activated with " + ior);
    // register special service components to the Manager
    manager.setManagerComponentReference(managerReference);
    // set transport
    manager.setTransport(new CORBATransport(orb, ior));
    // register NameService
    if (remoteDirectory != null) {
        String reference = remoteDirectory.getReference();
        if (reference != null) {
            // convert iiop to corbaloc
            if (reference.startsWith("iiop://")) {
                reference = reference.replaceFirst("iiop://", "corbaloc::");
                if (reference.charAt(reference.length() - 1) != '/')
                    reference += "/NameService";
                else
                    reference += "NameService";
            }
        }
        try {
            obj = NamingContextHelper.narrow(orb.string_to_object(reference));
        } catch (Exception ex) {
            // Something went wrong getting the NS
            logger.log(Level.SEVERE, "Error getting the NameServer. Manager exiting...");
            this.shutdownImplementation.shutdown(false);
        }
        manager.setRemoteDirectoryComponentReference(obj);
    }
    // intitialize federation here - after remote directory is set (if it is)
    // (this is not a nice solution)
    Hashtable federationDirectoryProperties = new Hashtable();
    // set CosNamingFactory 
    federationDirectoryProperties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
    // set orb
    federationDirectoryProperties.put("java.naming.corba.orb", orb);
    manager.initializeFederation(federationDirectoryProperties);
    // initialize remote logging
    new Thread(new Runnable() {

        public void run() {
            ClientLogManager.getAcsLogManager().initRemoteLogging(orb, managerReference, manager.getHandle(), true);
        }
    }, "Remote logging initializer").start();
    manager.initializationDone();
}
Also used : SnapshotPrevayler(org.prevayler.implementation.SnapshotPrevayler) LogConfigException(alma.acs.logging.config.LogConfigException) ManagerProxyImpl(com.cosylab.acs.maci.plug.ManagerProxyImpl) DefaultCORBAService(com.cosylab.acs.maci.plug.DefaultCORBAService) AcsORBProfiler(org.jacorb.orb.acs.AcsORBProfiler) NamingServiceRemoteDirectory(com.cosylab.acs.maci.plug.NamingServiceRemoteDirectory) AcsProfilingORB(org.jacorb.orb.acs.AcsProfilingORB) Context(javax.naming.Context) POA(org.omg.PortableServer.POA) CDBAccess(com.cosylab.cdb.client.CDBAccess) Hashtable(java.util.Hashtable) LogConfigException(alma.acs.logging.config.LogConfigException) CoreException(com.cosylab.acs.maci.CoreException) CoreException(com.cosylab.acs.maci.CoreException) ManagerImpl(com.cosylab.acs.maci.manager.ManagerImpl) CORBATransport(com.cosylab.acs.maci.plug.CORBATransport) File(java.io.File) ORB(org.omg.CORBA.ORB) AcsProfilingORB(org.jacorb.orb.acs.AcsProfilingORB) LogConfig(alma.acs.logging.config.LogConfig)

Example 85 with Context

use of javax.naming.Context in project aries by apache.

the class ServiceRegistryContextTest method testLookupWithPause.

@Test
public void testLookupWithPause() throws NamingException {
    BundleMock mock = new BundleMock("scooby.doo", new Properties());
    Thread.currentThread().setContextClassLoader(mock.getClassLoader());
    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(JNDIConstants.REBIND_TIMEOUT, 1000);
    InitialContext ctx = new InitialContext(env);
    Context ctx2 = (Context) ctx.lookup("osgi:service");
    Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable");
    reg.unregister();
    long startTime = System.currentTimeMillis();
    try {
        r1.run();
        fail("Should have received an exception");
    } catch (ServiceException e) {
        long endTime = System.currentTimeMillis();
        long diff = endTime - startTime;
        assertTrue("The run method did not fail in the expected time (1s): " + diff, diff >= 1000);
    }
}
Also used : Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) BundleContext(org.osgi.framework.BundleContext) ServiceException(org.osgi.framework.ServiceException) Hashtable(java.util.Hashtable) BundleMock(org.apache.aries.mocks.BundleMock) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

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