List of usage examples for javax.naming Context lookup
public Object lookup(String name) throws NamingException;
From source file:org.enlacerh.util.Seg007.java
/** * Leer registros en la tabla//from ww w.jav a 2 s . c o m * @throws NamingException * @throws IOException **/ public void counter(Object filterValue) throws SQLException, NamingException, IOException { try { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = null; String[] veccouser = pcoduser.split("\\ - ", -1); switch (productName) { case "Oracle": query = "SELECT count_seg007(" + Integer.parseInt(grupo) + ",'" + ((String) filterValue).toUpperCase() + "','" + veccouser[0].toUpperCase() + "') from dual"; break; case "PostgreSQL": query = "SELECT count_seg007(" + Integer.parseInt(grupo) + ",'" + ((String) filterValue).toUpperCase() + "','" + veccouser[0].toUpperCase() + "')"; break; } pstmt = con.prepareStatement(query); //System.out.println(query); r = pstmt.executeQuery(); while (r.next()) { rows = r.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } //Cierra las conecciones pstmt.close(); con.close(); r.close(); }
From source file:org.enlacerh.util.Seg007.java
/** * Inserta Compaa por seguridad./*from w ww .j a v a 2 s.c om*/ * @throws IOException **/ public void insert(String pcia) throws NamingException, IOException { if (licencia(grupo)) { msj = new FacesMessage(FacesMessage.SEVERITY_WARN, getMessage("licven"), ""); FacesContext.getCurrentInstance().addMessage(null, msj); } else { String[] veccouser = pcoduser.split("\\ - ", -1); //Chequea que las variables no sean nulas try { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); String query = "INSERT INTO SEG007 VALUES (?,?" + "," + Integer.parseInt(grupo) + ")"; pstmt = con.prepareStatement(query); pstmt.setString(1, veccouser[0].toUpperCase()); pstmt.setString(2, pcia.toUpperCase()); //System.out.println(query); //Antes de insertar verifica si el rol del usuario tiene permisos para insertar vGacc = acc.valAccmnu("seg03", "insert", login, JNDI);//LLama a la funcion que valida las opciones del rol if (vGacc) { msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnAccInsert"), ""); FacesContext.getCurrentInstance().addMessage(null, msj); } else { try { pstmt.executeUpdate(); } catch (SQLException e) { exito = "error"; e.printStackTrace(); msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), ""); FacesContext.getCurrentInstance().addMessage(null, msj); } } //Fin validacion pstmt.close(); con.close(); } catch (Exception e) { exito = "error"; //e.printStackTrace(); } } }
From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncherFactory.java
/** * Used to configure the migration launcher with properties from a servlet * context. You do not need migration.properties to use this method. * * @param launcher the launcher to configure * @param sce the event to get the context and associated parameters from * @throws MigrationException if a problem with the look up in JNDI occurs *///from w ww .j ava2 s .c om private void configureFromServletContext(JdbcMigrationLauncher launcher, ServletContextEvent sce) throws MigrationException { String readOnly = sce.getServletContext().getInitParameter("migration.readonly"); launcher.setReadOnly(false); if ("true".equals(readOnly)) { launcher.setReadOnly(true); } // See if they want to override the lock after a certain amount of time String lockPollRetries = sce.getServletContext().getInitParameter("migration.lockPollRetries"); if (lockPollRetries != null) { launcher.setLockPollRetries(Integer.parseInt(lockPollRetries)); } String patchPath = ConfigurationUtil.getRequiredParam("migration.patchpath", sce, this); launcher.setPatchPath(patchPath); String postPatchPath = sce.getServletContext().getInitParameter("migration.postpatchpath"); launcher.setPostPatchPath(postPatchPath); String databases = sce.getServletContext().getInitParameter("migration.jdbc.systems"); String[] databaseNames; if ((databases == null) || "".equals(databases)) { databaseNames = new String[1]; databaseNames[0] = ""; log.debug("jdbc.systems was null or empty, not multi-node"); } else { databaseNames = databases.split(","); log.debug("jdbc.systems was set to " + databases + ", configuring multi-node"); } for (int i = 0; i < databaseNames.length; i++) { String databaseName = databaseNames[i]; if (databaseName != "") { databaseName = databaseName + "."; } String databaseType = ConfigurationUtil.getRequiredParam("migration." + databaseName + "databasetype", sce, this); String systemName = ConfigurationUtil.getRequiredParam("migration.systemname", sce, this); String dataSource = ConfigurationUtil.getRequiredParam("migration." + databaseName + "datasource", sce, this); DataSourceMigrationContext context = getDataSourceMigrationContext(); context.setSystemName(systemName); context.setDatabaseType(new DatabaseType(databaseType)); try { Context ctx = new InitialContext(); if (ctx == null) { throw new IllegalArgumentException( "A jndi context must be " + "present to use this configuration."); } DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + dataSource); context.setDataSource(ds); log.debug("adding context with datasource " + dataSource + " of type " + databaseType); launcher.addContext(context); } catch (NamingException e) { throw new MigrationException("Problem with JNDI look up of " + dataSource, e); } } }
From source file:com.ritchey.naming.InitialContextFactory.java
/** * Get Context that has access to default Namespace. This method won't be * called if a name URL beginning with java: is passed to an InitialContext. * * @see org.mortbay.naming.java.javaURLContextFactory * @param env a <code>Hashtable</code> value * @return a <code>Context</code> value *//* w w w . jav a 2 s. com*/ public Context getInitialContext(Hashtable env) { Log.debug("InitialContext loaded"); Context ctx = new localContextRoot(env); Properties properties = new Properties(); try { properties.load(new FileInputStream("build.properties")); } catch (Exception e1) { e1.printStackTrace(); } Context jdbc = null; try { jdbc = ctx.createSubcontext("jdbc"); } catch (NamingException e) { try { jdbc = (Context) ctx.lookup("jdbc"); } catch (NamingException e1) { e1.printStackTrace(); } } Context ldap = null; try { ldap = ctx.createSubcontext("ldap"); } catch (NamingException e) { try { ldap = (Context) ctx.lookup("ldap"); } catch (NamingException e1) { e1.printStackTrace(); } } Log.debug("getInitialContext"); String databaseNames = properties.getProperty("database.jndi.names"); if (databaseNames == null) { Log.warn(new RuntimeException("database.jndi.names is not defined" + " in build.properties as a comma separated list in " + "build.properties")); return ctx; } for (String database : databaseNames.split(" *, *")) { Log.debug("create " + database); try { createDs(database, properties, jdbc); } catch (NamingException e) { e.printStackTrace(); } } try { createLdapStrings(properties, ldap); } catch (NamingException e1) { e1.printStackTrace(); } String url = getValue(false, "picture", null, properties); try { ctx.bind("picture", url); } catch (NamingException ex) { Logger.getLogger(InitialContextFactory.class.getName()).log(Level.SEVERE, null, ex); } try { Log.debug("jdbc initial context = " + ctx.listBindings("jdbc")); NamingEnumeration<Binding> ldapBindings = ctx.listBindings("ldap"); Log.debug("ldap initial context = " + ctx.listBindings("ldap")); while (ldapBindings.hasMore()) { Binding binding = ldapBindings.next(); Log.debug("binding: " + binding.getName()); } } catch (NamingException e) { e.printStackTrace(); } return ctx; }
From source file:org.fosstrak.epcis.repository.query.QuerySubscription.java
/** * Updates the subscription in the database. This is required in order to * correctly re-initialize the subscriptions, especially the * lastTimeExecuted field, after a context restart. * <p>/* w w w .ja va 2 s . c o m*/ * TODO: This is a back-end method: move this method to the * QueryOperationsBackend and delegate to it (thus we would need a reference * to the QueryOperationsBackend in this class). * * @param lastTimeExecuted * The new lastTimeExecuted. */ private void updateSubscription(final Calendar lastTimeExecuted) { String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB"); try { // open a database connection Context ctx = new InitialContext(); DataSource db = (DataSource) ctx.lookup(jndiName); Connection dbconnection = db.getConnection(); // update the subscription in the database String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);"; PreparedStatement stmt = dbconnection.prepareStatement(update); LOG.debug("SQL: " + update); Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis()); String time = ts.toString(); stmt.setString(1, time); LOG.debug(" query param 1: " + time); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(outStream); out.writeObject(queryParams); ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); stmt.setBinaryStream(2, inStream, inStream.available()); LOG.debug(" query param 2: [" + inStream.available() + " bytes]"); stmt.setString(3, subscriptionID); LOG.debug(" query param 3: " + subscriptionID); stmt.executeUpdate(); dbconnection.commit(); // close the database connection dbconnection.close(); } catch (SQLException e) { String msg = "An SQL error occurred while updating the subscriptions in the database."; LOG.error(msg, e); } catch (IOException e) { String msg = "Unable to update the subscription in the database: " + e.getMessage(); LOG.error(msg, e); } catch (NamingException e) { String msg = "Unable to find JNDI data source with name " + jndiName; LOG.error(msg, e); } }
From source file:org.accada.epcis.repository.query.QuerySubscription.java
/** * Updates the subscription in the database. This is required in order to * correctly re-initialize the subscriptions, especially the * lastTimeExecuted field, after a context restart. * <p>// w w w.j a v a 2s.c o m * TODO: This is a back-end method: move this method to the * QueryOperationsBackend and delegate to it (thus we would need a reference * to the QueryOperationsBackend in this class). * * @param lastTimeExecuted * The new lastTimeExecuted. */ private void updateSubscription(final GregorianCalendar lastTimeExecuted) { String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB"); try { // open a database connection Context ctx = new InitialContext(); DataSource db = (DataSource) ctx.lookup(jndiName); Connection dbconnection = db.getConnection(); // update the subscription in the database String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);"; PreparedStatement stmt = dbconnection.prepareStatement(update); LOG.debug("SQL: " + update); Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis()); String time = ts.toString(); stmt.setString(1, time); LOG.debug(" query param 1: " + time); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(outStream); out.writeObject(queryParams); ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); stmt.setBinaryStream(2, inStream, inStream.available()); LOG.debug(" query param 2: [" + inStream.available() + " bytes]"); stmt.setString(3, subscriptionID); LOG.debug(" query param 3: " + subscriptionID); stmt.executeUpdate(); // close the database connection dbconnection.close(); } catch (SQLException e) { String msg = "An SQL error occurred while updating the subscriptions in the database."; LOG.error(msg, e); } catch (IOException e) { String msg = "Unable to update the subscription in the database: " + e.getMessage(); LOG.error(msg, e); } catch (NamingException e) { String msg = "Unable to find JNDI data source with name " + jndiName; LOG.error(msg, e); } }
From source file:catalina.mbeans.GlobalResourcesLifecycleListener.java
/** * Create the MBeans for the interesting global JNDI resources in * the specified naming context.//w w w.j a v a 2 s. c o m * * @param prefix Prefix for complete object name paths * @param context Context to be scanned * * @exception NamingException if a JNDI exception occurs */ protected void createMBeans(String prefix, Context context) throws NamingException { if (debug >= 1) { log("Creating MBeans for Global JNDI Resources in Context '" + prefix + "'"); } NamingEnumeration bindings = context.listBindings(""); while (bindings.hasMore()) { Binding binding = (Binding) bindings.next(); String name = prefix + binding.getName(); Object value = context.lookup(binding.getName()); if (debug >= 2) { log("Checking resource " + name); } if (value instanceof Context) { createMBeans(name + "/", (Context) value); } else if (value instanceof UserDatabase) { try { createMBeans(name, (UserDatabase) value); } catch (Exception e) { log("Exception creating UserDatabase MBeans for " + name, e); } } } }
From source file:org.enlacerh.util.Seg007.java
/** * Borra Ciaseg// w w w. jav a 2 s .c om * <p> * Parametros del metodo: String p_coduser. Pool de conecciones * @throws IOException **/ public void delete() throws NamingException, IOException { if (licencia(grupo)) { msj = new FacesMessage(FacesMessage.SEVERITY_WARN, getMessage("licven"), ""); FacesContext.getCurrentInstance().addMessage(null, msj); } else { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); String[] chkbox = request.getParameterValues("toDelete"); if (chkbox == null) { msj = new FacesMessage(FacesMessage.SEVERITY_WARN, getMessage("del"), ""); } else { try { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = ""; String param = "'" + StringUtils.join(chkbox, "','") + "'"; switch (productName) { case "Oracle": query = "DELETE FROM seg007 WHERE P_CODUSER||P_CODCIA||grupo in (" + param + ")"; break; case "PostgreSQL": query = "DELETE FROM seg007 WHERE P_CODUSER||P_CODCIA||CAST(grupo AS text) in (" + param + ")"; break; } pstmt = con.prepareStatement(query); //System.out.println(query); //Antes de insertar verifica si el rol del usuario tiene permisos para insertar vGacc = acc.valAccmnu("seg03", "delete", login, JNDI);//LLama a la funcion que valida las opciones del rol if (vGacc) { msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnAccDelete"), ""); } else { try { //Avisando pstmt.executeUpdate(); if (pstmt.getUpdateCount() <= 1) { msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnDelete"), ""); } else { msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnDeletes"), ""); } } catch (SQLException e) { //e.printStackTrace(); msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), ""); } pstmt.close(); con.close(); } } catch (Exception e) { e.printStackTrace(); } } FacesContext.getCurrentInstance().addMessage(null, msj); } }
From source file:org.gss_project.gss.server.ejb.AdminAPIBean.java
public void indexFile(Long fileId, boolean delete) { Connection qConn = null;/*from w w w .j a va 2 s .com*/ Session session = null; MessageProducer sender = null; try { Context jndiCtx = new InitialContext(); ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA"); Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue"); qConn = factory.createConnection(); session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE); sender = session.createProducer(queue); MapMessage map = session.createMapMessage(); map.setObject("id", fileId); map.setBoolean("delete", delete); sender.send(map); } catch (NamingException e) { logger.error("Index was not updated: ", e); } catch (JMSException e) { logger.error("Index was not updated: ", e); } finally { try { if (sender != null) sender.close(); if (session != null) session.close(); if (qConn != null) qConn.close(); } catch (JMSException e) { logger.warn(e); } } }
From source file:org.enlacerh.util.Seg007.java
/** * Leer Datos de Ciaseg//from ww w . j a v a 2 s . co m * @throws NamingException * @throws SQLException * @throws IOException **/ public void select(int first, int pageSize, String sortField, Object filterValue) throws NamingException, SQLException, IOException { Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup(JNDI); con = ds.getConnection(); //Reconoce la base de datos de coneccin para ejecutar el query correspondiente a cada uno DatabaseMetaData databaseMetaData = con.getMetaData(); productName = databaseMetaData.getDatabaseProductName();//Identifica la base de datos de coneccin String query = ""; if (pcoduser == null) { pcoduser = " - "; } if (pcoduser == "") { pcoduser = " - "; } String[] vecuser = pcoduser.split("\\ - ", -1); switch (productName) { case "Oracle": //Consulta paginada query = " select * from "; query += " ( select query.*, rownum as rn from"; query += " ( SELECT trim(a.p_coduser), trim(c.nbr), trim(a.p_codcia), trim(b.nomcia1), trim(b.nomcia2), a.grupo"; query += " FROM SEG007 a , Pnt001 b, autos01 c"; query += " where a.p_codcia=b.codcia"; query += " and a.p_coduser=c.coduser"; query += " and a.grupo=c.grupo"; query += " and a.p_coduser like trim('" + vecuser[0] + "%')"; query += " and a.p_coduser||a.p_codcia||b.nomcia2 like '%" + ((String) filterValue).toUpperCase() + "%'"; query += " and a.grupo = '" + grupo + "'"; query += " order by " + sortField.replace("vp", "p_") + ", a.p_codcia" + ") query"; query += " ) where rownum <= " + pageSize; query += " and rn > (" + first + ")"; break; case "PostgreSQL": //Consulta paginada //Consulta paginada query = "SELECT trim(a.p_coduser), trim(c.nbr), trim(a.p_codcia), trim(b.nomcia1), trim(b.nomcia2), a.grupo"; query += " FROM SEG007 a , Pnt001 b, autos01 c"; query += " where a.p_codcia=b.codcia"; query += " and a.p_coduser=c.coduser"; query += " and a.grupo=c.grupo"; query += " and a.p_coduser like trim('" + vecuser[0] + "%')"; query += " and a.p_coduser||a.p_codcia||b.nomcia2 like '%" + ((String) filterValue).toUpperCase() + "%'"; query += " and CAST(a.grupo AS text) = '" + grupo + "'"; query += " order by " + sortField.replace("vp", "p_") + ", a.p_codcia"; query += " LIMIT " + pageSize; query += " OFFSET " + first; break; } pstmt = con.prepareStatement(query); System.out.println(query); ResultSet r = pstmt.executeQuery(); while (r.next()) { Segcia select = new Segcia(); select.setVpcodciadescia(r.getString(3) + " - " + r.getString(5)); select.setVpcoduser(r.getString(1)); select.setVdesuser(r.getString(2)); select.setVpcodcia(r.getString(3)); select.setVpdescia(r.getString(5)); select.setVpcoduserdesuser(r.getString(1) + " - " + r.getString(2)); select.setVgrupo(r.getString(6)); //Agrega la lista list.add(select); } //Cierra las conecciones pstmt.close(); con.close(); }