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:com.zotoh.maedr.device.JmsIO.java

private void inizConn() throws Exception {

    Hashtable<String, String> vars = new Hashtable<String, String>();
    Context ctx;
    Object obj;//from   w  w w  .j  a  va  2s . c  om

    if (!isEmpty(_ctxFac)) {
        vars.put(Context.INITIAL_CONTEXT_FACTORY, _ctxFac);
    }

    if (!isEmpty(_url)) {
        vars.put(Context.PROVIDER_URL, _url);
    }

    if (!isEmpty(_JNDIPwd)) {
        vars.put("jndi.password", _JNDIPwd);
    }

    if (!isEmpty(_JNDIUser)) {
        vars.put("jndi.user", _JNDIUser);
    }

    ctx = new InitialContext(vars);
    obj = ctx.lookup(_connFac);

    if (obj instanceof QueueConnectionFactory) {
        inizQueue(ctx, obj);
    } else if (obj instanceof TopicConnectionFactory) {
        inizTopic(ctx, obj);
    } else if (obj instanceof ConnectionFactory) {
        inizFac(ctx, obj);
    } else {
        throw new Exception("JmsIO: unsupported JMS Connection Factory");
    }

    if (_conn != null) {
        _conn.start();
    }
}

From source file:org.apache.openaz.xacml.admin.view.components.SQLPIPConfigurationComponent.java

protected void testJNDIConnection() {
    try {/*from  ww  w.j  a va2  s  .  c  o  m*/
        Context initialContext = new InitialContext();
        DataSource dataSource = (DataSource) initialContext.lookup(this.textFieldDataSource.getValue());
        try (Connection connection = dataSource.getConnection()) {
            new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                    .show(Page.getCurrent());
        }
    } catch (NamingException e) {
        logger.error(e);
        new Notification("JNDI Naming Exception",
                "<br/>" + e.getLocalizedMessage()
                        + "<br/>Is the context defined in this J2EE Container instance?",
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    } catch (SQLException e) {
        logger.error(e);
        new Notification("SQL Exception",
                "<br/>" + e.getLocalizedMessage() + "<br/>Are the configuration parameters correct?",
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public ClientJmsDelegate(final Context context) {
    try {/*from  w w  w.j ava2s  . co  m*/
        _context = context;
        final ConnectionFactory connectionFactory = (ConnectionFactory) _context.lookup("connectionfactory");
        _controllerConnection = connectionFactory.createConnection();
        _controllerConnection.start();
        _controllerQueue = (Destination) context.lookup(DistributedTestConstants.CONTROLLER_QUEUE_JNDI_NAME);
        _controllerSession = _controllerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        _controlQueueProducer = _controllerSession.createProducer(_controllerQueue);
        _clientName = UUID.randomUUID().toString();
        _testConnections = new HashMap<String, Connection>();
        _testSessions = new HashMap<String, Session>();
        _testProducers = new HashMap<String, MessageProducer>();
        _testConsumers = new HashMap<String, MessageConsumer>();
        _testSubscriptions = new HashMap<String, Session>();
        _testMessageProviders = new HashMap<String, MessageProvider>();
        _defaultMessageProvider = new MessageProvider(null);
    } catch (final NamingException ne) {
        throw new DistributedTestException("Unable to create client jms delegate", ne);
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create client jms delegate", jmse);
    }
}

From source file:edu.harvard.iq.dvn.core.web.subsetting.NetworkDataAnalysisPage.java

public void init() {
    super.init();

    try {//from  w w w .  j  a va 2s . c o m
        file = (NetworkDataFile) studyFileService.getStudyFile(fileId);

        if (versionNumber != null) {
            StudyVersion sv = file.getStudy().getStudyVersionByNumber(versionNumber);
            studyUI = new StudyUI(sv, null);
            if (sv == null) {
                redirect("/faces/IdDoesNotExistPage.xhtml?type=Study%20Version");
                return;
            }

        } else {
            studyUI = new StudyUI(file.getStudy().getReleasedVersion(), null);
        }

    } catch (Exception e) { // id not a long, or file is not a NetworkDataFile (TODO: redirect to a different page if not network data file)
        redirect("/faces/IdDoesNotExistPage.xhtml?type=File");
        return;
    }

    //init workspace and page components 
    try {
        Context ctx = new InitialContext();
        networkDataService = (NetworkDataServiceLocal) ctx.lookup("java:comp/env/networkData");
        String sessionId = FacesContext.getCurrentInstance().getExternalContext().getSession(false).toString();
        networkDataService.initAnalysis(file.getFileSystemLocation(), sessionId);
        initComponents();
    } catch (Exception ex) {
        Logger.getLogger(NetworkDataAnalysisPage.class.getName()).log(Level.SEVERE, null, ex);
        redirect("/faces/ErrorPage.xhtml?errorMsg=" + ex.getMessage());
    }
}

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

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

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

/**
 * Actualiza Compaias/*from w w w .j a va2s  .com*/
 **/
private void update() {
    //Valida que los campos no sean nulos
    String[] veccodpai = pcodpai.split("\\ - ", -1);
    String[] veccodciu = pcodciu.split("\\ - ", -1);

    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();
        String query = "UPDATE Pnt001 SET nomcia1 = ?";
        query += " ,nomcia2 = ?";
        query += " ,id1 = ?";
        query += " ,id2 = ?";
        query += " ,dir = ?";
        query += " ,p_codpai = " + Integer.parseInt(veccodpai[0]);
        query += " ,p_codciu = " + Integer.parseInt(veccodciu[0]);
        query += " ,tlf1 = " + BigInteger.valueOf(tlf1);
        query += " ,tlf2 = " + BigInteger.valueOf(tlf2);
        query += " ,FECACT = '" + getFecha() + "' , USRACT = '" + login + "'";
        query += " WHERE codcia = ?";
        query += " and grupo = " + Integer.parseInt(localgrupo);
        //System.out.println(query);
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, nomcia1.toUpperCase());
        pstmt.setString(2, nomcia2.toUpperCase());
        pstmt.setString(3, id1.toUpperCase());
        pstmt.setString(4, id2.toUpperCase());
        pstmt.setString(5, dir.toUpperCase());
        pstmt.setString(6, codcia.toUpperCase());
        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("bas03", "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();
                if (pstmt.getUpdateCount() == 0) {
                    msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnNoUpdate"), "");
                } else {
                    msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnUpdate"), "");
                }
                id1 = "";
                id2 = "";
                dir = "";
                pcodpai = "";
                pcodciu = "";
                tlf1 = 0;
                tlf2 = 0;
                pcodciudesciu = "";
                validarOperacion = 0;
            } catch (SQLException e) {
                e.printStackTrace();
                msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");
            }

            pstmt.close();
            con.close();

        } //Fin validacion de licencia

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

    FacesContext.getCurrentInstance().addMessage(null, msj);
}

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

/**
  * Inserta Compaias.//from   w w  w  .j av a  2s  . co m
  **/
private void insert() throws NamingException {
    //Valida que los campos no sean nulos
    String[] veccodpai = pcodpai.split("\\ - ", -1);
    String[] veccodciu = pcodciu.split("\\ - ", -1);

    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();

        String query = "INSERT INTO Pnt001 VALUES (?,?,?,?,?,?," + Integer.parseInt(veccodpai[0]) + ","
                + Integer.parseInt(veccodciu[0]) + "," + BigInteger.valueOf(tlf1) + ","
                + BigInteger.valueOf(tlf2) + ",?,'" + getFecha() + "',?,'" + getFecha() + "',"
                + Integer.parseInt(grupo) + ")";
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, codcia.toUpperCase());
        pstmt.setString(2, nomcia1.toUpperCase());
        pstmt.setString(3, nomcia2.toUpperCase());
        pstmt.setString(4, id1.toUpperCase());
        pstmt.setString(5, id2.toUpperCase());
        pstmt.setString(6, dir.toUpperCase());
        pstmt.setString(7, login);
        pstmt.setString(8, login);
        //System.out.println(query);
        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("bas03", "insert", login, JNDI);//LLama a la funcion que valida las opciones del rol
        if (vGacc) {
            msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("msnAccInsert"), "");
        } else {
            // Antes de ejecutar valida si existe el registro en la base de Datos.
            consulta.selectPntGenerica("select codcia from Pnt001 where codcia ='" + codcia.toUpperCase() + "'",
                    JNDI);
            if (consulta.getRows() > 0) {
                msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, getMessage("pnt001valCia"), "");
            } else {
                try {
                    pstmt.executeUpdate();

                    //
                    new Mkdir().crtCarpeta(ruta.toString(), codcia.toUpperCase());//Crea autoservicio
                    new Mkdir().crtCarpeta(ruta1.toString(), codcia.toUpperCase());//Crea querys externos
                    new Mkdir().crtCarpeta(ruta2.toString(), codcia.toUpperCase());//Crea tablas externas
                    new Mkdir().crtCarpeta(ruta3.toString(), codcia.toUpperCase());//Crea variables externas
                    new Mkdir().crtCarpeta(ruta4.toString(), codcia.toUpperCase());//Crea aumentos de sueldo externos
                    //
                    msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnInsert"), "");
                    limpiarValores();
                } catch (SQLException e) {
                    e.printStackTrace();
                    msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage(), "");

                    //Elimina las carpeta si hay algun error
                    new Mkdir().borraCarpeta(ruta.toString(), codcia.toUpperCase());//Borra autoservicio
                    new Mkdir().borraCarpeta(ruta1.toString(), codcia.toUpperCase());//Borra querys externos
                    new Mkdir().borraCarpeta(ruta2.toString(), codcia.toUpperCase());//Borra tablas externas
                    new Mkdir().borraCarpeta(ruta3.toString(), codcia.toUpperCase());//Borra variables externas
                    new Mkdir().borraCarpeta(ruta4.toString(), codcia.toUpperCase());//Borra aumentos de sueldo externos
                }
            } //Fin validacion 
            pstmt.close();
            con.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    FacesContext.getCurrentInstance().addMessage(null, msj);
}

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

/**
 * Borra Compaas//ww  w . j  ava2 s .  c om
 * @throws NamingException 
 * @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 PNT001 WHERE CODCIA||grupo in (" + param + ")";
                    break;
                case "PostgreSQL":
                    query = "DELETE FROM PNT001 WHERE 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("bas03", "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"), "");
                        }
                        limpiarValores();
                        deleteFolders();
                    } 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.enlacerh.util.Pnt001.java

/**
  * Leer Datos de paises/*w  w w. j a  v a  2s  .com*/
 * @throws SQLException 
  * @throws NamingException 
  * @throws IOException 
  **/
public void select(int first, int pageSize, String sortField, Object filterValue) throws SQLException {
    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 = "";

        switch (productName) {
        case "Oracle":
            //Consulta paginada
            query = "  select * from ";
            query += " ( select query.*, rownum as rn from";
            query += " ( select trim(a.codcia), trim(a.nomcia1), trim(a.nomcia2), trim(a.id1), trim(a.id2), trim(a.dir),";
            query += " a.p_codpai, a.p_codciu, a.tlf1, a.tlf2, trim(b.despai), trim(c.desciu), a.grupo";
            query += " from Pnt001 a, Pnt003 b, Pnt004 c";
            query += " where a.p_codpai=b.codpai";
            query += " and a.grupo=b.grupo";
            query += " and a.p_codciu=c.codciu";
            query += " and a.grupo=c.grupo";
            query += " and a.codcia like  '" + codcia.toUpperCase() + "%'";
            query += " and a.codcia||a.nomcia2||a.id1 like '%" + ((String) filterValue).toUpperCase() + "%'";
            query += " and a.grupo = '" + grupo + "'";
            query += " order by " + sortField.replace("v", "") + ") query";
            query += " ) where rownum <= " + pageSize;
            query += " and rn > (" + first + ")";

            break;
        case "PostgreSQL":
            //Consulta paginada
            //Consulta paginada
            query = "  select trim(a.codcia), trim(a.nomcia1), trim(a.nomcia2), trim(a.id1), trim(a.id2), trim(a.dir),";
            query += " a.p_codpai, a.p_codciu, a.tlf1, a.tlf2, trim(b.despai), trim(c.desciu), a.grupo";
            query += " from Pnt001 a, Pnt003 b, Pnt004 c";
            query += " where a.p_codpai=b.codpai";
            query += " and a.grupo=b.grupo";
            query += " and a.p_codciu=c.codciu";
            query += " and a.grupo=c.grupo";
            query += " and a.codcia like  '" + codcia.toUpperCase() + "%'";
            query += " and a.codcia||a.nomcia2||a.id1 like '%" + ((String) filterValue).toUpperCase() + "%'";
            query += " and CAST(a.grupo AS text) = '" + grupo + "'";
            query += " order by " + sortField.replace("v", "");
            query += " LIMIT " + pageSize;
            query += " OFFSET " + first;

            break;
        }

        pstmt = con.prepareStatement(query);
        //System.out.println(query);

        r = pstmt.executeQuery();

        while (r.next()) {
            Cia select = new Cia();
            select.setVcodcia(r.getString(1));
            select.setVnomcia1(r.getString(2));
            select.setVnomcia2(r.getString(3));
            select.setVid(r.getString(4));
            select.setVid2(r.getString(5));
            select.setVdir(r.getString(6));
            select.setVpcodpaidespai(r.getString(7) + " - " + r.getString(11));
            select.setVpcodciudesciu(r.getString(8) + " - " + r.getString(12));
            select.setTlf1(r.getString(9));
            select.setTlf2(r.getString(10));
            select.setVpcodpai(r.getString(11));
            select.setVgrupo(r.getString(13));
            //Agrega la lista
            list.add(select);

        }
    } catch (Exception e) {

    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();

}