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:eu.uqasar.util.UQasarUtil.java

/**
 * Writes the project entities to rdf/*  w  ww.j a va2s.c  o  m*/
 */
private static OntModel writeProjectEntries() {
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    try {
        thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
        InitialContext ic = new InitialContext();
        TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");
        List<Project> projects = treeNodeService.getAllProjects();
        for (Project proj : projects) {
            writer.save(proj);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return model;
}

From source file:org.rhq.enterprise.server.core.jaas.JDBCPrincipalCheckLoginModule.java

/**
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#getUsersPassword()
 *//* ww w  .ja  v  a 2  s  .com*/
@Override
protected String getUsersPassword() throws LoginException {
    String username = getUsername();
    if ("admin".equals(username)) {
        throw new FailedLoginException("Cannot log in as overlord");
    }
    String password = getUsernameAndPassword()[1]; // what did the user enter?
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        Properties props = getProperties();
        InitialContext ctx = new InitialContext(props);
        DataSource ds = (DataSource) ctx.lookup(dsJndiName);
        conn = ds.getConnection();

        ps = conn.prepareStatement(principalsQuery);
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next() == true) {
            throw new FailedLoginException("username found in principals - do not continue");
        }

        password = Util.createPasswordHash("MD5", "base64", null, null, password); // return back the string entered by the user as a hash
    } catch (NamingException ex) {
        throw new LoginException(ex.toString(true));
    } catch (SQLException ex) {
        throw new LoginException(ex.toString());
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }

        if (ps != null) {
            try {
                ps.close();
            } catch (Exception e) {
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
            }
        }
    }

    return password;
}

From source file:csiro.pidsvc.core.Settings.java

private Settings(HttpServlet servlet) throws NullPointerException, IOException {
    // Retrieve manifest.
    if ((_servlet = servlet) != null) {
        ServletConfig config = _servlet.getServletConfig();
        if (config != null) {
            ServletContext application = config.getServletContext();
            _manifest = new Manifest(application.getResourceAsStream("/META-INF/MANIFEST.MF"));
        }//from w ww .  j a va  2  s  . c  o m
    }

    // Retrieve settings.
    FileInputStream fis = null;
    try {
        InitialContext context = new InitialContext();
        String settingsFile = (String) context.lookup("java:comp/env/" + SETTINGS_OPT);
        fis = new FileInputStream(settingsFile);
        _properties = new PropertyResourceBundle(fis);
    } catch (NamingException ex) {
        _logger.debug("Using default pidsvc.properties file.");
        _properties = ResourceBundle.getBundle("pidsvc");
    } finally {
        if (fis != null)
            fis.close();
    }

    // Get additional system properties.
    _serverProperties.put("serverJavaVersion", System.getProperty("java.version"));
    _serverProperties.put("serverJavaVendor", System.getProperty("java.vendor"));
    _serverProperties.put("javaHome", System.getProperty("java.home"));
    _serverProperties.put("serverOsArch", System.getProperty("os.arch"));
    _serverProperties.put("serverOsName", System.getProperty("os.name"));
    _serverProperties.put("serverOsVersion", System.getProperty("os.version"));
}

From source file:com.flexive.shared.EJBLookup.java

/**
 * Discover which lookup strategy works for the given class
 *
 * @param appName     EJB application name
 * @param environment properties passed to the initial context
 * @param type        the class//from  w  w  w .  j ava2 s . c  o  m
 * @return appName (may have changed)
 */
private static <T> String discoverStrategy(String appName, final Hashtable<String, String> environment,
        Class<T> type) {
    InitialContext ctx = null;
    for (STRATEGY strat : STRATEGY.values()) {
        if (strat == STRATEGY.UNKNOWN)
            continue;
        used_strategy = strat;
        try {
            final Hashtable<String, String> env = environment != null
                    ? new Hashtable<String, String>(environment)
                    : new Hashtable<String, String>();
            prepareEnvironment(strat, env);
            ctx = new InitialContext(env);
            ctx.lookup(buildName(appName, type));

            if (used_strategy == STRATEGY.EJB31_MODULE) {
                // we need to resolve all interfaces required by non-web components (stream server, scheduler),
                // since they run outside the module context

                resolveKnownInterfaces();
            }
            return appName;
        } catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Strategy " + strat + " failed: " + e.getMessage(), e);
            }
            //ignore and try next
        }
    }
    //houston, we have a problem - try locale and remote with appname again iterating through all "root" ctx bindings
    //this can happen if the ear is not named flexive.ear
    try {
        if (ctx == null)
            ctx = new InitialContext(environment);
        NamingEnumeration<NameClassPair> ncpe = ctx.list("");
        while (ncpe.hasMore()) {
            NameClassPair ncp = ncpe.next();
            if (ncp.getClassName().endsWith("NamingContext")) {
                appName = ncp.getName();
                try {
                    used_strategy = STRATEGY.APP_SIMPLENAME_LOCAL;
                    ctx.lookup(buildName(ncp.getName(), type));
                    APPNAME = ncp.getName();
                    LOG.info("Using application name [" + appName + "] for lookups!");
                    return APPNAME;
                } catch (Exception e) {
                    //ignore and try remote
                }
                try {
                    used_strategy = STRATEGY.APP_SIMPLENAME_REMOTE;
                    ctx.lookup(buildName(ncp.getName(), type));
                    APPNAME = ncp.getName();
                    LOG.info("Using application name [" + appName + "] for lookups!");
                    return APPNAME;
                } catch (Exception e) {
                    //ignore and try remote
                }
            }
        }
    } catch (Exception e) {
        LOG.warn(e);
    }
    used_strategy = null;
    return appName;
}

From source file:org.josso.jbportal27.agent.JOSSOIdentityServiceImpl.java

/**
 * //  w w w .j a  v a2  s .c o  m
 *
 */
public void start() {
    try {
        InitialContext initialContext = new InitialContext();

        this.userModule = (UserModule) initialContext.lookup("java:/portal/UserModule");
        this.profileModule = (UserProfileModule) initialContext.lookup("java:/portal/UserProfileModule");
        this.membershipModule = (MembershipModule) initialContext.lookup("java:/portal/MembershipModule");
    } catch (Exception e) {
        logger.error(this, e);
        this.stop();
    }
}

From source file:org.nuxeo.ecm.core.event.jms.JmsEventForwarder.java

protected void produceJMSMessage(SerializableEventBundle message) throws JMSBusNotActiveException {
    InitialContext ctx;
    Topic nuxeoTopic;//  w ww  .  j  av a2  s. co m
    try {
        ctx = new InitialContext();
        nuxeoTopic = (Topic) ctx.lookup(NUXEO_JMS_TOPIC);
    } catch (NamingException e) {
        jmsBusIsActive = false;
        throw new JMSBusNotActiveException(e);
    }

    TopicConnection nuxeoTopicConnection = null;
    TopicSession nuxeoTopicSession = null;
    TopicPublisher nuxeoMessagePublisher = null;
    try {
        TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");
        nuxeoTopicConnection = factory.createTopicConnection();
        nuxeoTopicSession = nuxeoTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);

        ObjectMessage jmsMessage = nuxeoTopicSession.createObjectMessage(message);

        // add Headers for JMS message
        jmsMessage.setStringProperty("BundleEvent", message.getEventBundleName());

        nuxeoMessagePublisher = nuxeoTopicSession.createPublisher(nuxeoTopic);

        nuxeoMessagePublisher.send(jmsMessage);
        log.debug("Event bundle " + message.getEventBundleName() + " forwarded to JMS topic");

    } catch (Exception e) {
        log.error("Error during JMS forwarding", e);
    } finally {
        if (nuxeoTopicSession != null) {
            try {
                if (nuxeoMessagePublisher != null) {
                    nuxeoMessagePublisher.close();
                }
                nuxeoTopicConnection.close();
                nuxeoTopicSession.close();
            } catch (JMSException e) {
                log.error("Error during JMS cleanup", e);
            }
        }
    }
}

From source file:org.wso2.carbon.custom.connector.EJBConnector.java

/**
 * Calls the EJB Service. Will have to modify as need to fit your requirement.
 *
 * @throws Exception/*  ww w  .j a v  a  2  s .co  m*/
 */
public void callEJB() throws Exception {
    InitialContext context = getInitialContext();// new InitialContext();
    String serviceReference = "java:global/org.wso2.carbon.custom.ejb-1.0-SNAPSHOT/HelloBean";
    HelloIF clientBean = (HelloIF) context.lookup(serviceReference);
    log.info("EJB Service Response >>>>>>>>>>>>> " + clientBean.sayHello());
}

From source file:org.jetbrains.webdemo.servlet.KotlinHttpServlet.java

private boolean loadTomcatParameters() {
    InitialContext initCtx = null;
    try {/*from  www . j ava 2  s  .c  o m*/
        initCtx = new InitialContext();
        NamingContext envCtx = (NamingContext) initCtx.lookup("java:comp/env");
        try {
            CommandRunner.setServerSettingFromTomcatConfig("app_output_dir",
                    (String) envCtx.lookup("app_output_dir"));
        } catch (NamingException e) {
            File rootFolder = new File(ApplicationSettings.WEBAPP_ROOT_DIRECTORY);
            String appHome = rootFolder.getParentFile().getParentFile().getParent();
            CommandRunner.setServerSettingFromTomcatConfig("app_output_dir", appHome);
        }

        try {
            CommandRunner.setServerSettingFromTomcatConfig("is_test_version",
                    (String) envCtx.lookup("is_test_version"));
        } catch (NameNotFoundException e) {
            //Absent is_test_version variable in context.xml
            CommandRunner.setServerSettingFromTomcatConfig("is_test_version", "false");
        }

        CommandRunner.setServerSettingFromTomcatConfig("backend_url", (String) envCtx.lookup("backend_url"));
        return true;
    } catch (Throwable e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        return false;
    }

}

From source file:org.rhq.enterprise.server.core.jaas.JDBCLoginModule.java

/**
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#getUsersPassword()
 *///from w w  w . j av a2 s.  c  o m
@Override
protected String getUsersPassword() throws LoginException {
    String username = getUsername();
    if ("admin".equals(username)) {
        throw new FailedLoginException("Cannot log in as overlord");
    }
    String password = null;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        Properties props = getProperties();
        InitialContext ctx = new InitialContext(props);
        DataSource ds = (DataSource) ctx.lookup(dsJndiName);
        conn = ds.getConnection();

        ps = conn.prepareStatement(principalsQuery);
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next() == false) {
            throw new FailedLoginException("No matching username found in principals");
        }

        password = rs.getString(1);
    } catch (NamingException ex) {
        throw new LoginException(ex.toString(true));
    } catch (SQLException ex) {
        throw new LoginException(ex.toString());
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }

        if (ps != null) {
            try {
                ps.close();
            } catch (Exception e) {
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
            }
        }
    }

    return password;
}

From source file:org.hawkular.apm.server.jms.AbstractPublisherJMS.java

@PostConstruct
public void init() {
    try {/*from  w  w  w  . j a va2  s. co  m*/
        InitialContext context = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("java:/APMJMSCF");
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // TODO: Transacted?
        Destination destination = (Destination) context.lookup(getDestinationURI());
        producer = session.createProducer(destination);
        connection.start();
    } catch (Exception e) {
        msgLog.errorFailedToInitPublisher(getDestinationURI(), e);
    }
}