List of usage examples for org.apache.commons.fileupload FileUploadException getCause
public synchronized Throwable getCause()
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
/** * Tests, whether an IOException is properly delegated. */// w w w . jav a2 s .c om public void testIOException() throws IOException { byte[] request = newRequest(); InputStream stream = new FilterInputStream(new ByteArrayInputStream(request)) { private int num; @Override public int read() throws IOException { if (++num > 123) { throw new IOException("123"); } return super.read(); } @Override public int read(byte[] pB, int pOff, int pLen) throws IOException { for (int i = 0; i < pLen; i++) { int res = read(); if (res == -1) { return i == 0 ? -1 : i; } pB[pOff + i] = (byte) res; } return pLen; } }; try { parseUpload(stream, request.length); fail("Expected IOException"); } catch (FileUploadException e) { assertTrue(e.getCause() instanceof IOException); assertEquals("123", e.getCause().getMessage()); } }
From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java
/** * //from w w w . j a va 2s . co m * Uploads a file from the user's local machine to the *portal* server only. It won't store the file in the Storage * component of gUSE, and won't update database under WFS component * * @param file * - file to upload (can be get from the ActionRequest) * @param userID * - ID of the user * @param filename * - the file should be placed using this name * @return the uploaded file stored on the portal server * @throws Exception */ public File uploadFiletoPortalServer(FileItem file, String userID, String filename) throws Exception { // System.out.println("doUPLOADFiletoPortalServer called ..."); File serverSideFile = null; try { String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + userID; File f = new File(tempDir); if (!f.exists()) f.mkdirs(); serverSideFile = new File(tempDir, filename); file.write(serverSideFile); file.delete(); } catch (FileUploadException fue) { // response.setRenderParameter("full", "error.upload"); throw new Upload_ErrorDuringUploadException(fue.getCause(), userID); // context.log("[FileUploadPortlet] - failed to upload file - "+ fue.toString()); } catch (Exception e) { // response.setRenderParameter("full", "error.exception"); throw new Upload_GeneralException(e.getCause(), userID); // context.log("[FileUploadPortlet] - failed to upload file - "+ e.toString()); } return serverSideFile; }
From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java
@Override public List<Document> parseHttpRequest(HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (logger.isDebugEnabled()) { logger.info("Parse file item form HTTP servlet request."); }/* w w w . j av a 2s. co m*/ Document document = null; List<Document> documents = new ArrayList<Document>(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) return documents; File repository = FileUtils.forceMkdir(FilePathUtils.REPOSITORY_PATH); if (repository != null) logger.info("The" + FilePathUtils.REPOSITORY_PATH + " Directory is created"); if (FileUtils.forceMkdir(FilePathUtils.RESOURCE_PATH) != null) logger.info("To create specified sub-folder under " + FilePathUtils.ROOT_PATH + " top-level folder"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_CACHE_SIZE); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAXIMUM_FILE_SIZE); try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem fileItem = iterator.next(); if (!fileItem.isFormField()) { // Write file items to disk-based String absolutePath = writeFiles(fileItem, fileItem.getName()); document = Document.getInstance(); document.setFilename(fileItem.getName()); document.setContentType(fileItem.getContentType()); document.setSize(fileItem.getSize()); document.setUrl(absolutePath); document.setReadOnly(false); document.setArchive(false); document.setDirectory(false); document.setHidden(false); document.setSystem(false); document.setOther(false); document.setRegularFile(false); Date time = Calendar.getInstance().getTime(); document.setCreationTime(time); document.setLastAccessTime(time); document.setLastModifiedTime(time); documents.add(document); logger.info("File(s) " + document.getFilename() + " was/were uploaded successfully"); } } } catch (SizeLimitExceededException slee) { throw new SizeLimitExceededException( "The request was rejected because its size exceeds (" + slee.getActualSize() + "bytes) the configured maximum (" + slee.getPermittedSize() + "bytes)"); } catch (FileUploadException fue) { throw new FileUploadException("Upload file stream was been cancelled", fue.getCause()); } finally { try { FileUtils.cleanDirectory(factory.getRepository()); logger.info("Cleans a directory without deleting it"); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } } return documents; }
From source file:org.restlet.ext.jaxrs.internal.provider.FileUploadProvider.java
/** * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType, * MultivaluedMap, InputStream)/* ww w . j av a 2 s . c o m*/ */ public List<FileItem> readFrom(Class<List<FileItem>> type, Type genericType, Annotation[] annotations, MediaType mediaType, final MultivaluedMap<String, String> respHeaders, final InputStream entityStream) throws IOException { final FileUpload rfu = new FileUpload(); final RequestContext requCtx = new RequestContext(entityStream, respHeaders); try { return rfu.parseRequest(requCtx); } catch (FileUploadException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } final IOException ioExc = new IOException("Could not read the multipart/form-data"); ioExc.initCause(e); throw ioExc; } }
From source file:sai_cas.servlet.CrossMatchServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format;// w ww . j a va 2 s . c o m List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0 : fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString == null) || (formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(null); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; String inputFilename = fi.getName(); rad = Double.parseDouble(radString); if (fi == null) { throw new CrossMatchServletException("File should be specified" + fileItemList.size()); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn == null) || (decColumn == null)) { throw new CrossMatchServletException( "When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch", ".dat", new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn, tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException( "The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable(uploadedFile); break; } vot.randomizeResourceName(); vot.randomizeTableName(); String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi, userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch (format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException("Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } String outputFilename = cat + "." + (tab == null ? "" : tab) + "_" + String.format(Locale.US, "%.4f", rad) + "_" + inputFilename; response.setHeader("Content-Disposition", "attachment; filename=" + outputFilename); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b " + "ON q3c_join(a." + raDecArray1[0] + ",a." + raDecArray1[1] + ",b." + raDecArray[0] + ",b." + raDecArray[1] + "," + rad + ")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName()); voqro.setResourceDescription("This is the table obtained by " + "crossmatching the table " + cat + "." + tab + " with the " + "user supplied table from the file " + fi.getName() + "\n" + "Radius of the crossmatch: " + rad + "deg"); voqro.setTable("main"); } qro.print(out, dbi); } catch (VotableException e) { qro.printError(out, "Error occured: " + e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } finally { DBInterface.close(dbi, conn, false); /* Always rollback */ try { if (uploadedFile != null) { uploadedFile.delete(); } } catch (Exception e) { logger.error("Failed to delete the temporary file: " + uploadedFile.getCanonicalPath()); } } }