Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold.

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:pe.edu.upeu.application.web.controller.CDocumento_Trabajador.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String dgp = request.getParameter("iddgp");
    String idtr = request.getParameter("idtr");
    String opc = request.getParameter("opc");
    HttpSession sesion = request.getSession(true);
    String user = (String) sesion.getAttribute("IDUSER");

    try {/*  w ww.ja va2 s.  com*/
        if (opc != null) {
            if (opc.equals("Eliminar")) {
                String id_doc_adj = request.getParameter("id_doc");
                d.Desactivar_doc(id_doc_adj);
                sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
                sesion.setAttribute("Documentos", d.Documentos());
                sesion.setAttribute("Lis_doc_trabajador", d.Lis_doc_trabajador(idtr));
                sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));
                int s = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);
                //    response.sendRedirect("Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad + "&idtr=" + idtr + "&pro=pr_dgp&P2=TRUE");
                String pr = request.getParameter("P2");
                String url = "Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad
                        + "&idtr=" + idtr;
                if (pr != null) {
                    url += "&pro=pr_dgp&P2=TRUE";
                    response.sendRedirect(url);
                } else {
                    response.sendRedirect("Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad="
                            + num_ad + "&idtr=" + idtr);
                }

            }
            if (opc.equals("Ver_Documento")) {

                sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr));
                int i = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);
                sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
                sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));

                response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + i + "&num_ad=" + num_ad);
            }
            if (opc.equals("Reg_Pro_Dgp")) {
                sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr));
                int i = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);
                sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
                sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));

                response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + i + "&num_ad=" + num_ad
                        + "&pro=pr_dgp");
            }

            if (("Listar_doc").equals(opc)) {

                sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
                sesion.setAttribute("Documentos", d.Documentos());
                sesion.setAttribute("Lis_doc_trabajador", d.Lis_doc_trabajador(idtr));
                sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));
                int s = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);
                int count = d.count_documentos_x_tra(idtr);
                if (count > 0) {
                    response.sendRedirect("Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad="
                            + num_ad + "&Vol=volver&idtr=" + idtr);
                } else {
                    response.sendRedirect("Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad="
                            + num_ad + "&idtr=" + idtr);
                }

            }
        } else {

            String ubicacion = FactoryConnectionDB.url + "Archivo/";
            DiskFileItemFactory f = new DiskFileItemFactory();
            f.setSizeThreshold(1024);
            f.setRepository(new File(ubicacion));
            ServletFileUpload upload = new ServletFileUpload(f);
            ServletRequestContext src = new ServletRequestContext(request);
            List<FileItem> p = upload.parseRequest(src);
            int num_filas = 0;
            String iddgp = null;
            String pr = null;
            String id_ctr = null;
            String ms = null;
            String dt = null;
            String idh = null;
            List<String> list_files = new ArrayList<String>();
            Iterator itera = p.iterator();
            Random rnd = new Random();
            while (itera.hasNext()) {
                FileItem i_n_f = (FileItem) itera.next();

                if (i_n_f.isFormField()) {

                    String nombre = i_n_f.getFieldName();
                    String valor = i_n_f.getString();

                    num_filas = (nombre.equals("num")) ? Integer.parseInt(valor) : num_filas;
                    if (nombre.equals("iddgp") & iddgp == null) {
                        iddgp = valor;
                    }
                    if (nombre.equals("idtr") & idtr == null) {
                        idtr = valor;
                    }
                    if (nombre.equals("P2") & pr == null) {
                        pr = valor;
                    }

                    if (nombre.equals("idctr") & id_ctr == null) {
                        id_ctr = valor;
                    }

                    if (nombre.equals("ms") & ms == null) {
                        ms = valor;
                    }
                    if (nombre.equals("dt") & ms == null) {
                        dt = valor;
                    }

                }

            }

            String iddoc = null;
            String nombre_archivo = null;
            String desc = null;
            String estado = null;
            String archivo = null;
            int num = 0;
            String no_original = null;

            String validar_nombre = "";
            for (int i = 0; i < num_filas; i++) {
                Iterator it = p.iterator();
                while (it.hasNext()) {

                    FileItem item = (FileItem) it.next();

                    if (item.isFormField()) {
                        String nombre = item.getFieldName();
                        String valor = item.getString();
                        iddoc = (nombre.equals("iddoc" + i)) ? valor : iddoc;
                        idh = (nombre.equals("idh" + i)) ? valor : idh;
                        desc = (nombre.equals("lob_description" + i)) ? valor : desc;
                        estado = (nombre.equals("estado" + i)) ? valor : estado;
                    } else {
                        String fieldName = item.getFieldName();

                        num++;
                        Calendar fecha = new GregorianCalendar();
                        int hora = fecha.get(Calendar.HOUR_OF_DAY);
                        int min = fecha.get(Calendar.MINUTE);
                        int sec = fecha.get(Calendar.SECOND);

                        if (fieldName.equals("archivos" + i) & item.getName() != null) {
                            if (!item.getName().equals("")) {

                                //out.println(item.getFieldName() + " : " + item.getName());
                                //nombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + num + iddgp + "_" + item.getName().toUpperCase();
                                nombre_archivo = String.valueOf(hora) + String.valueOf(min)
                                        + String.valueOf(sec) + "_" + num;
                                no_original = item.getName();
                                Thread thread = new Thread(new Renombrar(item, ubicacion, nombre_archivo));
                                thread.start();
                                archivo = no_original + ":" + nombre_archivo;
                                list_files.add(archivo);
                            }

                        } else {
                            no_original = no_original;
                            nombre_archivo = nombre_archivo;
                        }
                    }
                }
                Thread.sleep(200);
                if (nombre_archivo != null) {

                    if (!nombre_archivo.equals("")) {

                        estado = ((estado == null) ? "0" : estado);

                        String id = d.INSERT_DOCUMENTO_ADJUNTO(null, iddoc, "1", user, null, null, null, null,
                                desc, null, estado, id_ctr);
                        //out.print(id);
                        d.INSERT_DGP_DOC_tra(null, null, id, null, idtr, idh);
                        for (int t = 0; t < list_files.size(); t++) {
                            String g[] = list_files.get(t).split(":");
                            d.INSERT_ARCHIVO_DOCUMENTO(null, id, g[1], g[0], null);
                        }
                        list_files.clear();

                    }

                }
                no_original = null;
                iddoc = null;
                nombre_archivo = null;
                desc = null;
                estado = null;

                no_original = null;

            }

            sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
            sesion.setAttribute("Documentos", d.Documentos());
            sesion.setAttribute("Lis_doc_trabajador", d.Lis_doc_trabajador(idtr));
            sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));

            int s = d.List_Req_nacionalidad(idtr);
            int num_ad = d.List_Adventista(idtr);

            out.print(idtr);
            int count = d.count_documentos_x_tra(idtr);

            if (count > 0) {
                String url = "Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad
                        + "&idtr=" + idtr + "&m=si";
                if (pr != null) {
                    url += "&P2=TRUE";
                }
                if (ms != null) {
                    url += "&ms=" + ms;
                }
                if (dt != null) {
                    url += "&dt=" + dt;
                }
                response.sendRedirect(url);

            } else {
                String url = "Vista/Trabajador/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad
                        + "&idtr=" + idtr + "&pro=pr_dgp&P2=TRUE";
                if (ms != null) {
                    url += "&ms=" + ms;
                }
                if (dt != null) {
                    url += "&dt=" + dt;
                }
                response.sendRedirect(url);
            }
        }
    } catch (Exception e) {
        out.println("Error : " + e.getMessage());
    } finally {
        out.close();
    }
}

From source file:pe.edu.upeu.application.web.controller.recruitment.CDocumento.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, Exception {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    String dgp = request.getParameter("iddgp");
    String idtr = request.getParameter("idtr");
    String opc = request.getParameter("opc");
    HttpSession sesion = request.getSession(true);
    String user = (String) sesion.getAttribute("IDUSER");
    String rol = (String) sesion.getAttribute("IDROL");
    Map<String, Object> rpta = new HashMap<String, Object>();
    boolean permissionEditDocument = false;
    if (rol.trim().equals("ROL-0002") | rol.trim().equals("ROL-0003") | rol.trim().equals("ROL-0005")
            | rol.trim().equals("ROL-0007") | rol.trim().equals("ROL-0001")) {
        permissionEditDocument = true;/*from  w  ww.  j a  v a2s .  com*/
    }
    try {
        if (opc != null) {
            if (opc.equals("Eliminar")) {
                String id_doc_adj = request.getParameter("id_doc");
                d.Desactivar_doc(id_doc_adj);
                int s = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);

                sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
                sesion.setAttribute("List_doc_req_pla", d.List_doc_req_pla(dgp, idtr));
                sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));
                response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + s + "&num_ad=" + num_ad
                        + "&idtr=" + idtr + "&iddgp=" + dgp + "&pro=pr_dgp&a=e");

            }
            if (opc.equals("Ver_Documento")) {
                int i = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);
                sesion.setAttribute("List_Hijos", d.List_Hijos(idtr));
                sesion.setAttribute("List_Conyugue", d.List_Conyugue(idtr));

                response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?n_nac=" + i + "&num_ad=" + num_ad
                        + "&idtr=" + idtr + "&iddgp=" + dgp);
            }
            if (opc.equals("ReqIncompletoNextStep")) {
                response.sendRedirect("Vista/Dgp/Documento/Reg_Documento.jsp?" + "idtr=" + idtr + "&iddgp="
                        + dgp + "&pro=pr_dgp");
            }
            if (opc.equals("listDocument")) {
                System.out.println("enter to listDocument");
                System.out.println("permissionEditDocument:" + permissionEditDocument);
                //    Boolean enterToProcessDGP = false;
                int n_nac = d.List_Req_nacionalidad(idtr);
                int num_ad = d.List_Adventista(idtr);
                // int documentsComplete = d.countDocumentsByIdTrabajador(idtr);
                Boolean enterToDGPProcess = false;
                List<Lis_Doc_tra> listDocumentsByIdtr = null;
                if (request.getParameter("enterToDGPProcess") != null) {
                    enterToDGPProcess = Boolean.parseBoolean(request.getParameter("enterToDGPProcess"));
                    listDocumentsByIdtr = d.List_doc_req_pla(dgp, idtr);
                } else {
                    //  List_doc_req_pla = d.Lis_doc_trabajador(idtr);
                    listDocumentsByIdtr = d.List_doc_req_pla(null, idtr);
                }
                Boolean enterToRegTrabajador = false;
                if (request.getParameter("enterToRegTrabajador") != null) {
                    enterToRegTrabajador = Boolean.parseBoolean(request.getParameter("enterToRegTrabajador"));
                }
                /*casos especiales*/
                Boolean enterToCasosEspecialesProcess = false;
                if (request.getParameter("enterToCasosEspecialesProcess") != null) {
                    enterToCasosEspecialesProcess = Boolean
                            .parseBoolean(request.getParameter("enterToCasosEspecialesProcess"));
                }

                List<Datos_Hijo_Trabajador> listHijosMenoresDeEdad = d.List_Hijos(idtr);
                List<Padre_Madre_Conyugue> List_Conyugue = d.List_Conyugue(idtr);

                String id_hijo_faltante = "";

                List<String> listDocumentItem = new ArrayList<String>();
                InterfaceDocumentoDAO doc_ = new DocumentoDAO();
                // String id_dgp = "";
                String html = "";
                html += " <form action='../../../documento' method='post' enctype='multipart/form-data'  class='form_dgp_doc' >";

                int i = 0;
                for (int z = 0; z < listDocumentsByIdtr.size(); z++) {
                    Lis_Doc_tra d = new Lis_Doc_tra();
                    d = (Lis_Doc_tra) listDocumentsByIdtr.get(z);

                    String htmlDoca = "";
                    if (d.getTi_documento().trim().equals("DOCA")) {
                        if (n_nac != 0) {

                            htmlDoca += "<div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                            htmlDoca += " <div class='well well-sm'>";

                            htmlDoca += "<div class=''>";
                            htmlDoca += "<label >" + d.getNo_documento() + "</label>";
                            htmlDoca += "  </div>";

                            htmlDoca += " <div class=' caji" + (i + 1) + "'  >";
                            if (d.getId_documento_adjunto() == null & (permissionEditDocument)) {

                                htmlDoca += " <input  class='fileDocument' type='file' multiple='true'   ";
                                if (d.getEs_obligatorio().equals("1") & !enterToRegTrabajador) {
                                    html += (" required='required' ");
                                }
                                htmlDoca += "name='archivos" + (i + 1) + "' >";

                            } else if (d.getId_documento_adjunto() == null) {
                                htmlDoca += " <label class='null'>No Registrado</label>";
                            } else {
                                htmlDoca += (doc_.List_files(d.getId_documento_adjunto().trim()));
                            }

                            htmlDoca += "</div>";

                            htmlDoca += " <div class=''>";
                            if (d.getDe_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlDoca += "<input type='text' placeholder='Escribe una descripcin' class='form-control' name='lob_description"
                                        + (i + 1) + "'>";

                            } else if (d.getDe_documento_adjunto() == null) {
                                htmlDoca += " <label class='null' >No Registrado</label>";
                            } else {
                                htmlDoca += "<label >Descripcin:</label>";
                                htmlDoca += "<label style='font-weight: normal;'>" + d.getDe_documento_adjunto()
                                        + "</label>";

                            }
                            htmlDoca += "</div>";

                            htmlDoca += " <div  class=''  >";
                            if (d.getEs_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlDoca += "  <label>Recibido en fisico?:</label> <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                        + (i + 1) + "'  >";
                                htmlDoca += " <i data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                            } else if (d.getEs_documento_adjunto() == null) {
                                htmlDoca += "<label class='null'>Recibido en fisico?:No Registrado</label>";
                            } else {
                                htmlDoca += " <label>";
                                if (d.getEs_documento_adjunto().trim().equals("1")) {

                                    htmlDoca += "Recibido en fisico?: Si";

                                } else {

                                    htmlDoca += "Recibido en fisico?: No";

                                }
                                htmlDoca += "  </label>";
                            }

                            htmlDoca += "</div>";

                            htmlDoca += "<div class=''>";
                            if (d.getEs_documento_adjunto() != null & (permissionEditDocument)) {
                                htmlDoca += "<a type='button'  class='btn btn-danger btn-sm  elimi'"
                                        + " href='../../../documento?opc=Eliminar&id_doc="
                                        + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp() + "&idtr="
                                        + d.getId_trabajador() + "'><i class='fa fa-trash-o'></i></a>";
                            }
                            htmlDoca += " </div>  ";

                            htmlDoca += "</div>";
                            htmlDoca += "  <input type='hidden' name='iddoc" + (i + 1) + "' value='"
                                    + d.getId_documentos() + "'>";
                            htmlDoca += "  </div>  ";
                        }
                        listDocumentItem.add(htmlDoca);
                    }
                    String htmlCOFE = "";
                    /*ok*/
                    if (d.getTi_documento().trim().equals("COFE")) {
                        /*constancia de feligresia*/
                        if (num_ad != 0) {
                            htmlCOFE += "  <div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                            htmlCOFE += "<div  class='well wel-sm'>";

                            htmlCOFE += " <div class=''>";
                            htmlCOFE += " <label>" + d.getNo_documento() + "</label>";
                            htmlCOFE += " </div>";

                            htmlCOFE += " <div  class='caji" + (i + 1) + "'  >";
                            if (d.getId_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlCOFE += "   <input class='fileDocument' type='file' multiple=true   ";
                                if (d.getEs_obligatorio().equals("1") & !enterToRegTrabajador) {
                                    htmlCOFE += " required='required' ";
                                }
                                htmlCOFE += "name='archivos" + (i + 1) + "' >";
                            } else if (d.getId_documento_adjunto() == null) {
                                htmlCOFE += " <label class='null'>No Registrado</label>";
                            } else {

                                htmlCOFE += doc_.List_files(d.getId_documento_adjunto().trim());

                            }
                            htmlCOFE += "  </div>";

                            htmlCOFE += " <div class=''>";

                            if (d.getDe_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlCOFE += " <input type='text'  placeholder='Escribe una descripcin' class='form-control' name='lob_description"
                                        + (i + 1) + "'>";
                            } else if (d.getDe_documento_adjunto() == null) {
                                htmlCOFE += " <label class='null' >No Registrado</label>";
                            } else {
                                htmlCOFE += " <label>Descripcin:</label> ";
                                htmlCOFE += "   <label >" + d.getDe_documento_adjunto() + " </label>";

                            }
                            htmlCOFE += " </div>";
                            htmlCOFE += "<div  class=''>";
                            if (d.getEs_documento_adjunto() == null & (permissionEditDocument)) {

                                htmlCOFE += "    <label>Recibido en fisico?:</label>";
                                htmlCOFE += " <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                        + (i + 1) + "'   >";
                                htmlCOFE += "<i data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                            } else if (d.getEs_documento_adjunto() == null) {

                                htmlCOFE += "    <label class='null'>Recibido en fisico?:No Registrado</label>";

                            } else {

                                htmlCOFE += "<label >";
                                if (d.getEs_documento_adjunto().trim().equals("1")) {

                                    htmlCOFE += "Recibido en fisico?:Si";

                                } else {

                                    htmlCOFE += " Recibido en fisico?:No";
                                    htmlCOFE += " </label>";
                                }
                            }
                            htmlCOFE += " </div>";

                            htmlCOFE += " <div class='' >";
                            if (d.getEs_documento_adjunto() != null & (permissionEditDocument)) {
                                htmlCOFE += " <a type='button'  class='btn btn-danger btn-sm  elimi' href='../../../documento?opc=Eliminar&id_doc="
                                        + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp() + "&idtr="
                                        + d.getId_trabajador() + "'><i class='fa fa-trash-o'></i></a>";
                            }

                            htmlCOFE += " </div>";
                            htmlCOFE += "  </div>";
                            htmlCOFE += " <input type='hidden' name='iddoc" + (i + 1) + "' value='"
                                    + d.getId_documentos() + "'>";
                            htmlCOFE += "   </div>  ";
                        }
                        listDocumentItem.add(htmlCOFE);
                    }
                    String htmlConyugue = "";
                    if (d.getTi_documento().trim().equals("DNIC") | d.getTi_documento().trim().equals("ACMA")) {

                        for (int kj = 0; kj < List_Conyugue.size(); kj++) {
                            Padre_Madre_Conyugue co = new Padre_Madre_Conyugue();
                            co = (Padre_Madre_Conyugue) List_Conyugue.get(kj);

                            htmlConyugue += "   <div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                            htmlConyugue += "  <div class='wel well-sm'>";

                            htmlConyugue += "  <div class=''> ";
                            htmlConyugue += "   <label>";

                            if (d.getTi_documento().trim().equals("ACMA")) {
                                htmlConyugue += ("Acta de matrimonio con: <p class='txt-color-red' >' "
                                        + co.getAp_nombres_conyugue() + " '</p>");
                            }
                            if (d.getTi_documento().trim().equals("DNIC")) {
                                htmlConyugue += " Copia DNI cnyugue : <p class='txt-color-red' >' "
                                        + co.getAp_nombres_conyugue() + " '</p>";
                            }

                            htmlConyugue += "    </label>";
                            htmlConyugue += "   </div>";

                            htmlConyugue += " <div class=' caji" + (i + 1) + "' >";
                            if (d.getId_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlConyugue += " <input  class='fileDocument' type='file' multiple=true ";
                                if (d.getEs_obligatorio().equals("1") & !enterToRegTrabajador) {
                                    htmlConyugue += (" required='required' ");
                                }
                                htmlConyugue += " name='archivos" + (i + 1) + "' >";
                            } else if (d.getId_documento_adjunto() == null) {
                                htmlConyugue += " <label class='null'>No Registrado</label>";
                            } else {
                                htmlConyugue += (doc_.List_files(d.getId_documento_adjunto().trim()));
                            }

                            htmlConyugue += " </div>";

                            htmlConyugue += " <div class=''>";

                            if (d.getDe_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlConyugue += "  <input type='text'  placeholder='Escribe una descripcin'  class='form-control' name='lob_description"
                                        + (i + 1) + "'>";
                            } else if (d.getDe_documento_adjunto() == null) {
                                htmlConyugue += "   <label class='null' >No Registrado</label>";
                            } else {
                                htmlConyugue += "   <label>Descripcin:</label>";
                                htmlConyugue += "   <label> " + d.getDe_documento_adjunto() + "</label>";

                            }
                            htmlConyugue += "     </div>";

                            htmlConyugue += " <div class='' >";
                            if (d.getEs_documento_adjunto() == null & (permissionEditDocument)) {
                                htmlConyugue += "  <label>Recibido en fisico?:</label>";
                                htmlConyugue += "  <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                        + (i + 1) + "'  >";
                                htmlConyugue += "  <i  data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                            } else if (d.getEs_documento_adjunto() == null) {

                                htmlConyugue += "    <label class='null'>Recibido en fisico?:No Registrado</label>";

                            } else {
                                htmlConyugue += "    <label >";
                                if (d.getEs_documento_adjunto().trim().equals("1")) {

                                    htmlConyugue += " Recibido en fisico?:Si";

                                } else {

                                    htmlConyugue += "  Recibido en fisico?:No";
                                    htmlConyugue += "     </label>";
                                }
                            }
                            htmlConyugue += "   </div>";

                            htmlConyugue += " <div class=''>";
                            if (d.getEs_documento_adjunto() != null & (permissionEditDocument)) {

                                htmlConyugue += " <a type='button'  class='btn btn-danger btn-sm  elimi' href='../../../documento?opc=Eliminar&id_doc="
                                        + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp() + "&idtr="
                                        + d.getId_trabajador() + "'><i class='fa fa-trash-o'></i></a>";
                            }
                            htmlConyugue += " </div>";

                            htmlConyugue += " </div>";

                            htmlConyugue += "  <input type='hidden' name='iddoc" + (i + 1) + "' value='"
                                    + d.getId_documentos() + "'>";
                            htmlConyugue += " </div>  ";

                            listDocumentItem.add(htmlConyugue);
                        }
                    }
                    String htmlDNIH = "";
                    if (d.getTi_documento().trim().equals("DNIH")) {
                        if (listHijosMenoresDeEdad.size() > 0) {
                            for (int kk = 0; kk < listHijosMenoresDeEdad.size(); kk++) {
                                Datos_Hijo_Trabajador h = new Datos_Hijo_Trabajador();
                                h = (Datos_Hijo_Trabajador) listHijosMenoresDeEdad.get(kk);
                                if (d.getId_datos_hijo() == null) {

                                    htmlDNIH += "   <div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                                    htmlDNIH += "   <div  class='well well-sm' >";

                                    htmlDNIH += " <div class=''>";
                                    htmlDNIH += "<label>Copia DNI hijo :   </label> <p class='txt-color-red'> "
                                            + h.getAp_paterno() + " " + h.getAp_materno() + " "
                                            + h.getNo_hijo_trabajador() + "</p>";

                                    htmlDNIH += "</div>";
                                    htmlDNIH += "<div  class=' caji" + (i + 1) + "' >";
                                    if (d.getId_documento_adjunto() == null
                                            & d.getEs_documento_adjunto() == null & (permissionEditDocument)) {

                                        htmlDNIH += " <input   class='fileDocument' type='file' multiple=true   name='archivos"
                                                + (i + 1) + "' >";
                                        htmlDNIH += "<input type='hidden' name='idh" + (i + 1) + "' value='"
                                                + h.getId_datos_hijos_trabajador().trim() + "' >";

                                    } else if (d.getId_documento_adjunto() == null) {
                                        htmlDNIH += "   <label class='null'>No Registrado</label>";
                                    } else {

                                        htmlDNIH += (doc_.List_file_url(d.getId_documento_adjunto().trim()));

                                    }
                                    htmlDNIH += " </div>";

                                    htmlDNIH += "<div class=''>";

                                    if (d.getDe_documento_adjunto() == null
                                            & d.getEs_documento_adjunto() == null & (permissionEditDocument)) {
                                        htmlDNIH += "  <input type='text'  placeholder='Escribe una descripcin'  class='form-control' name='lob_description"
                                                + (i + 1) + "'>";
                                    } else if (d.getDe_documento_adjunto() == null) {
                                        htmlDNIH += "  <label class='null' >No Registrado</label>";
                                    } else {
                                        htmlDNIH += "  <label>Descripcin:</label>";
                                        htmlDNIH += "  <label>" + d.getDe_documento_adjunto() + "</label>";

                                    }
                                    htmlDNIH += "  </div>";
                                    htmlDNIH += "   <div class=''>";
                                    if (d.getEs_documento_adjunto() == null & (permissionEditDocument)) {
                                        htmlDNIH += " <label class='toggle'>";
                                        htmlDNIH += "    <label>Recibido en fisico?:</label>";
                                        htmlDNIH += " <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                                + (i + 1) + "'   >";
                                        htmlDNIH += "<i data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                                    } else if (d.getEs_documento_adjunto() == null) {

                                        htmlDNIH += "    <label class='null'>Recibido en fisico?:No Registrado</label>";

                                    } else {
                                        htmlDNIH += "<label>";
                                        if (d.getEs_documento_adjunto().trim().equals("1")) {

                                            htmlDNIH += "Recibido en fisico?:Si";
                                        } else {

                                            htmlDNIH += "Recibido en fisico?:No";
                                            htmlDNIH += "  </label>";
                                        }
                                    }

                                    htmlDNIH += "  </div>";

                                    htmlDNIH += " <div class=''>";
                                    if (d.getEs_documento_adjunto() != null & (permissionEditDocument)) {

                                        htmlDNIH += " <a type='button'  class='btn btn-danger btn-sm  elimi' href='../../../documento?opc=Eliminar&id_doc="
                                                + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp()
                                                + "&idtr=" + d.getId_trabajador()
                                                + "'><i class='fa fa-trash-o'></i></a>";
                                    }
                                    htmlDNIH += " </div>";

                                    htmlDNIH += "  </div>";
                                    htmlDNIH += " <input type='hidden' name='iddoc" + (i + 1) + "' value='"
                                            + d.getId_documentos() + "'>";
                                    htmlDNIH += "   </div>  ";
                                    //out.println(html);
                                    listDocumentItem.add(htmlDNIH);
                                } else if (h.getVal_doc() > 0 & d.getId_datos_hijo()
                                        .equals(h.getId_datos_hijos_trabajador().trim())) {
                                    String htmlSecondDNIH = "";

                                    htmlSecondDNIH += "<div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                                    htmlSecondDNIH += "<div  class='well well-sm'>";

                                    htmlSecondDNIH += " <div class=''>";
                                    htmlSecondDNIH += "<label>Copia DNI hijo:   </label> <p class='txt-color-red'> "
                                            + h.getAp_paterno() + " " + h.getAp_materno() + " "
                                            + h.getNo_hijo_trabajador() + "</p>";

                                    htmlSecondDNIH += " </div>";

                                    htmlSecondDNIH += " <div  class='caji" + (i + 1) + "'  >";
                                    if (d.getId_documento_adjunto() == null & (permissionEditDocument)) {
                                        htmlSecondDNIH += " <input   class='fileDocument' type='file' multiple=true   name='archivos"
                                                + (i + 1) + "' >";
                                        htmlSecondDNIH += "<input type='hidden' name='idh" + (i + 1)
                                                + "' value='" + h.getId_datos_hijos_trabajador().trim() + "' >";
                                    } else if (d.getId_documento_adjunto() == null) {
                                        htmlSecondDNIH += " <label class='null'>No Registrado</label>";
                                    } else {

                                        htmlSecondDNIH += doc_.List_files(d.getId_documento_adjunto().trim());

                                    }
                                    htmlSecondDNIH += "  </div>";

                                    htmlSecondDNIH += " <div class=''>";

                                    if (d.getDe_documento_adjunto() == null & (permissionEditDocument)) {
                                        htmlSecondDNIH += " <input type='text'  placeholder='Escribe una descripcin' class='form-control' name='lob_description"
                                                + (i + 1) + "'>";
                                    } else if (d.getDe_documento_adjunto() == null) {
                                        htmlSecondDNIH += " <label class='null' >No Registrado</label>";
                                    } else {
                                        htmlSecondDNIH += " <label>Descripcin:</label> ";
                                        htmlSecondDNIH += "   <label >" + d.getDe_documento_adjunto()
                                                + " </label>";

                                    }
                                    htmlSecondDNIH += " </div>";

                                    htmlSecondDNIH += "<div  class=''>";
                                    if (d.getEs_documento_adjunto() == null & (permissionEditDocument)) {

                                        htmlSecondDNIH += "    <label>Recibido en fisico?:</label>";
                                        htmlSecondDNIH += " <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                                + (i + 1) + "'   >";
                                        htmlSecondDNIH += "<i data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                                    } else if (d.getEs_documento_adjunto() == null) {

                                        htmlSecondDNIH += "    <label class='null'>Recibido en fisico?:No Registrado</label>";

                                    } else {

                                        htmlSecondDNIH += "<label >";
                                        if (d.getEs_documento_adjunto().trim().equals("1")) {

                                            htmlSecondDNIH += "Recibido en fisico?:Si";

                                        } else {

                                            htmlSecondDNIH += " Recibido en fisico?:No";
                                            htmlSecondDNIH += " </label>";
                                        }
                                    }
                                    htmlSecondDNIH += " </div>";

                                    htmlSecondDNIH += " <div class='' >";
                                    if (d.getEs_documento_adjunto() != null & (permissionEditDocument)) {
                                        htmlSecondDNIH += " <a type='button'  class='btn btn-danger btn-sm  elimi' href='../../../documento?opc=Eliminar&id_doc="
                                                + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp()
                                                + "&idtr=" + d.getId_trabajador()
                                                + "'><i class='fa fa-trash-o'></i></a>";
                                    }

                                    htmlSecondDNIH += " </div>";
                                    htmlSecondDNIH += "  </div>";
                                    htmlSecondDNIH += " <input type='hidden' name='iddoc" + (i + 1)
                                            + "' value='" + d.getId_documentos() + "'>";
                                    htmlSecondDNIH += "   </div>  ";
                                    listDocumentItem.add(htmlSecondDNIH);

                                } else if (h.getVal_doc() == 0
                                        & !id_hijo_faltante.equals(h.getId_datos_hijos_trabajador())) {

                                    String htmlHijoFaltante = "";
                                    htmlHijoFaltante += "<div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                                    htmlHijoFaltante += "<div  class='well well-sm'>";

                                    htmlHijoFaltante += " <div class=''>";
                                    htmlHijoFaltante += "<label>Copia DNI hijo:   </label> <p class='txt-color-red'> "
                                            + h.getAp_paterno() + " " + h.getAp_materno() + " "
                                            + h.getNo_hijo_trabajador() + "</p>";

                                    htmlHijoFaltante += " </div>";
                                    htmlHijoFaltante += " <div  class='caji" + (i + 1) + "'  >";
                                    if ((permissionEditDocument)) {
                                        htmlHijoFaltante += " <input   class='fileDocument' type='file' multiple=true   name='archivos"
                                                + (i + 1) + "' >";
                                        htmlHijoFaltante += "<input type='hidden' name='idh" + (i + 1)
                                                + "' value='" + h.getId_datos_hijos_trabajador().trim() + "' >";
                                    } else {
                                        htmlHijoFaltante += " <label class='null'>No Registrado</label>";
                                    }
                                    /*else {
                                            
                                    htmlHijoFaltante += doc_.List_files(d.getId_documento_adjunto().trim());
                                            
                                    }*/
                                    htmlHijoFaltante += "  </div>";

                                    htmlHijoFaltante += " <div class=''>";

                                    if ((permissionEditDocument)) {
                                        htmlHijoFaltante += " <input type='text'  placeholder='Escribe una descripcin' class='form-control' name='lob_description"
                                                + (i + 1) + "'>";
                                    } else {
                                        htmlHijoFaltante += " <label class='null' >No Registrado</label>";
                                    }
                                    /*else {
                                    htmlHijoFaltante += " <label>Descripcin:</label> ";
                                    htmlHijoFaltante += "   <label >" + d.getDe_documento_adjunto() + " </label>";
                                            
                                    }*/
                                    htmlHijoFaltante += " </div>";

                                    htmlHijoFaltante += "<div  class=''>";
                                    if ((permissionEditDocument)) {

                                        htmlHijoFaltante += "    <label>Recibido en fisico?:</label>";
                                        htmlHijoFaltante += " <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                                + (i + 1) + "'   >";
                                        htmlHijoFaltante += "<i data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                                    } else {

                                        htmlHijoFaltante += "    <label class='null'>Recibido en fisico?:No Registrado</label>";

                                    }
                                    /* else {
                                            
                                    htmlHijoFaltante += "<label >";
                                    if (d.getEs_documento_adjunto().trim().equals("1")) {
                                            
                                        htmlHijoFaltante += "Recibido en fisico?:Si";
                                            
                                    } else {
                                            
                                        htmlHijoFaltante += " Recibido en fisico?:No";
                                        htmlHijoFaltante += " </label>";
                                    }
                                    }*/
                                    htmlHijoFaltante += " </div>";

                                    htmlHijoFaltante += " <div class='' >";
                                    if ((permissionEditDocument)) {
                                        /* htmlHijoFaltante += " <a type='button'  class='btn btn-danger btn-sm  elimi' href='../../../documento?opc=Eliminar&id_doc="
                                            + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp()
                                            + "&idtr=" + d.getId_trabajador() + "'><i class='fa fa-trash-o'></i></a>";*/
                                    }

                                    htmlHijoFaltante += " </div>";

                                    htmlHijoFaltante += "  </div>";
                                    htmlHijoFaltante += " <input type='hidden' name='iddoc" + (i + 1)
                                            + "' value='" + d.getId_documentos() + "'>";
                                    htmlHijoFaltante += "   </div>  ";
                                    listDocumentItem.add(htmlHijoFaltante);
                                    id_hijo_faltante = h.getId_datos_hijos_trabajador();
                                }

                                i++;
                            }
                        }
                    } else if (!d.getTi_documento().trim().equals("DNIH")
                            & !d.getTi_documento().trim().equals("DNIC")
                            & !d.getTi_documento().trim().equals("ACMA")
                            & !d.getTi_documento().trim().equals("COFE")
                            & !d.getTi_documento().trim().equals("DOCA")) {
                        String htmlOtherItem = "";
                        htmlOtherItem += "<div class='col-lg-4 col-md-6 col-sm-12 col-xs-12 documentItem'>";
                        htmlOtherItem += " <div class='well well-sm'>";

                        htmlOtherItem += "<div class=''>";
                        htmlOtherItem += "<label >" + d.getNo_documento() + "</label>";
                        htmlOtherItem += "  </div>";

                        htmlOtherItem += " <div class=' caji" + (i + 1) + "'  >";
                        if (d.getId_documento_adjunto() == null & (permissionEditDocument)) {

                            htmlOtherItem += " <input  class='fileDocument' type='file' multiple='true'   ";
                            if (d.getEs_obligatorio().equals("1") & !enterToRegTrabajador) {
                                htmlOtherItem += (" required='required' ");
                            }
                            htmlOtherItem += "name='archivos" + (i + 1) + "' >";

                        } else if (d.getId_documento_adjunto() == null) {
                            htmlOtherItem += " <label class='null'>No Registrado</label>";
                        } else {
                            htmlOtherItem += (doc_.List_files(d.getId_documento_adjunto().trim()));
                        }

                        htmlOtherItem += "</div>";

                        htmlOtherItem += " <div class=''>";
                        if (d.getDe_documento_adjunto() == null & (permissionEditDocument)) {
                            htmlOtherItem += "<input type='text' placeholder='Escribe una descripcin' class='form-control' name='lob_description"
                                    + (i + 1) + "'>";

                        } else if (d.getDe_documento_adjunto() == null) {
                            htmlOtherItem += " <label class='null' >No Registrado</label>";
                        } else {
                            htmlOtherItem += "<label >Descripcin:</label>";
                            htmlOtherItem += "<label style='font-weight: normal;'>"
                                    + d.getDe_documento_adjunto() + "</label>";

                        }
                        htmlOtherItem += "</div>";

                        htmlOtherItem += " <div  class=''  >";
                        if (d.getEs_documento_adjunto() == null & (permissionEditDocument)) {
                            htmlOtherItem += "  <label>Recibido en fisico?:</label> <label class='toggle'><input type='checkbox' value='1'   name='estado"
                                    + (i + 1) + "'  >";
                            htmlOtherItem += " <i data-swchon-text='SI' data-swchoff-text='NO'></i></label>";
                        } else if (d.getEs_documento_adjunto() == null) {

                            htmlOtherItem += "<label class='null'>Recibido en fisico?:No Registrado</label>";
                        } else {
                            htmlOtherItem += " <label>";
                            if (d.getEs_documento_adjunto().trim().equals("1")) {

                                htmlOtherItem += "Recibido en fisico?: Si";

                            } else {

                                htmlOtherItem += "Recibido en fisico?: No";

                            }
                            htmlOtherItem += "  </label>";
                        }

                        htmlOtherItem += "</div>";

                        htmlOtherItem += "<div class=''>";
                        if (d.getEs_documento_adjunto() != null & (permissionEditDocument)) {
                            htmlOtherItem += "<a type='button'  class='btn btn-danger btn-sm  elimi'"
                                    + " href='../../../documento?opc=Eliminar&id_doc="
                                    + d.getId_documento_adjunto() + "&iddgp=" + d.getId_dgp() + "&idtr="
                                    + d.getId_trabajador() + "'><i class='fa fa-trash-o'></i></a>";
                        }
                        htmlOtherItem += " </div>  ";

                        htmlOtherItem += "</div>";
                        html += "  <input type='hidden' name='iddoc" + (i + 1) + "' value='"
                                + d.getId_documentos() + "'>";
                        htmlOtherItem += "  <input type='hidden' name='iddgp' value='" + d.getId_dgp() + "'>";
                        htmlOtherItem += "  <input type='hidden' name='idctr' value='"
                                + request.getParameter("idctr") + "'>";
                        htmlOtherItem += "   <input type='hidden' name='idtr' value='"
                                + request.getParameter("idtr") + "'>";
                        htmlOtherItem += "  </div>  ";
                        listDocumentItem.add(htmlOtherItem);
                    }

                    i++;
                    // id_dgp = d.getId_dgp();

                }
                int countItem = 0;
                System.out.println("tamao de lista:" + listDocumentItem.size());
                for (int s = 0; s < listDocumentItem.size(); s++) {
                    if (!listDocumentItem.get(s).equals("")) {
                        if (countItem == 0) {
                            html += "<div class='row'>";
                        }
                        if (countItem == 1) {
                            //  html += listDocumentItem.get(s);
                        }
                        html += listDocumentItem.get(s);
                        System.out.println("item (" + s + ") :" + listDocumentItem.get(s));
                        if (countItem == 2) {
                            html += "</div>";
                            countItem = -1;
                        }
                        countItem++;
                    }
                }
                html += "<input type='hidden' name='num' value='" + (i + 1) + "'>";

                if (permissionEditDocument) {
                    html += "<input type='hidden' value='Registrar' name='opc'> ";
                }

                html += "</div>";
                html += "<div class='row'>";
                html += "<div class='col-md-12'>";

                html += (enterToDGPProcess)
                        ? "<a class='btn btn-success pull-right btn_continuar_det' href='../../../dgp?iddgp="
                                + dgp + "&idtr=" + idtr
                                + "&opc=rd'>Continuar<i class='fa fa-arrow-circle-right'></i></a>"
                        : "";
                html += (enterToRegTrabajador)
                        ? "<a class='btn btn-success pull-right btn_continuar_det' href='../../../trabajador?idtr="
                                + idtr
                                + "&opc=list_reg_tra'>Continuar<i class='fa fa-arrow-circle-right'></i></a>"
                        : "";
                html += (enterToCasosEspecialesProcess)
                        ? "<a class='btn btn-success pull-right btn_continuar_det' href='../../../contrato?idtr="
                                + idtr
                                + "&opc=Detalle_Contractual'>Continuar<i class='fa fa-arrow-circle-right'></i></a>"
                        : "";

                html += "  <button type='button' class='btn btn-primary btn_reg_doc pull-right' style='display:none'> <i class='fa fa-plus-square'></i>Registrar</button>";

                html += "</div>";
                html += "</div>";
                html += " </form>";
                rpta.put("htmlListDocument", html);

                rpta.put("status", true);
            }
        } else {
            //  String ubicacion = getServletConfig().getServletContext().getRealPath("/") + "Vista/Dgp/Documento/Archivo/";
            String ubicacion = FactoryConnectionDB.url + "Archivo/";
            DiskFileItemFactory f = new DiskFileItemFactory();
            f.setSizeThreshold(1024);
            f.setRepository(new File(ubicacion));
            ServletFileUpload upload = new ServletFileUpload(f);
            ServletRequestContext src = new ServletRequestContext(request);

            List<FileItem> p = upload.parseRequest(src);
            int num_filas = 0;
            String iddgp = null;
            String pr = null;
            String id_ctr = null;
            String id_h = null;
            List<String> list_files = new ArrayList<String>();
            for (FileItem i_n_f : p) {
                if (i_n_f.isFormField()) {

                    String nombre = i_n_f.getFieldName();
                    String valor = i_n_f.getString();

                    num_filas = (nombre.equals("num")) ? Integer.parseInt(valor) : num_filas;
                    if (nombre.equals("iddgp") & iddgp == null) {
                        iddgp = valor;
                    }
                    if (nombre.equals("idtr") & idtr == null) {
                        idtr = valor;
                    }
                    if (nombre.equals("P2") & pr == null) {
                        pr = valor;
                    }

                    if (nombre.equals("idctr") & id_ctr == null) {
                        id_ctr = valor;
                    }

                }
            }

            String iddoc = null;
            String nombre_archivo = null;
            String desc = null;
            String estado = null;
            String archivo = null;
            int num = 0;
            String no_original = null;

            //  String validar_nombre = "";
            // Random rnd = new Random();
            for (int i = 0; i < num_filas; i++) {
                for (FileItem item : p) {
                    if (item.isFormField()) {
                        String nombre = item.getFieldName();
                        String valor = item.getString();
                        iddoc = (nombre.equals("iddoc" + i)) ? valor : iddoc;
                        desc = (nombre.equals("lob_description" + i)) ? valor : desc;
                        estado = (nombre.equals("estado" + i)) ? valor : estado;
                        id_h = (nombre.equals("idh" + i)) ? valor : id_h;
                    } else {
                        String fieldName = item.getFieldName();

                        num++;
                        Calendar fecha = new GregorianCalendar();
                        int day = fecha.get(Calendar.DAY_OF_MONTH);
                        int month = fecha.get(Calendar.MONTH);
                        int year = fecha.get(Calendar.YEAR);
                        int hora = fecha.get(Calendar.HOUR_OF_DAY);
                        int min = fecha.get(Calendar.MINUTE);
                        int sec = fecha.get(Calendar.SECOND);

                        if (fieldName.equals("archivos" + i) & item.getName() != null) {
                            if (!item.getName().equals("")) {
                                no_original = item.getName();
                                String extension = FilenameUtils.getExtension(no_original);
                                nombre_archivo = String.valueOf(year) + String.valueOf(month)
                                        + String.valueOf(day) + String.valueOf(hora) + String.valueOf(min)
                                        + String.valueOf(sec) + "_sysgth." + extension;
                                //Thread thread = new Thread(new Renombrar(item, ubicacion, nombre_archivo));
                                //  thread.start();
                                System.out.println("nombre: " + nombre_archivo);
                                File files = new File(ubicacion, nombre_archivo);
                                item.write(files);

                                archivo = no_original + ":" + nombre_archivo;
                                list_files.add(archivo);
                            }

                        } else {
                            no_original = no_original;
                            nombre_archivo = nombre_archivo;
                        }
                    }
                }
                //  Thread.sleep(100);
                if (nombre_archivo != null) {
                    if (!nombre_archivo.equals("")) {
                        estado = ((estado == null) ? "0" : estado);
                        //out.println(iddoc);
                        String id = d.INSERT_DOCUMENTO_ADJUNTO(null, iddoc, "1", user, null, null, null, null,
                                desc, null, estado, id_ctr);

                        if (iddgp == null) {
                            iddgp = "";
                        }

                        System.out.println("::::iddgp:" + iddgp);
                        d.INSERT_DGP_DOC_ADJ(null, iddgp, id, null, idtr, id_h);
                        for (int t = 0; t < list_files.size(); t++) {
                            String g[] = list_files.get(t).split(":");
                            d.INSERT_ARCHIVO_DOCUMENTO(null, id, g[1], g[0], null);
                        }
                        list_files.clear();
                    }
                }
                no_original = null;
                iddoc = null;
                nombre_archivo = null;
                desc = null;
                estado = null;
                no_original = null;
            }
            rpta.put("status", true);
        }
    } catch (Exception e) {
        //  out.println("Error : " + e.getMessage());
        rpta.put("status", false);
        rpta.put("mensaje", e.getMessage());
    } finally {

        Gson gson = new Gson();
        out.print(gson.toJson(rpta));
        out.flush();
        out.close();
    }
}

From source file:podd.resources.services.TabImportService.java

/**
 * Creates a Tab transfer object from the Restlet Representation
 * @param entity//from  w w  w. j  ava  2  s  . c o m
 * @return
 */
private Tab createTab(Representation entity) {
    Tab tab = new Tab();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0); // always write to disk
    RestletFileUpload upload = new RestletFileUpload(factory);
    try {
        List<FileItem> list = upload.parseRepresentation(entity);
        for (FileItem item : list) {
            if (item.getFieldName().equals(PARAM_TAB) && !item.isFormField()) {
                tab.setTabStream(item.getInputStream());
            }
            if (item.getFieldName().equals(PARAM_ATTACHMENT) && !item.isFormField()) {
                DiskFileItem diskFileItem = (DiskFileItem) item;

                if (_DEBUG) {
                    LOGGER.debug("isInMemory = " + diskFileItem.isInMemory() + " diskFileItem exists = "
                            + diskFileItem.getStoreLocation().exists());
                }

                // If the file is not on disk, force to disk
                File copiedFile = FileUploadHelper.writeToDisk(diskFileItem, authenticatedUser);
                if (_DEBUG) {
                    LOGGER.debug("copiedFile = " + copiedFile);
                }

                if (copiedFile != null)
                    tab.addAttachment(copiedFile.getName(), copiedFile);
            }
        }
    } catch (FileUploadException e) {
        getResponse().setStatus(SERVER_ERROR_INTERNAL);
        final String msg = "Error reading form data. ";
        errorHandler.handleException(GENERAL_MESSAGE_ID, "File Initialisation Error", msg, e);
        auditLogHelper.auditAction(ERROR, authenticatedUser, "Tab import Service: " + msg, e.toString());
    } catch (IOException e) {
        getResponse().setStatus(SERVER_ERROR_INTERNAL);
        final String msg = "Error reading file. ";
        errorHandler.handleException(GENERAL_MESSAGE_ID, "File Initalisation Error", msg, e);
        auditLogHelper.auditAction(ERROR, authenticatedUser, "Tab import Service: " + msg, e.toString());

    }
    return tab;
}

From source file:prodocUI.servlet.AddDocAdv.java

private boolean AddDoc(HttpServletRequest Req) throws PDException, FileUploadException, IOException {
    String FileName = null;//from  www .  j  a  v  a 2s  .c om
    InputStream FileData = null;
    HashMap ListFields = new HashMap();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000000);
    ServletFileUpload upload = new ServletFileUpload(factory);
    boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
    List items = upload.parseRequest(Req);
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField())
            ListFields.put(item.getFieldName(), item.getString());
        else {
            FileName = item.getName();
            FileData = item.getInputStream();
        }
    }
    String Acept = (String) ListFields.get("BOk");
    if (Acept == null || Acept.length() == 0)
        return (false);
    DriverGeneric PDSession = SParent.getSessOPD(Req);
    String DType = (String) ListFields.get(PDDocs.fDOCTYPE);
    PDDocs Doc;
    if (DType == null)
        Doc = new PDDocs(PDSession);
    else
        Doc = new PDDocs(PDSession, DType);
    Record Rec = Doc.getRecSum();
    Rec.initList();
    Attribute Attr = Rec.nextAttr();
    while (Attr != null) {
        if (!List.contains(Attr.getName())) {
            String Val = (String) ListFields.get(Attr.getName());
            if (Attr.getType() == Attribute.tBOOLEAN) {
                if (Val == null)
                    Attr.setValue(false);
                else
                    Attr.setValue(true);
            } else if (Val != null) {
                SParent.FillAttr(Req, Attr, Val, false);
            }
        }
        Attr = Rec.nextAttr();
    }
    Doc.assignValues(Rec);
    Doc.setParentId(getActFolderId(Req));
    String RefFile = (String) ListFields.get(PDDocs.fNAME + "_");
    if (RefFile != null && RefFile.length() != 0) {
        Doc.setFile(RefFile);
    } else {
        Doc.setName(FileName);
        PDMimeType mt = new PDMimeType(PDSession);
        Doc.setMimeType(mt.SolveName(FileName));
        Doc.setStream(FileData);
    }
    Doc.insert();
    return (true);
}

From source file:prodocUI.servlet.ModDocAdv.java

private boolean ModDoc(HttpServletRequest Req) throws PDException, FileUploadException, IOException {
    PDDocs Doc;/*from   w  ww  .j av a  2s . c  o  m*/
    Record Rec;
    String FileName = null;
    InputStream FileData = null;
    HashMap ListFields = new HashMap();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000000);
    ServletFileUpload upload = new ServletFileUpload(factory);
    boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
    if (isMultipart) {
        List items = upload.parseRequest(Req);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                ListFields.put(item.getFieldName(), item.getString());
            else {
                FileName = item.getName();
                FileData = item.getInputStream();
            }
        }
        String Acept = (String) ListFields.get("BOk");
        if (Acept == null || Acept.length() == 0)
            return (false);
        DriverGeneric PDSession = SParent.getSessOPD(Req);
        String DType = (String) ListFields.get(PDDocs.fDOCTYPE);
        Doc = new PDDocs(PDSession);
        Doc.LoadFull(getActDocId(Req));
        Rec = Doc.getRecSum();
        Rec.initList();
        Attribute Attr = Rec.nextAttr();
        while (Attr != null) {
            if (!List.contains(Attr.getName())) {
                String Val = (String) ListFields.get(Attr.getName());
                if (Attr.getType() == Attribute.tBOOLEAN) {
                    if (Val == null)
                        Attr.setValue(false);
                    else
                        Attr.setValue(true);
                } else if (Val != null) {
                    SParent.FillAttr(Req, Attr, Val, false);
                }
            }
            Attr = Rec.nextAttr();
        }
    } else {
        String Acept = Req.getParameter("BOk");
        if (Acept == null || Acept.length() == 0)
            return (false);
        DriverGeneric PDSession = SParent.getSessOPD(Req);
        Doc = new PDDocs(PDSession);
        Doc.LoadFull(getActDocId(Req));
        Rec = Doc.getRecSum();
        Rec.initList();
        Attribute Attr = Rec.nextAttr();
        while (Attr != null) {
            if (!List.contains(Attr.getName())) {
                String Val = Req.getParameter(Attr.getName());
                if (Attr.getType() == Attribute.tBOOLEAN) {
                    if (Val == null)
                        Attr.setValue(false);
                    else
                        Attr.setValue(true);
                } else if (Val != null) {
                    SParent.FillAttr(Req, Attr, Val, false);
                }
            }
            Attr = Rec.nextAttr();
        }
    }
    Doc.assignValues(Rec);
    String RefFile = (String) ListFields.get(PDDocs.fNAME + "_");
    if (RefFile != null && RefFile.length() != 0)
        Doc.setFile(RefFile);
    else {
        if (FileName != null && FileName.length() > 0) {
            PDMimeType mt = new PDMimeType(SParent.getSessOPD(Req));
            Doc.setMimeType(mt.SolveName(FileName));
            Doc.setName(FileName);
            if (FileData != null)
                Doc.setStream(FileData);
        }
    }
    Doc.setParentId(getActFolderId(Req));
    Doc.update();
    return (true);
}

From source file:projectServlet.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;//from   ww  w .  j av a  2s .  c  o m
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    try {
        Map<String, String> map = new HashMap<String, String>();
        ArrayList<String> imgs_str = new ArrayList<String>();
        boolean result = false;
        float price = 0;

        ArrayList<ImageDO> imagesDO = new ArrayList<ImageDO>();
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        String field_name;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            field_name = item.getFieldName();
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();

                String fullFileName = field_name + "_" + System.currentTimeMillis() + "_" + fileName;

                String filePath = uploadFolder + File.separator + fullFileName;
                File uploadedFile = new File(filePath);

                System.out.print("filePath loop: " + filePath);
                if (field_name.equals("projectFile")) {
                    if (fileName == "" || fileName.isEmpty()) {
                        //RequestDispatcher rd = getServletContext().getRequestDispatcher("/PaginaDoDesenvolvedor/uploadprojeto.jsp");
                        PrintWriter out3 = response.getWriter();

                        //rd.include(request, response);

                        response.sendRedirect("./PaginaDoDesenvolvedor/uploadprojeto.jsp?error=nofile");
                        //out3.println("<font color=red>Favor escolher um arquivo.</font>");
                        return;
                    }
                    map.put(field_name, fullFileName);
                    System.out.print("projectFile: " + fullFileName);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                } else if (field_name.equals("image") && (fileName != "" && !fileName.isEmpty())) {
                    ImageDO image = new ImageDO();
                    image.setImagelink(fullFileName);
                    imagesDO.add(image);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            } else {
                System.out.print("var " + item.getFieldName() + ": " + item.getString());
                map.put(item.getFieldName(), item.getString());
            }
        }

        try {
            String price_str = map.get("price");
            if (!utils.MetodosUteis.isEmpty(price_str)) {
                price = Float.valueOf(price_str).floatValue();
            }
            project.projectDO project = new project.projectDO(map.get("name"), map.get("description"),
                    map.get("comments"), price, 0);
            project.versionDO version = new project.versionDO();
            version.setFilepath(map.get("projectFile"));
            System.out.print("filename:" + map.get("projectFile"));
            transaction.UploadProject upProject = new transaction.UploadProject();
            try {
                result = upProject.uploadProject(project, version, imagesDO);
            } catch (Exception e) {
                System.out.print("ERROR! Upload");
                response.sendRedirect("./PaginaDoDesenvolvedor/uploadprojeto.jsp?error=erroruploading");
                //RequestDispatcher rd = getServletContext().getRequestDispatcher("/done.jsp");
                //PrintWriter out = response.getWriter();
                //out.println("<font color=red>Erro ao subir pr0ojeto.</font>");
                //rd.include(request, response);

                return;
            }
        } catch (NumberFormatException e) {
            System.out.print("ERROR! Number Format");
        }

        // displays done.jsp page after upload finished

        PrintWriter out2 = response.getWriter();
        RequestDispatcher rd;
        if (result) {
            response.sendRedirect("./done.jsp");
            out2.println(
                    "<h3>Seu arquivo projeto foi enviado com sucesso para aprovao dos moderadores!</h3>");
        } else {
            //rd = getServletContext().getRequestDispatcher("/PaginaDoDesenvolvedor/uploadprojeto.jsp");
            //out2.println("<font color=red>Favor preencher os campos corretamente.</font>");
            response.sendRedirect("./PaginaDoDesenvolvedor/uploadprojeto.jsp?error=wrongfields");
        }
        //rd.include(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:rva.administrator.ASRepFileUpload.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;/*from   w w  w .jav  a  2s  .c  om*/
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                String upfile = filePath + fileName;
                ReadExcels.readExcels(upfile);
                out.println("<html>");
                out.println("<body>");
                HttpSession session = request.getSession();
                response.sendRedirect("fileuploading.jsp");
                session.setAttribute("filepathas", upfile);
                // RequestDispatcher rd=request.getRequestDispatcher("fileuploading.jsp");
                // rd.include(request, response);
                //out.println("Uploaded Filename:" +upfile+ "<br>");
                out.println("</body>");
                out.println("</html>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:rva.administrator.DTTRepFileUpload.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;//from   ww  w .  j a v a  2 s . c om
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                String upfile = filePath + fileName;

                new ReadDttReport().readDTTReport(upfile);
                out.println("<html>");
                out.println("<body>");
                HttpSession session = request.getSession();
                response.sendRedirect("dttreportfileupload.jsp");
                session.setAttribute("filepathdtt", upfile);
                // RequestDispatcher rd=request.getRequestDispatcher("fileuploading.jsp");
                // rd.include(request, response);
                //out.println("Uploaded Filename:" +upfile+ "<br>");
                out.println("</body>");
                out.println("</html>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:rva.taskinsert.RetelLog.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    HttpSession session = request.getSession();
    LogBean lb = (LogBean) session.getAttribute("currloginsession");
    String performdate = (String) session.getAttribute("logindate");
    String empname = lb.getAuditorname();
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");

    java.io.PrintWriter out = response.getWriter();
    // out.println(isMultipart);
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;// w  w w .j av  a 2  s  .co  m
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.

        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();

            if (!fi.isFormField())

            {

                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file

                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                String upfile = filePath + fileName;
                RetFileRead.readExcels(upfile, empname, performdate);
                out.println("<html>");
                out.println("<body>");
                //HttpSession session=request.getSession();
                response.sendRedirect("reteltaskinsert.jsp");
                session.setAttribute("filepathret", upfile);
                // RequestDispatcher rd=request.getRequestDispatcher("fileuploading.jsp");
                // rd.include(request, response);
                //out.println("Uploaded Filename:" +upfile+ "<br>");
                out.println("</body>");
                out.println("</html>");
            }
        }
        out.println("File3");
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:sbml.test.UploadUnzipTest.java

/**
 * Interface function invoked by uploadresults.jsp.
 *///from ww  w.  j a v  a 2  s.  c o  m
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Store these because they're unique per session & we need them often.

    httpRequest = request;
    httpResponse = response;

    OnlineSTS.logInvocation(request);

    // An upload from uploadresults.jsp is supposed to be a multipart
    // request.  If that's not what we got here, toss an error.

    if (!ServletFileUpload.isMultipartContent(request)) {
        propagateError(SERVER_ERROR, "Didn't get multipart content.");
        return;
    }

    // Create the user's upload directory.

    uploadDir = createUploadDir();

    // Set up objects that will extract the user's upload.

    refCasesDir = getReferenceCasesDir();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(uploadDir);
    factory.setSizeThreshold(1 * 1024 * 1024); // In bytes.

    ServletFileUpload reqHandler = new ServletFileUpload(factory);

    // Result files for the current 927 test suite cases adds up to ~1
    // MB.  Adding some room for growth, if we get something > 10 MB,
    // something's wrong.

    reqHandler.setSizeMax(10 * 1024 * 1024);

    // Unzip the user's uploaded archive.  This returns an ordered list
    // of the CSV file names extracted as a result.

    TreeSet<UserTestCase> userCases = unzipUserArchive(reqHandler);

    // If we managed to extract data files from the user's upload, test
    // them, get the results, & dispatch them to the results JSP page.

    if (userCases != null)
        try {
            TreeMap<Integer, UserTestResult> results = performAnalysis(userCases);
            OnlineSTS.logInfo(request, "Returning results to user.");
            httpRequest.setAttribute("testResults", results);
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(RESULTS_PAGE);
            dispatcher.forward(httpRequest, httpResponse);

            /* In the future, if rewrite things to use a redirect:
                    
            String where = OnlineSTS.getServiceRootURL(request) + RESULTS_PAGE;
            response.setStatus(307);
            response.setHeader("Location", where);
            response.sendRedirect(where);
            */
        } catch (Exception e) {
            e.printStackTrace();
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
}