Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Get the servlet configuration/*from  w w  w. ja  v  a2 s  . c  om*/
 * <p>
 * @return HTTP response containing the Servlet configuration in JSON format
 */
@GET
@Path("config")
@Produces(MediaType.APPLICATION_JSON)
public Response getConfig() {

    log.info("GET raml/config");

    Map<String, Object> configMap = new LinkedHashMap<String, Object>();

    try {
        Context initialContext = new InitialContext();
        Context envContext = (Context) initialContext.lookup("java:comp/env");

        configMap.put("vseServerUrl", envContext.lookup("vseServerUrl"));
        configMap.put("vseServicePortRange", envContext.lookup("vseServicePortRange"));
        configMap.put("vseServiceReadyWaitSeconds", envContext.lookup("vseServiceReadyWaitSeconds"));

    } catch (NamingException e) {
        e.printStackTrace();
        log.error("Failed to obtain servlet configuration", e.getCause());
    }

    GsonBuilder gsonBuilder = new GsonBuilder();

    gsonBuilder.setPrettyPrinting();
    gsonBuilder.serializeNulls();

    Gson gson = gsonBuilder.create();

    Response response = Response.status(200).entity(gson.toJson(configMap)).build();

    return response;
}

From source file:com.app.server.XMLDeploymentScanner.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    this.serviceList = serviceList;
    this.serverConfig = serverConfig;
    this.mbeanServer = mbeanServer;
    this.userLibDir = serverConfig.getServiceslibdirectory();
    File userLibJars = new File(userLibDir);
    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
    getUsersJars(userLibJars, jarList);//from   w w  w  .j  a  va2  s  .  c  o m
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    userLibJarLoader = new WebClassLoader(loader.getURLs());
    for (String jarFilePath : jarList) {
        try {
            userLibJarLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/")));
        } catch (Exception e) {
            log.error("Error in url " + "file:/" + jarFilePath.replace("\\", "/"), e);
            //e2.printStackTrace();            
        }
    }

    DigesterLoader xmlDigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {

            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/datasource-rules.xml")));
            } catch (Exception e) {
                log.error("Error in loading config rules ./config/datasource-rules.xml", e);
                //e.printStackTrace();
            }

        }
    });
    xmlDigester = xmlDigesterLoader.newDigester();
    try {
        ic = new InitialContext();
        ic.createSubcontext("java:");
    } catch (Exception e) {
        log.error("Error in creating subcontext", e);
    }
    log.info("initialized");
    // TODO Auto-generated constructor stub
}

From source file:minor.commodity.CommodityQuote.java

private CommodityDetailsFacadeLocal lookupCommodityDetailsFacadeLocal() {
    try {//from   ww w .  j  ava2 s  .  co m
        Context c = new InitialContext();
        return (CommodityDetailsFacadeLocal) c.lookup(
                "java:global/MinorTest/CommodityDetailsFacade!minor.session.CommodityDetailsFacadeLocal");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}

From source file:it.infn.ct.security.actions.ReactivateUser.java

private void sendMail(LDAPUser user) throws MailException {
    javax.mail.Session session = null;/*from w ww  .  j a va  2  s.  c o m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:com.boylesoftware.web.impl.auth.SessionlessAuthenticationService.java

/**
 * Create new authenticator./*from w  ww  .  j av a 2s  .co  m*/
 *
 * @param userRecordHandler User record handler.
 * @param userRecordsCache Authenticated user records cache.
 *
 * @throws UnavailableException If an error happens creating the service.
 */
public SessionlessAuthenticationService(final UserRecordHandler<T> userRecordHandler,
        final UserRecordsCache<T> userRecordsCache) throws UnavailableException {

    // store the references
    this.userRecordHandler = userRecordHandler;
    this.userRecordsCache = userRecordsCache;

    // get configured secret key from the JNDI
    String secretKeyStr;
    try {
        final InitialContext jndi = new InitialContext();
        try {
            secretKeyStr = (String) jndi.lookup("java:comp/env/secretKey");
        } finally {
            jndi.close();
        }
    } catch (final NamingException e) {
        throw new UnavailableException("Error looking up secret key in the JNDI: " + e);
    }
    if (!secretKeyStr.matches("[0-9A-Fa-f]{32}"))
        throw new UnavailableException("Configured secret key is" + " invalid. The key must be a 16 bytes value"
                + " encoded as a hexadecimal string.");
    final Key secretKey = new SecretKeySpec(Hex.decode(secretKeyStr), CipherToolbox.ALGORITHM);

    // create the cipher pool
    this.cipherPool = new FastPool<>(new PoolableObjectFactory<CipherToolbox>() {

        @Override
        public CipherToolbox makeNew(final FastPool<CipherToolbox> pool, final int pooledObjectId) {

            return new CipherToolbox(pool, pooledObjectId, secretKey);
        }
    }, "AuthenticatorCiphersPool");
}

From source file:com.funambol.server.db.DataSourceFactoryTest.java

/**
 * Test of getObjectInstance method, of class DataSourceFactory.
 *//*from  ww w  .  j  a  va2 s  . co  m*/
public void testGetObjectInstance_WitWrongJNDIName() throws Exception {
    DataSourceFactory dataSourceFactory = new DataSourceFactory();
    InitialContext context = new InitialContext();
    Hashtable environment = new Hashtable();

    Name name = new CompositeName("fnbl");

    Reference ref = new Reference("javax.sql.DataSource");
    RefAddr url = new StringRefAddr("url", "jdbc:hsqldb:hsql://localhost/funambol");
    ref.add(url);

    Object result = dataSourceFactory.getObjectInstance(ref, name, context, environment);
    assertTrue(result instanceof org.apache.tomcat.dbcp.dbcp.BasicDataSource);

    BasicDataSource bds = (BasicDataSource) result;
    assertNull(bds.getPassword());
    assertEquals("jdbc:hsqldb:hsql://localhost/funambol", bds.getUrl());
    //
    // These are read from the db.xml since there is not the fnbl.xml file
    //
    assertEquals("db", bds.getUsername());
    assertEquals("org.hsqldb.jdbcDriver", bds.getDriverClassName());

}

From source file:gov.nih.nci.logging.api.util.HibernateUtil.java

private static DataSource getDataSource(String jndiName) throws Exception {
    Context ctx = new InitialContext();
    if (ctx == null) {
        throw new Exception("No Context available");
    }//www  .  ja  va  2  s  . c o m
    return (DataSource) ctx.lookup(jndiName);
}

From source file:com.sf.ddao.JNDIDaoTest.java

protected void setUp() throws Exception {
    super.setUp();
    JDBCMockObjectFactory factory = getJDBCMockObjectFactory();
    MockDataSource ds = factory.getMockDataSource();
    MockContextFactory.setAsInitial();//  w w  w . j  a  v a 2s .  co m
    InitialContext context = new InitialContext();
    context.rebind(JNDIDataSourceHandler.DS_CTX_PREFIX + "jdbc/testdb", ds);
    this.injector = Guice.createInjector(new ChainModule(TestUserDao.class));
}

From source file:be.fedict.eid.idp.sp.StartupServletContextListener.java

private static Object getComponent(String jndiName) {

    try {// w ww  .ja  v a 2s.com
        InitialContext initialContext = new InitialContext();
        return initialContext.lookup(jndiName);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.esri.geoportal.harvester.migration.MigrationBroker.java

private void initDataSource(InitContext context) throws NamingException {
    Context initContext = new InitialContext();
    Context webContext = (Context) initContext.lookup("java:/comp/env");
    dataSource = (DataSource) webContext.lookup(definition.getJndi());
}