Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:com.adaptris.core.SharedComponentListTest.java

public void testRemoveConnection_unbindsJNDI() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());/*w w w. j  a va  2 s  .  co  m*/
    adapter.getSharedComponents().addConnection(new NullConnection(getName()));
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);
        NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName());
        assertNotNull(lookedup);
        assertEquals(getName(), lookedup.getUniqueId());
        adapter.getSharedComponents().removeConnection(getName());
        try {
            initialContext.lookup("adapter:comp/env/" + getName());
            fail();
        } catch (NamingException expected) {
        }
    } finally {
        stop(adapter);
    }
}

From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java

protected void generateMail(String destination, String copy, String title, String content)
        throws NamingException, MessagingException {

    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(getJavaMailJndiName());

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false));
    if (!isBlank(copy)) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false));
    }/*from   w  w  w  . j a va2 s  .  c o m*/

    msg.setSubject(title, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content, "text/html; charset=utf-8");

    Transport.send(msg);
}

From source file:com.boylesoftware.web.AbstractWebApplication.java

/**
 * Initialize the web-application. Called by the framework just before the
 * application is made available in the container.
 *
 * @throws UnavailableException If application cannot be initialized.
 * Throwing the exception makes the application fail to start.
 *///from  w  w  w . j  a v  a2  s  . c  om
void onRouterInit() throws UnavailableException {

    // get the log
    final Log log = LogFactory.getLog(AbstractWebApplication.class);
    log.debug("initializing the web-application");

    // initialize the application
    boolean success = false;
    try {

        // create configuration
        log.debug("creating configuration");
        this.configure(this.configProperties);

        // get the authenticator
        final ServletContext sc = this.servletContext;
        log.debug("creating authenticator");
        this.services.setAuthenticationService(this.getAuthenticationService(sc, this));

        // get validator factory
        log.debug("creating validator factory");
        this.services.setValidatorFactory(this.getValidatorFactory(sc, this));

        // get user locale finder
        log.debug("creating user locale finder");
        this.services.setUserLocaleFinder(this.getUserLocaleFinder(sc, this));

        // create entity manager factory
        log.debug("creating persistence manager factory");
        this.services.setEntityManagerFactory(this.getEntityManagerFactory(sc, this));

        // get JavaMail session from the JNDI
        log.debug("attempting to find JavaMail session in the JNDI");
        try {
            final InitialContext jndi = new InitialContext();
            try {
                this.services
                        .setMailSession((Session) jndi.lookup(this.getConfigProperty(MAIL_SESSION_JNDI_NAME,
                                String.class, ApplicationServices.DEFAULT_MAIL_SESSION_JNDI_NAME)));
            } catch (final NameNotFoundException e) {
                log.debug("no JavaMail session in the JNDI, JavaMail will" + " be unavailable", e);
            }
        } catch (final NamingException e) {
            log.error("Error accessing JNDI.", e);
        }

        // get the router configuration
        log.debug("creating routes configuration");
        this.routerConfiguration = this.getRouterConfiguration(sc, this, this.services);

        // initialize custom application
        log.debug("initializing custom application");
        this.init();

        // get the executor service
        log.debug("creating request processing executor service");
        this.executors = this.getExecutorService(sc, this);

        // done
        log.debug("initialized successfully");
        success = true;

    } finally {
        if (!success) {
            log.debug("initialization error");
            this.cleanup();
        }
    }
}

From source file:org.pepstock.jem.jbpm.tasks.workitems.MapManager.java

/**
 * Loads a map into another map, putting the instance of data description and data sources
 * @param parameters map of parameters prepared by JBPM
 * @return copy of the map but with the instances of data description and data sources
 *//*ww w  .ja  v  a2  s  .c  o m*/
final Map<String, Object> loadParameters(Map<String, Object> parameters) {
    // gets JNDI context
    InitialContext ic = null;
    try {
        ic = ContextUtils.getContext();
    } catch (NamingException e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    }

    // creates new map
    Map<String, Object> result = new HashMap<String, Object>();
    // scans all parameters
    for (Entry<String, Object> entry : parameters.entrySet()) {
        try {
            // gets key
            String name = entry.getKey();
            // is DD?
            if (name.startsWith(JBpmKeys.JBPM_DATA_DESCRIPTION_PREFIX)) {
                // gets data description name
                String ddn = StringUtils.substringAfter(name, JBpmKeys.JBPM_DATA_DESCRIPTION_PREFIX);
                // if context is not null, lookup and stores on the map
                if (ic != null) {
                    result.put(name, ic.lookup(ddn));
                }
            } else if (name.startsWith(JBpmKeys.JBPM_DATA_SOURCE_PREFIX)) {
                // is Data source?
                // gets datasource name
                String dds = StringUtils.substringAfter(name, JBpmKeys.JBPM_DATA_SOURCE_PREFIX);
                // if context is not null, lookup and stores on the map
                if (ic != null) {
                    result.put(name, ic.lookup(dds));
                }
            } else if (!name.equalsIgnoreCase(JBpmKeys.JBPM_LOCK_KEY)) {
                // is Lock? IGNORE
                result.put(name, entry.getValue());
            }
        } catch (NamingException e) {
            // ignore every naming exception
            LogAppl.getInstance().ignore(e.getMessage(), e);
        }
    }
    return result;
}

From source file:com.adaptris.core.runtime.AdapterRegistryTest.java

public void testProxy_DestroyAdapter_MBean_SharedConnection_JNDI() throws Exception {
    AdapterRegistry myAdapterRegistry = (AdapterRegistry) AdapterRegistry
            .findInstance(new JunitBootstrapProperties(new Properties()));
    AdapterRegistryMBean registry = JMX.newMBeanProxy(mBeanServer, myAdapterRegistry.createObjectName(),
            AdapterRegistryMBean.class);
    String adapterName = this.getClass().getSimpleName() + "." + getName();
    Adapter adapter = createAdapter(adapterName, 2, 2);
    adapter.getSharedComponents().addConnection(new NullConnection(getName()));
    String xml = DefaultMarshaller.getDefaultMarshaller().marshal(adapter);
    ObjectName objName = registry.createAdapter(xml);
    AdapterManagerMBean manager = JMX.newMBeanProxy(mBeanServer, objName, AdapterManagerMBean.class);
    manager.requestStart();/*www.  ja  v a 2s  .c  o  m*/
    InitialContext context = new InitialContext(contextEnv);
    context.lookup("adapter:comp/env/" + getName());
    myAdapterRegistry.destroyAdapter(manager);
    try {
        context.lookup("adapter:comp/env/" + getName());
    } catch (NamingException expected) {

    }
    assertFalse(mBeanServer.isRegistered(objName));
    assertEquals(0, registry.getAdapters().size());
}

From source file:org.wso2.carbon.bpel.b4p.coordination.db.DatabaseUtil.java

@SuppressWarnings("unchecked")
private <T> T lookupInJndi(String objName) throws Exception {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {/*from  w w w.j  ava2s .c o m*/
        InitialContext ctx = null;
        try {
            if (bpelServerConfiguration.getDataSourceJNDIRepoInitialContextFactory() != null
                    && bpelServerConfiguration.getDataSourceJNDIRepoProviderURL() != null) {
                Properties jndiProps = new Properties();

                jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                        bpelServerConfiguration.getDataSourceJNDIRepoInitialContextFactory());
                jndiProps.setProperty(Context.PROVIDER_URL,
                        bpelServerConfiguration.getDataSourceJNDIRepoProviderURL());
                ctx = new InitialContext(jndiProps);
            } else {
                ctx = new InitialContext();
            }
            return (T) ctx.lookup(objName);
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception ex1) {
                    log.error("Error closing JNDI connection.", ex1);
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:org.wso2.carbon.humantask.core.db.Database.java

@SuppressWarnings("unchecked")
private <T> T lookupInJndi(String objName) throws Exception {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {//www. j av a 2  s.  c  om
        InitialContext ctx = null;
        try {
            if (serverConfiguration.getDataSourceJNDIRepoInitialContextFactory() != null
                    && serverConfiguration.getDataSourceJNDIRepoProviderURL() != null) {
                Properties jndiProps = new Properties();

                jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                        serverConfiguration.getDataSourceJNDIRepoInitialContextFactory());
                jndiProps.setProperty(Context.PROVIDER_URL,
                        serverConfiguration.getDataSourceJNDIRepoProviderURL());

                ctx = new InitialContext(jndiProps);
            } else {
                ctx = new InitialContext();
            }
            return (T) ctx.lookup(objName);
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception ex1) {
                    log.error("Error closing JNDI connection.", ex1);
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
public void init(ServletConfig config) {
    /// List possible local address
    try {//from w  w  w  .j  ava  2  s. c om
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual())
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr instanceof Inet4Address)
                    ourIPs.add(current_addr.getHostAddress());
            }
        }
    } catch (Exception e) {
    }

    servContext = config.getServletContext();
    backend = config.getServletContext().getInitParameter("backendserver");
    server = config.getServletContext().getInitParameter("fileserver");
    try {
        String dataProviderName = config.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jetbrains.webdemo.database.MySqlConnector.java

private MySqlConnector() {
    try {// w  ww.  j av a 2 s. c  om
        InitialContext initCtx = new InitialContext();
        NamingContext envCtx = (NamingContext) initCtx.lookup("java:comp/env");
        dataSource = (DataSource) envCtx.lookup("jdbc/kotlin");
        Connection connection = dataSource.getConnection();
        databaseUrl = connection.toString();
        log.info("Connected to database: " + connection.toString());
        ErrorWriter.getInfoForLog("CONNECT_TO_DATABASE", "-1", "Connected to database: " + databaseUrl);
    } catch (Throwable e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e,
                SessionInfo.TypeOfRequest.WORK_WITH_DATABASE.name(), "unknown", databaseUrl);
    }
}