List of usage examples for org.apache.commons.fileupload.portlet PortletFileUpload PortletFileUpload
public PortletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:net.formio.portlet.PortletMultipartRequestParser.java
@Override protected List<FileItem> parseRequest(FileItemFactory fif, long singleFileSizeMax, long totalSizeMax, String defaultEncoding) throws FileUploadException { final PortletFileUpload upload = new PortletFileUpload(fif); configureUpload(upload, singleFileSizeMax, totalSizeMax, defaultEncoding); return upload.parseRequest(request); }
From source file:com.liferay.util.portlet.PortletRequestUtil.java
public static List<DiskFileItem> testMultipartWithCommonsFileUpload(ActionRequest actionRequest) throws Exception { // Check if the given request is a multipart request boolean multiPartContent = PortletFileUpload.isMultipartContent(actionRequest); if (multiPartContent) { _log.info("The given request is a multipart request"); } else {//w w w. j a v a2 s.c o m _log.info("The given request is NOT a multipart request"); } DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); List<DiskFileItem> diskFileItems = portletFileUpload.parseRequest(actionRequest); if (_log.isInfoEnabled()) { _log.info("Apache commons upload was able to parse " + diskFileItems.size() + " items"); } for (int i = 0; i < diskFileItems.size(); i++) { DiskFileItem diskFileItem = diskFileItems.get(i); if (_log.isInfoEnabled()) { _log.info("Item " + i + " " + diskFileItem); } } return diskFileItems; }
From source file:edu.vt.vbi.patric.portlets.CircosGenomeViewerPortlet.java
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { Map<String, Object> parameters = new LinkedHashMap<>(); int fileCount = 0; try {/*from w ww . jav a 2 s . c om*/ List<FileItem> items = new PortletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { parameters.put(item.getFieldName(), item.getString()); } else { if (item.getFieldName().matches("file_(\\d+)$")) { parameters.put("file_" + fileCount, item); fileCount++; } } } } catch (FileUploadException e) { LOGGER.error(e.getMessage(), e); } LOGGER.debug(parameters.toString()); // Generate Circo Image CircosData circosData = new CircosData(request); Circos circosConf = circosGenerator.createCircosImage(circosData, parameters); if (circosConf != null) { String baseUrl = "https://" + request.getServerName(); String redirectUrl = baseUrl + "/portal/portal/patric/CircosGenomeViewer/CircosGenomeViewerWindow?action=b&cacheability=PAGE&imageId=" + circosConf.getUuid() + "&trackList=" + StringUtils.join(circosConf.getTrackList(), ","); LOGGER.trace("redirect: {}", redirectUrl); response.sendRedirect(redirectUrl); } }
From source file:it.eng.spagobi.commons.utilities.PortletUtilities.java
/** * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, * parses the request, processes the uploaded items and then returns the first file as an * <code>UploadedFile</code> object. * @param portletRequest The input portlet request * @return The first uploaded file object. *//*from w w w . j a v a 2 s .c o m*/ public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest) { UploadedFile uploadedFile = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler PortletFileUpload upload = new PortletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest((ActionRequest) portletRequest); // Process the uploaded items Iterator iter = items.iterator(); boolean endLoop = false; while (iter.hasNext() && !endLoop) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //serviceRequest.setAttribute(item.getFieldName(), item.getString()); } else { uploadedFile = new UploadedFile(); uploadedFile.setFileContent(item.get()); uploadedFile.setFieldNameInForm(item.getFieldName()); uploadedFile.setSizeInBytes(item.getSize()); uploadedFile.setFileName(item.getName()); endLoop = true; } } } catch (Exception e) { logger.error("Cannot parse multipart request", e); } return uploadedFile; }
From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java
@Override public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, Collection<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();/*from w w w.j a va2s . 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 = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(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, Collection<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) FactoryExtensionFinder .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); } boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig); 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(); // If namespace optimization is enabled and the namespace is present in the field name, // then remove the portlet namespace from the field name. if (optimizeNamespace) { int pos = fieldName.indexOf(namespace); if (pos >= 0) { fieldName = fieldName.substring(pos + namespace.length()); } } // 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; }
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();/*from w w w . 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). 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; }
From source file:hu.sztaki.lpds.pgportal.portlets.workflow.WorkflowUploadPortlet.java
@Override protected void doUpload(ActionRequest request, ActionResponse response) { PortletContext context = getPortletContext(); context.log("[FileUploadPortlet] doUpload() called"); try {//from w w w . j a va 2 s . c o m DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(uploadMaxSize); // Maximum upload size pfu.setProgressListener((ProgressListener) new FileUploadProgressListener()); PortletSession ps = request.getPortletSession(); if (ps.getAttribute("uploads", ps.APPLICATION_SCOPE) == null) ps.setAttribute("uploads", new Hashtable<String, ProgressListener>()); //get the FileItems String fieldName = null; List fileItems = pfu.parseRequest(request); Iterator iter = fileItems.iterator(); File serverSideFile = null; Hashtable h = new Hashtable(); //fileupload while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // retrieve hidden parameters if item is a form field if (item.isFormField()) { fieldName = item.getFieldName(); if ("newGrafName".equals(fieldName)) h.put("newGrafName", item.getString()); if ("newAbstName".equals(fieldName)) h.put("newAbstName", item.getString()); if ("newRealName".equals(fieldName)) h.put("newRealName", item.getString()); } else { // item is not a form field, do file upload Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps .getAttribute("uploads");//,ps.APPLICATION_SCOPE pfu.setProgressListener((ProgressListener) new FileUploadProgressListener()); String s = item.getName(); s = FilenameUtils.getName(s); ProgressListener pl = pfu.getProgressListener(); tmp.put(s, pl); ps.setAttribute("uploads", tmp); String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser(); File f = new File(tempDir); if (!f.exists()) f.mkdirs(); serverSideFile = new File(tempDir, s); item.write(serverSideFile); item.delete(); context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir); } } // file upload to storage try { ServiceType st = InformationBase.getI().getService("wfs", "portal", new Hashtable(), new Vector()); h.put("senderObj", "ZipFileSender"); h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url")); h.put("wfsID", st.getServiceUrl()); h.put("userID", request.getRemoteUser()); Hashtable hsh = new Hashtable(); // st = InformationBase.getI().getService("storage", "portal", hsh, new Vector()); // hsh.put("url", "http://localhost:8080/storage"); st = InformationBase.getI().getService("storage", "portal", hsh, new Vector()); PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject()).newInstance(); psc.setServiceURL(st.getServiceUrl()); psc.setServiceID("/receiver"); if (serverSideFile != null) psc.fileUpload(serverSideFile, "fileName", h); } catch (Exception ex) { response.setRenderParameter("full", "error.upload"); ex.printStackTrace(); return; } ps.removeAttribute("uploads", ps.APPLICATION_SCOPE); } catch (FileUploadException fue) { response.setRenderParameter("full", "error.upload"); fue.printStackTrace(); context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString()); return; } catch (Exception e) { e.printStackTrace(); response.setRenderParameter("full", "error.exception"); context.log("[FileUploadPortlet] - failed to upload file - " + e.toString()); return; } response.setRenderParameter("full", "action.succesfull"); }
From source file:com.liferay.testmisc.portlet.TestPortlet.java
protected void testMultipartWithCommonsFileUpload(ActionRequest actionRequest) throws Exception { boolean multiPartContent = PortletFileUpload.isMultipartContent(actionRequest); if (_log.isInfoEnabled()) { if (multiPartContent) { _log.info("The request is a multipart request"); } else {/*from w w w .j a va 2 s .c om*/ _log.info("The request is not a multipart request"); } } DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); List<FileItem> fileItemsList = portletFileUpload.parseRequest(actionRequest); if (_log.isInfoEnabled()) { _log.info("Apache commons upload was able to parse " + fileItemsList.size() + " items"); } for (int i = 0; i < fileItemsList.size(); i++) { FileItem fileItem = fileItemsList.get(i); if (_log.isInfoEnabled()) { _log.info("Item " + i + " " + fileItem); } } }
From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java
public void execute(ActionRequest actionRequest, ActionResponse actionResponse) { try {/* w w w . j av a 2 s. c om*/ sCheckPermissions(actionRequest); String portletId = "_" + PortalUtil.getPortletId(actionRequest) + "_"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(100 * 1024 * 1024); PortletFileUpload upload = new PortletFileUpload(factory); FileItem fileUploaded = null; List<FileItem> items = upload.parseRequest(actionRequest); for (FileItem fi : items) { if (fi.isFormField()) { actionRequest.setAttribute(fi.getFieldName(), fi.getString()); if (fi.getFieldName().startsWith(portletId)) { actionRequest.setAttribute(fi.getFieldName().substring(portletId.length()), fi.getString()); } } else { fileUploaded = fi; } } String cmd = (String) actionRequest.getAttribute("cmd"); String language = (String) actionRequest.getAttribute("language"); String script = (String) actionRequest.getAttribute("script"); String editorheight = (String) actionRequest.getAttribute("editorheight"); String themesel = (String) actionRequest.getAttribute("themesel"); if (language == null) { language = getDefaultLanguage(); } if (script == null) { script = StringPool.BLANK; } actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); actionResponse.setRenderParameter("editorheight", editorheight); actionResponse.setRenderParameter("themesel", themesel); if ("execute".equals(cmd)) { Map<String, Object> portletObjects = ScriptingHelperUtil.getPortletObjects(getPortletConfig(), getPortletContext(), actionRequest, actionResponse); UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(); UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(unsyncByteArrayOutputStream); portletObjects.put("out", unsyncPrintWriter); _log.info("Executing script"); ScriptingUtil.exec(null, portletObjects, language, script, StringPool.EMPTY_ARRAY); unsyncPrintWriter.flush(); actionResponse.setRenderParameter("script_output", unsyncByteArrayOutputStream.toString()); } else if ("save".equals(cmd)) { String newscriptname = (String) actionRequest.getAttribute("newscriptname"); if (newscriptname == null || newscriptname.trim().length() == 0) { actionResponse.setRenderParameter("script_trace", "No script name specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving new script: " + newscriptname.trim()); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + newscriptname.trim(), script); prefs.setValue("lang." + newscriptname.trim(), language); prefs.store(); } else if ("saveinto".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to save into!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Saving saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + scriptname, script); prefs.setValue("lang." + scriptname, language); prefs.store(); } else if ("loadfrom".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to load from!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Loading saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); language = prefs.getValue("lang." + scriptname, getDefaultLanguage()); script = prefs.getValue("savedscript." + scriptname, StringPool.BLANK); actionResponse.setRenderParameter("language", language); actionResponse.setRenderParameter("script", script); } else if ("delete".equals(cmd)) { String scriptname = (String) actionRequest.getAttribute("savedscript"); if (scriptname == null) { actionResponse.setRenderParameter("script_trace", "No script specified to delete!"); SessionErrors.add(actionRequest, "error"); return; } _log.info("Deleting saved script: " + scriptname); PortletPreferences prefs = actionRequest.getPreferences(); prefs.reset("savedscript." + scriptname); prefs.reset("lang." + scriptname); prefs.store(); } else if ("import".equals(cmd)) { if (fileUploaded == null) { actionResponse.setRenderParameter("script_trace", "No file was uploaded for import!"); SessionErrors.add(actionRequest, "error"); return; } StringBuilder output = new StringBuilder(); InputStream instream = fileUploaded.getInputStream(); ZipInputStream zipstream = null; try { zipstream = new ZipInputStream(instream); ZipEntry entry = zipstream.getNextEntry(); while (entry != null) { String filename = entry.getName(); if (filename.contains("/")) { int qs = filename.lastIndexOf("/"); if (qs != -1) { filename = filename.substring(qs + 1); } } if (filename.contains("\\")) { int qs = filename.lastIndexOf("\\"); if (qs != -1) { filename = filename.substring(qs + 1); } } String ext = StringPool.BLANK; if (filename.length() > 0) { int qs = filename.lastIndexOf("."); if (qs > 0) { ext = filename.substring(qs + 1); filename = filename.substring(0, qs); } } String lang = resolveLanguage(ext); String imscript = getStreamAsString(zipstream, "utf-8", false); if (imscript != null && imscript.length() > 0) { _log.info("Importing script \"" + filename + "\" of type " + lang); output.append("Importing script \"" + filename + "\" of type " + lang + "\n"); PortletPreferences prefs = actionRequest.getPreferences(); prefs.setValue("savedscript." + filename, imscript); prefs.setValue("lang." + filename, lang); prefs.store(); } entry = zipstream.getNextEntry(); } actionResponse.setRenderParameter("script_output", output.toString()); } finally { try { if (zipstream != null) { zipstream.close(); } } catch (Exception e) { } try { if (instream != null) { instream.close(); } } catch (Exception e) { } } _log.info(fileUploaded.getName()); } SessionMessages.add(actionRequest, "success"); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.close(); actionResponse.setRenderParameter("script_trace", sw.toString()); _log.error(e); SessionErrors.add(actionRequest, e.toString()); } }
From source file:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java
/** * Uploading SAML file(s).//from w ww . j a va2 s . c o m * The parameters are filled in by the user on the saml/UploadAssertion.jsp page. * @param request ActionRequest * @param response ActionResponse */ @Override public synchronized void doUpload(ActionRequest request, ActionResponse response) { logger.trace(""); // logger.info("Assertion-doUpload"); FileItem samlFile = null; String sresource = null; // selected resource String action = request.getParameter("guse"); logger.info("Action:" + action); try { DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(1048576); // Maximum upload size 1Mb Iterator iter = pfu.parseRequest(request).iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // retrieve parameters if item is a form field if ("sresource".equals(item.getFieldName())) { sresource = item.getString(); } } else { if ("samlFile".equals(item.getFieldName())) { samlFile = item; } } } List<String> result = uploadSaml(request.getPortletSession(), samlFile, sresource, request.getRemoteUser()); StringBuilder sb = new StringBuilder(); boolean flag = false; for (String msg : result) { if (flag) { sb.append("<br />"); } else { flag = true; } sb.append(msg); } request.setAttribute("msg", sb.toString()); } catch (Exception e) { request.setAttribute("msg", "Upload failed. Reason: " + e.getMessage()); logger.info("Upload of asseriont failed. Reason: " + e.getMessage()); logger.debug("Exception:", e); } }