Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

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

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*from  w  ww. j av a2  s .c om*/
 * @param type
 * @param value
 * @return
 */
public boolean isRdnExists(LdapName rootDn, RdnType type, String value) {
    Object result = null;
    Context ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());
        result = ctx.lookup(NamingFactory.createRdn(type, value).toString());

    } catch (NamingException e) {
        throw new RuntimeException(type.toString() + "=" + value + "," + rootDn.toString(), e);
    } finally {
        contextFactory.closeContext(ctx);
    }

    if (result != null)
        return true;
    else
        return false;
}

From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java

@Before
public void setup() throws Exception {
    File folder = new File("/tmp");
    File[] files = folder.listFiles(new FilenameFilter() {
        @Override//from   www  .  j a  v a 2  s.co m
        public boolean accept(final File dir, final String name) {
            return name.startsWith("test.db");
        }
    });
    for (final File file : files) {
        if (!file.delete()) {
            System.out.println("Failed to remove " + file.getAbsolutePath());
        }
    }

    mongo.dropDatabase(DB_NAME);
    mongo.dropDatabase("local");
    mongo.dropDatabase("admin");
    mongo.dropDatabase("mongo");
    mongo.getDB(DB_NAME).dropDatabase();
    mongo.getDB("local").dropDatabase();
    mongo.getDB("admin").dropDatabase();
    mongo.getDB("mongo").dropDatabase();

    db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).remove(new BasicDBObject());
    mongo.getDB("mongo").getCollection("metadata").remove(new BasicDBObject());

    db.createCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION, null);
    BasicDBObject index = new BasicDBObject("name", 1);
    index.put("version.value", 1);
    db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).ensureIndex(index, "name", true);

    if (notRegistered) {
        notRegistered = false;
        try {
            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            // already tried System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
            InitialContext ic = new InitialContext();

            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            JdbcConnectionPool ds = JdbcConnectionPool.create(
                    "jdbc:h2:file:/tmp/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa");

            ic.bind("java:/mydatasource", ds);
        } catch (NamingException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        Context initCtx = new InitialContext();
        DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource");
        Connection conn = ds.getConnection();
        Statement stmt = conn.createStatement();
        stmt.execute("DROP ALL OBJECTS ");
        stmt.close();
    }
}

From source file:org.enlacerh.util.Seg002.java

/**
* Inserta roles./* w  w w. ja va 2  s .c o m*/
**/
private void insert() {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();

        String query = "INSERT INTO Seg002 VALUES (trim(?),?,?,'" + getFecha() + "',?,'" + getFecha() + "',"
                + Integer.parseInt(grupo) + ")";
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, codrol.toUpperCase());
        pstmt.setString(2, desrol.toUpperCase());
        pstmt.setString(3, login);
        pstmt.setString(4, login);

        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("seg01", "insert", login, JNDI);//LLama a la funcion que valida las opciones del rol
        if (vGacc) {
            msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnAccInsert"), "");
        } else {
            try {
                //Avisando
                pstmt.executeUpdate();
                limpiarValores();
                msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnInsert"), "");
            } catch (SQLException e) {
                msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");
            }
        }
        pstmt.close();
        con.close();
    } catch (Exception e) {
    }
    FacesContext.getCurrentInstance().addMessage(null, msj);
}

From source file:org.enlacerh.util.Seg001.java

/**
  * Inserta JNDI./*from w w w .  j a v  a 2s  . c  om*/
  * <p>
  * Parametros del Metodo: String codpai, String despai. Pool de conecciones y login
 * @throws NamingException 
  **/
public void insert() throws NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();

        String query = "INSERT INTO seg001 VALUES (?,?,'" + getFechaFormat(fecven) + "',?,?, now(), ?)";
        pstmt = con.prepareStatement(query);
        pstmt.setInt(1, Integer.parseInt(grupo));
        pstmt.setInt(2, Integer.parseInt(cantrab));
        pstmt.setString(3, estatus);
        pstmt.setString(4, empresa);
        pstmt.setString(5, jndi);
        //System.out.println(query);
        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        try {
            pstmt.executeUpdate();
            msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnInsert"), "");
            limpiarValores();
        } catch (SQLException e) {
            //e.printStackTrace();
            msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");
        }
        pstmt.close();
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");
    }
    FacesContext.getCurrentInstance().addMessage(null, msj);
}

From source file:org.enlacerh.util.Seg002.java

/**
* Leer registros en la tabla//from w  w w.  j a va  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;

        switch (productName) {
        case "Oracle":
            query = "SELECT count_seg002(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_seg002(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).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.Seg001.java

/**
  * Leer registros en la tabla/*  ww w .  j a v a2  s  .co 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;

        switch (productName) {
        case "Oracle":
            query = "SELECT count_seg001('" + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_seg001('" + ((String) filterValue).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.Seg002.java

/**
* Actualiza roles//from w  w w . j a  v  a2  s . com
**/
private void update() {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();

        String query = "UPDATE Seg002";
        query += " SET desrol = ?, usract = ?, fecact='" + getFecha() + "'";
        query += " WHERE codrol = ?";
        query += " and grupo = " + Integer.parseInt(grupo);
        //System.out.println(query);
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, desrol.toUpperCase());
        pstmt.setString(2, login);
        pstmt.setString(3, codrol.toUpperCase());

        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("seg01", "update", login, JNDI);//LLama a la funcion que valida las opciones del rol
        if (vGacc) {
            msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnAccUpdate"), "");
        } else {
            try {
                //Avisando
                pstmt.executeUpdate();
                desrol = "";
                localgrupo = "";
                validarOperacion = 0;
                if (pstmt.getUpdateCount() == 0) {
                    msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnNoUpdate"), "");
                } else {
                    msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnUpdate"), "");
                }
            } catch (SQLException e) {
                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.enlacerh.util.Pnt003.java

/**
* Inserta Paises.//from w  w  w  .  j a v  a2  s .c o m
* <p>
* Parametros del Metodo: String codpai, String despai. Pool de conecciones y login
 * @throws NamingException 
**/
private void insert() throws NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();

        String query = "INSERT INTO PNT003 VALUES (" + Integer.parseInt(codpai) + ",?,?,'" + getFecha()
                + "',?,'" + getFecha() + "'," + Integer.parseInt(grupo) + ")";
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, despai.toUpperCase());
        pstmt.setString(2, login);
        pstmt.setString(3, login);
        //System.out.println(query);
        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("bas01", "insert", login, JNDI);//LLama a la funcion que valida las opciones del rol
        if (vGacc) {
            msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnAccInsert"), "");
        } else {
            try {
                pstmt.executeUpdate();
                msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnInsert"), "");
                limpiarValores();
            } catch (SQLException e) {
                //e.printStackTrace();
                msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");
            }
        } //Fin validacion 

        pstmt.close();
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");
    }
    FacesContext.getCurrentInstance().addMessage(null, msj);
}

From source file:com.silverpeas.workflow.engine.model.ProcessModelManagerImpl.java

/**
 * @return the DB connection//from  w  ww  .j  a  v a 2s.  c om
 */
private Connection getConnection() throws WorkflowException {
    Connection con = null;
    try {
        // con = DBUtil.makeConnection(dbName);
        Context ctx = new InitialContext();
        DataSource src = (DataSource) ctx.lookup(dbName);
        con = src.getConnection();
        return con;
    } catch (NamingException e) {
        // throw new UtilException("Schema.Schema", SilverpeasException.ERROR,
        // "root.EX_DATASOURCE_NOT_FOUND", e);
        // the JNDI name have not been found in the current context
        // The caller is not takes place in any context (web application nor ejb
        // container)
        // So lookup operation cannot find JNDI properties !
        // This is absolutly normal according to the j2ee specification
        // Unfortunately, only BES takes care about this spec. This exception
        // doesn't appear with orion or BEA !
        try {
            // Get the initial Context
            Context ctx = new InitialContext();
            // Look up the datasource directly without JNDI access
            DataSource dataSource = (DataSource) ctx.lookup(JNDINames.DIRECT_DATASOURCE);
            // Create a connection object
            con = dataSource.getConnection();
            return con;
        } catch (NamingException ne) {
            throw new WorkflowException("ProcessModelManagerImpl.getConnection", "root.EX_DATASOURCE_NOT_FOUND",
                    "Data source " + JNDINames.DIRECT_DATASOURCE + " not found", ne);
        } catch (SQLException se) {
            throw new WorkflowException("ProcessModelManagerImpl.getConnection",
                    "can't get connection for dataSource " + JNDINames.DIRECT_DATASOURCE, se);
        }
    } catch (SQLException se) {
        throw new WorkflowException("ProcessModelManagerImpl.getConnection()", "root.EX_CONNECTION_OPEN_FAILED",
                se);
    }
}

From source file:org.enlacerh.util.Pnt003.java

/**
* Leer registros en la tabla/*from w w  w. jav a 2 s. c  o m*/
* @throws NamingException 
* @throws IOException 
**/
public void counter(Object filterValue) throws SQLException, NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);

        String query = null;

        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

        switch (productName) {
        case "Oracle":
            query = "SELECT count_pnt003(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_pnt003(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).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();

}