List of usage examples for org.apache.commons.fileupload.util Streams asString
public static String asString(InputStream pStream) throws IOException
From source file:org.elissa.server.StencilSetExtensionGeneratorServlet.java
/** * Request parameters are documented in/*from w ww .j av a 2 s. com*/ * editor/test/examples/stencilset-extension-generator.xhtml * The parameter 'csvFile' is always required. * An example CSV file can be found in * editor/test/examples/design-thinking-example-data.csv * which has been exported using OpenOffice.org from * editor/test/examples/design-thinking-example-data.ods */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; this.baseUrl = Repository.getBaseUrl(request); this.repository = new Repository(baseUrl); // parameters and their default values String modelNamePrefix = "Generated Model using "; String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX; String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH; String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET; String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL; List<String> stencilSetExtensionUrls = new ArrayList<String>(); String[] columnPropertyMapping = null; String[] csvHeader = null; List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>(); String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator."; String additionalERDFContentForGeneratedModel = ""; String[] modelTags = null; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iterator; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // ordinary form field String value = Streams.asString(stream); //System.out.println("Form field " + name + " with value " // + value + " detected."); if (name.equals("modelNamePrefix")) { modelNamePrefix = value; } else if (name.equals("stencilSetExtensionNamePrefix")) { stencilSetExtensionNamePrefix = value; } else if (name.equals("baseStencilSetPath")) { baseStencilSetPath = value; } else if (name.equals("baseStencilSet")) { baseStencilSet = value; } else if (name.equals("stencilSetExtension")) { stencilSetExtensionUrls.add(value); } else if (name.equals("baseStencil")) { baseStencil = value; } else if (name.equals("columnPropertyMapping")) { columnPropertyMapping = value.split(","); } else if (name.equals("modelDescription")) { modelDescription = value; } else if (name.equals("modelTags")) { modelTags = value.split(","); } else if (name.equals("additionalERDFContentForGeneratedModel")) { additionalERDFContentForGeneratedModel = value; } } else { // file field //System.out.println("File field " + name + " with file name " // + item.getName() + " detected."); // Process the input stream if (name.equals("csvFile")) { CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream), CsvPreference.EXCEL_PREFERENCE); csvHeader = csvFileReader.getCSVHeader(true); if (columnPropertyMapping != null || columnPropertyMapping.length > 0) { csvHeader = columnPropertyMapping; } Map<String, String> row; while ((row = csvFileReader.read(csvHeader)) != null) { stencilPropertyMatrix.add(row); } } } } // generate stencil set Date creationDate = new Date(System.currentTimeMillis()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS"); String stencilSetExtensionName = stencilSetExtensionNamePrefix + " " + dateFormat.format(creationDate); stencilSetExtensionUrls .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName, stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil)); // generate new model String modelName = modelNamePrefix + stencilSetExtensionName; String model = repository.generateERDF(UUID.randomUUID().toString(), additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet, stencilSetExtensionUrls, modelName, modelDescription); String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription, baseStencilSet, baseStencilSetPath); // hack for reverse proxies: modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://")); // tag model if (modelTags != null) { for (String tagName : modelTags) { repository.addTag(modelUrl, tagName.trim()); } } // redirect client to editor with that newly generated model response.setHeader("Location", modelUrl); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // TODO Add some error message } }
From source file:org.gatein.wsrp.consumer.handlers.MultiPartUtil.java
public static MultiPartResult getMultiPartContent(RequestContext requestContext) { RequestContextWrapper requestContextWrapper = new RequestContextWrapper(requestContext); MultiPartResult result = null;//ww w . j a v a 2 s . c o m try { if (FileUpload.isMultipartContent(requestContextWrapper)) { result = new MultiPartResult(); // content is multipart, we need to parse it (that includes form parameters) FileUpload upload = new FileUpload(); FileItemIterator iter = upload.getItemIterator(requestContextWrapper); List<UploadContext> uploadContexts = new ArrayList<UploadContext>(7); List<NamedString> formParameters = new ArrayList<NamedString>(7); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (!item.isFormField()) { String contentType = item.getContentType(); if (log.isDebugEnabled()) { log.debug("File field " + item.getFieldName() + " with file name " + item.getName() + " and content type " + contentType + " detected."); } BufferedInputStream bufIn = new BufferedInputStream(stream); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); int c = bufIn.read(); while (c != -1) { bos.write(c); c = bufIn.read(); } bos.flush(); baos.flush(); bufIn.close(); bos.close(); final byte[] uploadData = baos.toByteArray(); if (uploadData.length != 0) { UploadContext uploadContext = WSRPTypeFactory.createUploadContext(contentType, uploadData); List<NamedString> mimeAttributes = new ArrayList<NamedString>(2); String value = FileUpload.FORM_DATA + ";" + " name=\"" + item.getFieldName() + "\";" + " filename=\"" + item.getName() + "\""; NamedString mimeAttribute = WSRPTypeFactory .createNamedString(FileUpload.CONTENT_DISPOSITION, value); mimeAttributes.add(mimeAttribute); mimeAttribute = WSRPTypeFactory.createNamedString(FileUpload.CONTENT_TYPE, item.getContentType()); mimeAttributes.add(mimeAttribute); uploadContext.getMimeAttributes().addAll(mimeAttributes); uploadContexts.add(uploadContext); } else { log.debug("Ignoring empty file " + item.getName()); } } else { NamedString formParameter = WSRPTypeFactory.createNamedString(item.getFieldName(), Streams.asString(stream)); formParameters.add(formParameter); } } result.getUploadContexts().addAll(uploadContexts); result.getFormParameters().addAll(formParameters); } } catch (Exception e) { log.debug("Couldn't create UploadContext", e); } return result; }
From source file:org.grible.servlets.app.imp.StorageImport.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*from w w w . j a va 2s . c o m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (Security.anyServletEntryCheckFailed(request, response)) { return; } String className = Streams.asString(request.getPart("class").getInputStream()); Part filePart = request.getPart("file"); String fileName = ServletHelper.getFilename(filePart); String storageName = StringUtils.substringBefore(fileName, ".xls"); int categoryId = Integer.parseInt(request.getParameter("category")); String categoryPath = StringHelper .getFolderPathWithoutLastSeparator(request.getParameter("categorypath")); int productId = Integer.parseInt(request.getParameter("product")); InputStream filecontent = filePart.getInputStream(); ExcelFile excelFile = new ExcelFile(filecontent, ServletHelper.isXlsx(fileName)); Category category = null; if (ServletHelper.isJson()) { jDao = new JsonDao(); category = new Category(categoryPath, TableType.STORAGE, productId); } else { pDao = new PostgresDao(); category = new Category(categoryId); } if (DataManager.getInstance().getDao().isTableInProductExist(storageName, TableType.STORAGE, category)) { Table table = null; int currentKeysCount = 0; if (ServletHelper.isJson()) { table = jDao.getTable(storageName, TableType.STORAGE, category); currentKeysCount = table.getTableJson().getKeys().length; } else { table = pDao.getTable(storageName, categoryId); currentKeysCount = table.getKeys().length; } int importedKeysCount = excelFile.getKeys().length; if (currentKeysCount != importedKeysCount) { throw new Exception("Parameters number is different.<br>In the current storage: " + currentKeysCount + ". In the Excel file: " + importedKeysCount + "."); } request.getSession(true).setAttribute("importedTable", table); request.getSession(false).setAttribute("importedFile", excelFile); String destination = "/storages/?product=" + productId + "&id=" + table.getId(); response.sendRedirect(destination); } else { int storageId = 0; Key[] keys = excelFile.getKeys(); String[][] values = excelFile.getValues(); storageId = DataManager.getInstance().getDao().insertTable(storageName, TableType.STORAGE, category, null, className, keys, values); String message = ""; if (className.equals("")) { message = "'" + storageName + "' storage was successfully imported. WARNING: Class name is empty."; } else if (!className.endsWith("Info")) { message = "'" + storageName + "' storage was successfully imported. WARNING: Class name does not end with 'Info'."; } else { message = "'" + storageName + "' storage was successfully imported."; } String destination = ""; if (storageId > 0) { destination = "/storages/?product=" + productId + "&id=" + storageId; } else { destination = "/storages/?product=" + productId; } request.getSession(true).setAttribute("importResult", message); response.sendRedirect(destination); } } catch (Exception e) { int productId = Integer.parseInt(request.getParameter("product")); String destination = "/storages/?product=" + productId; String message = Lang.get("error") + ": " + e.getMessage(); e.printStackTrace(); request.getSession(true).setAttribute("importResult", message); response.sendRedirect(destination); } }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * A method for handling multipart POST requests for uploading * files from browser-based JavaScript clients. * * @param request the HTTP request//from ww w . ja va 2 s. c o m * @param response the HTTP response * @param path the resource path * @throws IOException in case an error occurs writing to the * response stream */ private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path) throws IOException { if (logger.isDebugEnabled()) logger.debug("Multipart POST for resource: " + path); User owner = getOwner(request); boolean exists = true; Object resource = null; FileHeader file = null; try { resource = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) { file = (FileHeader) resource; if (file.isDeleted()) { response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash"); return; } } else { response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder"); return; } Object parent; String parentPath = null; try { parentPath = getParentPath(path); parent = getService().getResourceAtPath(owner.getId(), parentPath, true); } catch (ObjectNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath); return; } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (!(parent instanceof Folder)) { response.sendError(HttpServletResponse.SC_CONFLICT); return; } final Folder folderLocal = (Folder) parent; final String fileName = getLastElement(path); if (!isValidResourceName(fileName)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } FileItemIterator iter; File uploadedFile = null; try { // Create a new file upload handler. ServletFileUpload upload = new ServletFileUpload(); StatusProgressListener progressListener = new StatusProgressListener(getService()); upload.setProgressListener(progressListener); iter = upload.getItemIterator(request); String dateParam = null; String auth = null; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); if (name.equals(DATE_PARAMETER)) dateParam = value; else if (name.equals(AUTHORIZATION_PARAMETER)) auth = value; if (logger.isDebugEnabled()) logger.debug(name + ":" + value); } else { // Fetch the timestamp used to guard against replay attacks. if (dateParam == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter"); return; } long timestamp; try { timestamp = DateUtil.parseDate(dateParam).getTime(); } catch (DateParseException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } // Fetch the Authorization parameter and find the user specified in it. if (auth == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter"); return; } String[] authParts = auth.split(" "); if (authParts.length != 2) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String username = authParts[0]; String signature = authParts[1]; User user = null; try { user = getService().findUser(username); } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (user == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } request.setAttribute(USER_ATTRIBUTE, user); // Remove the servlet path from the request URI. String p = request.getRequestURI(); String servletPath = request.getContextPath() + request.getServletPath(); p = p.substring(servletPath.length()); // Validate the signature in the Authorization parameter. String data = request.getMethod() + dateParam + p; if (!isSignatureValid(signature, user, data)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } progressListener.setUserId(user.getId()); progressListener.setFilename(fileName); final String contentType = item.getContentType(); try { uploadedFile = getService().uploadFile(stream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } FileHeader fileLocal = null; final File upf = uploadedFile; final FileHeader f = file; final User u = user; if (file == null) fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(u.getId(), folderLocal.getId(), fileName, contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath()); } }); else fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(u.getId(), f.getId(), contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath()); } }); updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize()); getService().removeFileUploadProgress(user.getId(), fileName); } } // We can't return 204 here since GWT's onSubmitComplete won't fire. response.setContentType("text/html"); response.getWriter().print("<pre></pre>"); } catch (FileUploadException e) { String error = "Error while uploading file"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (GSSIOException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "Error while uploading file"; if (e.logAsError()) logger.error(error, e); else logger.debug(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (DuplicateNameException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "The specified file name already exists in this folder"; logger.error(error, e); response.sendError(HttpServletResponse.SC_CONFLICT, error); } catch (InsufficientPermissionsException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "You don't have the necessary permissions"; logger.error(error, e); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error); } catch (QuotaExceededException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "Not enough free space available"; if (logger.isDebugEnabled()) logger.debug(error, e); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error); } catch (ObjectNotFoundException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "A specified object was not found"; logger.error(error, e); response.sendError(HttpServletResponse.SC_NOT_FOUND, error); } catch (RpcException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "An error occurred while communicating with the service"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (Exception e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "An internal server error occurred"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } }
From source file:org.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java
/** * Request parameters are documented in/*from w ww. j av a2s. com*/ * editor/test/examples/stencilset-extension-generator.xhtml * The parameter 'csvFile' is always required. * An example CSV file can be found in * editor/test/examples/design-thinking-example-data.csv * which has been exported using OpenOffice.org from * editor/test/examples/design-thinking-example-data.ods */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; this.baseUrl = Repository.getBaseUrl(request); this.repository = new Repository(baseUrl); // parameters and their default values String modelNamePrefix = "Generated Model using "; String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX; String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH; String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET; String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL; List<String> stencilSetExtensionUrls = new ArrayList<String>(); String[] columnPropertyMapping = null; String[] csvHeader = null; List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>(); String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator."; String additionalERDFContentForGeneratedModel = ""; String[] modelTags = null; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iterator; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // ordinary form field String value = Streams.asString(stream); //System.out.println("Form field " + name + " with value " // + value + " detected."); if (name.equals("modelNamePrefix")) { modelNamePrefix = value; } else if (name.equals("stencilSetExtensionNamePrefix")) { stencilSetExtensionNamePrefix = value; } else if (name.equals("baseStencilSetPath")) { baseStencilSetPath = value; } else if (name.equals("baseStencilSet")) { baseStencilSet = value; } else if (name.equals("stencilSetExtension")) { stencilSetExtensionUrls.add(value); } else if (name.equals("baseStencil")) { baseStencil = value; } else if (name.equals("columnPropertyMapping")) { columnPropertyMapping = value.split(","); } else if (name.equals("modelDescription")) { modelDescription = value; } else if (name.equals("modelTags")) { modelTags = value.split(","); } else if (name.equals("additionalERDFContentForGeneratedModel")) { additionalERDFContentForGeneratedModel = value; } } } // generate stencil set Date creationDate = new Date(System.currentTimeMillis()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS"); String stencilSetExtensionName = stencilSetExtensionNamePrefix + " " + dateFormat.format(creationDate); stencilSetExtensionUrls .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName, stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil)); // generate new model String modelName = modelNamePrefix + stencilSetExtensionName; String model = repository.generateERDF(UUID.randomUUID().toString(), additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet, stencilSetExtensionUrls, modelName, modelDescription); String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription, baseStencilSet, baseStencilSetPath); // hack for reverse proxies: modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://")); // tag model if (modelTags != null) { for (String tagName : modelTags) { repository.addTag(modelUrl, tagName.trim()); } } // redirect client to editor with that newly generated model response.setHeader("Location", modelUrl); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // TODO Add some error message } }
From source file:org.jbpm.designer.web.server.menu.connector.AbstractConnectorServlet.java
/** * Parse request parameters and files.//from ww w. j a v a 2 s. c o m * @param request * @param response */ protected void parseRequest(HttpServletRequest request, HttpServletResponse response) { requestParams = new HashMap<String, Object>(); listFiles = new ArrayList<FileItemStream>(); listFileStreams = new ArrayList<ByteArrayOutputStream>(); // Parse the request if (ServletFileUpload.isMultipartContent(request)) { // multipart request try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { listFiles.add(item); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); listFileStreams.add(os); } } } } catch (Exception e) { logger.error("Unexpected error parsing multipart content", e); } } else { // not a multipart for (Object mapKey : request.getParameterMap().keySet()) { String mapKeyString = (String) mapKey; if (mapKeyString.endsWith("[]")) { // multiple values String values[] = request.getParameterValues(mapKeyString); List<String> listeValues = new ArrayList<String>(); for (String value : values) { listeValues.add(value); } requestParams.put(mapKeyString, listeValues); } else { // single value String value = request.getParameter(mapKeyString); requestParams.put(mapKeyString, value); } } } }
From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java
private void upload(HttpServletRequest req, HttpServletResponse resp) { ServletFileUpload upload = new ServletFileUpload(); boolean sizeExceeded = false; String repositoryName = req.getParameter("repository"); ConfigurationService conf = (ConfigurationService) context.getBean("template"); upload.setSizeMax(conf.getOperationInputBandwidth()); try {/*from w ww .j a va 2 s.c om*/ params = new HashMap(); FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { params.put(item.getFieldName(), Streams.asString(stream)); } else { params.put("filename", item.getName()); uploadDocumentStructure(req, resp, repositoryName, stream); } } } catch (SizeLimitExceededException e) { sizeExceeded = true; if (repositoryName == null || "".equals(repositoryName)) { repositoryName = (String) params.get("repository"); } logErrorAndForward(req, resp, repositoryName, e, "Bandwith exceeded"); } catch (FileUploadException e) { logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document."); } catch (IOException e) { logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document."); } catch (Exception t) { logErrorAndForward(req, resp, repositoryName, t, "There was a problem uploading the document."); } }
From source file:org.kawanfw.file.servlet.convert.StreamsEncrypted.java
/** * @param stream//from ww w . jav a 2 s. c om * The ServletFileUpload input stream * @param commonsConfigurator * Used to get the password for encryption */ public static String asString(InputStream stream, CommonsConfigurator commonsConfigurator) throws IOException { String value = Streams.asString(stream); if (isEncrypted(value, commonsConfigurator)) { try { value = StringUtils.substringAfter(value, Pbe.KAWANFW_ENCRYPTED); value = new Pbe().decryptFromHexa(value, CommonsConfiguratorCall.getEncryptionPassword(commonsConfigurator)); return value; } catch (Exception e) { String message = Tag.PRODUCT_USER_CONFIG_FAIL + " Impossible to decrypt the value " + value; message += ". Check that password values are the same on client and server side."; throw new IOException(message, e); } } else { return value; } }
From source file:org.kie.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java
/** * Request parameters are documented in//from w w w . java 2 s. c o m * editor/test/examples/stencilset-extension-generator.xhtml * The parameter 'csvFile' is always required. * An example CSV file can be found in * editor/test/examples/design-thinking-example-data.csv * which has been exported using OpenOffice.org from * editor/test/examples/design-thinking-example-data.ods */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; this.baseUrl = Repository.getBaseUrl(request); this.repository = new Repository(baseUrl); // parameters and their default values String modelNamePrefix = "Generated Model using "; String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX; String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH; String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET; String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL; List<String> stencilSetExtensionUrls = new ArrayList<String>(); String[] columnPropertyMapping = null; String[] csvHeader = null; List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>(); String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator."; String additionalERDFContentForGeneratedModel = ""; String[] modelTags = null; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iterator; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // ordinary form field String value = Streams.asString(stream); //System.out.println("Form field " + name + " with value " // + value + " detected."); if (name.equals("modelNamePrefix")) { modelNamePrefix = value; } else if (name.equals("stencilSetExtensionNamePrefix")) { stencilSetExtensionNamePrefix = value; } else if (name.equals("baseStencilSetPath")) { baseStencilSetPath = value; } else if (name.equals("baseStencilSet")) { baseStencilSet = value; } else if (name.equals("stencilSetExtension")) { stencilSetExtensionUrls.add(value); } else if (name.equals("baseStencil")) { baseStencil = value; } else if (name.equals("columnPropertyMapping")) { columnPropertyMapping = value.split(","); } else if (name.equals("modelDescription")) { modelDescription = value; } else if (name.equals("modelTags")) { modelTags = value.split(","); } else if (name.equals("additionalERDFContentForGeneratedModel")) { additionalERDFContentForGeneratedModel = value; } } else { // file field //System.out.println("File field " + name + " with file name " // + item.getName() + " detected."); // Process the input stream if (name.equals("csvFile")) { CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream, "UTF-8"), CsvPreference.EXCEL_PREFERENCE); csvHeader = csvFileReader.getCSVHeader(true); if (columnPropertyMapping != null || columnPropertyMapping.length > 0) { csvHeader = columnPropertyMapping; } Map<String, String> row; while ((row = csvFileReader.read(csvHeader)) != null) { stencilPropertyMatrix.add(row); } } } } // generate stencil set Date creationDate = new Date(System.currentTimeMillis()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS"); String stencilSetExtensionName = stencilSetExtensionNamePrefix + " " + dateFormat.format(creationDate); stencilSetExtensionUrls .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName, stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil)); // generate new model String modelName = modelNamePrefix + stencilSetExtensionName; String model = repository.generateERDF(UUID.randomUUID().toString(), additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet, stencilSetExtensionUrls, modelName, modelDescription); String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription, baseStencilSet, baseStencilSetPath); // hack for reverse proxies: modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://")); // tag model if (modelTags != null) { for (String tagName : modelTags) { repository.addTag(modelUrl, tagName.trim()); } } // redirect client to editor with that newly generated model response.setHeader("Location", modelUrl); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // TODO Add some error message } }
From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UploadStatus status = new UploadStatus(); request.getSession().setAttribute(request.getParameter("uploadId"), status); try {/*from w w w. j ava 2 s . co m*/ ServletFileUpload upload = new ServletFileUpload(); upload.setProgressListener( new DocumentProgressListener(request.getParameter("uploadId"), request.getSession())); FileItemIterator iter = upload.getItemIterator(request); DocumentInfo info = new DocumentInfo(); boolean fileError = false; int currentItem = 0; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if (name.equals("documentDescription")) { RichTextInfo text = new RichTextInfo(); text.setPlain(value); info.setDescr(text); } } else { String fullFileName = item.getName(); if (fullFileName != null) { String filename = FilenameUtils.getName(fullFileName); FileStatus fileStatus = new FileStatus(); fileStatus.setFileName(filename); status.getFileStatusList().add(currentItem, fileStatus); DocumentBinaryInfo bInfo = new DocumentBinaryInfo(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; while (true) { int read = stream.read(buffer); if (read == -1) { break; } else { bytes.write(buffer, 0, read); fileStatus.setProgress(fileStatus.getProgress() + read); } } bytes.flush(); fileStatus.setStatus(FileTransferStatus.UPLOAD_FINISHED); bInfo.setBinary(new String(Base64.encodeBase64(bytes.toByteArray()))); info.setDocumentBinary(bInfo); info.setStateKey(DtoState.ACTIVE.toString()); info.setFileName(filename); int extSeperator = filename.lastIndexOf("."); info.setName(filename.substring(0, extSeperator)); //FIXME Probably temporary solution for type on document info String type = "documentType." + filename.substring(extSeperator + 1).toLowerCase(); info.setTypeKey(type); } else { //No file specified error status.setStatus(UploadTransferStatus.ERROR); } } if (info.getDescr() != null && info.getDocumentBinary() != null && info.getType() != null) { //FileStatus fileStatus = status.getFileStatusMap().get(info.getFileName()); FileStatus fileStatus = status.getFileStatusList().get(currentItem); try { DocumentInfo createdDoc = documentService.createDocument(info.getTypeKey(), "documentCategory.proposal", info, ContextUtils.getContextInfo()); fileStatus.setStatus(FileTransferStatus.COMMIT_FINISHED); if (createdDoc != null) { status.getCreatedDocIds().add(createdDoc.getId()); fileStatus.setDocId(createdDoc.getId()); } RefDocRelationInfo relationInfo = new RefDocRelationInfo(); relationInfo.setStateKey(DtoState.ACTIVE.toString()); relationInfo.setDescr(info.getDescr()); relationInfo.setRefObjectId(request.getParameter("referenceId")); relationInfo.setRefObjectTypeKey(request.getParameter("refObjectTypeKey")); relationInfo.setTitle(info.getFileName()); relationInfo.setDocumentId(createdDoc.getId()); relationInfo.setType(request.getParameter("refDocRelationTypeKey")); documentService.createRefDocRelation(relationInfo.getRefObjectTypeKey(), relationInfo.getRefObjectId(), relationInfo.getDocumentId(), relationInfo.getTypeKey(), relationInfo, ContextUtils.getContextInfo()); } catch (Exception e) { fileError = true; LOG.error("Exception occurred", e); fileStatus.setStatus(FileTransferStatus.ERROR); } info = new DocumentInfo(); currentItem++; } } if (fileError) { status.setStatus(UploadTransferStatus.ERROR); } else { status.setStatus(UploadTransferStatus.COMMIT_FINISHED); } } catch (Exception e) { status.setStatus(UploadTransferStatus.ERROR); LOG.error("Exception occurred", e); } }