List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:co.com.rempe.impresiones.negocio.servlets.SubirArchivosServlet.java
private Respuesta subirArchivo(HttpServletRequest request) throws FileUploadException, Exception { Respuesta respuesta = new Respuesta(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // req es la HttpServletRequest que recibimos del formulario. // Los items obtenidos sern cada uno de los campos del formulario, // tanto campos normales como ficheros subidos. // System.out.println("Items-------"); List items = upload.parseRequest(request); System.out.println(items);// w w w . j a v a2s.c om // System.out.println("Request-----------------"); System.out.println(request); // Se recorren todos los items, que son de tipo FileItem for (Object item : items) { FileItem uploaded = (FileItem) item; // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero // subido donde nos interese // System.out.println("Item---------------"); System.out.println(uploaded.isFormField()); if (!uploaded.isFormField()) { // No es campo de formulario, guardamos el fichero en algn sitio //El sisguiente bloque simplemente es para divorciar el nombre del archivo de las rutas //posibles que pueda traernos el getName() sobre el objeto de la clase FileItem, //pues he descuvierto que el explorer especificamente es el nico que enva //la ruta adjuntada al nombre, por lo cual es importante corregirlo. String nombreArchivo = uploaded.getName(); String cadena = nombreArchivo; System.out.println(cadena); while (cadena.contains("\\")) { cadena = cadena.replace("\\", "&"); } // System.out.println(cadena); String[] ruta = cadena.split("&"); for (int i = 0; i < ruta.length; i++) { String string = ruta[i]; System.out.println(string); } nombreArchivo = ruta[ruta.length - 1]; // System.out.println("Ruta archivo: " + nombreArchivo); //Fin correccin nombre. String nombreArchivoEscrito = System.currentTimeMillis() + "-" + nombreArchivo; String rutaEscritura = new File(request.getRealPath("archivos-subidos"), nombreArchivoEscrito) .toString(); File fichero = new File(rutaEscritura); ArchivosAdjuntos archivo = new ArchivosAdjuntos(); archivo.setNombreArchivo(nombreArchivo); archivo.setRutaArchivo(rutaEscritura); archivo.setTamanioArchivo(uploaded.getSize()); if (nombreArchivo.endsWith(".pdf") || nombreArchivo.endsWith(".png") || nombreArchivo.endsWith(".jpg") || nombreArchivo.endsWith(".bmp") || nombreArchivo.endsWith(".svg")) { // System.out.println("Archivo subido: " + uploaded.getName()); uploaded.write(fichero); respuesta.setCodigo(1); respuesta.setDatos(archivo); respuesta.setMensaje("Se ha subido exitosamente el archivo: " + uploaded.getName()); } else { respuesta.setCodigo(0); respuesta.setDatos(archivo); respuesta.setMensaje("El formato del archivo " + nombreArchivo + " es invalido!"); } } // else { // // es un campo de formulario, podemos obtener clave y valor // String key = uploaded.getFieldName(); // String valor = uploaded.getString(); // System.out.println("Archivo subido: " + key); // } } return respuesta; }
From source file:byps.http.HHttpServlet.java
protected void doHtmlUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { if (log.isDebugEnabled()) log.debug("doHtmlUpload("); try {/*www.j av a 2 s. co m*/ // NDC.push(hsess.getId()); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new IllegalStateException("File upload must be sent as multipart/form-data."); } // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(HConstants.INCOMING_STREAM_BUFFER, getConfig().getTempDir()); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint long maxSize = getHtmlUploadMaxSize(); if (log.isDebugEnabled()) log.debug("set max upload file size=" + maxSize); upload.setSizeMax(maxSize); // Parse the request @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); if (log.isDebugEnabled()) log.debug("received #items=" + items.size()); ArrayList<HFileUploadItem> uploadItems = new ArrayList<HFileUploadItem>(); for (FileItem item : items) { String fieldName = item.getFieldName(); if (log.isDebugEnabled()) log.debug("fieldName=" + fieldName); String fileName = item.getName(); if (log.isDebugEnabled()) log.debug("fileName=" + fileName); boolean formField = item.isFormField(); if (log.isDebugEnabled()) log.debug("formField=" + formField); if (!formField && fileName.length() == 0) continue; long streamId = formField ? 0L : (System.currentTimeMillis() ^ ((((long) fileName.hashCode()) << 16L) | (long) System.identityHashCode(this))); // used as pseudo random number HFileUploadItem uploadItem = new HFileUploadItem(formField, fieldName, fileName, item.getContentType(), item.getSize(), Long.toString(streamId)); uploadItems.add(uploadItem); if (log.isDebugEnabled()) log.debug("uploadItem=" + uploadItem); if (item.isFormField()) continue; final BTargetId targetId = new BTargetId(getConfig().getMyServerId(), 0, streamId); getActiveMessages().addIncomingUploadStream( new HFileUploadItemIncomingStream(item, targetId, getConfig().getTempDir())); } makeHtmlUploadResult(request, response, uploadItems); } catch (Throwable e) { if (log.isInfoEnabled()) log.info("Failed to process message.", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().print(e.toString()); response.getWriter().close(); } finally { // NDC.pop(); } if (log.isDebugEnabled()) log.debug(")doHtmlUpload"); }
From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java
@Override public String getDestination(String function, VersioningSessionController versioningSC, HttpServletRequest request) {// w w w . j a v a 2 s. c o m String destination = ""; SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "User=" + versioningSC.getUserId() + " Function=" + function); String rootDestination = "/versioningPeas/jsp/"; ResourceLocator messages = new ResourceLocator( "com.stratelia.silverpeas.versioningPeas.multilang.versioning", versioningSC.getLanguage()); try { String flag = versioningSC.getProfile(); request.setAttribute("Profile", flag); if (function.startsWith("ViewReadersList")) { List<Group> groups = new ArrayList<Group>(); List<String> users = new ArrayList<String>(); ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.READER); if (profile != null) { groups = versioningSC.groupIds2Groups(profile.getAllGroups()); users = versioningSC.userIds2Users(profile.getAllUsers()); } request.setAttribute("Groups", groups); request.setAttribute("Users", users); destination = rootDestination + "ReadList.jsp"; } else if (function.startsWith("ViewWritersList")) { Document document = versioningSC.getEditingDocument(); ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.WRITER); ArrayList<Worker> workers = new ArrayList<Worker>(); if (profile != null) { workers = document.getWorkList(); if (document.getCurrentWorkListOrder() == Integer .parseInt(VersioningSessionController.WRITERS_LIST_ORDERED) && !versioningSC.isAlreadyMerged() && !profile.getAllGroups().isEmpty()) { // Need to merge users from groups with other users workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers); } } request.setAttribute("Workers", workers); destination = rootDestination + "WorkList.jsp"; } else if (function.startsWith("ChangeOrder")) { String lines = request.getParameter("lines"); Document document = versioningSC.getEditingDocument(); ArrayList<Worker> users = document.getWorkList(); if (lines != null) { int users_count = Integer.parseInt(lines); if (users_count == users.size()) { ArrayList<Worker> new_users = new ArrayList<Worker>(users_count); for (int i = 0; i < users_count; i++) { Worker user = users.get(i); boolean v_value = false; // Validator String chvi = request.getParameter("chv" + i); if (chvi != null) { v_value = true; } user.setApproval(v_value); new_users.add(user); } // Sorting begin int upIndex = Integer.parseInt(request.getParameter("up")); int downIndex = Integer.parseInt(request.getParameter("down")); int addIndex = Integer.parseInt(request.getParameter("add")); // Remove user to change order if (upIndex > 0 && upIndex < users_count) { Worker user = new_users.remove(upIndex); new_users.add(upIndex - 1, user); } if (downIndex >= 0 && downIndex < users_count - 1) { Worker user = new_users.remove(downIndex); new_users.add(downIndex + 1, user); } if (addIndex >= 0 && addIndex < users_count) { Worker user = new_users.get(addIndex); Worker new_user = new Worker(user.getUserId(), Integer.parseInt(versioningSC.getEditingDocument().getPk().getId()), 0, user.isApproval(), true, versioningSC.getComponentId(), user.getType(), user.isSaved(), user.isUsed(), user.getListType()); new_users.add(addIndex + 1, new_user); users_count++; } for (int i = 0; i < users_count; i++) { new_users.get(i).setOrder(i); } document.setWorkList(new_users); } } destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("ChangeListType")) { Document document = versioningSC.getEditingDocument(); String listType = request.getParameter("ListType"); if (!StringUtil.isDefined(listType)) { listType = VersioningSessionController.WRITERS_LIST_SIMPLE; } document.setCurrentWorkListOrder(Integer.parseInt(listType)); ProfileInst profile = versioningSC.getProfile(VersioningSessionController.WRITER); ArrayList<Worker> workers = new ArrayList<Worker>(); if (profile != null) { if (listType.equals(VersioningSessionController.WRITERS_LIST_ORDERED)) { // Need to merge users from groups with other users workers = document.getWorkList(); workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers); versioningSC.setAlreadyMerged(true); } else { ArrayList<Worker> workersUsers = new ArrayList<Worker>(); ArrayList<Worker> workersGroups = new ArrayList<Worker>(); workersGroups = versioningSC.convertGroupsToWorkers(workers, profile.getAllGroups()); workers.addAll(workersGroups); workersUsers = versioningSC.convertUsersToWorkers(workers, profile.getAllUsers()); workers.addAll(workersUsers); } } document.setWorkList(workers); versioningSC.updateWorkList(document); versioningSC.updateDocument(document); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("SaveListType")) { Document document = versioningSC.getEditingDocument(); ArrayList<Worker> users = document.getWorkList(); ArrayList<Worker> updateUsers = new ArrayList<Worker>(); for (int i = 0; i < users.size(); i++) { Worker user = users.get(i); // Set approval rights to users String chvi = request.getParameter("chv" + i); boolean v_value = false; if (chvi != null) { v_value = true; } user.setApproval(v_value); updateUsers.add(user); } versioningSC.updateWorkList(document); versioningSC.updateDocument(document); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("ViewVersions")) { request.setAttribute("Document", versioningSC.getEditingDocument()); destination = rootDestination + "versions.jsp"; } else if (function.equals("SelectUsersGroupsProfileInstance")) { String role = request.getParameter("Role"); String listType = request.getParameter("ListType"); if (StringUtil.isDefined(listType)) { versioningSC.getEditingDocument().setCurrentWorkListOrder(Integer.parseInt(listType)); } versioningSC.initUserPanelInstanceForGroupsUsers(role); destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.startsWith("DocumentProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); ProfileInst profile = versioningSC.getProfile(role); versioningSC.updateDocumentProfile(profile); if (role.equals(VersioningSessionController.WRITER)) { ArrayList<Worker> oldWorkers = versioningSC.getEditingDocument().getWorkList(); ArrayList<Worker> workers = new ArrayList<Worker>(); ArrayList<Worker> workersUsers = new ArrayList<Worker>(); ArrayList<Worker> workersGroups = new ArrayList<Worker>(); workersGroups = versioningSC.convertGroupsToWorkers(oldWorkers, profile.getAllGroups()); workers.addAll(workersGroups); workersUsers = versioningSC.convertUsersToWorkers(oldWorkers, profile.getAllUsers()); workers.addAll(workersUsers); ArrayList<Worker> sortedWorkers = new ArrayList<Worker>(); if (workers != null) { for (int i = 0; i < workers.size(); i++) { Worker sortedWorker = workers.get(i); sortedWorker.setOrder(i); sortedWorkers.add(sortedWorker); } workers = sortedWorkers; } versioningSC.getEditingDocument().setWorkList(workers); versioningSC.updateWorkList(versioningSC.getEditingDocument()); request.setAttribute("urlToReload", "ViewWritersList"); } else { request.setAttribute("urlToReload", "ViewReadersList"); } destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("SaveList")) { String role = request.getParameter("Role"); String fromFunction = request.getParameter("From"); if (versioningSC.isAccessListExist(role)) { versioningSC.removeAccessList(role); } versioningSC.saveAccessList(role); request.setAttribute("Message", messages.getString("versioning.ListSaved", "")); destination = getDestination(fromFunction, versioningSC, request); } else if (function.startsWith("DeleteReaderProfile")) { ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.READER); if (profile != null) { profile.removeAllGroups(); profile.removeAllUsers(); versioningSC.updateProfileInst(profile); } destination = getDestination("ViewReadersList", versioningSC, request); } else if (function.startsWith("DeleteWriterProfile")) { ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.WRITER); if (profile != null) { profile.removeAllGroups(); profile.removeAllUsers(); versioningSC.updateProfileInst(profile); } versioningSC.deleteWorkers(true); versioningSC.setAlreadyMerged(false); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("Update")) { String docId = request.getParameter("DocId"); String name = request.getParameter("name"); String description = request.getParameter("description"); String comments = request.getParameter("comments"); Document document = versioningSC .getDocument(new DocumentPK(Integer.parseInt(docId), versioningSC.getComponentId())); document.setDescription(description); document.setName(name); document.setAdditionalInfo(comments); versioningSC.updateDocument(document); versioningSC.setEditingDocument(document); destination = getDestination("ViewVersions", versioningSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("AddNewVersion")) { // Display xmlForm if used if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(request.getParameter("documentId"), versioningSC, request); } destination = rootDestination + "newVersion.jsp"; } else if (function.equals("AddNewOnlineVersion")) { String documentId = request.getParameter("documentId"); request.setAttribute("DocumentId", documentId); // Display xmlForm if used if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(documentId, versioningSC, request); } destination = rootDestination + "newOnlineVersion.jsp"; } else if (function.equals("ChangeValidator")) { String setTypeId = request.getParameter("VV"); String setType = request.getParameter("SetType"); // 'U'for users or 'G' // for groups versioningSC.setWorkerValidator(versioningSC.getEditingDocument().getWorkList(), Integer.parseInt(setTypeId), setType); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.equals("ListPublicVersionsOfDocument")) { String documentId = request.getParameter("DocId"); String isAlias = request.getParameter("Alias"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); List<DocumentVersion> publicVersions = versioningSC.getPublicDocumentVersions(documentPK); request.setAttribute("Document", document); request.setAttribute("PublicVersions", publicVersions); request.setAttribute("Alias", isAlias); destination = "/versioningPeas/jsp/publicVersions.jsp"; } else if ("ViewAllVersions".equals(function)) { return viewVersions(request, versioningSC); } else if ("saveOnline".equals(function)) { if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); String userId = versioningSC.getUserId(); String radio = FileUploadUtil.getParameter(items, "radio", "", encoding); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); boolean force = "true".equalsIgnoreCase(request.getParameter("force_release")); String callback = FileUploadUtil.getParameter(items, "Callback"); request.setAttribute("Callback", callback); destination = "/versioningPeas/jsp/documentSaved.jsp"; boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); DocumentVersionPK newVersionPK = versioningSC.saveOnline(document, comments, radio, Integer.parseInt(userId), force, addXmlForm); if (newVersionPK != null) { request.setAttribute("DocumentId", documentId); DocumentVersion version = versioningSC.getLastVersion(documentPK); request.setAttribute("Version", version); if (addXmlForm) { saveXMLData(versioningSC, newVersionPK, items); } } else { if ("admin".equals(versioningSC.getUserRoleLevel())) { // TODO MANU ecrire la page pour ressoumettre en forcant destination = "/versioningPeas/jsp/forceDocumentLocked.jsp"; } else { destination = "/versioningPeas/jsp/documentLocked.jsp"; } } } else if ("Checkout".equals(function)) { String documentId = request.getParameter("DocId"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); document.setStatus(1); document.setLastCheckOutDate(new Date()); versioningSC.checkDocumentOut(documentPK, Integer.parseInt(versioningSC.getUserId()), new Date()); document = versioningSC.getDocument(documentPK); versioningSC.setEditingDocument(document); request.setAttribute("Document", document); destination = rootDestination + "versions.jsp"; } else if ("DeleteDocumentRequest".equals(function)) { String documentId = request.getParameter("DocId"); String url = request.getParameter("Url"); request.setAttribute("DocId", documentId); request.setAttribute("Url", url); destination = rootDestination + "deleteDocument.jsp"; } else if (function.equals("DeleteDocument")) { String documentId = request.getParameter("DocId"); String url = request.getParameter("Url"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); versioningSC.deleteDocument(documentPK); SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "url=" + url); request.setAttribute("urlToReload", url); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("AddNewDocument")) { String pubId = request.getParameter("PubId"); request.setAttribute("PubId", pubId); if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(null, versioningSC, request); } destination = rootDestination + "newDocument.jsp"; } else if (function.equals("SaveNewDocument")) { saveNewDocument(request, versioningSC); destination = getDestination("ViewVersions", versioningSC, request); } else if (function.equals("SaveNewVersion")) { if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String type = FileUploadUtil.getParameter(items, "type", "", encoding); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); String radio = FileUploadUtil.getParameter(items, "radio", "", encoding); String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding); // Save file on disk FileItem fileItem = FileUploadUtil.getFile(items, "file_upload"); boolean runOnUnix = !FileUtil.isWindows(); String logicalName = fileItem.getName(); String physicalName = "dummy"; String mimeType = "dummy"; File dir = null; int size = 0; if (logicalName != null) { if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = FileUtil.getMimeType(logicalName); if (!StringUtil.isDefined(mimeType)) { mimeType = "unknown"; } dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName); size = new Long(fileItem.getSize()).intValue(); fileItem.write(dir); } // create DocumentVersion String componentId = versioningSC.getComponentId(); DocumentPK docPK = new DocumentPK(Integer.parseInt(documentId), "useless", componentId); int userId = Integer.parseInt(versioningSC.getUserId()); DocumentVersion documentVersion = null; DocumentVersion lastVersion = versioningSC.getLastVersion(docPK); if (com.stratelia.silverpeas.versioning.ejb.RepositoryHelper.getJcrDocumentService() .isNodeLocked(lastVersion)) { destination = rootDestination + "documentLocked.jsp"; } else { List<DocumentVersion> versions = versioningSC.getDocumentVersions(docPK); int majorNumber = 0; int minorNumber = 1; if (versions != null && versions.size() > 0) { documentVersion = versions.get(0); majorNumber = documentVersion.getMajorNumber(); minorNumber = documentVersion.getMinorNumber(); DocumentVersion newVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber, userId, new Date(), comments, Integer.parseInt(radio), documentVersion.getStatus(), physicalName, logicalName, mimeType, size, componentId); boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); if (addXmlForm) { newVersion.setXmlForm(versioningSC.getXmlForm()); } newVersion = versioningSC.addNewDocumentVersion(newVersion); ResourceLocator settings = new ResourceLocator( "com.stratelia.webactiv.util.attachment.Attachment", ""); boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false); // Specific case: 3d file to convert by Actify Publisher if (actifyPublisherEnable) { String extensions = settings.getString("Actify3dFiles"); StringTokenizer tokenizer = new StringTokenizer(extensions, ","); // 3d native file ? boolean fileForActify = false; SilverTrace.info("versioningPeas", "saveFile.jsp", "root.MSG_GEN_PARAM_VALUE", "nb tokenizer =" + tokenizer.countTokens()); while (tokenizer.hasMoreTokens() && !fileForActify) { String extension = tokenizer.nextToken(); if (type.equalsIgnoreCase(extension)) { fileForActify = true; } } if (fileForActify) { String dirDestName = "v_" + componentId + "_" + documentId; String actifyWorkingPath = settings.getString("ActifyPathSource") + File.separator + dirDestName; String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath; if (!new File(destPath).exists()) { FileRepositoryManager.createGlobalTempPath(actifyWorkingPath); } String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath + File.separator + logicalName; FileRepositoryManager.copyFile( versioningSC.createPath(componentId, null) + File.separator + physicalName, destFile); } } if (addXmlForm) { saveXMLData(versioningSC, newVersion.getPk(), items); } } String returnURL = FileUploadUtil.getParameter(items, "ReturnURL"); if (!StringUtil.isDefined(returnURL)) { destination = getDestination("ViewVersions", versioningSC, request); } else { request.setAttribute("urlToReload", returnURL); destination = rootDestination + "closeWindow.jsp"; } } } else { destination = rootDestination + function; } } catch (Exception e) { SilverTrace.error("versioning", "VersioningRequestRouter.getDestination", "root.EX_CANT_GET_REQUEST_DESTINATION", e); request.setAttribute("javax.servlet.jsp.jspException", e); destination = "/admin/jsp/errorpageMain.jsp"; } SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Destination=" + destination); return destination; }
From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java
@SuppressWarnings("unchecked") protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ("GET".equalsIgnoreCase(request.getMethod())) { //just render blank page for upload String pageUuid = request.getParameter("puuid"); String spaceUname = request.getParameter("uname"); String draft = request.getParameter("draft"); request.setAttribute("pageUuid", pageUuid); request.setAttribute("spaceUname", spaceUname); request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value())); request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response); return;//from www . ja va 2 s. c om } //post - upload // if(WikiUtil.getUser().isAnonymous()){ // //anonymous can not allow to upload any files PageService pageService = getPageService(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); List<FileNode> files = new ArrayList<FileNode>(); String pageUuid = null, spaceUname = null; try { int status = PageType.NONE_DRAFT.value(); // index->filename Map<String, FileItem> fileMap = new HashMap<String, FileItem>(); Map<String, String> descMap = new HashMap<String, String>(); // index->index Map<String, String> indexMap = new HashMap<String, String>(); //offline submission, filename put into hidden variable rather than <input type="file> tag Map<String, String> filenameMap = new HashMap<String, String>(); //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check: //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case Map<String, String> versionMap = new HashMap<String, String>(); Map<String, Boolean> bulkMap = new HashMap<String, Boolean>(); Map<String, Boolean> sharedMap = new HashMap<String, Boolean>(); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (StringUtils.equals(name, "spaceUname")) { spaceUname = item.getString(Constants.UTF8); } else if (StringUtils.equals(name, "pageUuid")) { pageUuid = item.getString(); } else if (name.startsWith("draft")) { // check this upload is from "click save button" or "auto upload in draft status" status = Integer.parseInt(item.getString()); } else if (name.startsWith("file")) { fileMap.put(name.substring(4), item); indexMap.put(name.substring(4), name.substring(4)); } else if (name.startsWith("desc")) { descMap.put(name.substring(4), item.getString(Constants.UTF8)); } else if (name.startsWith("shar")) { sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString())); } else if (name.startsWith("name")) { filenameMap.put(name.substring(4), item.getString()); } else if (name.startsWith("vers")) { versionMap.put(name.substring(4), item.getString()); } else if (name.startsWith("bulk")) { bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString())); } } if (StringUtils.isBlank(pageUuid)) { log.error("Attachment can not be load because of page does not save successfully."); throw new PageException("Attachment can not be load because of page does not save successfully."); } List<FileNode> bulkFiles = new ArrayList<FileNode>(); String username = request.getRemoteUser(); // put file/desc pair into final Map for (String id : fileMap.keySet()) { FileItem item = fileMap.get(id); if (item == null || item.getInputStream() == null || item.getSize() <= 0) { log.warn("Empty upload item:" + (item != null ? item.getName() : "")); continue; } FileNode node = new FileNode(); node.setComment(descMap.get(id)); node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id)); node.setFile(item.getInputStream()); String filename = item.getName(); if (StringUtils.isBlank(filename)) { //this could be offline submission, get name from map filename = filenameMap.get(id); } node.setFilename(FileUtil.getFileName(filename)); node.setContentType(item.getContentType()); node.setIndex(indexMap.get(id)); node.setType(RepositoryService.TYPE_ATTACHMENT); node.setIdentifier(pageUuid); node.setCreateor(username); node.setStatus(status); node.setSize(item.getSize()); node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id)); files.add(node); if (node.isBulkZip()) bulkFiles.add(node); } if (spaceUname != null && pageUuid != null && files.size() > 0) { files = pageService.uploadAttachments(spaceUname, pageUuid, files, false); //only save non-draft uploaded attachment if (status == 0) { try { getActivityLog().logAttachmentUploaded(spaceUname, pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files); } catch (Exception e) { log.warn("Activity log save error for attachment upload", e); } } //as bulk files won't in return list in PageService.uploadAttachments(), here need //append to all return list, but only for client side "uploading panel" clean purpose files.addAll(bulkFiles); //TODO: if version come in together, then do check // if(versionMap.size() > 0){ // for (FileNode node: files) { // // } // } } } catch (RepositoryQuotaException e) { FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.quota.exhaust")); files = Arrays.asList(att); } catch (AuthenticationException e) { String redir = ((RedirectResponseWrapper) response).getRedirect(); if (redir == null) redir = WikiConstants.URL_LOGIN; log.info("Send Authentication redirect URL " + redir); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.authentication.required")); files = Arrays.asList(att); } catch (AccessDeniedException e) { String redir = ((RedirectResponseWrapper) response).getRedirect(); if (redir == null) redir = WikiConstants.URL_ACCESS_DENIED; log.info("Send AccessDenied redirect URL " + redir); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.access.denied")); files = Arrays.asList(att); } catch (Exception e) { // FileUploadException,RepositoryException log.error("File upload failed ", e); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.upload")); files = Arrays.asList(att); } try { String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(), getUserReadingService()); //TODO: does not compress request in Gzip, refer to //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first byte[] reply = json.getBytes(Constants.UTF8); response.setContentLength(reply.length); response.setContentType("text/plain; charset=utf-8"); response.getOutputStream().write(reply); } catch (IOException e) { log.error(e.toString(), e); } }
From source file:com.kmetop.demsy.modules.ckfinder.FileUploadCommand.java
/** * validates uploaded file./*from www . j a va2s. c o m*/ * * @param item * uploaded item. * @param path * file path * @return true if validation */ private boolean validateUploadItem(final FileItem item, final String path) { if (item.getName() != null && item.getName().length() > 0) { this.fileName = getFileItemName(item); } else { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID; return false; } this.newFileName = this.fileName; String unsafeFileName = this.newFileName; for (char c : UNSAFE_FILE_NAME_CHARS) { this.newFileName = unsafeFileName.replace(c, '_'); } if (configuration.forceASCII()) { this.newFileName = FileUtils.convertToASCII(this.newFileName); } if (!unsafeFileName.equals(this.newFileName)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID_NAME_RENAMED; } if (FileUtils.checkIfDirIsHidden(this.currentFolder, configuration)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST; return false; } if (!FileUtils.checkFileName(this.newFileName) || FileUtils.checkIfFileIsHidden(this.newFileName, configuration)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME; return false; } int checkFileExt = FileUtils.checkFileExtension(this.newFileName, configuration.getTypes().get(type), configuration, true); if (checkFileExt == 1) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION; return false; } else if (checkFileExt == 2) { this.newFileName = FileUtils.renameFileWithBadExt(this.newFileName); } try { File file = new File(path, getFinalFileName(path, this.newFileName)); if (!FileUtils.checkFileSize(configuration.getTypes().get(this.type), item.getSize()) && !(configuration.checkSizeAfterScaling() && ImageUtils.isImage(file))) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } if (configuration.getSecureImageUploads() && ImageUtils.isImage(file) && !ImageUtils.checkImageFile(item)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT; return false; } if (!FileUtils.checkIfFileIsHtmlFile(file.getName(), configuration) && FileUtils.detectHtml(item)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_WRONG_HTML_FILE; return false; } } catch (SecurityException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } catch (IOException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } return true; }
From source file:com.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * validates uploaded file.//from www . j a v a 2 s .c om * * @param item uploaded item. * @param path file path * @return true if validation */ private boolean validateUploadItem(final FileItem item, final String path) { if (item.getName() != null && item.getName().length() > 0) { this.fileName = getFileItemName(item); } else { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID; return false; } this.newFileName = this.fileName; for (char c : UNSAFE_FILE_NAME_CHARS) { this.newFileName = this.newFileName.replace(c, '_'); } if (configuration.isDisallowUnsafeCharacters()) { this.newFileName = this.newFileName.replace(';', '_'); } if (configuration.forceASCII()) { this.newFileName = FileUtils.convertToASCII(this.newFileName); } if (!this.newFileName.equals(this.fileName)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_INVALID_NAME_RENAMED; } if (FileUtils.checkIfDirIsHidden(this.currentFolder, configuration)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST; return false; } if (!FileUtils.checkFileName(this.newFileName) || FileUtils.checkIfFileIsHidden(this.newFileName, configuration)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME; return false; } int checkFileExt = FileUtils.checkFileExtension(this.newFileName, configuration.getTypes().get(type)); if (checkFileExt == 1) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION; return false; } if (configuration.ckeckDoubleFileExtensions()) { this.newFileName = FileUtils.renameFileWithBadExt(configuration.getTypes().get(type), this.newFileName); } try { File file = new File(path, getFinalFileName(path, this.newFileName)); if (!FileUtils.checkFileSize(configuration.getTypes().get(this.type), item.getSize()) && !(configuration.checkSizeAfterScaling() && ImageUtils.isImage(file))) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } if (configuration.getSecureImageUploads() && ImageUtils.isImage(file) && !ImageUtils.checkImageFile(item)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT; return false; } if (!FileUtils.checkIfFileIsHtmlFile(file.getName(), configuration) && FileUtils.detectHtml(item)) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_WRONG_HTML_FILE; return false; } } catch (SecurityException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } catch (IOException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } return true; }
From source file:com.mycom.products.mywebsite.backend.util.UploadHandler.java
@Override @ResponseBody/*from w w w.j a v a 2s . co m*/ @RequestMapping(method = RequestMethod.POST) protected final void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } JSONObject json = new JSONObject(); SimpleDateFormat fmtYMD = new SimpleDateFormat("/" + "yyyyMMdd"); Date today = new Date(); String uploadPath = EntryPoint.getUploadPath() + "/"; try { List<FileItem> items = uploadHandler.parseRequest(request); if (items != null && items.size() > 0) { String saveDir = "", fileCategory = ""; for (FileItem item : items) { if (item.isFormField()) { fileCategory = item.getString(); } } saveDir = fileCategory + fmtYMD.format(today); // creates the directory if it does not exist File uploadDir = new File(uploadPath + saveDir); if (!uploadDir.exists()) { uploadDir.mkdirs(); } List<HashMap<String, String>> uploadFiles = new ArrayList<>(); for (FileItem item : items) { // processes only fields that are not form fields if (!item.isFormField()) { if (saveDir.length() == 0) { json.put("messageCode", "V1001"); json.put("messageParams", "File upload type"); json.put("status", HttpStatus.BAD_REQUEST); response.setContentType("application/json"); writer.write(json.toString()); writer.flush(); } String originalFileName = "", saveFileName = "", format = "", fileSize = ""; // set the default format to png when it is profileImage if (fileCategory.equals("profilePicture")) { format = ".png"; } // can't predict fileName and format would be included. // For instance, blob won't be. try { originalFileName = item.getName().substring(0, item.getName().lastIndexOf(".")); } catch (Exception e) { // Nothing to do. Skip } try { format = item.getName().substring(item.getName().lastIndexOf("."), item.getName().length()); } catch (Exception e) { // Nothing to do. Skip } fileSize = getReadableFileSize(item.getSize()); UUID uuid = UUID.randomUUID(); saveFileName = new File(uuid.toString() + format).getName(); String filePath = uploadPath + saveDir + "/" + saveFileName; if (fileCategory.equals("profilePicture")) { saveProfileImage(item, filePath); } // Time to save in DB LoggedUserBean loginUser; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof LoggedUserBean) { loginUser = (LoggedUserBean) principal; } else { throw new SecurityException("Unauthorize File Upload process was attempted."); } StaticContentBean content = new StaticContentBean(); content.setFileName(originalFileName + format); content.setFilePath(filePath); content.setFileSize(fileSize); content.setFileType(FileType.valueOf(getFileType(format))); long lastInsertedId = contentService.insert(content, loginUser.getId()); // else .... other file types go here HashMap<String, String> fileItem = new HashMap<>(); fileItem.put("contentId", "" + lastInsertedId); uploadFiles.add(fileItem); } } json.put("uploadFiles", uploadFiles); json.put("status", HttpStatus.OK); response.setContentType("application/json"); writer.write(json.toString()); writer.flush(); } } catch (FileUploadException e) { throw new RuntimeException("File upload Error !", e); } catch (Exception e) { throw new RuntimeException("File upload Error !", e); } finally { writer.close(); } }
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobDAOImpl.java
@Override public HrmsDocs uploadFile(FileItem fi, ConfigRecruitmentData ConfigRecruitmentDataobj, HashMap arrparam, boolean flag) { HrmsDocs docObj = new HrmsDocs(); User userObj = null;//from w w w . j a v a 2 s .co m Jobapplicant jobapp = null; try { String fileName = new String(fi.getName().getBytes(), "UTF8"); String Ext = ""; if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } docObj.setDocname(fileName); docObj.setReferenceid(ConfigRecruitmentDataobj.getId()); docObj.setStorename(""); docObj.setDoctype(""); docObj.setUploadedon(new Date()); docObj.setStorageindex(1); docObj.setDocsize(fi.getSize() + ""); docObj.setDeleted(false); if (StringUtil.isNullOrEmpty((String) arrparam.get("docname")) == false) { docObj.setDispdocname((String) arrparam.get("docname")); } if (StringUtil.isNullOrEmpty((String) arrparam.get("docdesc")) == false) { docObj.setDocdesc((String) arrparam.get("docdesc")); } hibernateTemplate.save(docObj); String fileid = docObj.getDocid(); if (Ext.length() > 0) { fileid = fileid + Ext; } docObj.setStorename(fileid); hibernateTemplate.update(docObj); String temp = StorageHandler.GetDocStorePath1(); uploadFile(fi, temp, fileid); } catch (Exception e) { System.out.println("Error is " + e); } return docObj; }
From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java
/** * Uploads a specific mime multipart input set, intercepts exceptions. * @param req The servlet request// ww w . j a va 2 s. co m * @return The page to which we should go next. * @throws RedirectException If there's an error and a redirection is needed * @throws IOException If upload fails * @throws FileUploadException */ @SuppressWarnings("unchecked") protected String upload(HttpServletRequest req) throws RedirectException, IOException { String msg = ""; String attName = "(unknown)"; String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad // happened, Upload // should be able to // take care of most // stuff String nextPage = errorPage; String progressId = req.getParameter("progressid"); // Check that we have a file upload request if (!ServletFileUpload.isMultipartContent(req)) { throw new RedirectException("Not a file upload", errorPage); } try { FileItemFactory factory = new DiskFileItemFactory(); // Create the context _before_ Multipart operations, otherwise // strict servlet containers may fail when setting encoding. WikiContext context = m_engine.createContext(req, WikiContext.ATTACH); UploadListener pl = new UploadListener(); m_engine.getProgressManager().startProgress(pl, progressId); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); upload.setFileSizeMax(m_maxSize); upload.setProgressListener(pl); List<FileItem> items = upload.parseRequest(req); String wikipage = null; String changeNote = null; FileItem actualFile = null; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("page")) { // // FIXME: Kludge alert. We must end up with the parent page name, // if this is an upload of a new revision // wikipage = item.getString("UTF-8"); int x = wikipage.indexOf("/"); if (x != -1) { wikipage = wikipage.substring(0, x); } } else if (item.getFieldName().equals("changenote")) { changeNote = item.getString("UTF-8"); } else if (item.getFieldName().equals("nextpage")) { nextPage = validateNextPage(item.getString("UTF-8"), errorPage); } } else { actualFile = item; } } if (actualFile == null) { throw new RedirectException("Broken file upload", errorPage); } // // FIXME: Unfortunately, with Apache fileupload we will get the form fields in // order. This means that we have to gather all the metadata from the // request prior to actually touching the uploaded file itself. This // is because the changenote appears after the file upload box, and we // would not have this information when uploading. This also means // that with current structure we can only support a single file upload // at a time. // String filename = actualFile.getName(); long fileSize = actualFile.getSize(); InputStream in = actualFile.getInputStream(); try { executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize); } finally { in.close(); } } catch (ProviderException e) { msg = "Upload failed because the provider failed: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } catch (IOException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw e; } catch (FileUploadException e) { // Show the submit page again, but with a bit more // intimidating output. msg = "Upload failure: " + e.getMessage(); log.warn(msg + " (attachment: " + attName + ")", e); throw new IOException(msg); } finally { m_engine.getProgressManager().stopProgress(progressId); // FIXME: In case of exceptions should absolutely // remove the uploaded file. } return nextPage; }
From source file:de.innovationgate.wgpublisher.webtml.form.TMLForm.java
/** * Constructor to read form from posted data * @param core The WGACore object/*from www .jav a 2s . com*/ * @param formData The posted data * @throws WGException * @throws UnsupportedEncodingException */ @CodeCompletion public TMLForm(WGACore core, TMLForm.MultipartFormData formData) throws WGException, UnsupportedEncodingException { _log = core.getLog(); _submitted = true; _filesDropped = formData.isFilesDropped(); // Retrieve system field information _formInfo = retrieveFormInfo(formData, core); _passwordSalt = createPasswordSalt(); _formSourceModuleDefinition = fetchFormSourceModuleDefinition(); if (formData.getFormActionItem() != null) { _formAction = formData.getDecodedItemValue(formData.getFormActionItem()); } // Parse fields into submitted fields map Map<String, TMLFormField> submittedFields = new HashMap<String, TMLFormField>(); Iterator<FileItem> iter = formData.getFileItems().iterator(); // put all FileItemObject into Map and put all transmitted fields into field map while (iter.hasNext()) { FileItem fi = iter.next(); // File items if (!fi.isFormField()) { if (fi.getSize() > 0) { parseFileItem(fi); } } // Standard form items else if (!fi.getFieldName().startsWith("$")) { TMLFormField field = (TMLFormField) submittedFields.get(fi.getFieldName()); if (field == null) { field = new TMLFormField(fi.getFieldName()); submittedFields.put(fi.getFieldName(), field); } field.addValue(formData.getDecodedItemValue(fi)); } } processSubmittedFields(submittedFields); retrieveCustomFields(); enforceFieldDefs(); }