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.agilejava.spring4.config.ApplicationConfig.java

/**
 * Get the CDI Manager from initial context.
 * @return the cdi manager//from w w  w  .  ja v  a2s.  com
 */
private BeanManager getCDIBeanManager() {
    try {
        InitialContext initialContext = new InitialContext();
        return (BeanManager) initialContext.lookup("java:comp/BeanManager");
    } catch (NamingException e) {
        LOGGER.severe(() -> "Could not look up initialcontext: " + e.getMessage());
        return null;
    }
}

From source file:quickforms.controller.UpdateLookup.java

/**
 * Handles the HTTP/*from  ww  w. j a  va 2s.  c  o  m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Map<String, String[]> inParams = request.getParameterMap();
    Map<String, String[]> params = new HashMap<String, String[]>(inParams);//inParams is read only
    System.out.println("Updating Lookup");
    response.setContentType("text/html;charset=UTF-8");
    String application = request.getParameter("app");
    String lookup = request.getParameter("lookup");
    String values = request.getParameter("values");
    System.out.println(values);
    Database db = null;
    String json = null;
    PrintWriter out = response.getWriter();
    try {
        InitialContext cxt = new InitialContext();
        DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/" + application);
        db = new Database(ds);

        db.updateLookup(application, lookup, jsonToHashMap(values), new ArrayList<LookupPair>());

    } catch (Exception e) {
        Logger.log(application, e);
        out.append(e.toString());
        db.disconnect();
    }

    out.close();
}

From source file:com.t2tierp.controller.LoginController.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String nomeUsuario = authentication.getName();
    String senha = authentication.getCredentials().toString();
    try {//from ww  w. ja  va  2  s  . c o m
        InitialContext initialContext = new InitialContext();
        dao = (UsuarioDAO) initialContext.lookup("java:comp/ejb/usuarioDAO");

        Md5PasswordEncoder enc = new Md5PasswordEncoder();
        senha = enc.encodePassword(nomeUsuario + senha, null);
        Usuario usuario = dao.getUsuario(nomeUsuario, senha);
        if (usuario != null) {
            List<PapelFuncao> funcoes = dao.getPapelFuncao(usuario);
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            for (PapelFuncao p : funcoes) {
                grantedAuths.add(new SimpleGrantedAuthority(p.getFuncao().getNome()));
            }
            Authentication auth = new UsernamePasswordAuthenticationToken(nomeUsuario, senha, grantedAuths);

            return auth;
        }
    } catch (Exception e) {
        //e.printStackTrace();
    }
    return null;
}

From source file:com.googlecode.datasourcetester.server.DataSourceTesterServiceImpl.java

public String[][] queryDataSource(String dataSourceJndiName, String query) {
    Connection conn = null;/*from w w  w  .j a v  a 2  s  .  c  om*/
    try {
        InitialContext jndiContext = new InitialContext();
        DataSource ds = (DataSource) jndiContext.lookup(dataSourceJndiName);
        conn = ds.getConnection();
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData resMeta = rs.getMetaData();
        LinkedList<String[]> rowList = new LinkedList<String[]>();
        String[] colLabels = new String[resMeta.getColumnCount()];
        for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
            colLabels[colNr - 1] = resMeta.getColumnName(colNr);
        }
        rowList.add(colLabels);
        while (rs.next()) {
            String[] rowData = new String[resMeta.getColumnCount()];
            for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
                rowData[colNr - 1] = rs.getString(colNr);
            }
            rowList.add(rowData);
        }
        conn.close();
        return rowList.toArray(new String[rowList.size()][]);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException sqlEx) {
            logger.error(sqlEx.getMessage(), sqlEx);
        }
        return null;
    }
}

From source file:io.apiman.gateway.engine.ispn.InfinispanRegistry.java

/**
 * @return gets the registry cache//from w ww  . j av  a 2s .c o  m
 */
private Cache<Object, Object> getCache() {
    if (cache != null) {
        return cache;
    }

    try {
        InitialContext ic = new InitialContext();
        CacheContainer container = (CacheContainer) ic.lookup(cacheContainer);
        cache = container.getCache(cacheName);
        return cache;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opentaps.testsuit.web.IntegrTestsServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*www.  j a  va2 s.  co m*/
        String serviceName = request.getParameter("service");
        String testName = request.getParameter("test");
        if (GenericValidator.isBlankOrNull(serviceName) || GenericValidator.isBlankOrNull(testName)) {
            throw new ServletException("Missing required parameters.");
        }

        InitialContext context = new InitialContext();
        Object testSrvc = context.lookup(String.format("osgi:service/%1$s", serviceName));
        if (testSrvc == null) {
            throw new ServletException("Test service is unavailable.");
        }

        PrintWriter out = response.getWriter();

        try {
            Method testCase = ClassUtils.getPublicMethod(testSrvc.getClass(), testName, new Class[0]);
            testCase.invoke(testSrvc, new Object[] {});

            out.println(BaseTestCase.SUCCESS_RET_CODE);

        } catch (InvocationTargetException e) {
            out.println(e.getTargetException().getLocalizedMessage());
            return;
        }

    } catch (NamingException e) {
        throw new ServletException(e);
    } catch (IllegalArgumentException e) {
        throw new ServletException(e);
    } catch (IllegalAccessException e) {
        throw new ServletException(e);
    } catch (SecurityException e) {
        throw new ServletException(e);
    } catch (NoSuchMethodException e) {
        throw new ServletException(e);
    }
}

From source file:org.josso.gateway.session.service.store.db.DataSourceSessionStore.java

/**
 * Lazy load the datasource instace used by this store.
 *
 * @throws SSOSessionException/*from   w ww .j  ava2 s.c o m*/
 */
protected synchronized DataSource getDataSource() throws SSOSessionException {
    if (_datasource == null) {
        try {
            if (logger.isDebugEnabled())
                logger.debug("[getDatasource() : ]" + _dsJndiName);

            InitialContext ic = new InitialContext();
            _datasource = (DataSource) ic.lookup(_dsJndiName);

        } catch (NamingException ne) {
            logger.error("Error during DB connection lookup", ne);
            throw new SSOSessionException("Error During Lookup\n" + ne.getMessage());
        }

    }

    return _datasource;
}

From source file:org.josso.gateway.assertion.service.store.db.DataSourceAssertionStore.java

/**
 * Lazy load the datasource instace used by this store.
 *
 * @throws org.josso.gateway.assertion.exceptions.AssertionException
 *
 *//* w w w.  j  a  v a  2  s . c om*/
protected synchronized DataSource getDataSource() throws AssertionException {
    if (_datasource == null) {
        try {
            if (logger.isDebugEnabled())
                logger.debug("[getDatasource() : ]" + _dsJndiName);

            InitialContext ic = new InitialContext();
            _datasource = (DataSource) ic.lookup(_dsJndiName);

        } catch (NamingException ne) {
            logger.error("Error during DB connection lookup", ne);
            throw new AssertionException("Error During Lookup\n" + ne.getMessage());
        }

    }

    return _datasource;
}

From source file:com.jsquant.listener.JsquantContextListener.java

protected String getFileCachePath(ServletContext context) {
    String fileCachePath = null;//from   w  w  w .j a v a  2s .c o m
    try {
        InitialContext initial = new InitialContext();
        fileCachePath = (String) initial.lookup(JNDI_DATA_PATH);
    } catch (Throwable err) {
        // ignore when JNDI not available or no param set
    }
    if (fileCachePath == null) {
        fileCachePath = System.getProperty("filecache.path");
    }
    if (fileCachePath == null) {
        fileCachePath = DEFAULT_FILE_CACHE_PATH;
    }
    log.info("fileCachePath=" + fileCachePath);
    return fileCachePath;
}

From source file:org.pepstock.jem.junit.test.springbatch.java.RestRunnable.java

@Override
public void run() {

    try {//w  w  w. ja  v a  2s . co m
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.pepstock.jem.node.tasks.jndi.JemContextFactory");

        InitialContext context = new InitialContext(env);
        RestClient rest = (RestClient) context.lookup("JUNIT-REST-RESOURCE");
        System.err.println();
        System.err.println("*** REST XML");
        get(rest, MediaType.APPLICATION_XML);
        get(rest, MediaType.APPLICATION_JSON);
        get(rest, MediaType.APPLICATION_XML);
        get(rest, MediaType.APPLICATION_JSON);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        System.err.println();
        System.err.println("*** REST XML");
        get(restC, MediaType.APPLICATION_XML);
        get(restC, MediaType.APPLICATION_JSON);
        get(restC, MediaType.APPLICATION_XML);
        get(restC, MediaType.APPLICATION_JSON);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}