List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *//*from ww w . j a v a 2 s . co m*/ @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:controlador.CPersona.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* www. j a v a 2 s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); //request.setCharacterEncoding("charset=utf-8"); response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); Persona persona = null; FormacionAcademica academica = null; ExperienciaLaboral experienciaLaboral = null; int PERSONA_personaId; PrintWriter out = response.getWriter(); int opc = Integer.parseInt(request.getParameter("OPC")); switch (opc) { case Constans.LISTARPERSONA: ArrayList<Persona> personas = interPersona .listarPersona(Integer.parseInt(request.getParameter("IDPERSONA"))); String jsonPersona = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(personas); out.println(jsonPersona); break; case Constans.ACTUALIZARPERSONA://This is for save update int id = Integer.parseInt(request.getParameter("ID")); String nombres = request.getParameter("NOMBRES"); String apPaterno = request.getParameter("PATERNO"); String apMaterno = request.getParameter("MATERNO"); String direccion = request.getParameter("DIRECCION"); String celular = request.getParameter("CELULAR"); String correo = request.getParameter("CORREO"); String dni = request.getParameter("DNI"); String fecha = request.getParameter("FECHAN"); String civil = request.getParameter("CIVIL"); String nacionalidad = request.getParameter("NACIONALIDAD"); int idregimen = Integer.parseInt(request.getParameter("IDREGIMEN")); String lugarNacimiento = request.getParameter("LUGAR"); String url = request.getParameter("URL"); persona = new Persona(id, nombres, apPaterno, apMaterno, direccion, celular, correo, dni, url, civil, nacionalidad, fecha, "", idregimen, lugarNacimiento, ""); int actualizo = interPersona.actualizarPersona(persona); out.println(actualizo); break; case Constans.CREARPERSONA: String dniP = request.getParameter("DNI"); int inserto = interPersona.crearPorDni(dniP); out.println(inserto); break; case Constans.CREARFORMACIONACADEMICA: String especialidad = request.getParameter("ESPECIALIDAD"); String fecha_concluye = request.getParameter("FECHA"); int nivelFormacion = Integer.parseInt(request.getParameter("NIVEL")); int idPersona = Integer.parseInt(request.getParameter("IDPERSONA")); int estadoConcluyo = Integer.parseInt(request.getParameter("ESTADO")); String nombreIns = request.getParameter("NOMBRE"); academica = new FormacionAcademica(0, especialidad, fecha_concluye, 1, estadoConcluyo, nivelFormacion, idPersona, "", nombreIns); int es = interPersona.agregarFormacionAcademica(academica); out.println(es); break; case Constans.LISTARFORMACIONACADEMICA: int ids = Integer.parseInt(request.getParameter("ID")); ArrayList<FormacionAcademica> academ = interPersona.listarFormacionAcademica(ids); String jsonStringl = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(academ); out.println(jsonStringl); break; case Constans.ELIMINARFORMACIONACADEMICA: int idFormacion = Integer.parseInt(request.getParameter("IDFORMACION")); int estadoEl = interPersona.eliminarFormacion(idFormacion); out.println(estadoEl); break; case Constans.LISTARCOMBONIVELFORMACION: ArrayList<NivelFormacion> nivelFormacions = interPersona.listarNivelesFormacion(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(nivelFormacions); out.println(json); break; case Constans.AGREGAREXPLABORAL: String dependencia = request.getParameter("DEPENDENCIA"); String cargo = request.getParameter("CARGO"); int tipo = Integer.parseInt(request.getParameter("TIPO")); String annoInicio = request.getParameter("AINICIO"); String annoFin = request.getParameter("AFIN"); String lugar = request.getParameter("LUGAR"); PERSONA_personaId = Integer.parseInt(request.getParameter("IDPERSONA")); experienciaLaboral = new ExperienciaLaboral(0, dependencia, cargo, annoInicio, annoFin, lugar, tipo, "", PERSONA_personaId, ""); int agregar = interPersona.agregarExperienciaLaboral(experienciaLaboral); out.println(agregar); break; case Constans.LISTARCOMBOREXPLABORAL: String tipoDes = request.getParameter("TIPODESCRIPCION"); ArrayList<Tipos> arrayListipos = interPersona.listComboTipos(tipoDes); String jsonTipos = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayListipos); out.println(jsonTipos); break; case Constans.LISTAREXPROFESIONAL: int idPers = Integer.parseInt(request.getParameter("IDPERSONA")); ArrayList<ExperienciaLaboral> experienciaLaborals = interPersona.lisExperienciaLaboral(idPers); String jsonExpP = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(experienciaLaborals); out.println(jsonExpP); break; case Constans.ELIMINAREXPROFESIONAL: int idExpP = Integer.parseInt(request.getParameter("IDEXPROFE")); int estDelExpP = interPersona.eliminarExpLaboral(idExpP); out.println(estDelExpP); break; case Constans.LISTARCOMBOCATEGORIA: String tipoCat = request.getParameter("TIPODESCRIPCION"); ArrayList<Categoria> arrayListCat = interPersona.listarComboCategoria(tipoCat); String jsonCat = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayListCat); out.println(jsonCat); break; case Constans.AGREGARCATEGORIA: String institucion = request.getParameter("INSTITUCION"); String categoria = request.getParameter("CATEDRA"); int catDocente = Integer.parseInt(request.getParameter("CATDOCENTE")); String fechaIni = request.getParameter("DINICIO"); String fechaFin = request.getParameter("DFIN"); int idPer = Integer.parseInt(request.getParameter("PERSONA")); CategoriaDocente categoriaDocente = new CategoriaDocente(0, institucion, categoria, categoria, catDocente, fechaIni, fechaFin, "", idPer); int insCat = interPersona.agregarCategoria(categoriaDocente); out.println(insCat); break; case Constans.LISTARCATEGORIADOCENTE: int idPerCD = Integer.parseInt(request.getParameter("IDPERSONA")); ArrayList<CategoriaDocente> categoriaDocentes = interPersona.arrayListCategoriaDocente(idPerCD); String jsonCatDocente = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(categoriaDocentes); out.println(jsonCatDocente); break; case Constans.ELIMINARCATEGORIADOCENTE: int idCatDoc = Integer.parseInt(request.getParameter("IDCATDOC")); int estidCatDoc = interPersona.eliminarCatDocente(idCatDoc); out.println(estidCatDoc); break; case Constans.AGREGAREGIMENDOCENTE: String dedicacion = request.getParameter("DEDICACION"); String tCompleto = request.getParameter("TCOMPLETO"); String tParcial = request.getParameter("TPARCIAL"); String pasantia = request.getParameter("PASANTIA"); String practicante = request.getParameter("PRACTICANTE"); int idPerReg = Integer.parseInt(request.getParameter("IDPERSONA")); RegimenDocente regimenDocente = new RegimenDocente(0, dedicacion, tCompleto, tParcial, pasantia, practicante, 1, idPerReg); int insRD = interPersona.agregarRegimen(regimenDocente); out.println(insRD); break; case Constans.LISTAREGIMENDOCENTE: int idRD = Integer.parseInt(request.getParameter("IDPERSONA")); ArrayList<RegimenDocente> regimenDocentes = interPersona.listaRegimenDocente(idRD); String jsonRegDocente = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(regimenDocentes); out.println(jsonRegDocente); break; case Constans.ELIMINAREGIMENDOCENTE: int idRDE = Integer.parseInt(request.getParameter("IDREGDOC")); int delRD = interPersona.eliminarRegimenDocente(idRDE); out.println(delRD); break; case Constans.AGREGAREXPERIENCIA: String instiEdu = request.getParameter("INSTITUCION"); String catedraEdu = request.getParameter("CATEDRA"); int categoriaId = Integer.parseInt(request.getParameter("CATEGORIA")); int regimenId = Integer.parseInt(request.getParameter("REGIMENPEN")); String fechInicio = request.getParameter("FECHAINICIO"); String fechFin = request.getParameter("FECHAFIN"); String lugarEdu = request.getParameter("LUGAR"); int idPersEdu = Integer.parseInt(request.getParameter("IDPERSONA")); String resolucion = request.getParameter("RESOLUCION"); String funcion = request.getParameter("FUNCION"); int tipoExp = Integer.parseInt(request.getParameter("TIPO")); int idRegimenLaboral = Integer.parseInt(request.getParameter("REGIMENLABORAL")); int totalDiaz = 8; Experiencia experiencia = new Experiencia(0, catedraEdu, fechInicio, fechFin, "", lugarEdu, instiEdu, 1, resolucion, tipoExp, categoriaId, "", regimenId, "", idPersEdu, funcion, idRegimenLaboral, ""); int isExperiencia = interPersona.agregarExperiencia(experiencia); out.println(isExperiencia); break; case Constans.LISTAREXPERIENCIA: int idP = Integer.parseInt(request.getParameter("IDPERSONA")); int idTipoExp = Integer.parseInt(request.getParameter("TIPOEXPE")); ArrayList<Experiencia> experiencias = interPersona.listarExperiencia(idP, idTipoExp); String jsonExpDocUni = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(experiencias); out.println(jsonExpDocUni); break; case Constans.ELIMINAREXPERIENCIA: int idElExp = Integer.parseInt(request.getParameter("IDEXP")); int delIdExp = interPersona.eliminarExperiencia(idElExp); out.println(delIdExp); break; case Constans.AGREGARIDIOMA: String idiomaID = request.getParameter("IDIOMA"); int nivelID = Integer.parseInt(request.getParameter("NIVEL")); int dominioID = Integer.parseInt(request.getParameter("DOMINIO")); String institucionID = request.getParameter("INSTITUCION"); String anno = request.getParameter("ANNO"); int idPersonaID = Integer.parseInt(request.getParameter("IDPERSONA")); Idioma idioma = new Idioma(0, idiomaID, institucionID, anno, nivelID, "", dominioID, "", 1, idPersonaID); int insID = interPersona.agregarIdioma(idioma); out.println(insID); break; case Constans.LISTARIDIOMA: int idPID = Integer.parseInt(request.getParameter("IDPERSONA")); ArrayList<Idioma> idiomas = interPersona.listarIdioma(idPID); String jsonIdioma = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(idiomas); out.println(jsonIdioma); break; case Constans.ELIMINARIDIOMA: int idIdioma = Integer.parseInt(request.getParameter("ID")); int insIDa = interPersona.eliminarIdioma(idIdioma); out.println(insIDa); break; case Constans.AGREGARTECNOLOGIA: Tecnologia tecnologia = new Tecnologia(0, request.getParameter("TECNOLOGIA"), Integer.parseInt(request.getParameter("DOMINIO")), Integer.parseInt(request.getParameter("NIVEL")), 1, Integer.parseInt(request.getParameter("IDPERSONA")), "", ""); int insTec = interPersona.agregarTecnologia(tecnologia); out.println(insTec); break; case Constans.LISTARTECNOLOGIA: ArrayList<Tecnologia> tecnologias = interPersona .listarTecnologia(Integer.parseInt(request.getParameter("IDPERSONA"))); String jsonTec = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tecnologias); out.println(jsonTec); break; case Constans.ELIMINARTECNOLOGIA: int delTec = interPersona.eliminarTecnologia(Integer.parseInt(request.getParameter("ID"))); out.println(delTec); break; case Constans.AGREGARACTUALIZACION: Actualizacion actualizacion = new Actualizacion(0, request.getParameter("ANNO"), request.getParameter("PONENCIA"), request.getParameter("EVENTO"), request.getParameter("ENTIDAD"), request.getParameter("HORAS"), request.getParameter("LUGAR"), Integer.parseInt(request.getParameter("TIPO")), 1, Integer.parseInt(request.getParameter("IDPERSONA"))); int insActu = interPersona.agregarActualizacion(actualizacion); out.println(insActu); break; case Constans.LISTARACTUALIZACION: ArrayList<Actualizacion> arrayListActualizacion = interPersona.listarActualizacion( Integer.parseInt(request.getParameter("ID")), Integer.parseInt(request.getParameter("TIPO"))); String jsonActualizacion = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(arrayListActualizacion); out.println(jsonActualizacion); break; case Constans.ELIMINARACTUALIZACION: int delActua = interPersona.eliminarActualizacion(Integer.parseInt(request.getParameter("ID"))); out.println(delActua); break; case Constans.AGREGARPASANTIA: Pasantia pasantia1 = new Pasantia(0, request.getParameter("ANNOINICIO"), request.getParameter("ANNOFIN"), request.getParameter("INSTITUCION"), request.getParameter("LABOR"), request.getParameter("LUGAR"), Integer.parseInt(request.getParameter("IDPERSONA"))); int insPasan = interPersona.agregarPasantia(pasantia1); out.println(insPasan); break; case Constans.LISTARPASANTIA: ArrayList<Pasantia> arrayListPasantia = interPersona .listarPasantia(Integer.parseInt(request.getParameter("ID"))); String jsonPasantia = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayListPasantia); out.println(jsonPasantia); break; case Constans.ELIMINARPASANTIA: int delPasan = interPersona.eliminarPasantia(Integer.parseInt(request.getParameter("ID"))); out.println(delPasan); break; case Constans.LISTARINVESTIGACION: ArrayList<Investigacion> investigacions = interPersona.listarInvestigacion( Integer.parseInt(request.getParameter("ID")), Integer.parseInt(request.getParameter("TIPO"))); String jsonInventigacion = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(investigacions); out.println(jsonInventigacion); break; case Constans.AGREGARINVESTIGACION: Investigacion investigacion = new Investigacion(0, request.getParameter("ANNOPUB"), Integer.parseInt(request.getParameter("TIPOPUB")), request.getParameter("TITUPUB"), request.getParameter("MEDPU"), request.getParameter("EDIPUB"), request.getParameter("ISBN"), Integer.parseInt(request.getParameter("NROPAG")), request.getParameter("LUGPUB"), Integer.parseInt(request.getParameter("TIPOINVES")), request.getParameter("AUTOR"), request.getParameter("ANNO"), request.getParameter("ESPECIALIDAD"), 1, Integer.parseInt(request.getParameter("IDPERSONA")), request.getParameter("RESOLUCION"), ""); int insInvestigacion = interPersona.agregarInvestigacion(investigacion); out.println(insInvestigacion); break; case Constans.ELIMINARINVESTIGACION: int delInves = interPersona.eliminarInvestigacion(Integer.parseInt(request.getParameter("ID"))); out.println(delInves); break; case Constans.AGREGARPROYECCION: Proyeccion proyeccion = new Proyeccion(0, request.getParameter("ORANNO"), request.getParameter("ORACTIVIDAD"), request.getParameter("ORENTIDAD"), request.getParameter("ORINVERSION"), Integer.parseInt(request.getParameter("ORBENEFICIARIOS")), Integer.parseInt(request.getParameter("ORPARTICIPANTES")), request.getParameter("ORLUGAR"), Integer.parseInt(request.getParameter("ORTIPO")), 1, Integer.parseInt(request.getParameter("IDPERSONA")), ""); int insertProyeccion = interPersona.agregarProyeccion(proyeccion); out.println(insertProyeccion); break; case Constans.LISTARPROYECCION: ArrayList<Proyeccion> proyeccions = interPersona .listarProyeccion(Integer.parseInt(request.getParameter("ID")), request.getParameter("TIPO")); String jsonProyeccion = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(proyeccions); out.println(jsonProyeccion); break; case Constans.ELIMINARPROYECCION: int delProyeccion = interPersona.eliminarProyeccion(Integer.parseInt(request.getParameter("ID"))); out.println(delProyeccion); break; case Constans.ELIMINARRECONOCIMIENTO: int delReconocimiento = interPersona .eliminarReconocimiento(Integer.parseInt(request.getParameter("ID"))); out.println(delReconocimiento); break; case Constans.AGREGARRECONOCIMIENTO: Reconocimiento reconocimiento = new Reconocimiento(0, request.getParameter("FECHA"), request.getParameter("INSTITUCION"), request.getParameter("RECONOCIMIENTO"), request.getParameter("LUGAR"), Integer.parseInt(request.getParameter("TIPO")), request.getParameter("ACTIVIDAD"), 1, Integer.parseInt(request.getParameter("IDPERSONA")), request.getParameter("ANNO")); int insertReconocimiento = interPersona.agregarReconocimiento(reconocimiento); out.println(insertReconocimiento); break; case Constans.LISTARRECONOCIMIENTO: ArrayList<Reconocimiento> reconocimientos = interPersona.listarReconocimiento( Integer.parseInt(request.getParameter("IDPERSONA")), Integer.parseInt(request.getParameter("TIPO"))); String jsonReconocimiento = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reconocimientos); out.println(jsonReconocimiento); break; case Constans.SUBIRDOCUMENTO: String urlSave = "C:\\Users\\Kelvin\\Documents\\NetBeansProjects\\Legajo\\web\\documents"; DiskFileItemFactory factory = new DiskFileItemFactory(); //factory.setSizeThreshold(2014); factory.setRepository(new File(urlSave)); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> paList = upload.parseRequest(request); for (FileItem item : paList) { File file = new File(urlSave, "kelvin" + item.getName()); item.write(file); } out.println("Listo"); } catch (Exception e) { out.println("Execption: " + e.getMessage()); } break; case Constans.LISTARDOCUMENTO: ArrayList<Documento> documentos = interPersona .listarDocumento(Integer.parseInt(request.getParameter("IDPERSONA"))); String jsonDocumento = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(documentos); out.println(jsonDocumento); break; } }
From source file:isl.FIMS.servlet.imports.ImportXML.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("EisagwghXML_RDF"); String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; String displayMsg = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); // ArrayList<String> notValidMXL = new ArrayList<String>(); HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap(); if (!ServletFileUpload.isMultipartContent(request)) { displayMsg = "form"; } else {/*from w w w.jav a 2 s .co m*/ // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ArrayList<String> savedIDs = new ArrayList<String>(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; int xmlCount = 0; String[] id = null; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; 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(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); Utils.unzip(fileName, uploadPath); File dir = new File(uploadPath); String[] extensions = new String[] { "xml", "x3ml" }; List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true); xmlCount = files.size(); for (File file : files) { // saves the file on disk Document doc = ParseXMLFile.parseFile(file.getPath()); String xmlContent = doc.getDocumentElement().getTextContent(); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { ex.printStackTrace(); } String uriValue = this.URI_Reference_Path + uri_name + "/"; boolean insertEntity = false; if (xmlContent.contains(uriValue) || file.getName().contains(type)) { insertEntity = true; } Element root = doc.getDocumentElement(); Node admin = Utils.removeNode(root, "admin", true); // File rename = new File(uploadPath + File.separator + id[0] + ".xml"); // boolean isRename = storeFile.renameTo(rename); // ParseXMLFile.saveXMLDocument(rename.getPath(), doc); String schemaFilename = ""; schemaFilename = type; SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String xmlString = writer.getBuffer().toString().replaceAll("\r", ""); //without admin boolean isValid = sch.validate(xmlString); if ((!isValid && insertEntity)) { notValidMXL.put(file.getName(), null); } else if (insertEntity) { id = initInsertFile(type, false); doc = createAdminPart(id[0], type, doc, username); writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); xmlString = writer.getBuffer().toString().replaceAll("\r", ""); DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser, this.DBpassword); DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile"); dbF.setXMLAsString(xmlString); dbF.store(); ArrayList<String> externalFiles = new <String>ArrayList(); ArrayList<String> externalDBFiles = new <String>ArrayList(); String q = "//*["; for (String attrSet : this.uploadAttributes) { String[] temp = attrSet.split("#"); String func = temp[0]; String attr = temp[1]; if (func.contains("text")) { q += "@" + attr + "]/text()"; } else { q = "data(//*[@" + attr + "]/@" + attr + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalFiles.add(extFile + "#" + attr); } } q = "//"; if (!dbSchemaPath[0].equals("")) { for (String attrSet : this.dbSchemaPath) { String[] temp = attrSet.split("#"); String func = temp[0]; String path = temp[1]; if (func.contains("text")) { q += path + "//text()"; } else { q = "data(//" + path + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalDBFiles.add(extFile); } } } ArrayList<String> missingExternalFiles = new <String>ArrayList(); for (String extFile : externalFiles) { extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); if (f.size() == 0) { missingExternalFiles.add(extFile); } } if (missingExternalFiles.size() > 0) { notValidMXL.put(file.getName(), missingExternalFiles); } XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword, type, id[0]); ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type, this.DBuser, this.DBpassword); if (worngFiles.size() > 0) { //dbF.remove(); notValidMXL.put(file.getName(), worngFiles); } //remove duplicates from externalFiles if any HashSet hs = new HashSet(); hs.addAll(missingExternalFiles); missingExternalFiles.clear(); missingExternalFiles.addAll(hs); if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) { for (String extFile : externalFiles) { String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length()); extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); File uploadFile = f.iterator().next(); String content = FileUtils.readFileToString(uploadFile); DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml", this.DBuser, this.DBpassword); String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr); String uniqueName = Utils.createUniqueFilename(uploadFile.getName()); File uploadFileUnique = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(File.separator)) + File.separator + uniqueName); uploadFile.renameTo(uploadFileUnique); xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName); String upload_path = this.systemUploads + type; File upload_dir = null; ; if (mime.equals("Photos")) { upload_path += File.separator + mime + File.separator + "original" + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "thumbs"), thumbSize); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "normal"), normalSize); xmlString = xmlString.replace("</versions>", "</versions>" + "\n" + "<type>Photos</type>"); } else { upload_path += File.separator + mime + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); } if (!dbSchemaFolder.equals("")) { if (externalDBFiles.contains(extFile)) { try { DBCollection colSchema = new DBCollection(this.DBURI, dbSchemaFolder, this.DBuser, this.DBpassword); DBFile dbFSchema = colSchema.createFile(uniqueName, "XMLDBFile"); dbFSchema.setXMLAsString(content); dbFSchema.store(); } catch (Exception e) { } } } uploadFileUnique.renameTo(uploadFile); } dbF.setXMLAsString(xmlString); dbF.store(); Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser); Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser, lang); savedIDs.add(id[0]); } else { dbF.remove(); } } } } } Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml"); Element root = doc.getDocumentElement(); Element contextTag = (Element) root.getElementsByTagName("context").item(0); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { } if (notValidMXL.size() == 0) { xsl = conf.DISPLAY_XSL; displayMsg = Messages.ACTION_SUCCESS; displayMsg += Messages.NL + Messages.NL + Messages.URI_ID; String uriValue = ""; xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<backPages>").append('2').append("</backPages>\n"); for (String saveId : savedIDs) { uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL; xml.append("<codeValue>").append(uriValue).append("</codeValue>\n"); } } else if (notValidMXL.size() >= 1) { xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; Iterator it = notValidMXL.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); ArrayList<String> value = notValidMXL.get(key); if (value != null) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace("?", key); for (String mis_res : value) { displayMsg += mis_res + ","; } displayMsg = displayMsg.substring(0, displayMsg.length() - 1); displayMsg += "."; displayMsg += "</line>"; } else { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace(";", key); displayMsg += "</line>"; } displayMsg += "<line>"; displayMsg += "</line>"; } if (notValidMXL.size() < xmlCount) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg += "</line>"; for (String saveId : savedIDs) { displayMsg += "<line>"; String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId; select = (Element) contextTag.getElementsByTagName("URI_ID").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": " + uriValue; displayMsg += "</line>"; } } } Utils.deleteDir(currentDir); } catch (Exception ex) { ex.printStackTrace(); displayMsg += Messages.NOT_VALID_IMPORT; } } xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<EntityType>").append(type).append("</EntityType>\n"); xml.append(this.xmlEnd()); try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java
public Object processRequest(HttpServletRequest request) throws Exception { HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper ? (HttpServletRequestTwsWrapper) request : null;/*from w ww . j av a2 s . c o m*/ File temporaryFile = null; try { // Check multipart request if (ServletFileUpload.isMultipartContent(request)) { Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(1000); temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp"); int cptFile = 0; temporaryFile.delete(); temporaryFile.mkdirs(); factory.setRepository(temporaryFile); Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : " + temporaryFile.getAbsolutePath()); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax( EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE)); upload.setFileSizeMax( EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE)); // Parse the request List<FileItem> items = GenericUtils.cast(upload.parseRequest(request)); for (FileItem fileItem : items) { String parameterName = fileItem.getFieldName(); String parameterValue; if (fileItem.isFormField()) { parameterValue = fileItem.getString(); Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName + "' : " + parameterValue); } else { String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1"); if (name.length() > 0) { File wDir = new File(temporaryFile, "" + (++cptFile)); wDir.mkdirs(); File wFile = new File(wDir, name); fileItem.write(wFile); fileItem.delete(); parameterValue = wFile.getAbsolutePath(); Engine.logContext .debug("(ServletRequester.initContext) Temporary uploaded file for field '" + parameterName + "' : " + parameterValue); } else { Engine.logContext .debug("(ServletRequester.initContext) No temporary uploaded file for field '" + parameterName + "', empty name"); parameterValue = ""; } } if (twsRequest != null) { twsRequest.addParameter(parameterName, parameterValue); } } } Requester requester = getRequester(); request.setAttribute("convertigo.requester", requester); Object result = requester.processRequest(request); request.setAttribute("convertigo.cookies", requester.context.getCookieStrings()); String trSessionId = requester.context.getSequenceTransactionSessionId(); if (trSessionId != null) { request.setAttribute("sequence.transaction.sessionid", trSessionId); } if (requester.context.requireEndOfContext) { // request.setAttribute("convertigo.requireEndOfContext", // requester); request.setAttribute("convertigo.requireEndOfContext", Boolean.TRUE); } if (request.getAttribute("convertigo.contentType") == null) { // if // contentType // set by // webclipper // servlet // (#320) request.setAttribute("convertigo.contentType", requester.context.contentType); } request.setAttribute("convertigo.cacheControl", requester.context.cacheControl); request.setAttribute("convertigo.context.contextID", requester.context.contextID); request.setAttribute("convertigo.isErrorDocument", new Boolean(requester.context.isErrorDocument)); request.setAttribute("convertigo.context.removalRequired", new Boolean(requester.context.removalRequired())); if (requester.context.requestedObject != null) { // #397 : charset HTTP // header missing request.setAttribute("convertigo.charset", requester.context.requestedObject.getEncodingCharSet()); } else { // #3803 Engine.logEngine.warn( "(GenericServlet) requestedObject is null. Set encoding to UTF-8 for processRequest."); request.setAttribute("convertigo.charset", "UTF-8"); } return result; } finally { if (temporaryFile != null) { try { Engine.logEngine.debug( "(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath()); FileUtils.deleteDirectory(temporaryFile); } catch (IOException e) { } } } }
From source file:com.thejustdo.servlet.CargaMasivaServlet.java
/** * Processes requests for both HTTP/* w w w.ja v a 2 s . com*/ * <code>GET</code> and * <code>POST</code> methods. * * @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 { log.info(String.format("Welcome to the MULTI-PART!!!")); ResourceBundle messages = ResourceBundle.getBundle("com.thejustdo.resources.messages"); // 0. If no user logged, nothing can be done. if (!SecureValidator.checkUserLogged(request, response)) { return; } // 1. Check that we have a file upload request. boolean isMultipart = ServletFileUpload.isMultipartContent(request); log.info(String.format("Is multipart?: %s", isMultipart)); // 2. Getting all the parameters. String social_reason = request.getParameter("razon_social"); String nit = request.getParameter("nit"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String email = request.getParameter("email"); String office = (String) request.getSession().getAttribute("actualOffice"); String open_amount = (String) request.getParameter("valor_tarjeta"); String open_user = (String) request.getSession().getAttribute("actualUser"); List<String> errors = new ArrayList<String>(); // 6. Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // 7. Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); log.info(String.format("Temporal repository: %s", repository.getAbsolutePath())); factory.setRepository(repository); // 8. Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { utx.begin(); EntityManager em = emf.createEntityManager(); // Parse the request List<FileItem> items = upload.parseRequest(request); // 8.0 A set of generated box codes must be maintained. Map<String, String> matrix = new HashMap<String, String>(); // ADDED: Validation 'o file extension. String filename = null; // Runing through the parameters. for (FileItem fi : items) { if (fi.isFormField()) { if ("razon_social".equalsIgnoreCase(fi.getFieldName())) { social_reason = fi.getString(); continue; } if ("nit".equalsIgnoreCase(fi.getFieldName())) { nit = fi.getString(); continue; } if ("name".equalsIgnoreCase(fi.getFieldName())) { name = fi.getString(); continue; } if ("phone".equalsIgnoreCase(fi.getFieldName())) { phone = fi.getString(); continue; } if ("email".equalsIgnoreCase(fi.getFieldName())) { email = fi.getString(); continue; } if ("valor_tarjeta".equalsIgnoreCase(fi.getFieldName())) { open_amount = fi.getString(); continue; } } else { filename = fi.getName(); } } // 3. If we got no file, then a error is generated and re-directed to the exact same page. if (!isMultipart) { errors.add(messages.getString("error.massive.no_file")); log.log(Level.SEVERE, errors.toString()); } // 4. If any of the others paramaeters are missing, then a error must be issued. if ((social_reason == null) || ("".equalsIgnoreCase(social_reason.trim()))) { errors.add(messages.getString("error.massive.no_social_reason")); log.log(Level.SEVERE, errors.toString()); } if ((nit == null) || ("".equalsIgnoreCase(nit.trim()))) { errors.add(messages.getString("error.massive.no_nit")); log.log(Level.SEVERE, errors.toString()); } if ((name == null) || ("".equalsIgnoreCase(name.trim()))) { errors.add(messages.getString("error.massive.no_name")); log.log(Level.SEVERE, errors.toString()); } if ((phone == null) || ("".equalsIgnoreCase(phone.trim()))) { errors.add(messages.getString("error.massive.no_phone")); log.log(Level.SEVERE, errors.toString()); } if ((email == null) || ("".equalsIgnoreCase(email.trim()))) { errors.add(messages.getString("error.massive.no_email")); log.log(Level.SEVERE, errors.toString()); } // If no filename or incorrect extension. if ((filename == null) || (!(filename.endsWith(Constants.MASSIVE_EXT.toLowerCase(Locale.FRENCH))) && !(filename.endsWith(Constants.MASSIVE_EXT.toUpperCase())))) { errors.add(messages.getString("error.massive.invalid_ext")); log.log(Level.SEVERE, errors.toString()); } // 5. If any errors found, we must break the flow. if (errors.size() > 0) { request.setAttribute(Constants.ERROR, errors); //Redirect the response request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response); } for (FileItem fi : items) { if (!fi.isFormField()) { // 8.1 Processing the file and building the Beneficiaries. List<Beneficiary> beneficiaries = processFile(fi); log.info(String.format("Beneficiaries built: %d", beneficiaries.size())); // 8.2 If any beneficiaries, then an error is generated. if ((beneficiaries == null) || (beneficiaries.size() < 0)) { errors.add(messages.getString("error.massive.empty_file")); log.log(Level.SEVERE, errors.toString()); request.setAttribute(Constants.ERROR, errors); //Redirect the response request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response); } // 8.3 Building main parts. Buyer b = buildGeneralBuyer(em, social_reason, nit, name, phone, email); // 8.3.1 The DreamBox has to be re-newed per beneficiary. DreamBox db; for (Beneficiary _b : beneficiaries) { // 8.3.2 Completing each beneficiary. log.info(String.format("Completying the beneficiary: %d", _b.getIdNumber())); db = buildDreamBox(em, b, office, open_amount, open_user); matrix.put(db.getNumber() + "", _b.getGivenNames() + " " + _b.getLastName()); _b.setOwner(b); _b.setBox(db); em.merge(_b); } } } // 8.4 Commiting to persistence layer. utx.commit(); // 8.5 Re-directing to the right jsp. request.getSession().setAttribute("boxes", matrix); request.getSession().setAttribute("boxamount", open_amount + ""); //Redirect the response generateZIP(request, response); } catch (Exception ex) { errors.add(messages.getString("error.massive.couldnot_process")); log.log(Level.SEVERE, errors.toString()); request.setAttribute(Constants.ERROR, errors); request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response); } }
From source file:com.esd.cs.worker.WorkerController.java
/** * ?//from w w w. ja va 2 s . co m * * @param request * @param response * @return */ public Map<String, String> importfile(String upLoadPath, HttpServletRequest request, HttpServletResponse response) { // ??? // String fileType = "xls"; DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(5 * 1024); // factory.setRepository(new File(upLoadPath)); ServletFileUpload fileUpload = new ServletFileUpload(factory); Map<String, String> result = new HashMap<String, String>(); if (LoadUpFileMaxSize != null && !StringUtils.equals(LoadUpFileMaxSize.trim(), "")) { // ? fileUpload.setSizeMax(Integer.valueOf(LoadUpFileMaxSize) * 1024 * 1024); } try { // ? List<FileItem> items = fileUpload.parseRequest(request); for (FileItem item : items) { // ? if (!item.isFormField()) { // ?? String fileName = item.getName(); // ?? String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // ?? String uuid = UUID.randomUUID().toString(); // StringBuffer sbRealPath = new StringBuffer(); sbRealPath.append(upLoadPath).append(uuid).append(".").append(fileEnd); // File file = new File(sbRealPath.toString()); item.write(file); logger.info("?,filePath" + file.getPath()); // result.put("filePath", file.getPath()); // form?? } else { // item.getFieldName():??keyitem.getString()??value result.put(item.getFieldName(), item.getString()); } } } catch (Exception e) { // ??? result.put("fileError", ",??" + LoadUpFileMaxSize + "M!"); logger.error("uplaodWorkerFileError:{}", e.getMessage()); return result; } return result; }
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given {@link HttpServletRequest} * /*from www . j ava2 s . c om*/ * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod} */ private void handleMultipart(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // //////////////////////////////////////////// // Create a factory for disk-based file items // //////////////////////////////////////////// DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // ///////////////////////////// // Set factory constraints // ///////////////////////////// diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(Utils.DEFAULT_FILE_UPLOAD_TEMP_DIRECTORY); // ////////////////////////////////// // Create a new file upload handler // ////////////////////////////////// ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // ////////////////////////// // Parse the request // ////////////////////////// try { // ///////////////////////////////////// // Get the multipart items as a list // ///////////////////////////////////// List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // ///////////////////////////////////////// // Create a list to hold all of the parts // ///////////////////////////////////////// List<Part> listParts = new ArrayList<Part>(); // ///////////////////////////////////////// // Iterate the multipart items list // ///////////////////////////////////////// for (FileItem fileItemCurrent : listFileItems) { // ////////////////////////////////////// // If the current item is a form field, // then create a string part // ////////////////////////////////////// if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart( // The field name fileItemCurrent.getFieldName(), // The field value fileItemCurrent.getString()); // //////////////////////////// // Add the part to the list // //////////////////////////// listParts.add(stringPart); } else { // ///////////////////////////////////////////////////// // The item is a file upload, so we create a FilePart // ///////////////////////////////////////////////////// FilePart filePart = new FilePart( // ///////////////////// // The field name // ///////////////////// fileItemCurrent.getFieldName(), new ByteArrayPartSource( // The uploaded file name fileItemCurrent.getName(), // The uploaded file contents fileItemCurrent.get())); // ///////////////////////////// // Add the part to the list // ///////////////////////////// listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), methodProxyRequest.getParams()); methodProxyRequest.setRequestEntity(multipartRequestEntity); // //////////////////////////////////////////////////////////////////////// // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string // //////////////////////////////////////////////////////////////////////// methodProxyRequest.setRequestHeader(Utils.CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:it.infn.ct.g_hmmer_portlet.java
/** * This method manages the user input fields managing two cases * distinguished by the type of the input <form ... statement * The use of upload file controls needs the use of "multipart/form-data" * while the else condition of the isMultipartContent check manages the * standard input case. The multipart content needs a manual processing of * all <form items//from www. j ava 2 s. c om * All form' input items are identified by the 'name' input property * inside the jsp file * * @param request ActionRequest instance (processAction) * @param appInput AppInput instance storing the jobSubmission data */ void getInputForm(ActionRequest request, AppInput appInput) { if (PortletFileUpload.isMultipartContent(request)) try { FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List items = upload.parseRequest(request); File repositoryPath = new File("/tmp"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(repositoryPath); Iterator iter = items.iterator(); String logstring = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // Prepare a log string with field list logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'"; switch (inputControlsIds.valueOf(fieldName)) { case file_inputFile: appInput.inputFileName = item.getString(); processInputFile(item, appInput); break; case inputFile: appInput.inputFileText = item.getString(); break; case JobIdentifier: appInput.jobIdentifier = item.getString(); break; default: _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'"); } // switch fieldName } // while iter.hasNext() _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS); } // try catch (Exception e) { _log.info("Caught exception while processing files to upload: '" + e.toString() + "'"); } // The input form do not use the "multipart/form-data" else { // Retrieve from the input form the given application values appInput.inputFileName = (String) request.getParameter("file_inputFile"); appInput.inputFileText = (String) request.getParameter("inputFile"); appInput.jobIdentifier = (String) request.getParameter("JobIdentifier"); } // ! isMultipartContent // Show into the log the taken inputs _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '" + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS); }
From source file:it.infn.mib.AndreaPortlet.java
/** * This method manages the user input fields managing two cases * distinguished by the type of the input <form ... statement * The use of upload file controls needs the use of "multipart/form-data" * while the else condition of the isMultipartContent check manages the * standard input case. The multipart content needs a manual processing of * all <form items/*from w w w . ja v a 2 s .c o m*/ * All form' input items are identified by the 'name' input property * inside the jsp file * * @param request ActionRequest instance (processAction) * @param appInput AppInput instance storing the jobSubmission data */ @SuppressWarnings("rawtypes") void getInputForm(ActionRequest request, AppInput appInput) { if (PortletFileUpload.isMultipartContent(request)) try { FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List items = upload.parseRequest(request); File repositoryPath = new File("/tmp"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(repositoryPath); Iterator iter = items.iterator(); String logstring = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); //String fileName = item.getName(); //String contentType = item.getContentType(); //boolean isInMemory = item.isInMemory(); //long sizeInBytes = item.getSize(); // Prepare a log string with field list logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'"; switch (inputControlsIds.valueOf(fieldName)) { case file_inputFile: appInput.inputFileName = item.getString(); processInputFile(item, appInput); break; case inputFile: appInput.inputFileText = item.getString(); break; case JobIdentifier: appInput.jobIdentifier = item.getString(); break; default: _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'"); } // switch fieldName } // while iter.hasNext() _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS); } // try catch (Exception e) { _log.info("Caught exception while processing files to upload: '" + e.toString() + "'"); } // The input form do not use the "multipart/form-data" else { // Retrieve from the input form the given application values appInput.inputFileName = (String) request.getParameter("file_inputFile"); appInput.inputFileText = (String) request.getParameter("inputFile"); appInput.jobIdentifier = (String) request.getParameter("JobIdentifier"); } // ! isMultipartContent // Show into the log the taken inputs _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '" + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS); }
From source file:it.infn.ct.SemanticSearch_portlet.java
public void getInputForm(ActionRequest request, App_Input appInput) { if (PortletFileUpload.isMultipartContent(request)) { try {/*www . ja v a 2 s . c om*/ FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List items = upload.parseRequest(request); File repositoryPath = new File("/tmp"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(repositoryPath); Iterator iter = items.iterator(); String logstring = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // Prepare a log string with field list logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'"; switch (inputControlsIds.valueOf(fieldName)) { case JobIdentifier: appInput.jobIdentifier = item.getString(); break; default: _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'"); } // switch fieldName } // while iter.hasNext() _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS); } // try catch (Exception e) { _log.info("Caught exception while processing files to upload: '" + e.toString() + "'"); } } // The input form do not use the "multipart/form-data" else { // Retrieve from the input form the given application values appInput.search_word = (String) request.getParameter("search_word"); appInput.jobIdentifier = (String) request.getParameter("JobIdentifier"); appInput.nameSubject = (String) request.getParameter("nameSubject"); appInput.idResouce = (String) request.getParameter("idResource"); appInput.selected_language = (String) request.getParameter("selLanguage"); appInput.numberPage = (String) request.getParameter("numberOfPage"); appInput.numRecordsForPage = (String) request.getParameter("numberOfRecords"); appInput.title_GS = (String) request.getParameter("title_GS"); appInput.moreInfo = (String) request.getParameter("moreInfo"); if (appInput.selected_language == null) { appInput.selected_language = (String) request.getParameter("nameLanguageDefault"); } } // ! isMultipartContent // Show into the log the taken inputs _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "Search Word: '" + appInput.search_word + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS + "subject: '" + appInput.nameSubject + "'" + LS + "idResource: '" + appInput.idResouce + "'" + LS + "language selected: '" + appInput.selected_language + "'" + LS + "number page selected: '" + appInput.numberPage + "'" + LS + "number record for page: '" + appInput.numRecordsForPage + "'" + LS + "moreInfo: '" + appInput.moreInfo + "'" + LS); }