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:edu.harvard.hul.ois.pds.ws.PDSWebService.java

/**
 * Initialize the servlet.//  w w w .jav  a 2s. co m
 */

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        PdsConf pdsConf = (PdsConf) envContext.lookup("bean/PdsConf");
        conf = pdsConf.getConf();
        memcache = (CacheController) envContext.lookup("bean/CacheController");
        ds = (DataSource) envContext.lookup("jdbc/DrsDB");
    } catch (NamingException e) {
        e.printStackTrace();
    }

    cache = conf.getString("cache");
    idsUrl = conf.getString("ids");
    ftsUrl = conf.getString("fts");
    giffy = conf.getString("t2gif");
    cacheUrl = conf.getString("cacheUrl");
    pdsUrl = conf.getString("pds");
    nrsUrl = conf.getString("nrsUrl");
    String logFile = conf.getString("logFile");

    maxThumbnails = conf.getString("maxThumbnails");

    //Configure the logger
    logger = Logger.getLogger("edu.harvard.hul.ois.pds.ws");
    try {
        XmlLayout myLayout = new XmlLayout();
        //an appender for the access log
        Appender myAppender = new DailyRollingFileAppender(myLayout, logFile, conf.getString("logRollover"));
        logger.addAppender(myAppender);
    } catch (Exception e) {
        WebAppLogMessage message = new WebAppLogMessage();
        message.setContext("init logger");
        message.setMessage("Error initializing logger");
        logger.error(message, e);
        throw new ServletException(e.getMessage());
    }
    //reset the logger for this class
    logger = Logger.getLogger(PDSWebService.class);

    System.setProperty("org.xml.sax.driver", "org.apache.xerces.parsers.SAXParser");

    //init pdf conversions hash
    pdfConversions = new Hashtable<String, ArrayList<Integer>>();

    //Log successful servlet init
    WebAppLogMessage message = new WebAppLogMessage();
    message.setMessage("Servlet init()");
    logger.info(message);

    drs2Service = new ServiceWrapper(conf.getString("drs2ServiceURL"), conf.getString("drs2AppKey"), 1);

}

From source file:jdao.JDAO.java

public static Context unbind(Context ctx, String nameStr) throws NamingException {
    log("unbinding " + nameStr);

    Name name = ctx.getNameParser("").parse(nameStr);

    //no name, nothing to do
    if (name.size() == 0)
        return null;

    Context subCtx = ctx;

    for (int i = 0; i < name.size() - 1; i++) {
        try {//from   w  w  w .  j a v a  2  s .c om
            subCtx = (Context) subCtx.lookup(name.get(i));
        } catch (NameNotFoundException e) {
            log("Subcontext " + name.get(i) + " undefined", e);
            return null;
        }
    }

    subCtx.unbind(name.get(name.size() - 1));
    log("unbound object " + nameStr);
    return subCtx;
}

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

/**
* Rutina que ejecuta el control de proceso de licencias de grupos de trabajadores.
* Por ejemplo si la licencia es hasta 25 y el usuario carga mas de 25 el procedimiento
* almacenado en la base de datos elimina los trabajadres de 25 en adelante
**//*from   ww  w  . j  a va 2 s  .  c o  m*/
private void actCaracteres() throws NamingException {
    //Pool de conecciones JNDI(). Cambio de metodologa de conexin a bd. Julio 2010
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    try {
        Connection con = ds.getConnection();
        CallableStatement proc = null;

        proc = con.prepareCall("{? = CALL act_caracteres()}");
        proc.registerOutParameter(1, Types.OTHER);
        proc.execute();
        //System.out.println("Compaa: " + cia);
        //System.out.println("Ao: " + anio);
        //System.out.println("Mes: " + mes);
        //System.out.println("Usuario: " + user);
        //System.out.println("Opcin " + opcauto);
        //
        proc.close();
        con.close();

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

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

/**
* Rutina que ejecuta el control de proceso de licencias de grupos de trabajadores.
* Por ejemplo si la licencia es hasta 25 y el usuario carga mas de 25 el procedimiento
* almacenado en la base de datos elimina los trabajadres de 25 en adelante
**///from www. ja va 2s.c  o  m
private void actAutoSrv(String cia, Integer anio, Integer mes, String user, String opcauto)
        throws NamingException {
    //Pool de conecciones JNDI(). Cambio de metodologa de conexin a bd. Julio 2010
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    try {
        Connection con = ds.getConnection();
        CallableStatement proc = null;

        proc = con.prepareCall("{? = CALL act_autosrv(?,?,?,?,?)}");
        proc.registerOutParameter(1, Types.OTHER);
        proc.setString(2, cia);
        proc.setInt(3, anio);
        proc.setInt(4, mes);
        proc.setString(5, user);
        proc.setString(6, opcauto);
        proc.execute();
        //System.out.println("Compaa: " + cia);
        //System.out.println("Ao: " + anio);
        //System.out.println("Mes: " + mes);
        //System.out.println("Usuario: " + user);
        //System.out.println("Opcin " + opcauto);
        //
        proc.close();
        con.close();

        //System.out.println("Actualizando");

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

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

/**
* Borra autos02/*w w  w .  j a va2  s  .c o  m*/
**/
public void deleteAutos(String tabla, String codcia, String opc) throws NamingException {
    try {
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup(JNDI);
        con = ds.getConnection();

        String query = "";
        if (opc.equals("0")) {
            query = "DELETE FROM " + tabla + " WHERE PCODCIA = '" + codcia + "' AND ANIO = "
                    + Integer.parseInt(anio) + " and MES = " + Integer.parseInt(mes);
        } else {
            query = "DELETE FROM " + tabla + " WHERE PCODCIA = '" + codcia + "'";
        }
        pstmt = con.prepareStatement(query);
        //System.out.println(query);                  
        try {
            //Avisando
            pstmt.executeUpdate();
            //System.out.println("Registros:" + pstmt.getUpdateCount());   
            count = pstmt.getUpdateCount();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        pstmt.close();
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
* Leer registros en la tabla//  w w w . ja v  a2s.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);

        con = ds.getConnection();
        String ciaselected = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                .get("ciaselected");

        //Consulta paginada
        String query = "SELECT count_recibos_enviados('" + ((String) filterValue).toUpperCase() + "','"
                + ciaselected.toUpperCase() + "')";

        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:jdao.JDAO.java

public static Context bind(Context ctx, String nameStr, Object obj) throws NamingException {
    log("binding " + nameStr);

    Name name = ctx.getNameParser("").parse(nameStr);

    //no name, nothing to do
    if (name.size() == 0)
        return null;

    Context subCtx = ctx;

    //last component of the name will be the name to bind
    for (int i = 0; i < name.size() - 1; i++) {
        try {/*from w  ww  .ja  v a 2  s .com*/
            subCtx = (Context) subCtx.lookup(name.get(i));
            log("Subcontext " + name.get(i) + " already exists");
        } catch (NameNotFoundException e) {
            subCtx = subCtx.createSubcontext(name.get(i));
            log("Subcontext " + name.get(i) + " created");
        }
    }

    subCtx.rebind(name.get(name.size() - 1), obj);
    log("Bound object to " + name.get(name.size() - 1));
    return subCtx;
}

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

/**
* Leer Datos de TipoConsulta/*from   www . ja  v  a2  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();

        String ciaselected = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                .get("ciaselected");

        //Consulta paginada
        String query = "select distinct  id,  anio, mes, periodo, case when isenv = '1' then '"
                + getMessage("autos02EnviadoS") + "' else '" + getMessage("autos02EnviadoN") + "' end";
        query += " from recibos_enviados";
        query += " where id||cast(anio as text)||cast(mes as text)||cast(periodo as text)  like '%"
                + ((String) filterValue).toUpperCase() + "%'";
        query += " and pcodcia = '" + ciaselected.toUpperCase() + "'";
        query += " order by anio, periodo desc ";
        query += " LIMIT " + pageSize;
        query += " OFFSET " + first;

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

        r = pstmt.executeQuery();

        while (r.next()) {
            Autonom select = new Autonom();
            select.setVid(r.getString(1));
            select.setVanio(r.getString(2));
            select.setVmes(r.getString(3));
            select.setVperiodo(r.getString(4));
            select.setVcodcto(r.getString(5));
            //Agrega la lista
            list.add(select);

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //Cierra las conecciones
    pstmt.close();
    con.close();
    r.close();
}

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

/**
 * Mtodo que enva los recibos de pago a cada usuario
 * @throws IOException /*from w  w  w .ja v a  2 s  .c om*/
 * @throws NumberFormatException 
 * **/
public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException {
    try {
        //System.out.println("Enviando recibo");
        //System.out.println(jndimail());
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(jndimail());
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);

        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailRP"));
        //mm.setText(getMessage("mailContent"));

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = laruta + File.separator + file + ".pdf";
        javax.activation.DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        mm.setContent(multipart);

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente a :" + to);
        //System.out.println("Fin recibo");
    } catch (Exception e) {
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, "");
        FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
    }
}

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

/**
* Borra TipoConsulta//from   w w w  .  j a  v a2  s.  c  o  m
* <p>
* Parametros del metodo: String codcentro. Pool de conecciones
* @throws NamingException 
 * @throws IOException 
**/
public void delete_recibos_enviados() 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();

                String param = "'" + StringUtils.join(chkbox, "','") + "'";

                String ciaselected = (String) FacesContext.getCurrentInstance().getExternalContext()
                        .getSessionMap().get("ciaselected");

                String query = "DELETE FROM recibos_enviados WHERE cast(anio as text)||cast(mes as text)||cast(periodo as text) in ("
                        + param + ") and pcodcia = '" + ciaselected + "'";
                pstmt = con.prepareStatement(query);
                //System.out.println(query);

                try {
                    //Avisando
                    pstmt.executeUpdate();
                    if (pstmt.getUpdateCount() <= 1) {
                        msj = new FacesMessage(FacesMessage.SEVERITY_INFO, getMessage("msnDelete"), "");
                    } else {
                        msj = new FacesMessage(FacesMessage.SEVERITY_INFO,
                                pstmt.getUpdateCount() + " " + 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);
    }
}