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

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

Introduction

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

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

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 {/*from w  w  w .  j a v  a2  s  . c  om*/
        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  w  w  .j  a  v a2  s.  c  o  m
    }
    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: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;/* w  ww .  j  a v a2 s  . 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 .  j  a  va2s  .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;
                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;/* ww w.j a v a 2s .  c  o  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;

                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;//from  w  w w. jav a  2s  .com
    }

    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 .ja  va  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);
        }
}

From source file:se.tillvaxtverket.ttsigvalws.ttwebservice.TTSigValServlet.java

private void processFileUpload(HttpServletRequest request, HttpServletResponse response) {
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;/*from   ww w  . jav a 2 s  .com*/
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    File storageDir = new File(baseModel.getConf().getDataDirectory() + "/uploads");
    if (!storageDir.exists()) {
        storageDir.mkdirs();
    }
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                uploadedFile = new File(storageDir, fileName);
                try {
                    item.write(uploadedFile);
                    uploaded = true;
                } catch (Exception ex) {
                }
            }

        }
        if (uploaded && paraMap.containsKey("policy")) {
            String verifyResult = verifySignature(request, paraMap.get("policy"), uploadedFile.getName(),
                    uploadedFile.getAbsolutePath(), null);
            sendValidationReport(verifyResult, response);
            return;
        }
        if (paraMap.containsKey("policy") && paraMap.containsKey("fileName")) {
            File sigFile = new File(getFullSigFileName(paraMap.get("fileName")));
            String verifyResult = verifySignature(request, paraMap.get("policy"), sigFile.getName(),
                    sigFile.getAbsolutePath(), null);
            sendValidationReport(verifyResult, response);
            return;
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    nullResponse(response);
}

From source file:servlet.BPMNAnimationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    PrintWriter out = null;//from   w  w  w .j a  v a 2s .  c o m
    List<Log> logs = new ArrayList<>();
    Set<XLog> xlogs = new HashSet<>();
    //Set<XLog> optimizedLogs = new HashSet<>();
    String jsonData = "";
    Definitions bpmnDefinition = null;

    if (!ServletFileUpload.isMultipartContent(req)) {
        res.getWriter().println("Does not support!");
        // if not, we stop here
        return;
    }

    /*
     * ------------------------------------------
     * Import event log files
     * logs variable contains list of imported logs
     * ------------------------------------------
     */
    // configures some settings

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {

        // parses the request's content to extract file data
        List<FileItem> formItems = upload.parseRequest(req);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
                LOGGER.info("Finish writing uploaded file to temp dir: " + filePath);

                LOGGER.info("Start importing file: " + filePath);
                item.getInputStream();
                OpenLogFilePlugin logImporter = new OpenLogFilePlugin();
                XLog xlog = (XLog) logImporter.importFile(storeFile);

                // color field must follow the log file
                item = (FileItem) iter.next();
                assert item.isFormField();
                assert "color".equals(item.getFieldName());
                LOGGER.info("Log color: " + item.getString());
                String color = item.getString();

                // Record the log
                Log log = new Log();
                log.fileName = fileName;
                log.xlog = xlog;
                log.color = item.getString();
                logs.add(log);
                xlogs.add(xlog);
            } else {
                if (item.getFieldName().equals("json")) {
                    jsonData = item.getString();
                }
            }
        }

        /*
        * ------------------------------------------
        * Convert JSON map to BPMN objects
        * ------------------------------------------
        */
        LOGGER.info("Then, convert JSON to BPMN map objects");
        if (!jsonData.equals("")) {
            bpmnDefinition = this.getBPMNfromJson(jsonData);
            LOGGER.info("BPMN Diagram Definition" + bpmnDefinition.toString());
        } else {
            LOGGER.info("JSON data sent to server is empty");
        }

        /*
        * ------------------------------------------
        * Optimize logs and process model
        * ------------------------------------------
        */
        Optimizer optimizer = new Optimizer();
        for (Log log : logs) {
            //optimizedLogs.add(optimizer.optimizeLog(log.xlog));
            log.xlog = optimizer.optimizeLog(log.xlog);
        }
        bpmnDefinition = optimizer.optimizeProcessModel(bpmnDefinition);

        /*
        * ------------------------------------------
        * Check BPMN diagram validity and replay log
        * ------------------------------------------
        */

        //Reading backtracking properties for testing
        String propertyFile = "/editor/animation/properties.xml";
        InputStream is = getServletContext().getResourceAsStream(propertyFile);
        Properties props = new Properties();
        props.loadFromXML(is);
        ReplayParams params = new ReplayParams();
        params.setMaxCost(Double.valueOf(props.getProperty("MaxCost")).doubleValue());
        params.setMaxDepth(Integer.valueOf(props.getProperty("MaxDepth")).intValue());
        params.setMinMatchPercent(Double.valueOf(props.getProperty("MinMatchPercent")).doubleValue());
        params.setMaxMatchPercent(Double.valueOf(props.getProperty("MaxMatchPercent")).doubleValue());
        params.setMaxConsecutiveUnmatch(Integer.valueOf(props.getProperty("MaxConsecutiveUnmatch")).intValue());
        params.setActivityMatchCost(Double.valueOf(props.getProperty("ActivityMatchCost")).doubleValue());
        params.setActivitySkipCost(Double.valueOf(props.getProperty("ActivitySkipCost")).doubleValue());
        params.setEventSkipCost(Double.valueOf(props.getProperty("EventSkipCost")).doubleValue());
        params.setNonActivityMoveCost(Double.valueOf(props.getProperty("NonActivityMoveCost")).doubleValue());
        params.setTraceChunkSize(Integer.valueOf(props.getProperty("TraceChunkSize")).intValue());
        params.setMaxNumberOfNodesVisited(
                Integer.valueOf(props.getProperty("MaxNumberOfNodesVisited")).intValue());
        params.setMaxActivitySkipPercent(
                Double.valueOf(props.getProperty("MaxActivitySkipPercent")).doubleValue());
        params.setMaxNodeDistance(Integer.valueOf(props.getProperty("MaxNodeDistance")).intValue());
        params.setTimelineSlots(Integer.valueOf(props.getProperty("TimelineSlots")).intValue());
        params.setTotalEngineSeconds(Integer.valueOf(props.getProperty("TotalEngineSeconds")).intValue());
        params.setProgressCircleBarRadius(
                Integer.valueOf(props.getProperty("ProgressCircleBarRadius")).intValue());
        params.setSequenceTokenDiffThreshold(
                Integer.valueOf(props.getProperty("SequenceTokenDiffThreshold")).intValue());
        params.setMaxTimePerTrace(Long.valueOf(props.getProperty("MaxTimePerTrace")).longValue());
        params.setMaxTimeShortestPathExploration(
                Long.valueOf(props.getProperty("MaxTimeShortestPathExploration")).longValue());
        params.setExactTraceFitnessCalculation(props.getProperty("ExactTraceFitnessCalculation"));
        params.setBacktrackingDebug(props.getProperty("BacktrackingDebug"));
        params.setExploreShortestPathDebug(props.getProperty("ExploreShortestPathDebug"));
        params.setCheckViciousCycle(props.getProperty("CheckViciousCycle"));
        params.setStartEventToFirstEventDuration(
                Integer.valueOf(props.getProperty("StartEventToFirstEventDuration")).intValue());
        params.setLastEventToEndEventDuration(
                Integer.valueOf(props.getProperty("LastEventToEndEventDuration")).intValue());

        Replayer replayer = new Replayer(bpmnDefinition, params);
        ArrayList<AnimationLog> replayedLogs = new ArrayList();
        if (replayer.isValidProcess()) {
            LOGGER.info("Process " + bpmnDefinition.getId() + " is valid");
            EncodeTraces.getEncodeTraces().read(xlogs); //build a mapping from traceId to charstream
            for (Log log : logs) {

                AnimationLog animationLog = replayer.replay(log.xlog, log.color);
                //AnimationLog animationLog = replayer.replayWithMultiThreading(log.xlog, log.color);
                if (animationLog != null && !animationLog.isEmpty()) {
                    replayedLogs.add(animationLog);
                }
            }

        } else {
            LOGGER.info(replayer.getProcessCheckingMsg());
        }

        /*
        * ------------------------------------------
        * Return Json animation
        * ------------------------------------------
        */
        LOGGER.info("Start sending back JSON animation script to browser");
        if (replayedLogs.size() > 0) {
            out = res.getWriter();
            res.setContentType("text/html"); // Ext2JS's file upload requires this rather than "application/json"
            res.setStatus(200);

            //To be replaced
            AnimationJSONBuilder jsonBuilder = new AnimationJSONBuilder(replayedLogs, replayer, params);
            JSONObject json = jsonBuilder.parseLogCollection();
            json.put("success", true); // Ext2JS's file upload requires this flag
            String string = json.toString();
            //LOGGER.info(string);
            jsonBuilder.clear();

            out.write(string);
        } else {
            /*
            out = res.getWriter();
            res.setContentType("text/html");
            res.setStatus(204);
            out.write("");
            */
            String json = "{success:false, errors: {errormsg: '" + "No logs can be played." + "'}}";
            res.setContentType("text/html; charset=UTF-8");
            res.getWriter().print(json);
        }

    } catch (Exception e) {
        try {
            LOGGER.severe(e.toString());
            /*
            res.setStatus(500);
            res.setContentType("text/plain");
            PrintWriter writer = new PrintWriter(out);
            writer.println("Failed to generate animation JSON script " + e);
            e.printStackTrace(writer);
            e.printStackTrace();
            res.getWriter().write(e.toString());
            */
            String json = "{success:false, errors: {errormsg: '" + e.getMessage() + "'}}";
            res.setContentType("text/html; charset=UTF-8");
            res.getWriter().print(json);
        } catch (Exception el) {
            System.err.println("Original exception was:");
            e.printStackTrace();
            System.err.println("Exception in exception handler was:");
            el.printStackTrace();
        }
    }

}

From source file:servlet.PreProcessServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  www  . j  a v a 2 s .  c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    uploadRootPath = getServletContext().getInitParameter("file-upload");
    File upload = new File(uploadRootPath);
    if (upload.exists()) {
        deleteFolderContent(upload);
    }
    createDirectoryIfNotExisting(uploadRootPath);
    String programRootPath = getServletContext().getInitParameter("program-root-path");
    boolean isGeneral = false;
    String copyrightStoplist = "";
    String customizedPackageList = "";
    String projectName = "";
    int topicCount = -1;

    String inputRootFilePath = uploadRootPath;
    String outputFilePath = programRootPath + "preprocessOutput/PreProcessTool";
    File outputFile = new File(outputFilePath);
    if (outputFile.exists()) {
        deleteFolderContent(outputFile);
    }

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");

        out.println("<html lang=\"en\">");
        out.println("<head>" + "<meta charset=\"utf-8\">"
                + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
                + "<meta name=\"description\" content=\"\">" + "<meta name=\"author\" content=\"\">"
                + "<link rel=\"icon\" href=\"./image/analysis.jpg\">" + "<title>Programmer Assistor</title>"
                + "<link href=\"./css/bootstrap.min.css\" rel=\"stylesheet\">"
                + "<script src=\"./js/ie-emulation-modes-warning.js\">"
                + "</script><!-- Custom styles for this template -->"
                + "<link href=\"./css/list.css\" rel=\"stylesheet\">" + "</head>");
        out.println("<body>" + "<div class=\"navbar-wrapper\">" + "<div class=\"container\">"
                + "<nav class=\"navbar navbar-inverse navbar-static-top\" role=\"navigation\">"
                + "<div class=\"container\">" + "<div class=\"navbar-header\">"
                + "<a class=\"navbar-brand\" href=\"home.html\">Programmer Assistor</a>" + "</div>"
                + "<div id=\"navbar\" class=\"navbar-collapse collapse\">" + "<ul class=\"nav navbar-nav\">"
                + "<li>" + "<a href=\"home.html\">Home </a>" + "</li>" + "<li>"
                + "<a href=\"help.html\">Help </a>" + "</li>" + "<li>" + "<a href=\"show.html\">Show </a>"
                + "</li>" + "<li>" + "<a href=\"search.html\">Search </a>" + "</li>" + "</ul>" + "</div>"
                + "</div>" + "</nav>" + "</div>" + "</div>");
        out.println("<div class=\"container marketing\">");
        out.println("<div class=\"row featurette files\" id=\"fileList\">");
        out.println("<h2>1. Preprocessing </h2>");
        out.println("<h3>Preprocessed Data Directory: </h3>");
        out.println("<p>");
        out.println(programRootPath + "preprocessOutput/PreProcessTool");
        out.println("</p>");
        out.println("<h3>Uploaded Files: </h3>");

        isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            out.println("<p>the request isn't multipart</p>");
            return;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(programRootPath, "temp"));

        ServletFileUpload uploadProcess = new ServletFileUpload(factory);
        uploadProcess.setSizeMax(maxFileSize);

        try {
            List fileItems = uploadProcess.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    file = new File(inputRootFilePath + fileName.replace('/', '-'));//replace all / to -
                    fi.write(file);

                    out.println("<p>");
                    out.println(fileName);
                    out.println("</p>");
                } else {
                    String fieldName = fi.getFieldName();
                    String fieldValue = fi.getString();
                    if (fieldName.equals("general") && fieldValue.equals("on")) {
                        isGeneral = true;
                    } else if (fieldName.equals("project_type")) {
                        if (fieldValue.equals("Drawing")) {
                            libraryTypeCondition.remove("Drawing");
                            libraryTypeCondition.put("Drawing", true);
                        } else if (fieldValue.equals("Modeling")) {
                            libraryTypeCondition.remove("Modeling");
                            libraryTypeCondition.put("Modeling", true);
                        }
                    } else if (fieldName.equals("customizePackageInfoContent")) {
                        String customizePackageInfoContent = fieldValue;
                        customizedPackageList = customizePackageInfoContent.toLowerCase()
                                .replaceAll("\\*|\n|[0-9]|,|;|`|'|\"", "");
                        customizedPackageList = customizedPackageList.replaceAll("\\(|\\)|-|//|:|~|/|\\.", " ");

                    } else if (fieldName.equals("copyrightInfoContent")) {
                        String copyrightInfoContent = fieldValue;
                        copyrightInfoContent = copyrightInfoContent.replaceAll(".java", "java");
                        copyrightStoplist = copyrightInfoContent.toLowerCase()
                                .replaceAll("\\*|\n|[0-9]|,|;|`|'|\"", "");
                        copyrightStoplist = copyrightStoplist.replaceAll("\\(|\\)|-|//|:|~|/|\\.", " ");

                    } else if (fieldName.equals("projectNameContent")) {
                        projectName = fieldValue;
                    } else if (fieldName.equals("topicCountContent")) {
                        topicCount = Integer.parseInt(fieldValue);
                    }
                }
            }

            //                out.println("<p>"+ copyrightStoplist.toString() +"</p>");

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block  
            out.println("The size of files is too much, please upload files less than 50MB");
            e.printStackTrace();
        } catch (Exception ex) {
            out.println(ex);

        }

        PreProcessTool preProcessTool = new PreProcessTool(inputRootFilePath, outputFilePath, isGeneral,
                libraryTypeCondition, copyrightStoplist, customizedPackageList);
        preProcessTool.preProcess();
        out.println("<h3 id = \"success\" class=\"fileHead\"> Successful Uploading and preprocessing!</h3>");

        //topic modeling
        out.println("<p></p>");
        out.println("<h2>2. Topic Modeling: </h2>");
        out.println("<p>The project name: ");
        out.println(projectName);
        out.println("</p>");
        out.println("<p> The number of topics: ");
        out.println(topicCount);
        out.println("</p>");
        out.println("<h3 id=\"topModelingLogHeader\">Start Topic Modeling: </h3>");
        out.println("<script>" + "window.wtx = window.setInterval(function () {"
                + "var div = document.getElementById('topModelingLog'); " + "div.scrollTop = div.scrollHeight; "
                + "div.scrollIntoView(true); " + "}, 100);" + "</script>");
        out.println("<div id=\"topModelingLog\" style=\"height: 300px; overflow:scroll;\">");
        Executor executor = new Executor(projectName, topicCount, new ProcessPrinter(out::println));
        executor.run();
        out.println("</div>");
        out.println("<script>window.clearInterval(window.wtx);</script>");

        //prepare for search
        File compositeFile = new File(programRootPath + "showFile/composition.txt");
        String top3DocumentsFilePath = programRootPath + "showFile/top3Documents.txt";
        Map<String, String> top3Documents = new HashMap<>();
        Map<Integer, String[]> top3DocAndPer = new HashMap<>();

        int totalFileNo = 0;

        try (InputStream inComposite = new FileInputStream(compositeFile.getPath());
                BufferedReader readerComposite = new BufferedReader(new InputStreamReader(inComposite))) {

            String compositeLine = "";
            while ((compositeLine = readerComposite.readLine()) != null) {
                totalFileNo++;
            }
        }

        try (InputStream inComposite = new FileInputStream(compositeFile.getPath());
                BufferedReader readerComposite = new BufferedReader(new InputStreamReader(inComposite))) {

            String compositeLine = "";
            Double[][] topicDocMatrix = new Double[topicCount][totalFileNo];
            String[] fileNameList = new String[totalFileNo];
            int fileNo = 0;
            while ((compositeLine = readerComposite.readLine()) != null) {
                String[] linePart = compositeLine.split("\t| ");
                String[] nameParts = linePart[1].split("/");
                String textName = nameParts[nameParts.length - 1];
                int lastIndexOfStrigula = textName.lastIndexOf('-');
                if (lastIndexOfStrigula >= 0) {
                    String fileName = textName.substring(0, lastIndexOfStrigula);
                    fileNameList[fileNo] = fileName;
                }

                for (int i = 2; i < linePart.length; i++) {
                    topicDocMatrix[i - 2][fileNo] = Double.parseDouble(linePart[i]);
                }

                fileNo++;
            }

            //find top3 document for each topic
            for (int i = 0; i < topicDocMatrix.length; i++) {
                double max1 = 0;
                String file1 = "";
                double max2 = 0;
                String file2 = "";
                double max3 = 0;
                String file3 = "";
                for (int j = 0; j < topicDocMatrix[i].length; j++) {
                    if (topicDocMatrix[i][j] > max1) {
                        max3 = max2;
                        max2 = max1;
                        max1 = topicDocMatrix[i][j];
                        file1 = fileNameList[j];
                    } else if (topicDocMatrix[i][j] > max2) {
                        max3 = max2;
                        max2 = topicDocMatrix[i][j];
                        file2 = fileNameList[j];
                    } else if (topicDocMatrix[i][j] > max3) {
                        max3 = topicDocMatrix[i][j];
                        file3 = fileNameList[j];
                    }
                }
                String[] docAndPerList = new String[3];
                docAndPerList[0] = file1 + "\t" + max1;
                docAndPerList[1] = file2 + "\t" + max2;
                docAndPerList[2] = file3 + "\t" + max3;
                top3DocAndPer.put(i, docAndPerList);
            }

        }

        File top3DocumentsFile = new File(top3DocumentsFilePath);
        if (top3DocumentsFile.createNewFile()) {
            System.out.println("Create successful: " + top3DocumentsFile.getName());
        }
        writeMapIntStrAToFile(top3DocumentsFile, top3DocAndPer);

        out.println("<h3 id = \"success\" class=\"fileHead\">Successful Topic Modeling!</h3>");
        out.println(
                "<h2 id = \"success\" class=\"fileHead\">Now, you can start using the \"Show\" function and the \"Search\" function.</h2>");

        out.println("</div>");
        out.println("<hr class=\"featurette-divider\">");
        out.println("<footer>" + "<p class=\"pull-right\">" + "<a href=\"#\">Back to top</a>" + "</p>"
                + "<p>2017 @Tianxia, Wang</p>" + "</footer>");
        out.println("</div>");
        out.println("<script src=\"./js/jquery.min.js\"></script>");
        out.println("<script src=\"./js/bootstrap.min.js\"></script>");
        out.println("<script src=\"./js/docs.min.js\"></script>");
        out.println("<script src=\"./js/ie10-viewport-bug-workaround.js\"></script>");
        out.println("<script src=\"./js/home.js\"></script>");
        out.println("</body>");
        out.println("</html>");

    }
}