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:de.griffel.confluence.plugins.plantuml.AbstractDatabaseStructureMacroImpl.java

/**
 * Returns database meta data.//from w  w w .ja v a 2s  . com
 *
 * Returned object must be closed using "closeDatabaseMetaData"
 *
 * @param jdbcName Database which is configured at "java:comp/env/jdbc/<jdbcName>"
 * @return Connection or null if none could be made. _errorMessage contains reason in the latter case.
 */
private DatabaseMetaData openDatabaseMetaData() {
    Context jndiContext = null;
    DatabaseMetaData dbmd = null;
    try {
        jndiContext = new InitialContext();
        javax.sql.DataSource ds = (javax.sql.DataSource) jndiContext
                .lookup("java:comp/env/jdbc/" + _macroParams.getDatasource());
        try {
            _con = ds.getConnection();
            dbmd = _con.getMetaData();
        } catch (SQLException e) {
            sqlException(_macroParams.getDatasource(), e);
        }
    } catch (NamingException e) {
        _errorMessage = e.getMessage();
        log.error("NamingException " + _macroParams.getDatasource() + _errorMessage, e);
    } finally {
        if (jndiContext != null) {
            try {
                jndiContext.close();
            } catch (NamingException e2) {
                log.debug("Exception closing JNDI context", e2);
            }
        }
    }
    return dbmd;
}

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

/**
 * Inserta Ciudades./* w w  w  . j a v  a2  s  .  c  om*/
 * <p>
 * Parametros del Metodo: String codciu, String desciu, String estado, String p_codpai. Pool de conecciones y login
 * @throws SQLException 
 **/
private void insert() {
    String[] vecValores = p_codpai.split("\\ - ", -1);

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

        String query = "INSERT INTO PNT004 VALUES (" + Integer.parseInt(codciu) + ",?,?,"
                + Integer.parseInt(vecValores[0]) + ",?,'" + getFecha() + "',?,'" + getFecha() + "',"
                + Integer.parseInt(grupo) + ")";
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, desciu.toUpperCase());
        pstmt.setString(2, estado.toUpperCase());
        pstmt.setString(3, login);
        pstmt.setString(4, login);
        //System.out.println(query);
        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("bas02", "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();
    }

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

From source file:com.edgenius.wiki.installation.DBLoader.java

public ConnectionProxy getConnection(String dbType, Server server) throws Exception {
    if (server.getDbConnectType() != null && server.getDbConnectType().equalsIgnoreCase(Server.CONN_TYPE_DS)) {
        // Datasource
        Context ctx = new InitialContext();
        if (ctx == null)
            throw new Exception("Boom - No Context");

        //this just confirm java:comp/env exist, then go next step
        Context envCtx = (Context) ctx.lookup(Server.JNDI_PREFIX);
        if (envCtx == null)
            throw new Exception("Boom - No java:comp/env Context");

        //jndi should be full URL
        DataSource ds = (DataSource) ctx.lookup(server.getDbJNDI());
        if (ds != null) {
            //TODO: does JNDI datasource need schmea?
            return new ConnectionProxy(dbType, ds.getConnection(), null);
        }//from ww  w . j av  a  2  s  .  c o  m
    } else {
        // JDBC:
        return getConnection(dbType, server.getDbUrl(), server.getDbSchema(), server.getDbUsername(),
                server.getDbPassword());
    }

    return null;
}

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

/**
* Leer registros en la tabla/* w w w . j a  va2 s .  c  om*/
* @throws NamingException 
* @throws IOException 
**/
public void counter(Object filterValue) throws SQLException, NamingException {
    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;

        if (p_codpai == null) {
            p_codpai = " - ";
        }
        if (p_codpai == "") {
            p_codpai = " - ";
        }

        String[] vecValores = p_codpai.split("\\ - ", -1);

        switch (productName) {
        case "Oracle":
            query = "SELECT count_pnt004(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "','" + vecValores[0] + "') from dual";
            break;
        case "PostgreSQL":
            query = "SELECT count_pnt004(" + Integer.parseInt(grupo) + ",'"
                    + ((String) filterValue).toUpperCase() + "','" + vecValores[0] + "')";
            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.dhatim.routing.jms.JMSRouter.java

protected MessageProducer createMessageProducer(final Destination destination, final Context context)
        throws JMSException {
    try {// w  w  w . j  a va 2 s .c o  m
        final ConnectionFactory connFactory = (ConnectionFactory) context
                .lookup(jmsProperties.getConnectionFactoryName());

        connection = (jmsProperties.getSecurityPrincipal() == null
                && jmsProperties.getSecurityCredential() == null) ? connFactory.createConnection()
                        : connFactory.createConnection(jmsProperties.getSecurityPrincipal(),
                                jmsProperties.getSecurityCredential());

        session = connection.createSession(jmsProperties.isTransacted(), AcknowledgeModeEnum
                .getAckMode(jmsProperties.getAcknowledgeMode().toUpperCase()).getAcknowledgeModeInt());

        msgProducer = session.createProducer(destination);
        connection.start();
        logger.info("JMS Connection started");
    } catch (JMSException e) {
        final String errorMsg = "JMSException while trying to create MessageProducer for Queue ["
                + jmsProperties.getDestinationName() + "]";
        releaseJMSResources();
        throw new SmooksConfigurationException(errorMsg, e);
    } catch (NamingException e) {
        final String errorMsg = "NamingException while trying to lookup ConnectionFactory ["
                + jmsProperties.getConnectionFactoryName() + "]";
        releaseJMSResources();
        throw new SmooksConfigurationException(errorMsg, e);
    }

    return msgProducer;
}

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

/**
 * Actualiza ciudades/*from   w  w w . j av  a  2s  .com*/
 **/
private void update() {

    String[] vecValores = p_codpai.split("\\ - ", -1);

    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":
            query = "UPDATE PNT004 SET desciu = ?, estado = ?,";
            query += "p_codpai = " + Integer.parseInt(vecValores[0]);
            query += ",FECACT = '" + getFecha() + "' , USRACT = '" + login + "'";
            query += " WHERE codciu = '" + codciu + "'";
            query += " and grupo = " + Integer.parseInt(localgrupo);
            break;
        case "PostgreSQL":
            query = "UPDATE PNT004 SET desciu = ?, estado = ?,";
            query += "p_codpai = " + Integer.parseInt(vecValores[0]);
            query += ",FECACT = '" + getFecha() + "' , USRACT = '" + login + "'";
            query += " WHERE CAST(codciu AS text) = '" + codciu + "'";
            query += " and grupo = " + Integer.parseInt(localgrupo);
            break;
        }

        //System.out.println(query);
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, desciu.toUpperCase());
        pstmt.setString(2, estado.toUpperCase());
        //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
        vGacc = acc.valAccmnu("bas02", "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"), "");
                }
                desciu = "";
                p_codpai = "";
                estado = "";
                validarOperacion = 0;
                localgrupo = "";
            } 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.Pnt004.java

/**
 * Borra Ciudades// ww w .  j  a  v  a  2s .c  o m
 * <p>
 * Parametros del metodo: String param. String cuenta
 * @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("pnt003DelPai"), "");
        } 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  PNT004 WHERE codciu||grupo in (" + param + ")";
                    break;
                case "PostgreSQL":
                    query = "DELETE FROM  PNT004 WHERE CAST(codciu AS text)||CAST(grupo AS text) in (" + param
                            + ")";
                    break;
                }

                pstmt = con.prepareStatement(query);

                //Antes de insertar verifica si el rol del usuario tiene permisos para insertar
                vGacc = acc.valAccmnu("bas02", "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();
                        list.clear();
                    } 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:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java

public void submitTicketForPollingToQueue(String ticket, String queueName, String batchProcessorSystemID)
        throws Exception {
    Context ctx = null;
    QueueConnection cnn = null;/*w  w w .jav  a2  s.  c  om*/
    QueueSession sess = null;
    Queue queue = null;
    QueueSender sender = null;
    try {
        ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(QueueConnectionFactoryName);
        queue = (Queue) ctx.lookup(queueName);
        cnn = factory.createQueueConnection();
        sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        //create the message to send to the MDB e.g. a TextMessage
        TextMessage message = sess.createTextMessage(ticket);
        message.setStringProperty(BatchProcessor.QUEUE_PROPERTY_NAME_FOR_SENDING, batchProcessorSystemID);

        //and finally send the message to the queue.
        sender = sess.createSender(queue);
        sender.send(message);
        log.debug("TestbedWEEBatchProcessor: sent message to queue, ID:" + message.getJMSMessageID());
    } finally {
        try {
            if (null != sender)
                sender.close();
        } catch (Exception ex) {
        }
        try {
            if (null != sess)
                sess.close();
        } catch (Exception ex) {
        }
        try {
            if (null != cnn)
                cnn.close();
        } catch (Exception ex) {
        }
        try {
            if (null != ctx)
                ctx.close();
        } catch (Exception ex) {
        }
    }
}

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

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

        if (p_codpai == null) {
            p_codpai = " - ";
        }
        if (p_codpai == "") {
            p_codpai = " - ";
        }

        String[] vecValores = p_codpai.split("\\ - ", -1);

        switch (productName) {
        case "Oracle":
            //Consulta paginada
            query = "  select * from ";
            query += " ( select query.*, rownum as rn from";
            query += " ( SELECT a.codciu, trim(a.desciu), trim(a.estado), b.codpai, trim(b.despai), a.grupo";
            query += " FROM Pnt004 a, Pnt003 b";
            query += " where a.p_codpai=b.codpai";
            query += " and a.grupo=b.grupo";
            query += " and a.codciu like '" + codciu.toUpperCase() + "%'";
            query += " and a.p_codpai like '%" + vecValores[0] + "%'";
            query += " and a.codciu||a.desciu 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
            query = "SELECT a.codciu, trim(a.desciu), trim(a.estado), b.codpai, trim(b.despai), a.grupo";
            query += " FROM Pnt004 a, Pnt003 b";
            query += " where a.p_codpai=b.codpai";
            query += " and a.grupo=b.grupo";
            query += " and CAST(a.codciu AS text) like '" + codciu.toUpperCase() + "%'";
            query += " and cast(a.p_codpai AS text) like '%" + vecValores[0] + "%'";
            query += " and cast(a.codciu AS text)||a.desciu 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()) {
            Ciudades ciudad = new Ciudades();
            ciudad.setVcodciu(r.getString(1));
            ciudad.setVdesciu(r.getString(2));
            ciudad.setVestado(r.getString(3));
            ciudad.setVp_pcodpai(r.getString(4));
            ciudad.setVcodpaidespai(r.getString(4) + " - " + r.getString(5));
            ciudad.setVgrupo(r.getString(6));
            //Agrega la lista
            list.add(ciudad);
        }
        //Cierra las conecciones
        pstmt.close();
        con.close();
        r.close();

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

}

From source file:de.catma.repository.db.SourceDocumentHandler.java

public SourceDocumentHandler(DBRepository dbRepository, String repoFolderPath) throws NamingException {
    this.dbRepository = dbRepository;
    this.sourceDocsPath = repoFolderPath + "/" + SOURCEDOCS_FOLDER + "/";
    File file = new File(sourceDocsPath);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            throw new IllegalStateException("cannot access/create repository folder " + sourceDocsPath);
        }/*from w ww  . j av a 2s  .  c  o  m*/
    }
    this.sourceDocumentsByID = new HashMap<String, SourceDocument>();
    Context context = new InitialContext();
    this.dataSource = (DataSource) context.lookup("catmads");
}