List of usage examples for org.apache.commons.fileupload.util Streams copy
public static long copy(InputStream pInputStream, OutputStream pOutputStream, boolean pClose) throws IOException
From source file:net.formio.servlet.MockServletRequests.java
/** * Creates new servlet request that contains given resource as multi part. * @param paramName// w ww .j a va 2 s . com * @param resourceName * @return */ public static MockHttpServletRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockHttpServletRequest request = new MockHttpServletRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockServletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); request.setMethod("POST"); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:net.formio.portlet.MockPortletRequests.java
/** * Creates new portlet request that contains given resource as multi part. * @param paramName/*w ww .j av a 2 s. c o m*/ * @param resourceName * @return */ public static MockMultipartActionRequest newRequest(String paramName, String resourceName, String mimeType) { try { MockMultipartActionRequest request = new MockMultipartActionRequest(); // Load resource being uploaded ByteArrayOutputStream bos = new ByteArrayOutputStream(); Streams.copy(MockPortletRequests.class.getResourceAsStream(resourceName), bos, true); byte[] fileContent = bos.toByteArray(); // Create part & entity from resource Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent), mimeType, (String) null) }; MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new PostMethod().getParams()); ByteArrayOutputStream requestContent = new ByteArrayOutputStream(); multipartRequestEntity.writeRequest(requestContent); request.setContent(requestContent.toByteArray()); // Set content type of request (important, includes MIME boundary string) String contentType = multipartRequestEntity.getContentType(); request.setContentType(contentType); return request; } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:com.xclinical.mdr.server.impexp.ZipResourceResolver.java
public ZipResourceResolver(InputStream stm) throws IOException { File file = File.createTempFile("mdrres", ".tmp"); FileOutputStream out = new FileOutputStream(file); Streams.copy(stm, out, true); this.file = new ZipFile(file); }
From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // text/html IE?? response.setContentType("text/plain;charset=utf-8"); StringBuffer responseMessage = new StringBuffer("<?xml version=\"1.0\" encoding=\"GB2312\"?>"); responseMessage.append("<root>"); StringBuffer errorMsg = new StringBuffer(responseMessage).append("<result>").append("FAILED") .append("</result>"); String info = ""; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = null;/*from w ww . j av a 2s .com*/ try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { info = "Form field " + name + " with value " + Streams.asString(stream) + " detected."; responseMessage = new StringBuffer(responseMessage).append(errorMsg).append("<info>") .append(info).append("</info>"); finishPrintResponseMsg(response, responseMessage); return; } else { BufferedInputStream inputStream = new BufferedInputStream(stream);// ? String uploadPath = getUploadPath(request, "upload"); if (uploadPath != null) { String fileName = getOutputFileName(item); String outputFilePath = getOutputFilePath(uploadPath, fileName); int widthdist = 72; int heightdist = 72; widthdist = 200; heightdist = 200; BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File(outputFilePath)));// ? Streams.copy(inputStream, outputStream, true); // // stream.close(); reduceImg(inputStream, outputFilePath, outputFilePath, widthdist, heightdist, 0); stream.close(); responseMessage.append("<result>").append("SUCCESS").append("</result>"); responseMessage.append("<info>"); responseMessage.append(fileName); responseMessage.append(info).append("</info>"); } else { responseMessage = errorMsg.append("<info>").append("") .append("</info>"); } } } } catch (Exception e) { e.printStackTrace(); responseMessage = errorMsg.append("<info>").append(":" + e.getMessage()) .append("</info>"); } finishPrintResponseMsg(response, responseMessage); }
From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java
@Override public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try {/*from w ww .jav a 2 s . c o m*/ // We always return xhtml in utf-8 response.setContentType("application/xhtml+xml"); response.setCharacterEncoding("utf-8"); // Default filename just in case none is found in form String filename = defaultFilename; // Commons file upload ServletFileUpload upload = new ServletFileUpload(); // Go through upload items FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // Parse form fields String fieldname = item.getFieldName(); if ("chartFilename".equals(fieldname)) { // Ordering is important in client page! We expect filename BEFORE data. Otherwise filename will be default // See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 // "The parts are sent to the processing agent in the same order the // corresponding controls appear in the document stream." filename = Streams.asString(stream, "utf-8"); } else if ("chartDataXML".equals(fieldname)) { log.info("Doing form bounce"); String filenameAscii = formSafeAscii(filename); String fileNameUtf = formSafeUtfName(filename); String cdh = "attachment; filename=\"" + filenameAscii + "\"; filename*=utf-8''" + fileNameUtf; response.setHeader("Content-Disposition", cdh); ServletOutputStream out = response.getOutputStream(); Streams.copy(stream, out, false); out.flush(); // No more processing needed (prevent BOTH form AND upload from happening) return; } } else { // Handle upload log.info("Doing file bounce"); ServletOutputStream out = response.getOutputStream(); Streams.copy(stream, out, false); out.flush(); // No more processing needed (prevent BOTH form AND upload from happening) return; } } } catch (Exception ex) { throw new ServletException(ex); } }
From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();// w w w . ja v a 2 s . co m } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();//from w ww . j a v a 2 s. c om } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(externalContext, UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.chinarewards.gwt.license.util.FileUploadServlet.java
/** * @param imgsrc//w w w . j a va2 s. co m * * @param imgdist * ? * @param widthdist * * @param heightdist * * @param int benchmark :0,12 * */ public void reduceImg(InputStream inputStream, String outputFilePath, String imgdist, int widthdist, int heightdist, int benchmark) { try { // File srcfile = new File(srcFile); // if (!srcfile.exists()) { // return; // } boolean flag = true; Image srcImage = javax.imageio.ImageIO.read(inputStream); if (srcImage != null) { int width = srcImage.getWidth(null); int height = srcImage.getHeight(null); if (width <= widthdist && height <= heightdist) {// ?? BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File(outputFilePath))); Streams.copy(inputStream, outputStream, true); flag = false; } if (flag) { // float wh = (float) width / (float) height; if (benchmark == 0) { if (wh > 1) { float tmp_heigth = (float) widthdist / wh; BufferedImage tag = new BufferedImage(widthdist, (int) tmp_heigth, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(srcImage, 0, 0, widthdist, (int) tmp_heigth, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } else { float tmp_width = (float) heightdist * wh; BufferedImage tag = new BufferedImage((int) tmp_width, heightdist, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(srcImage, 0, 0, (int) tmp_width, heightdist, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } } if (benchmark == 1) { float tmp_heigth = (float) widthdist / wh; BufferedImage tag = new BufferedImage(widthdist, (int) tmp_heigth, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(srcImage, 0, 0, widthdist, (int) tmp_heigth, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } if (benchmark == 2) { float tmp_width = (float) heightdist * wh; BufferedImage tag = new BufferedImage((int) tmp_width, heightdist, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(srcImage, 0, 0, (int) tmp_width, heightdist, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } } } } catch (IOException ex) { ex.printStackTrace(); } }
From source file:cn.webwheel.ActionSetter.java
@SuppressWarnings("unchecked") public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException { SetterConfig cfg = ai.getSetterConfig(); List<SetterInfo> setters; if (action != null) { Class cls = action.getClass(); setters = setterMap.get(cls);/* ww w . j av a2s .c o m*/ if (setters == null) { synchronized (this) { setters = setterMap.get(cls); if (setters == null) { Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap); map.put(cls, setters = parseSetters(cls)); setterMap = map; } } } } else { setters = Collections.emptyList(); } List<SetterInfo> args = argMap.get(ai.actionMethod); if (args == null) { synchronized (this) { args = argMap.get(ai.actionMethod); if (args == null) { Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap); map.put(ai.actionMethod, args = parseArgs(ai.actionMethod)); argMap = map; } } } if (setters.isEmpty() && args.isEmpty()) return new Object[0]; Map<String, Object> params; try { if (cfg.getCharset() != null) { request.setCharacterEncoding(cfg.getCharset()); } } catch (UnsupportedEncodingException e) { // } if (ServletFileUpload.isMultipartContent(request)) { params = new HashMap<String, Object>(request.getParameterMap()); request.setAttribute(WRPName, params); ServletFileUpload fileUpload = new ServletFileUpload(); if (cfg.getCharset() != null) { fileUpload.setHeaderEncoding(cfg.getCharset()); } if (cfg.getFileUploadSizeMax() != 0) { fileUpload.setSizeMax(cfg.getFileUploadSizeMax()); } if (cfg.getFileUploadFileSizeMax() != 0) { fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax()); } boolean throwe = false; try { FileItemIterator it = fileUpload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { String s = Streams.asString(fis.openStream(), cfg.getCharset()); Object o = params.get(fis.getFieldName()); if (o == null) { params.put(fis.getFieldName(), new String[] { s }); } else if (o instanceof String[]) { String[] ss = (String[]) o; String[] nss = new String[ss.length + 1]; System.arraycopy(ss, 0, nss, 0, ss.length); nss[ss.length] = s; params.put(fis.getFieldName(), nss); } } else if (!fis.getName().isEmpty()) { File tempFile; try { tempFile = File.createTempFile("wfu", null); } catch (IOException e) { throwe = true; throw e; } FileExImpl fileEx = new FileExImpl(tempFile); Object o = params.get(fis.getFieldName()); if (o == null) { params.put(fis.getFieldName(), new FileEx[] { fileEx }); } else if (o instanceof FileEx[]) { FileEx[] ss = (FileEx[]) o; FileEx[] nss = new FileEx[ss.length + 1]; System.arraycopy(ss, 0, nss, 0, ss.length); nss[ss.length] = fileEx; params.put(fis.getFieldName(), nss); } Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true); fileEx.fileName = fis.getName(); fileEx.contentType = fis.getContentType(); } } } catch (FileUploadException e) { if (action instanceof FileUploadExceptionAware) { ((FileUploadExceptionAware) action).setFileUploadException(e); } } catch (IOException e) { if (throwe) { throw e; } } } else { params = request.getParameterMap(); } if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) { for (SetterInfo si : setters) { si.setter.set(action, si.member, params, si.paramName); } } Object[] as = new Object[args.size()]; for (int i = 0; i < as.length; i++) { SetterInfo si = args.get(i); as[i] = si.setter.set(action, null, params, si.paramName); } return as; }
From source file:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java
@Override public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, List<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();// ww w.j a va 2 s .co m } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }