List of usage examples for javax.naming InitialContext lookup
public Object lookup(Name name) throws NamingException
From source file:org.exoplatform.services.naming.InitialContextTest.java
public void testGetContext() throws Exception { assertNotNull(System.getProperty(Context.INITIAL_CONTEXT_FACTORY)); InitialContext ctx = new InitialContext(); assertNotNull(ctx);/*from ww w . j a va 2 s . c om*/ ctx.bind("test", "test"); assertEquals("test", ctx.lookup("test")); try { ctx.bind("test", "test2"); fail("A NameAlreadyBoundException is expected here"); } catch (NameAlreadyBoundException e) { // expected exception } assertEquals("test", ctx.lookup("test")); ctx.rebind("test", "test2"); assertEquals("test2", ctx.lookup("test")); initializer.getInitialContext().bind("test", "test3"); assertEquals("test3", ctx.lookup("test")); ctx.rebind("test", "test4"); assertEquals("test3", ctx.lookup("test")); initializer.getInitialContext().rebind("test", "test5"); assertEquals("test5", ctx.lookup("test")); initializer.getInitialContext().unbind("test"); try { initializer.getInitialContext().lookup("test"); fail("A NameNotFoundException is expected here"); } catch (NameNotFoundException e) { // expected exception } assertEquals("test4", ctx.lookup("test")); ctx.unbind("test"); try { ctx.lookup("test"); fail("A NameNotFoundException is expected here"); } catch (NameNotFoundException e) { // expected exception } try { initializer.getInitialContext().unbind("test2"); fail("A NameNotFoundException is expected here"); } catch (NameNotFoundException e) { // expected exception } initializer.getInitialContext().bind("foo", "foo"); assertEquals("foo", ctx.lookup("foo")); initializer.getInitialContext().bind("foo2", "foo2"); assertEquals("foo2", ctx.lookup("foo2")); try { initializer.getInitialContext().rename("foo", "foo2"); fail("A NameAlreadyBoundException is expected here"); } catch (NameAlreadyBoundException e) { // expected exception } assertEquals("foo", ctx.lookup("foo")); assertEquals("foo2", ctx.lookup("foo2")); try { initializer.getInitialContext().rename("foo3", "foo4"); fail("A NameNotFoundException is expected here"); } catch (NameNotFoundException e) { // expected exception } initializer.getInitialContext().rename("foo", "foo3"); assertEquals("foo", ctx.lookup("foo3")); assertEquals("foo2", ctx.lookup("foo2")); try { initializer.getInitialContext().lookup("foo"); fail("A NameNotFoundException is expected here"); } catch (NameNotFoundException e) { // expected exception } // check same instance initializer.getInitialContext().bind("bla", "bla"); Object obj1 = initializer.getInitialContext().lookup("bla"); Object obj2 = initializer.getInitialContext().lookup("bla"); assertTrue(obj1 == obj2); }
From source file:org.artificer.repository.jcr.JCRRepository.java
public void startup() throws RepositoryException { URL configUrl = null;/* w w w.j av a2s. co m*/ try { configUrl = getModeshapeConfigurationUrl(); } catch (Exception e) { log.error(e.getMessage(), e); } //Using the Modeshape Service if (configUrl == null) { String srampJndiLocation = ArtificerConfig .getConfigProperty(ArtificerConstants.ARTIFICER_CONFIG_JCR_REPO_JNDI_PATH, ARTIFICER_JNDI); log.info(Messages.i18n.format("CONNECT_TO_MS", srampJndiLocation)); try { InitialContext context = new InitialContext(); repository = (javax.jcr.Repository) context.lookup(srampJndiLocation); } catch (NamingException e) { throw new RepositoryException(e.getMessage(), e); } if (repository == null) { throw new RepositoryException(Messages.i18n.format("JNDI_BINDING_NOT_FOUND", srampJndiLocation)); } } //Using Modeshape embedded else { log.info(Messages.i18n.format("STARTING_MS")); try { Map<String, String> parameters = new HashMap<String, String>(); RepositoryConfiguration config = RepositoryConfiguration.read(configUrl); Problems problems = config.validate(); if (problems.hasErrors()) { throw new RepositoryException(problems.toString()); } parameters.put("org.modeshape.jcr.URL", configUrl.toExternalForm()); Set<RepositoryFactory> services = ServiceRegistryUtil.getServices(RepositoryFactory.class); if (services.isEmpty()) throw new RepositoryException(Messages.i18n.format("FAILED_TO_CREATE_JCR_REPO")); for (RepositoryFactory factory : services) { theFactory = factory; repository = factory.getRepository(parameters); if (repository != null) break; } } catch (RepositoryException e) { throw e; } catch (Exception e) { throw new RepositoryException(e); } finally { if (this.tempConfigDir != null && this.tempConfigDir.isDirectory()) { FileUtils.deleteQuietly(tempConfigDir); } } } configureNodeTypes(); createQueryIndexes(); }
From source file:org.asimba.engine.cluster.JGroupsCluster.java
/** * Return the JChannel instance configured for this JGroupsCluster<br/> * Note: the JChannel is connected to upon first instantiation *//*from ww w . j a v a2 s . co m*/ @Override public Object getChannel() { if (_jChannel == null) { String sNodeId = null; // initialize channel from initialcontext try { InitialContext ic = new InitialContext(); sNodeId = (String) ic.lookup("java:comp/env/" + PROP_ASIMBA_NODE_ID); _oLogger.debug("Trying to read the node id from initial context"); } catch (NamingException e) { _oLogger.warn("Getting initialcontext failed! " + e.getMessage()); } if (StringUtils.isEmpty(sNodeId)) { // Initialize the channel, based on configuration sNodeId = System.getProperty(PROP_ASIMBA_NODE_ID); } if (StringUtils.isEmpty(sNodeId)) { try { // Initialize the channel, based on hostname sNodeId = getHostName(); } catch (UnknownHostException ex) { _oLogger.error("Getting hostname failed! " + ex.getMessage()); } } try { if (sNodeId != null) { // Apply custom options: Map<String, String> mOptions = _mCustomOptions.get(sNodeId); _oLogger.info("System property " + PROP_ASIMBA_NODE_ID + " specified; applying" + "custom properties JGroupsCluster '" + _sID + "', node '" + sNodeId + "'"); for (Entry<String, String> prop : mOptions.entrySet()) { System.setProperty(prop.getKey(), prop.getValue()); } } else { _oLogger.info("No " + PROP_ASIMBA_NODE_ID + " system property specified, so no " + "custom properties applied for JGroupsCluster '" + _sID + "'"); } _jChannel = new JChannel(_sConfigLocation); if (_sID != null) _jChannel.setName(_sID); _oLogger.info("Connecting to cluster " + _sID + " with name " + _sClusterName); _jChannel.connect(_sClusterName); } catch (Exception e) { _oLogger.error("Could not create JChannel: " + e.getMessage(), e); return null; } } return _jChannel; }
From source file:net.chrisrichardson.foodToGo.ejb3.facadeWithSpringDI.PlaceOrderFacadeUsingIntegratedDependencyInjectImpl.java
private void lookForEM() { try {//from ww w. j a va 2 s . co m InitialContext initialContext = new InitialContext(); String root = "java:comp.ejb3"; logger.debug("Starting listing"); listContext(initialContext, root); logger.debug("End listing"); EntityManager em = (EntityManager) initialContext.lookup("java:comp.ejb3/env/ejb/EntityManager"); logger.debug("Got entity manager2"); } catch (NamingException e) { logger.error(e); } }
From source file:gov.nih.nci.security.util.ConfigurationHelper.java
private DataSource getDataSourceFromConfiguration(Properties configPropetries) { DataSource ds = null;/* w w w . j ava2 s . com*/ if (configPropetries != null) { String datasource = configPropetries.getProperty("hibernate.connection.datasource"); if (!StringUtils.isEmpty(datasource)) { log.info("Datasource::" + datasource); try { InitialContext initialContext = new InitialContext(); ds = (DataSource) initialContext.lookup(datasource); } catch (NamingException ex) { log.info("Exception occured while looking up datasource::" + datasource); } } else { String urlProperty = configPropetries.getProperty("hibernate.connection.url"); String usernameProperty = configPropetries.getProperty("hibernate.connection.username"); String passwordProperty = configPropetries.getProperty("hibernate.connection.password"); String driverProperty = configPropetries.getProperty("hibernate.connection.driver_class"); log.info("Connection:user:" + configPropetries.getProperty("hibernate.connection.username")); log.info("Connection:url:" + configPropetries.getProperty("hibernate.connection.url")); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driverProperty); dataSource.setUrl(urlProperty); dataSource.setUsername(usernameProperty); dataSource.setPassword(passwordProperty); ds = dataSource; } } return ds; }
From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageReceiver.java
public QueueMessageReceiver(String connectionString, String hostName, String port, String userName, String password, String queueName, int ackMode, boolean useMessageListener, AtomicInteger messageCounter, int delayBetweenMessages, int printNumberOfMessagesPer, boolean isToPrintEachMessage, String fileToWriteReceivedMessages, int stopAfter, int ackAfterEach, int commitAfterEach, int rollbackAfterEach) { this.hostName = hostName; this.port = port; this.connectionString = connectionString; this.useMessageListener = useMessageListener; this.delayBetweenMessages = delayBetweenMessages; this.messageCounter = messageCounter; this.queueName = queueName; this.printNumberOfMessagesPer = printNumberOfMessagesPer; this.isToPrintEachMessage = isToPrintEachMessage; this.fileToWriteReceivedMessages = fileToWriteReceivedMessages; this.stopAfter = stopAfter; this.ackAfterEach = ackAfterEach; this.commitAfterEach = commitAfterEach; this.rollbackAfterEach = rollbackAfterEach; Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF); properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password)); properties.put("queue." + queueName, queueName); try {/*from ww w . ja v a2 s . c o m*/ InitialContext ctx = new InitialContext(properties); // Lookup connection factory QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME); queueConnection = connFactory.createQueueConnection(); queueConnection.start(); if (ackMode == QueueSession.SESSION_TRANSACTED) { queueSession = queueConnection.createQueueSession(true, ackMode); } else { queueSession = queueConnection.createQueueSession(false, ackMode); } Queue queue = (Queue) ctx.lookup(queueName); queueReceiver = queueSession.createReceiver(queue); } catch (NamingException e) { log.error("Error while looking up for queue", e); } catch (JMSException e) { log.error("Error while initializing queue connection", e); } }
From source file:org.jmws.webapp.action.UserLogInAction.java
/** * Executes the UserLogIn Struts Action. * @param mapping//from w ww .ja v a 2s. com * @param form * @param request * @param response * @return */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // retrieve form's parameters String login = null; String password = null; try { login = (String) PropertyUtils.getSimpleProperty(form, "login"); password = (String) PropertyUtils.getSimpleProperty(form, "password"); } catch (Exception e) { } // Form validation ActionErrors errors = new ActionErrors(); if ((login == null) || (login.equals(""))) errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.login.notfound")); else if ((password == null) || (password.equals(""))) errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.password.notfound")); // If any errors, forward errors to input page if (!errors.isEmpty()) { saveErrors(request, errors); return mapping.getInputForward(); } else { try { // JNDI naming context InitialContext context = new InitialContext(); // Get the UserLogInHome interface UserLogInHome home; Object obj = context.lookup(UserLogIn.JNDI_NAME); home = (UserLogInHome) obj; // Get a new UserLogIn session bean. UserLogInRemote remote = home.create(); // Checks log in for the specified User. Boolean logged = remote.checkLogIn(login, password); // Check failed ? if (logged.equals(Boolean.FALSE)) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.failed")); saveErrors(request, errors); return mapping.getInputForward(); } // Check succeeded ? else { // Save User logged in state into Session HttpSession session = request.getSession(); session.setAttribute(Constants.USER_KEY, login); // Forward to success page return mapping.findForward("success"); } } catch (NamingException ne) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.namingexception")); saveErrors(request, errors); return mapping.getInputForward(); } catch (RemoteException re) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.remoteexception")); saveErrors(request, errors); return mapping.getInputForward(); } catch (CreateException ce) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.createexception")); saveErrors(request, errors); return mapping.getInputForward(); } catch (UserWrongPasswordException uspe) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.userwrongpasswordexception")); saveErrors(request, errors); return mapping.getInputForward(); } catch (UserInactiveException uia) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.login.userinactiveexception")); saveErrors(request, errors); return mapping.getInputForward(); } catch (FinderException fe) { // Forward the error to input page errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.global.finderexception")); saveErrors(request, errors); return mapping.getInputForward(); } } }
From source file:org.wso2.mb.integration.common.clients.operations.topic.TopicMessagePublisher.java
public TopicMessagePublisher(String connectionString, String hostName, String port, String userName, String password, String topicName, AtomicInteger messageCounter, int numOfMessagesToSend, int delayBetweenMessages, String filePath, int printNumberOfMessagesPer, boolean isToPrintEachMessage, long jmsExpiration) { this.hostName = hostName; this.port = port; this.connectionString = connectionString; this.messageCounter = messageCounter; this.topicName = topicName; this.numOfMessagesToSend = numOfMessagesToSend; this.delay = delayBetweenMessages; this.filePath = filePath; if (filePath != null && !filePath.equals("")) { readFromFile = true;//from w ww . j a v a2 s. com } this.printNumberOfMessagesPer = printNumberOfMessagesPer; this.isToPrintEachMessage = isToPrintEachMessage; this.jmsExpiration = jmsExpiration; Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF); properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password)); properties.put("topic." + topicName, topicName); try { InitialContext ctx = new InitialContext(properties); // Lookup connection factory TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME); topicConnection = connFactory.createTopicConnection(); topicConnection.start(); topicSession = topicConnection.createTopicSession(true, TopicSession.SESSION_TRANSACTED); // Send message Topic topic = (Topic) ctx.lookup(topicName); topicPublisher = topicSession.createPublisher(topic); } catch (NamingException e) { log.error("Error while looking up for topic", e); } catch (JMSException e) { log.error("Error while initializing topic connection", e); } }
From source file:org.jboss.test.classloader.test.ScopingUnitTestCase.java
/** Test the ability to override the server classes with ejb local versions *///from www. j a v a2 s.c o m public void testEjbOverrides() throws Exception { getLog().debug("+++ testEjbOverrides"); try { deploy("log4j113-ejb.jar"); InitialContext ctx = new InitialContext(); StatelessSessionHome home = (StatelessSessionHome) ctx.lookup("Log4j113StatelessBean"); StatelessSession bean = home.create(); Throwable error = bean.checkVersion(); getLog().debug("StatelessSession.checkVersion returned:", error); assertTrue("checkVersion returned null", error == null); } catch (Exception e) { getLog().info("Failed to access Log4j113StatelessBean in log4j113-ejb.jar", e); throw e; } finally { undeploy("log4j113-ejb.jar"); } }
From source file:velo.ejb.impl.EmailBean.java
public void sendEmailsToApproversGroup(String agUniqueName, String emailTemplateName, Map<String, Object> varsMap) throws EmailNotificationException { ApproversGroup ag = approversGroupManager.findApproversGroup(agUniqueName); if (ag == null) { throw new EmailNotificationException("Could not find Approvers Group with name '" + agUniqueName + "'"); }//from ww w . j a v a 2s . c o m EmailTemplate et = findEmailTemplate(emailTemplateName); if (et == null) { throw new EmailNotificationException( "Could not find Email Template with name '" + emailTemplateName + "'"); } InitialContext ctx = null; TransactionManager tm = null; try { ctx = new InitialContext(); tm = (TransactionManager) ctx.lookup("java:/TransactionManager"); } catch (Exception e) { e.printStackTrace(); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } } /* try { System.out.println("!!!!!!!!!!!!!!!zzzzzzzzzzZ2: " + tm.getStatus()); System.out.println("!!!!!!!!!!!!!!!Zzzzzzzzzz2: " + tm.getTransaction().getStatus()); }catch(SystemException e) { e.printStackTrace(); } */ //throw new EmailNotificationException("ERROR ERROR ERROR!"); et.setContentVars(varsMap); EdmEmailSender es = new EdmEmailSender(); Email email = null; try { email = es.factoryEmail(et.getSubject(), et.getParsedContent()); //email.addTo("asaf@mydomain.com"); //email.send(); } catch (EmailException e) { log.error("Could not factory email objecT: " + e.getMessage()); throw new EmailNotificationException(e); } catch (ExpressionCreationException e) { log.error("Could parsing email content: " + e.getMessage()); throw new EmailNotificationException(e); } for (User currUser : ag.getApprovers()) { try { if (Generic.isEmailValid(currUser.getEmail())) { email.addTo(currUser.getEmail()); } else { log.warn("The specified email address is not valid, skipping email: " + currUser.getEmail()); } } catch (EmailException e) { log.error("Could not send email to user: " + currUser.getName() + " (email address: '" + currUser.getEmail() + "'), part of ApproversGroup '" + ag.getDescription() + "' due to: " + e.getMessage()); } } try { email.send(); } catch (EmailException e) { throw new EmailNotificationException(e); } }