/** * Get an uploaded file item. * * @param request * @param response * @throws IOException */ public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(PARAM_SHOW); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { logger.debug( "UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize() + " bytes"); response.setContentType(item.getContentType()); copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream()); } else { logger.info( "UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " file isn't in session."); renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND); } }
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, containing * Spring MultipartFile instances and a Map of multipart parameter. * * @param fileItems the Commons FileIterms to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) */ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); Map<String, String> multipartParameterContentTypes = new HashMap<String, String>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); if (partEncoding != null) { try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn( "Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); multipartFiles.add(file.getName(), file); if (logger.isDebugEnabled()) { logger.debug( "Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult( multipartFiles, multipartParameters, multipartParameterContentTypes); }
/** * Override executeAction to save the received files in a custom place and delete this items from * session. */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; HttpSession session = request.getSession(true); if (sessionFiles.size() == 0) { LOG.info("No hay imagenes en la session"); return "No hay imagenes en la session"; } if (session.getAttribute(ATTR_ARCHIVOS) == null) session.setAttribute(ATTR_ARCHIVOS, new ArrayList<String>()); List<String> photos = (List<String>) session.getAttribute(ATTR_ARCHIVOS); for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { // / Create a new file based on the remote file name in the // client // String saveName = // item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", // "_"); // File file =new File("/tmp/" + saveName); // / Create a temporary file placed in /tmp (only works in // unix) // File file = File.createTempFile("upload-", ".bin", new // File("/tmp")); // / Create a temporary file placed in the default system // temp folder String name = item.getName(); int posPunto = name.lastIndexOf("."); String ext = name.substring(posPunto + 1); File file = File.createTempFile("gha", "." + ext); item.write(file); // / Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); photos.add(file.getName()); // / Send a customized message to the client. response += file.getName(); } catch (Exception e) { throw new UploadActionException(e); } } } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send your customized message to the client. return response; }
public void handle(FileItem item, Map<String, Object> result) { BlobWriter writer = blobManager.newFile(item.getContentType()); OutputStream out = writer.getOutputStream(); InputStream in = null; try { in = item.getInputStream(); try { int size = 0; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } } finally { IOTools.close(in, out); } BlobInfo info = writer.getBlobInfo(); result.put("fileId", info.id()); result.put("contentType", info.contentType()); result.put("md5", info.md5()); result.put("sucessful", "true"); blobManager.commit(writer); } catch (Exception ex) { result.put("sucessful", "false"); blobManager.cancel(writer); } }
/** * Returns the content type passed by the browser or <code>null</code> if not defined. The passed * ContentType may differ dependingon the browser / operating system used. */ public String getContentType() { String result = null; if (fileItem != null) { result = fileItem.getContentType(); } return result; }
@Put public AttachmentResponse addAttachment(Representation entity) { if (authenticate() == false) return null; String taskId = (String) getRequest().getAttributes().get("taskId"); try { RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(entity); FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.getName() != null) { uploadItem = fileItem; } } String fileName = uploadItem.getName(); Attachment attachment = ActivitiUtil.getTaskService() .createAttachment( uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream()); return new AttachmentResponse(attachment); } catch (Exception e) { throw new ActivitiException("Unable to add new attachment to task " + taskId); } }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!ServletFileUpload.isMultipartContent(request)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { List<FileItem> files = uploadHandler.parseRequest(request); if (files.size() == 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } FileItem fileItem = files.get(0); if (!fileItem.getContentType().equals(Constants.CLASS_CONTENT_TYPE) || fileItem.isFormField()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } String folderName = baseDir + request.getRequestURI().replaceAll("/", Constants.FILE_SEPARATOR); File folder = new File(folderName); if (folder.exists() && !folder.isDirectory()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (!folder.exists()) { folder.mkdirs(); } fileItem.write(new File(folderName + Constants.FILE_SEPARATOR + fileItem.getName())); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } }
@SuppressWarnings("null") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); // if (!isMultipart) { return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. // factory.setRepository(new File("d:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // System.out.println(empid); try { // out = response.getWriter( ); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); readBOM(file); break; } } RequestDispatcher ReqDis = request.getRequestDispatcher("afterBOM.jsp"); ReqDis.forward(request, response); } catch (Exception ex) { ex.printStackTrace(); RequestDispatcher ReqDis = request.getRequestDispatcher("Error.jsp"); ReqDis.forward(request, response); } }
@SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("upload start------"); request.setCharacterEncoding("UTF-8"); StringBuffer savePath = new StringBuffer("/mnt/web/static/images/album/"); Calendar c = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy/MM/dd/"); String date = df.format(c.getTime()); savePath.append(date); File dir = new File(savePath.toString()); if (!dir.exists()) { dir.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); List<FileItem> list = null; try { list = upload.parseRequest(request); } catch (FileUploadException e) { log.error(e.getMessage(), e); return; } log.info("file size:{}", list.size()); for (FileItem it : list) { if (!it.isFormField()) { String name = it.getName(); long size = it.getSize(); String type = it.getContentType(); log.info("name:{},size:{},type:{}", name, size, type); if (StringUtils.isBlank(name)) { continue; } String extName = null; if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } File file = null; do { name = UUIDUtil.getRandomUUID(); file = new File(savePath + name + extName); } while (file.exists()); File saveFile = new File(savePath + name + extName); log.info("path:{}", saveFile.getAbsolutePath()); try { it.write(saveFile); albumService.newPhoto(1, saveFile.getAbsolutePath(), "none"); } catch (Exception e) { e.printStackTrace(); } } } response.getWriter().write("1"); log.info("upload end------"); }
/** * Responsible for constructing a FileBean object for the named file parameter. If there is no * file parameter with the specified name this method should return null. * * @param name the name of the file parameter * @return a FileBean object wrapping the uploaded file */ public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); if (item == null || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included String filename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) { index = filename.lastIndexOf('\\'); } else { index = filename.lastIndexOf('/'); } if (index >= 0 && index + 1 < filename.length() - 1) { filename = filename.substring(index + 1); } // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
protected Map<String, String> getFileItemsSummary( HttpServletRequest request, Map<String, String> ret) { if (ret == null) { ret = new HashMap<String, String>(); } @SuppressWarnings("unchecked") List<FileItem> s = (List<FileItem>) request.getSession().getAttribute(ATTR_LAST_FILES); if (s != null) { for (FileItem i : s) { if (false == i.isFormField()) { ret.put("ctype", i.getContentType() != null ? i.getContentType() : "unknown"); ret.put("size", "" + i.getSize()); ret.put("name", "" + i.getName()); ret.put("field", "" + i.getFieldName()); } } ret.put(TAG_FINISHED, "ok"); } return ret; }
protected void processFile(FileItem item, String name, MutableRequest request) { try { String fileName = FilenameUtils.getName(item.getName()); UploadedFile upload = new DefaultUploadedFile( item.getInputStream(), fileName, item.getContentType(), item.getSize()); request.setParameter(name, name); request.setAttribute(name, upload); logger.debug("Uploaded file: {} with {}", name, upload); } catch (IOException e) { throw new InvalidParameterException("Can't parse uploaded file " + item.getName(), e); } }
/* * (non-Javadoc) * * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getContentType(java.lang.String) */ public String[] getContentType(String fieldName) { List<FileItem> items = files.get(fieldName); if (items == null) { return null; } List<String> contentTypes = new ArrayList<String>(items.size()); for (FileItem fileItem : items) { contentTypes.add(fileItem.getContentType()); } return contentTypes.toArray(new String[contentTypes.size()]); }
/* * (non-Javadoc) * * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getContentType(java.lang.String) */ @Override public String[] getContentType(String fieldName) { List<FileItem> items = files.get(fieldName); if (items == null) { return null; } List<String> contentTypes = new ArrayList<String>(items.size()); for (int i = 0; i < items.size(); i++) { FileItem fileItem = items.get(i); contentTypes.add(fileItem.getContentType()); } return (String[]) contentTypes.toArray(new String[contentTypes.size()]); }
/** * Uploads the file containing the video and that is identified by the specified field name. * * @param items the items of the form. One of them is containg the video file. * @param itemKey the key of the item containing the video. * @param pageContext the context of the page displaying the form. * @throws Exception if an error occurs while uploading the video file. * @return the identifier of the uploaded attached video file. */ private String uploadVideoFile( final List<FileItem> items, final String itemKey, final PagesContext pageContext) throws Exception { String attachmentId = ""; FileItem item = FileUploadUtil.getFile(items, itemKey); if (!item.isFormField()) { String componentId = pageContext.getComponentId(); String userId = pageContext.getUserId(); String objectId = pageContext.getObjectId(); String logicalName = item.getName(); long size = item.getSize(); if (StringUtil.isDefined(logicalName)) { if (!FileUtil.isWindows()) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info( "form", "VideoFieldDisplayer.uploadVideoFile", "root.MSG_GEN_PARAM_VALUE", "fullFileName on Unix = " + logicalName); } logicalName = logicalName.substring( logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); String type = FileRepositoryManager.getFileExtension(logicalName); String mimeType = item.getContentType(); String physicalName = Long.toString(System.currentTimeMillis()) + "." + type; File dir = getVideoPath(componentId, physicalName); item.write(dir); AttachmentDetail attachmentDetail = createAttachmentDetail( objectId, componentId, physicalName, logicalName, mimeType, size, VideoFieldDisplayer.CONTEXT_FORM_VIDEO, userId); attachmentDetail = AttachmentController.createAttachment(attachmentDetail, true); attachmentId = attachmentDetail.getPK().getId(); } } return attachmentId; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String error = ""; String contextPath = getServletContext().getContextPath(); String funcNum = req.getParameter("CKEditorFuncNum"); resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); PropertyProcessor instance = PropertyProcessor.getInstance(contextPath); CkProperties properties = instance.getProperties(); FileItem fileItem = fetchFileFromRequest(req, properties.getUploadFieldName()); String contentType = fileItem.getContentType(); String output = ""; if (contentType.contains("image")) { byte[] bytes = fileItem.get(); Dimensions currentDimensions = ImageUtil.getCurrentDimensions(bytes); BufferedImage displayImage = createDisplayImage(properties, bytes, currentDimensions); BufferedImage thumbnailImage = createThumbnailImage(properties, bytes, currentDimensions); FilePathStrategy strategy = properties.getStrategy(); FilePaths paths = strategy.createPaths(fileItem.getName(), properties); ImageUtil.saveImage(displayImage, paths.getDisplayImageServerPath()); ImageUtil.saveImage(thumbnailImage, paths.getThumbnailServerpath()); output = String.format( "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');</script>", funcNum, paths.getDisplayImageRelativeUrl(), error); } else { output = String.format( "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');</script>", funcNum, "", properties.getNoImageError()); } writer.write(output); }
public static void init(HttpServletRequest request) throws Exception { reset(); if (ServletFileUpload.isMultipartContent(request)) { isUpload = true; try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { fileName = new File(item.getName()).getName(); int index = fileName.lastIndexOf("."); // file extension index if (!item.getContentType().equals("text/plain")) { uploadErrMsg = "Variant file only support text/plain file format."; return; } fileName = fileName.substring(0, index) + "_" + System.currentTimeMillis() + fileName.substring(index); File file = new File(rootPath + File.separator + fileName); filePath = file.getAbsolutePath(); item.write(file); checkFileSize(file); } } } catch (Exception ex) { uploadErrMsg = "File Upload Failed due to " + ex; } } }
/** * The doPost method of the servlet. <br> * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String originalName = ""; String savePath = this.getServletConfig().getServletContext().getRealPath("/"); savePath = savePath + "/Accessory/"; File f1 = new File(savePath); if (!f1.exists()) { f1.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8"); List fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException ex) { return; } Iterator<FileItem> it = fileList.iterator(); String name = ""; String extName = ""; while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { name = item.getName(); long size = item.getSize(); String type = item.getContentType(); System.out.println(size + " " + type); if (name == null || name.trim().equals("")) { continue; } // 扩展名格式: if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } originalName = name; File file = null; do { // 生成文件名: name = UUID.randomUUID().toString(); file = new File(savePath + name + extName); } while (file.exists()); File saveFile = new File(savePath + name + extName); try { item.write(saveFile); } catch (Exception e) { e.printStackTrace(); } } } JSONObject json = new JSONObject(); json.put("address", "Accessory/" + name + extName); json.put("filename", originalName); out.print(name + extName); out.flush(); out.close(); }
@SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getSession().isNew()) { response.sendRedirect(request.getContextPath() + "/salir.jsp"); } int numEmpleado = request.getSession().getAttribute("numEmp") != null ? Integer.parseInt(request.getSession().getAttribute("numEmp").toString()) : -1; int areaSeguimiento = request.getSession().getAttribute("cveAreaUsr") != null ? Integer.parseInt(request.getSession().getAttribute("cveAreaUsr").toString()) : -1; String filename = ""; SeguimientoAreaDTO seguimiento = new SeguimientoAreaDTO(); ArchivoDTO archivoAnexo = new ArchivoDTO(); try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Archivos input text, textarea, checkbox, hidden, radiobutton, // select if (item.getFieldName().equals("folioBuzon")) { seguimiento.setFolioBuzon(Integer.parseInt(item.getString())); } else if (item.getFieldName().equals("tipoFolio")) { seguimiento.setTipoFolio(Integer.parseInt(item.getString())); } else if (item.getFieldName().equals("evaluacion")) { seguimiento.setCveStatus(Integer.parseInt(item.getString())); } else if (item.getFieldName().equals("marca")) { seguimiento.setCveMarca(Integer.parseInt(item.getString())); } else if (item.getFieldName().equals("v_accionimpl_seg")) { seguimiento.setAccionImplementada(item.getString()); } else if (item.getFieldName().equals("v_observacion_seg")) { seguimiento.setObservaciones(item.getString()); } else if (item.getFieldName().equals("contactaNuevamente")) { // seguimiento.setRequiereContacto(item.getString().equals("on") ? 1 : 0); seguimiento.setRequiereContacto(Integer.parseInt(item.getString())); } } else { // input file filename = FilenameUtils.getName(item.getName()); if (item.getSize() > THRESHOLD_SIZE) { throw new BuzonException( "El archivo <b>" + filename + "</b> contiene <b>" + item.getSize() + "</b> Bytes rebasando los 5MB permitidos, <br>favor de verificar."); } archivoAnexo.setNbArchivo(filename); archivoAnexo.setTpArchivo(filename.trim().equals("") ? "" : item.getContentType()); archivoAnexo.setArchivoInputStream(item.getInputStream()); } } seguimiento.setNumEmpCaptura(numEmpleado); seguimiento.setCveAreaSeguimiento(areaSeguimiento); seguimiento.setArchivo(archivoAnexo); areaAsignModel.guardarSeguimientoAreaAsignada(seguimiento); request.setAttribute("msg", "Buzón atendido exitósamente"); getServletContext().getRequestDispatcher(PAG_OK).forward(request, response); } catch (BuzonException be) { logger.error(be.toString()); request.setAttribute("msg", be.getMensajeUsuario()); getServletContext().getRequestDispatcher(PAG_ERROR).forward(request, response); } catch (Exception ex) { logger.error(ex.toString()); request.setAttribute("msg", ex.getMessage()); getServletContext().getRequestDispatcher(PAG_ERROR).forward(request, response); } }
public String getContentType() { return wrapped.getContentType(); }
@Override public SaveOrApproveEventRpcResponse execute(SaveEventRpcRequest request, EventContext context) { if (request.getEvent().hasContact() && (request.getEvent().getContact().getExternalId() == null || !request .getEvent() .getContact() .getExternalId() .equals(context.getUser().getExternalUserId()))) { switch (request.getEvent().getType()) { case Special: case Course: case Unavailabile: context.checkPermission(Right.EventLookupContact); } } if (request.getEvent().getId() == null) { // new even switch (request.getEvent().getType()) { case Special: context.checkPermission(Right.EventAddSpecial); break; case Course: context.checkPermission(Right.EventAddCourseRelated); break; case Unavailabile: context.checkPermission(Right.EventAddUnavailable); break; default: throw context.getException(); } } else { // existing event context.checkPermission(request.getEvent().getId(), "Event", Right.EventEdit); } // Check main contact email if (request.getEvent().hasContact() && request.getEvent().getContact().hasEmail()) { try { new InternetAddress(request.getEvent().getContact().getEmail(), true); } catch (AddressException e) { throw new GwtRpcException( MESSAGES.badEmailAddress(request.getEvent().getContact().getEmail(), e.getMessage())); } } // Check additional emails if (request.getEvent().hasEmail()) { String suffix = ApplicationProperty.EmailDefaultAddressSuffix.value(); for (String address : request.getEvent().getEmail().split("[\n,]")) { String email = address.trim(); if (email.isEmpty()) continue; if (suffix != null && email.indexOf('@') < 0) email += suffix; try { new InternetAddress(email, true); } catch (AddressException e) { throw new GwtRpcException(MESSAGES.badEmailAddress(address, e.getMessage())); } } } org.hibernate.Session hibSession = SessionDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try { Session session = SessionDAO.getInstance().get(request.getSessionId(), hibSession); Date now = new Date(); Event event = null; if (request.getEvent().getId() != null) { event = EventDAO.getInstance().get(request.getEvent().getId(), hibSession); } else { switch (request.getEvent().getType()) { case Special: event = new SpecialEvent(); break; case Course: event = new CourseEvent(); break; case Unavailabile: event = new UnavailableEvent(); break; default: throw new GwtRpcException( MESSAGES.failedSaveEventWrongType(request.getEvent().getType().getName(CONSTANTS))); } } SaveOrApproveEventRpcResponse response = new SaveOrApproveEventRpcResponse(); event.setEventName(request.getEvent().getName()); if (event.getEventName() == null || event.getEventName().isEmpty() && request.getEvent().getType() == EventType.Unavailabile) event.setEventName(MESSAGES.unavailableEventDefaultName()); event.setEmail(request.getEvent().getEmail()); if (context.hasPermission(Right.EventSetExpiration) || event.getExpirationDate() != null) event.setExpirationDate(request.getEvent().getExpirationDate()); event.setSponsoringOrganization( request.getEvent().hasSponsor() ? SponsoringOrganizationDAO.getInstance() .get(request.getEvent().getSponsor().getUniqueId()) : null); if (event instanceof UnavailableEvent) { } else if (event instanceof SpecialEvent) { event.setMinCapacity(request.getEvent().getMaxCapacity()); event.setMaxCapacity(request.getEvent().getMaxCapacity()); } if (event.getAdditionalContacts() == null) { event.setAdditionalContacts(new HashSet<EventContact>()); } if (context.hasPermission(Right.EventLookupContact)) { Set<EventContact> existingContacts = new HashSet<EventContact>(event.getAdditionalContacts()); event.getAdditionalContacts().clear(); if (request.getEvent().hasAdditionalContacts()) for (ContactInterface c : request.getEvent().getAdditionalContacts()) { if (c.getExternalId() == null) continue; EventContact contact = null; for (EventContact x : existingContacts) if (c.getExternalId().equals(x.getExternalUniqueId())) { contact = x; break; } if (contact == null) { contact = (EventContact) hibSession .createQuery("from EventContact where externalUniqueId = :externalId") .setString("externalId", c.getExternalId()) .setMaxResults(1) .uniqueResult(); } if (contact == null) { contact = new EventContact(); contact.setExternalUniqueId(c.getExternalId()); contact.setFirstName(c.getFirstName()); contact.setMiddleName(c.getMiddleName()); contact.setLastName(c.getLastName()); contact.setAcademicTitle(c.getAcademicTitle()); contact.setEmailAddress(c.getEmail()); contact.setPhone(c.getPhone()); hibSession.save(contact); } event.getAdditionalContacts().add(contact); } } EventContact main = event.getMainContact(); if (main == null || main.getExternalUniqueId() == null || !main.getExternalUniqueId().equals(request.getEvent().getContact().getExternalId())) { main = (EventContact) hibSession .createQuery("from EventContact where externalUniqueId = :externalId") .setString("externalId", request.getEvent().getContact().getExternalId()) .setMaxResults(1) .uniqueResult(); if (main == null) { main = new EventContact(); main.setExternalUniqueId(request.getEvent().getContact().getExternalId()); } } main.setFirstName(request.getEvent().getContact().getFirstName()); main.setMiddleName(request.getEvent().getContact().getMiddleName()); main.setLastName(request.getEvent().getContact().getLastName()); main.setAcademicTitle(request.getEvent().getContact().getAcademicTitle()); main.setEmailAddress(request.getEvent().getContact().getEmail()); main.setPhone(request.getEvent().getContact().getPhone()); hibSession.saveOrUpdate(main); event.setMainContact(main); if (event.getNotes() == null) event.setNotes(new HashSet<EventNote>()); if (event.getMeetings() == null) event.setMeetings(new HashSet<Meeting>()); Set<Meeting> remove = new HashSet<Meeting>(event.getMeetings()); TreeSet<Meeting> createdMeetings = new TreeSet<Meeting>(); Set<Meeting> cancelledMeetings = new TreeSet<Meeting>(); Set<Meeting> updatedMeetings = new TreeSet<Meeting>(); for (MeetingInterface m : request.getEvent().getMeetings()) { Meeting meeting = null; if (m.getApprovalStatus() == ApprovalStatus.Deleted) { if (!context.hasPermission(meeting, Right.EventMeetingDelete) && context.hasPermission(meeting, Right.EventMeetingCancel)) { // Cannot delete, but can cancel --> cancel the meeting instead m.setApprovalStatus(ApprovalStatus.Cancelled); } else { continue; } } if (m.getId() != null) for (Iterator<Meeting> i = remove.iterator(); i.hasNext(); ) { Meeting x = i.next(); if (m.getId().equals(x.getUniqueId())) { meeting = x; i.remove(); break; } } if (meeting != null) { if (m.getApprovalStatus().ordinal() != meeting.getApprovalStatus()) { switch (m.getApprovalStatus()) { case Cancelled: switch (meeting.getEvent().getEventType()) { case Event.sEventTypeFinalExam: case Event.sEventTypeMidtermExam: if (!context.hasPermission(meeting, Right.EventMeetingCancelExam)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; case Event.sEventTypeClass: if (!context.hasPermission(meeting, Right.EventMeetingCancelClass)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; default: if (!context.hasPermission(meeting, Right.EventMeetingCancel)) throw new GwtRpcException( MESSAGES.failedApproveEventNoRightsToCancel(toString(meeting))); break; } meeting.setStatus(Meeting.Status.CANCELLED); meeting.setApprovalDate(now); hibSession.update(meeting); cancelledMeetings.add(meeting); response.addCancelledMeeting(m); } } else { if (m.getStartOffset() != (meeting.getStartOffset() == null ? 0 : meeting.getStartOffset()) || m.getEndOffset() != (meeting.getStopOffset() == null ? 0 : meeting.getStopOffset())) { if (!context.hasPermission(meeting, Right.EventMeetingEdit)) throw new GwtRpcException( MESSAGES.failedSaveEventCanNotEditMeeting(toString(meeting))); meeting.setStartOffset(m.getStartOffset()); meeting.setStopOffset(m.getEndOffset()); hibSession.update(meeting); response.addUpdatedMeeting(m); updatedMeetings.add(meeting); } } } else { response.addCreatedMeeting(m); meeting = new Meeting(); meeting.setEvent(event); Location location = null; if (m.hasLocation()) { if (m.getLocation().getId() != null) location = LocationDAO.getInstance().get(m.getLocation().getId(), hibSession); else if (m.getLocation().getName() != null) location = Location.findByName( hibSession, request.getSessionId(), m.getLocation().getName()); } if (location == null) throw new GwtRpcException(MESSAGES.failedSaveEventNoLocation(toString(m))); meeting.setLocationPermanentId(location.getPermanentId()); meeting.setStatus(Meeting.Status.PENDING); meeting.setApprovalDate(null); if (!context.hasPermission(location, Right.EventLocation)) throw new GwtRpcException(MESSAGES.failedSaveEventWrongLocation(m.getLocationName())); if (request.getEvent().getType() == EventType.Unavailabile && !context.hasPermission(location, Right.EventLocationUnavailable)) throw new GwtRpcException( MESSAGES.failedSaveCannotMakeUnavailable(m.getLocationName())); if (m.getApprovalStatus() == ApprovalStatus.Approved && context.hasPermission(location, Right.EventLocationApprove)) { meeting.setStatus(Meeting.Status.APPROVED); meeting.setApprovalDate(now); } if (context.isPastOrOutside(m.getMeetingDate())) throw new GwtRpcException( MESSAGES.failedSaveEventPastOrOutside(getDateFormat().format(m.getMeetingDate()))); if (!context.hasPermission(location, Right.EventLocationOverbook)) { List<MeetingConflictInterface> conflicts = computeConflicts(hibSession, m, event.getUniqueId()); if (!conflicts.isEmpty()) throw new GwtRpcException( MESSAGES.failedSaveEventConflict(toString(m), toString(conflicts.get(0)))); } m.setApprovalDate(meeting.getApprovalDate()); m.setApprovalStatus(meeting.getApprovalStatus()); meeting.setStartPeriod(m.getStartSlot()); meeting.setStopPeriod(m.getEndSlot()); meeting.setStartOffset(m.getStartOffset()); meeting.setStopOffset(m.getEndOffset()); meeting.setClassCanOverride(true); meeting.setMeetingDate(m.getMeetingDate()); event.getMeetings().add(meeting); createdMeetings.add(meeting); } // automatic approval if (meeting.getApprovalDate() == null) { switch (request.getEvent().getType()) { case Unavailabile: case Class: case FinalExam: case MidtermExam: meeting.setStatus(Meeting.Status.APPROVED); meeting.setApprovalDate(now); break; } } } if (!remove.isEmpty()) { for (Iterator<Meeting> i = remove.iterator(); i.hasNext(); ) { Meeting m = i.next(); if (!context.hasPermission(m, Right.EventMeetingDelete)) { if (m.getStatus() == Status.CANCELLED || m.getStatus() == Status.REJECTED) { i.remove(); continue; } throw new GwtRpcException(MESSAGES.failedSaveEventCanNotDeleteMeeting(toString(m))); } MeetingInterface meeting = new MeetingInterface(); meeting.setId(m.getUniqueId()); meeting.setMeetingDate(m.getMeetingDate()); meeting.setDayOfWeek(Constants.getDayOfWeek(m.getMeetingDate())); meeting.setStartTime(m.getStartTime().getTime()); meeting.setStopTime(m.getStopTime().getTime()); meeting.setDayOfYear( CalendarUtils.date2dayOfYear(session.getSessionStartYear(), m.getMeetingDate())); meeting.setStartSlot(m.getStartPeriod()); meeting.setEndSlot(m.getStopPeriod()); meeting.setStartOffset(m.getStartOffset() == null ? 0 : m.getStartOffset()); meeting.setEndOffset(m.getStopOffset() == null ? 0 : m.getStopOffset()); meeting.setPast(context.isPastOrOutside(m.getStartTime())); meeting.setApprovalDate(m.getApprovalDate()); meeting.setApprovalStatus(m.getApprovalStatus()); if (m.getLocation() != null) { ResourceInterface location = new ResourceInterface(); location.setType(ResourceType.ROOM); location.setId(m.getLocation().getUniqueId()); location.setName(m.getLocation().getLabel()); location.setSize(m.getLocation().getCapacity()); location.setRoomType(m.getLocation().getRoomTypeLabel()); location.setBreakTime(m.getLocation().getEffectiveBreakTime()); location.setMessage(m.getLocation().getEventMessage()); location.setIgnoreRoomCheck(m.getLocation().isIgnoreRoomCheck()); meeting.setLocation(location); } response.addDeletedMeeting(meeting); } event.getMeetings().removeAll(remove); } EventInterface.DateFormatter df = new EventInterface.DateFormatter() { Formats.Format<Date> dfShort = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_SHORT); Formats.Format<Date> dfLong = Formats.getDateFormat(Formats.Pattern.DATE_EVENT_LONG); @Override public String formatFirstDate(Date date) { return dfShort.format(date); } @Override public String formatLastDate(Date date) { return dfLong.format(date); } }; FileItem attachment = (FileItem) context.getAttribute(UploadServlet.SESSION_LAST_FILE); boolean attached = false; if (response.hasCreatedMeetings()) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType( event.getUniqueId() == null ? EventNote.sEventNoteTypeCreateEvent : EventNote.sEventNoteTypeAddMeetings); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); if (request.hasMessage()) note.setTextNote(request.getMessage()); note.setMeetings( EventInterface.toString(response.getCreatedMeetings(), CONSTANTS, "\n", df)); note.setAffectedMeetings(createdMeetings); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (response.hasUpdatedMeetings() || (!response.hasCreatedMeetings() && !response.hasDeletedMeetings() && !response.hasCancelledMeetings())) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(EventNote.sEventNoteTypeEditEvent); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); note.setAffectedMeetings(updatedMeetings); if (request.hasMessage()) note.setTextNote(request.getMessage()); if (response.hasUpdatedMeetings()) note.setMeetings( EventInterface.toString(response.getUpdatedMeetings(), CONSTANTS, "\n", df)); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null && !attached) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (response.hasDeletedMeetings()) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(EventNote.sEventNoteTypeDeletion); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); if (request.hasMessage()) note.setTextNote(request.getMessage()); note.setMeetings( EventInterface.toString(response.getDeletedMeetings(), CONSTANTS, "\n", df)); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null && !attached) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (response.hasCancelledMeetings()) { EventNote note = new EventNote(); note.setEvent(event); note.setNoteType(EventNote.sEventNoteTypeCancel); note.setTimeStamp(now); note.setUser(context.getUser().getTrueName()); note.setUserId(context.getUser().getTrueExternalUserId()); note.setAffectedMeetings(cancelledMeetings); if (request.hasMessage()) note.setTextNote(request.getMessage()); note.setMeetings( EventInterface.toString(response.getCancelledMeetings(), CONSTANTS, "\n", df)); event.getNotes().add(note); NoteInterface n = new NoteInterface(); n.setDate(now); n.setMeetings(note.getMeetings()); n.setUser(context.getUser().getTrueName()); n.setType(NoteInterface.NoteType.values()[note.getNoteType()]); n.setNote(note.getTextNote()); if (attachment != null && !attached) { note.setAttachedName(attachment.getName()); note.setAttachedFile(attachment.get()); note.setAttachedContentType(attachment.getContentType()); attached = true; n.setAttachment(attachment.getName()); } response.addNote(n); } if (request.getEvent().getType() == EventType.Course) { CourseEvent ce = (CourseEvent) event; ce.setReqAttendance(request.getEvent().hasRequiredAttendance()); if (ce.getRelatedCourses() == null) ce.setRelatedCourses(new HashSet<RelatedCourseInfo>()); else ce.getRelatedCourses().clear(); if (request.getEvent().hasRelatedObjects()) for (RelatedObjectInterface r : request.getEvent().getRelatedObjects()) { RelatedCourseInfo related = new RelatedCourseInfo(); related.setEvent(ce); if (r.getSelection() != null) { related.setOwnerId(r.getUniqueId()); related.setOwnerType(r.getType().ordinal()); related.setCourse( CourseOfferingDAO.getInstance().get(r.getSelection()[1], hibSession)); } else { switch (r.getType()) { case Course: related.setOwner(CourseOfferingDAO.getInstance().get(r.getUniqueId())); break; case Class: related.setOwner(Class_DAO.getInstance().get(r.getUniqueId())); break; case Config: related.setOwner(InstrOfferingConfigDAO.getInstance().get(r.getUniqueId())); break; case Offering: related.setOwner(InstructionalOfferingDAO.getInstance().get(r.getUniqueId())); break; } } ce.getRelatedCourses().add(related); } } if (event.getUniqueId() == null) { hibSession.save(event); response.setEvent( EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); } else if (event.getMeetings().isEmpty()) { response.setEvent( EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); response.getEvent().setId(null); hibSession.delete(event); } else { hibSession.update(event); response.setEvent( EventDetailBackend.getEventDetail( SessionDAO.getInstance().get(request.getSessionId(), hibSession), event, context)); } tx.commit(); new EventEmail(request, response).send(context); return response; } catch (Exception ex) { tx.rollback(); if (ex instanceof GwtRpcException) throw (GwtRpcException) ex; throw new GwtRpcException(ex.getMessage(), ex); } }
protected void myDoGetPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ajaxUpdateResult = ""; try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { ajaxUpdateResult += "Field " + item.getFieldName() + " with value: " + item.getString() + " is successfully read\n\r"; } else { String filename = item.getName(); System.out.println(filename); String imageType = item.getContentType(); System.out.println("context type: " + imageType); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String theImageExt = ""; String sendText = ""; if (MyString.myContains(imageType, MyImageEnum.JPEG.toString())) { theImageExt = MyImageEnum.JPEG.toString(); } else if (MyString.myContains(imageType, MyImageEnum.JPG.toString())) { theImageExt = MyImageEnum.JPEG.toString(); } else if (MyString.myContains(imageType, MyImageEnum.PNG.toString())) { theImageExt = MyImageEnum.PNG.toString(); } else if (MyString.myContains(imageType, MyImageEnum.GIF.toString())) { theImageExt = MyImageEnum.GIF.toString(); } if (myMainHelper.getUserId() != null && !theImageExt.equals("")) { InputStream in = item.getInputStream(); BufferedImage newImageLarge = MyImage.resizeImage(in, maxWidthLarge, maxHeightLarge); BufferedImage newImageSmall = MyImage.resizeImage(newImageLarge, maxWidthSmall, maxHeightSmall); String pathToDynamicImages = "includes/dynamic_content/images/mate/user_image/"; String fieNameLarge = myMainHelper.getUserId() + "_large_" + MyDate.myGetDateString() + "." + theImageExt; String fieNameSmall = myMainHelper.getUserId() + "_small_" + MyDate.myGetDateString() + "." + theImageExt; String fieNameLargeFull = MyInit.webAppMainPath + pathToDynamicImages + fieNameLarge; String fieNameSmallFull = MyInit.webAppMainPath + pathToDynamicImages + fieNameSmall; System.out.println(fieNameLarge); MyImage.saveImage(newImageLarge, fieNameLargeFull); MyImage.saveImage(newImageSmall, fieNameSmallFull); sendText += "<img id='the_image_tag' src='" + pathToDynamicImages + fieNameLarge + "'>"; System.out.println(sendText); } else { } response.getWriter().write(sendText); } } } catch (FileUploadException e) { throw new ServletException("Parsing file upload failed.", e); } }
private void executeDeploy(HttpServletRequest req, HttpServletResponse resp) throws IOException { String contentType = null; File packageFile = null; FileItem item = null; String serviceName = null; String fieldName = null; String token = ""; boolean forward = false; try { // checking if uploaded file is a file descriptor DiskFileUpload upload = new DiskFileUpload(); List items = upload.parseRequest(req); Iterator iter = items.iterator(); while (iter.hasNext()) { // geting item item = (FileItem) iter.next(); contentType = item.getContentType(); fieldName = item.getFieldName(); if ((fieldName != null && fieldName.equals("importFile")) || (contentType != null && contentType.contains(ZIP_DEPLOY_PACKAGE_MIME_TYPE))) { packageFile = new File(System.getProperty("java.io.tmpdir"), item.getName()); item.write(packageFile); } else if (fieldName.equals("newName")) { serviceName = item.getString(); } else if (fieldName.equals("authToken")) { token = item.getString(); } else if (fieldName.equals("forwardToPage")) { forward = true; } } String deployAdminToken = Toolbox.getInstance().getDeployAdminToken(); if (deployAdminToken != null && token.equals(deployAdminToken) == false) { resp.sendError(500); } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); return; } if (serviceName == null || serviceName.equals("")) { serviceName = packageFile.getName(); serviceName = serviceName.substring(0, serviceName.lastIndexOf('.')); } try { ServiceManager serviceManager; serviceManager = ServiceManager.getInstance(); serviceManager.deployService(packageFile, serviceName); } catch (Exception e) { resp.sendRedirect( "selectImportOrCreate.jsp?serviceName=" + serviceName + "&error=serviceexist"); return; } if (forward == true) { resp.sendRedirect("serviceConfiguration.jsp?serviceName=" + serviceName); } else { resp.setStatus(HttpServletResponse.SC_OK); } }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { long start = System.currentTimeMillis(); ServletContext ctx = getServletContext(); if (req.getCharacterEncoding() == null) req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); String accept = req.getHeader("Accept"); SerializationFormat formatter = Listener.getSerializationFormat(accept); if (formatter == null) { sendError( ctx, req, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "no known mime type in Accept header"); return; } PrintWriter out_r = resp.getWriter(); String resp_msg = ""; // check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { sendError(ctx, req, resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "no file upload"); return; } // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(req); // bulk load options int threads = -1; String format = "nt"; int batchSizeMB = 1; // get store AbstractCassandraRdfHector crdf = (AbstractCassandraRdfHector) ctx.getAttribute(Listener.STORE); crdf.setBatchSize(batchSizeMB); // Process the uploaded items Iterator iter = items.iterator(); String a = ""; String graph = ""; boolean a_exists = false; String file = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); if (name.equals("g")) { a_exists = true; a = new String(value); // escape if the accept header is not text/plain graph = new String(a); if (formatter.getContentType().equals("text/html")) graph = escapeHtml(a); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // Process a file upload InputStream uploadedStream = item.getInputStream(); // write the inputStream to a FileOutputStream file = "/tmp/upload_bulkload_" + UUID.randomUUID(); OutputStream out = new FileOutputStream(new File(file)); int read = 0; byte[] bytes = new byte[1024]; while ((read = uploadedStream.read(bytes)) != -1) { out.write(bytes, 0, read); } uploadedStream.close(); out.flush(); out.close(); resp_msg += "Bulkload " + fileName + ", size " + sizeInBytes; } } if (!a_exists || a == null || a.isEmpty()) { sendError( ctx, req, resp, HttpServletResponse.SC_BAD_REQUEST, "Please pass also the graph name as 'g' parameter"); } else { if (!a.startsWith("<") || !a.endsWith(">")) { sendError( ctx, req, resp, HttpServletResponse.SC_BAD_REQUEST, "Please pass a resource as the graph name."); return; } // load here // note: if threads==-1, it will be then set to the number of hosts if (crdf.bulkLoad(new File(file), format, threads, Store.encodeKeyspace(a)) == 1) sendError( ctx, req, resp, HttpServletResponse.SC_CONFLICT, "Graph " + graph + " does not exist yet. Please create it before bulk loading."); else { resp_msg = "Graph " + graph + " time " + (System.currentTimeMillis() - start) + "ms"; sendResponse(ctx, req, resp, HttpServletResponse.SC_BAD_REQUEST, resp_msg); _log.info(resp_msg); } } // delete the tmp file new File(file).delete(); out_r.println(resp_msg); out_r.close(); } catch (FileUploadException ex) { ex.printStackTrace(); return; } catch (StoreException ex) { ex.printStackTrace(); return; } return; }
/** * Process the blog entries * * @param httpServletRequest Request * @param httpServletResponse Response * @param user {@link org.blojsom.blog.BlogUser} instance * @param context Context * @param entries Blog entries retrieved for the particular request * @return Modified set of blog entries * @throws BlojsomPluginException If there is an error processing the blog entries */ public BlogEntry[] process( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlogUser user, Map context, BlogEntry[] entries) throws BlojsomPluginException { if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) { httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE); return entries; } String username = getUsernameFromSession(httpServletRequest, user.getBlog()); if (!checkPermission(user, null, username, FILE_UPLOAD_PERMISSION)) { httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE); addOperationResultMessage(context, "You are not allowed to upload files"); return entries; } File resourceDirectory = new File( _blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/"); String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest); if (BlojsomUtils.checkNullOrBlank(action)) { _logger.debug("User did not request edit action"); httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE); } else if (PAGE_ACTION.equals(action)) { _logger.debug("User requested file upload page"); httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } else if (UPLOAD_FILE_ACTION.equals(action)) { _logger.debug("User requested file upload action"); // Create a new disk file upload and set its parameters DiskFileUpload diskFileUpload = new DiskFileUpload(); diskFileUpload.setRepositoryPath(_temporaryDirectory); diskFileUpload.setSizeThreshold(_maximumMemorySize); diskFileUpload.setSizeMax(_maximumUploadSize); try { List items = diskFileUpload.parseRequest(httpServletRequest); Iterator itemsIterator = items.iterator(); while (itemsIterator.hasNext()) { FileItem item = (FileItem) itemsIterator.next(); // Check for the file upload form item if (!item.isFormField()) { String itemNameWithoutPath = BlojsomUtils.getFilenameFromPath(item.getName()); _logger.debug( "Found file item: " + itemNameWithoutPath + " of type: " + item.getContentType()); // Is it one of the accepted file types? String fileType = item.getContentType(); boolean isAcceptedFileType = _acceptedFileTypes.containsKey(fileType); String extension = BlojsomUtils.getFileExtension(itemNameWithoutPath); boolean isAcceptedFileExtension = true; for (int i = 0; i < _invalidFileExtensions.length; i++) { String invalidFileExtension = _invalidFileExtensions[i]; if (itemNameWithoutPath.indexOf(invalidFileExtension) != -1) { isAcceptedFileExtension = false; break; } } // If so, upload the file to the resources directory if (isAcceptedFileType && isAcceptedFileExtension) { if (!resourceDirectory.exists()) { if (!resourceDirectory.mkdirs()) { _logger.error( "Unable to create resource directory for user: "******"Unable to create resource directory"); return entries; } } File resourceFile = new File( _blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/" + itemNameWithoutPath); try { item.write(resourceFile); } catch (Exception e) { _logger.error(e); addOperationResultMessage( context, "Unknown error in file upload: " + e.getMessage()); } String resourceURL = user.getBlog().getBlogBaseURL() + _blojsomConfiguration.getResourceDirectory() + user.getId() + "/" + item.getName(); _logger.debug("Successfully uploaded resource file: " + resourceFile.toString()); addOperationResultMessage( context, "Successfully upload resource file: " + item.getName() + ". <p></p>Here is a link to <a href=\"" + resourceURL + "\">" + item.getName() + "</a>. Right-click and copy the link to the resource to use in a blog entry."); } else { if (!isAcceptedFileExtension) { _logger.error("Upload file does not have an accepted extension: " + extension); addOperationResultMessage( context, "Upload file does not have an accepted extension: " + extension); } else { _logger.error( "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType()); addOperationResultMessage( context, "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType()); } } } } } catch (FileUploadException e) { _logger.error(e); addOperationResultMessage(context, "Unknown error in file upload: " + e.getMessage()); } httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } else if (DELETE_UPLOAD_FILES.equals(action)) { String[] filesToDelete = httpServletRequest.getParameterValues(FILE_TO_DELETE); if (filesToDelete != null && filesToDelete.length > 0) { File deletedFile; for (int i = 0; i < filesToDelete.length; i++) { String fileToDelete = filesToDelete[i]; deletedFile = new File(resourceDirectory, fileToDelete); if (!deletedFile.delete()) { _logger.debug("Unable to delete resource file: " + deletedFile.toString()); } } addOperationResultMessage( context, "Deleted " + filesToDelete.length + " file(s) from resources directory"); } httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } // Create a list of files in the user's resource directory Map resourceFilesMap = null; if (resourceDirectory.exists()) { File[] resourceFiles = resourceDirectory.listFiles(); if (resourceFiles != null) { resourceFilesMap = new HashMap(resourceFiles.length); for (int i = 0; i < resourceFiles.length; i++) { File resourceFile = resourceFiles[i]; resourceFilesMap.put(resourceFile.getName(), resourceFile.getName()); } } } else { resourceFilesMap = new HashMap(); } resourceFilesMap = new TreeMap(resourceFilesMap); context.put(PLUGIN_ADMIN_FILE_UPLOAD_FILES, resourceFilesMap); return entries; }
/** Returns the content type passed by the browser or <code>null</code> if not defined. */ public String getMediaType() { return fileItem.getContentType(); }
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @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 { String id_book = "", len = ""; // Imposto il content type della risposta e prendo l'output response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // La dimensione massima di ogni singolo file su system int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB // Dimensione massima della request int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB // Cartella temporanea File cartellaTemporanea = new File("C:\\tempo"); try { // Creo un factory per l'accesso al filesystem DiskFileItemFactory factory = new DiskFileItemFactory(); // Setto la dimensione massima di ogni file, opzionale factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte); // Setto la cartella temporanea, Opzionale factory.setRepository(cartellaTemporanea); // Istanzio la classe per l'upload ServletFileUpload upload = new ServletFileUpload(factory); // Setto la dimensione massima della request, opzionale upload.setSizeMax(dimensioneMassimaDellaRequestInByte); // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con // tutti i field sia di tipo file che gli altri List<FileItem> items = upload.parseRequest(request); /* * * Giro per tutti i campi inviati */ for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); // Controllo se si tratta di un campo di input normale if (item.isFormField()) { // Prendo solo il nome e il valore String name = item.getFieldName(); String value = item.getString(); if (name.equals("id_book")) { id_book = value; } if (name.equals("len")) { len = value; } } // Se si stratta invece di un file ho varie possibilità else { // Dopo aver ripreso tutti i dati disponibili String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // scrivo direttamente su filesystem File uploadedFile = new File("/Users/Babol/Desktop/dVruhero/aMuseWebsite/web/userPhoto/" + fileName); // Solo se veramente ho inviato qualcosa if (item.getSize() > 0) { item.write(uploadedFile); DBconnection.EditCoverBook(fileName, Integer.parseInt(id_book)); } } } // out.println("</body>"); // out.println("</html>"); } catch (Exception ex) { System.out.println("Errore: " + ex.getMessage()); } finally { if (len.equals("ita")) response.sendRedirect("modify_book.jsp?id_book=" + id_book); else response.sendRedirect("modify_book_eng.jsp?id_book=" + id_book); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // InputStream in = request.getInputStream(); // Reader reader = new InputStreamReader(in); // BufferedReader bufferedReader = new BufferedReader(reader); // String str = null; // while ((str = bufferedReader.readLine()) != null) { // System.out.println(str); // } // 1. 得到 FileItem 的集合 items // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // FileCleaningTracker fileCleaningTracker = // FileCleanerCleanup.getFileCleaningTracker(getServletContext()); // factory.setFileCleaningTracker(fileCleaningTracker); // Set factory constraints // 超过500k写到临时文件里 factory.setSizeThreshold(1024 * 500); File tempDirectory = new File("d:\\tempDirectory"); if (!tempDirectory.exists()) { tempDirectory.createNewFile(); } factory.setRepository(tempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // 设置总的大小,(这里不能超过5M) upload.setSizeMax(1024 * 1024 * 5); // Parse the request try { List<FileItem> /* FileItem */ items = upload.parseRequest(request); // 2. 遍历 items: for (FileItem item : items) { // 若是一个一般的表单域, 打印信息 if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); System.out.println(name + ": " + value); } else { // 若是文件域则把文件保存到 d:\\files 目录下. String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); long sizeInBytes = item.getSize(); System.out.println(fieldName); // 原始文件名 System.out.println(fileName); System.out.println(contentType); System.out.println(sizeInBytes); // 输入流 InputStream in = item.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; fileName = "d:\\files\\" + fileName; System.out.println(fileName); if (!new File(fieldName).exists()) { new File(fieldName).createNewFile(); } OutputStream out = new FileOutputStream(fileName); while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
protected void processUploadedFile(FileItem item, String projectName) throws Exception { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); // boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (fieldName == null || !fieldName.equals("scormFile") || fileName == null || !fileName.endsWith(".scorm.zip") || !"application/zip".equals(contentType)) { status = "error"; err = "Tipus de fitxer incorrecte!"; } else if (sizeInBytes > (quota - userSpace.currentSize)) { status = "error"; err = "Heu excedit l'espai disponible!"; } else { // Get a valid project name if (projectName == null || "".equals(projectName)) { projectName = fileName.substring(0, fileName.indexOf('.')); } projectName = UserProject.getValidName(projectName); // Reset project if exists userSpace.removeProject(projectName); prj = new UserProject(projectName, userSpace); String prjBase = prj.prjRoot.getCanonicalPath() + File.separator; // Treat input as a ZIP stream ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream())); ZipEntry entry; boolean interrupted = false; int fileCount = 0; while ((entry = zis.getNextEntry()) != null) { // Process files File entryFile = new File(prj.prjRoot, entry.getName()); if (!entryFile.getCanonicalPath().startsWith(prjBase)) { // File is out of project's directory prj.clean(); interrupted = true; break; } if (entry.isDirectory()) { entryFile.mkdirs(); } else { entryFile.getParentFile().mkdirs(); IOUtils.copy(zis, new FileOutputStream(entryFile)); fileCount++; } } zis.close(); // Add project to collection userSpace.addProject(prj); if (interrupted) { status = "error"; err = "Nom de fitxer incorrecte dins del fitxer ZIP"; } else if (fileCount == 0) { status = "error"; err = "El fitxer no tenia cap contingut vàlid"; } else { status = "ok"; } } }