List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:net.sourceforge.jwebunit.tests.util.ParamsServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write(HtmlHelper.getStart("Submitted parameters")); out.write("<h1>Submitted parameters</h1>\n<p>Params are:<br/>"); /*//from w ww . ja va 2s .c o m * Prints POST and GET parameters as name=[value1[,value2...]] separated * by <BR/> */ // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } String ref = null; // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { out.write(" " + item.getFieldName() + "=[" + item.getString()); if (item.getFieldName().equals("myReferer")) { ref = item.getString(); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); out.write(" " + fieldName + "=[" + fileName + "{" + new String(item.get()) + "}"); } if (iter.hasNext()) { out.write("]<br/>\n"); } } out.write("]</p>\n"); out.write(HtmlHelper.getLinkParagraph("return", ref)); } else { java.util.Enumeration params = request.getParameterNames(); for (; params.hasMoreElements();) { String p = params.nextElement().toString(); String[] v = request.getParameterValues(p); out.write(p + "=["); int n = v.length; if (n > 0) { out.write(v[0] != null ? v[0] : ""); for (int i = 1; i < n; i++) { out.write("," + (v[i] != null ? v[i] : "")); } } if (params.hasMoreElements()) { out.write("]<br/>\n"); } } out.write("]</p>\n"); String ref = request.getHeader("Referer"); if (ref == null) { if (request.getParameterValues("myReferer") != null) { ref = request.getParameterValues("myReferer")[0]; } } out.write(HtmlHelper.getLinkParagraph("return", ref)); } out.write(HtmlHelper.getEnd()); }
From source file:fr.paris.lutece.plugins.directory.utils.DirectoryUtils.java
/** * Get the file contains in the request from the name of the input file * * @param strFileInputName//from w w w. ja va 2 s . c o m * le name of the input file file * @param request * the request * @return file the file contains in the request from the name of the input * file */ public static File getFileData(String strFileInputName, HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(strFileInputName); if ((fileItem != null) && (fileItem.getName() != null) && !EMPTY_STRING.equals(fileItem.getName())) { File file = new File(); PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); file.setTitle(FileUploadService.getFileNameOnly(fileItem)); file.setSize((int) fileItem.getSize()); file.setPhysicalFile(physicalFile); file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem))); return file; } return null; }
From source file:fr.paris.lutece.plugins.calendar.web.CalendarStyleSheetJspBean.java
/** * Reads stylesheet's data// w ww.j a va2 s . com * @param multipartRequest The request * @param stylesheet The style sheet * @return An error message URL or null if no error * @throws AccessDeniedException If the user is not allowed to access this * feature */ private String getData(MultipartHttpServletRequest multipartRequest, StyleSheet stylesheet) throws AccessDeniedException { if (!RBACService.isAuthorized(CalendarResourceIdService.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID, CalendarResourceIdService.PERMISSION_MANAGE, getUser())) { throw new AccessDeniedException(); } String strErrorUrl = null; String strDescription = multipartRequest.getParameter(Parameters.STYLESHEET_NAME); //String strStyleId = multipartRequest.getParameter( Parameters.STYLES ); //String strModeId = multipartRequest.getParameter( Parameters.MODE_STYLESHEET ); FileItem fileSource = multipartRequest.getFile(Parameters.STYLESHEET_SOURCE); byte[] baXslSource = fileSource.get(); String strFilename = FileUploadService.getFileNameOnly(fileSource); String strFileExtension = multipartRequest.getParameter(Constants.PARAMETER_EXPORT_EXTENSION); // Mandatory fields if (strDescription.equals("") || (strFileExtension.equals("")) || (strFilename == null) || strFilename.equals("")) { return AdminMessageService.getMessageUrl(multipartRequest, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } // Check the XML validity of the XSL stylesheet if (isValid(baXslSource) != null) { Object[] args = { isValid(baXslSource) }; return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_STYLESHEET_NOT_VALID, args, AdminMessage.TYPE_STOP); } stylesheet.setDescription(strDescription); //stylesheet.setStyleId( Integer.parseInt( strStyleId ) ); //stylesheet.setModeId( Integer.parseInt( strModeId ) ); stylesheet.setSource(baXslSource); stylesheet.setFile(strFilename); return strErrorUrl; }
From source file:fr.paris.lutece.portal.web.style.PageTemplatesJspBean.java
/** * Write the templates files (html and image) * * @param strFileName The name of the file * @param strPath The path of the file// w w w.ja v a 2 s. c o m * @param fileItem The fileItem object which contains the new file */ private void writeTemplateFile(String strFileName, String strPath, FileItem fileItem) { FileOutputStream fosFile = null; try { File file = new File(strPath + strFileName); if (file.exists()) { file.delete(); } fosFile = new FileOutputStream(file); fosFile.flush(); fosFile.write(fileItem.get()); fosFile.close(); } catch (IOException e) { AppLogService.error(e.getMessage(), e); } finally { if (fosFile != null) { try { fosFile.close(); } catch (IOException e) { AppLogService.error(e.getMessage(), e); } } } }
From source file:com.threecrickets.prudence.util.FormWithFiles.java
/** * Constructor.// w w w.j av a 2 s . c o m * * @param webForm * The URL encoded web form * @param fileItemFactory * The file item factory * @throws ResourceException * In case of an upload handling error */ public FormWithFiles(Representation webForm, FileItemFactory fileItemFactory) throws ResourceException { if (webForm.getMediaType().includes(MediaType.MULTIPART_FORM_DATA)) { RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory); try { for (FileItem fileItem : fileUpload.parseRepresentation(webForm)) { Parameter parameter; if (fileItem.isFormField()) parameter = new Parameter(fileItem.getFieldName(), fileItem.getString()); else { if (fileItem instanceof DiskFileItem) { File file = ((DiskFileItem) fileItem).getStoreLocation(); if (file == null) // In memory parameter = new FileParameter(fileItem.getFieldName(), fileItem.get(), fileItem.getContentType(), fileItem.getSize()); else // On disk parameter = new FileParameter(fileItem.getFieldName(), file, fileItem.getContentType(), fileItem.getSize()); } else // Non-file form item parameter = new Parameter(fileItem.getFieldName(), fileItem.getString()); } add(parameter); } } catch (FileUploadException x) { throw new ResourceException(x); } } else { // Default parsing addAll(new Form(webForm)); } }
From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { long now = System.currentTimeMillis(); Timestamp submissionTimestamp = new Timestamp(now); // these are set by filters or previous servlets Project project = (Project) request.getAttribute(PROJECT); StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION); MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue(); String clientTool = multipartRequest.getCheckedParameter("submitClientTool"); String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion"); String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp"); Collection<FileItem> files = multipartRequest.getFileItems(); Kind kind;/*from w w w . j a va2 s . c o m*/ byte[] zipOutput = null; // zipped version of bytesForUpload boolean fixedZip = false; try { if (files.size() > 1) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); for (FileItem item : files) { String name = item.getName(); if (name == null || name.length() == 0) continue; byte[] bytes = item.get(); ZipEntry zentry = new ZipEntry(name); zentry.setSize(bytes.length); zentry.setTime(now); zos.putNextEntry(zentry); zos.write(bytes); zos.closeEntry(); } zos.flush(); zos.close(); zipOutput = bos.toByteArray(); kind = Kind.MULTIFILE_UPLOAD; } else { FileItem fileItem = multipartRequest.getFileItem(); if (fileItem == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was a problem processing your submission. " + "No files were found in your submission"); return; } // get size in bytes long sizeInBytes = fileItem.getSize(); if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Trying upload file of size " + sizeInBytes); return; } // copy the fileItem into a byte array byte[] bytesForUpload = fileItem.get(); String fileName = fileItem.getName(); boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches(); FormatDescription desc = FormatIdentification.identify(bytesForUpload); if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) { fixedZip = FixZip.hasProblem(bytesForUpload); kind = Kind.ZIP_UPLOAD; if (fixedZip) { bytesForUpload = FixZip.fixProblem(bytesForUpload, studentRegistration.getStudentRegistrationPK()); kind = Kind.FIXED_ZIP_UPLOAD; } zipOutput = bytesForUpload; } else { // ========================================================================================== // [NAT] [Buffer to ZIP Part] // Check the type of the upload and convert to zip format if // possible // NOTE: I use both MagicMatch and FormatDescription (above) // because MagicMatch was having // some trouble identifying all zips String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName); if (!isSpecialSingleFile && mime == null) try { MagicMatch match = Magic.getMagicMatch(bytesForUpload, true); if (match != null) mime = match.getMimeType(); } catch (Exception e) { // leave mime as null } if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) { zipOutput = bytesForUpload; kind = Kind.ZIP_UPLOAD2; } else { InputStream ins = new ByteArrayInputStream(bytesForUpload); if ("application/x-gzip".equalsIgnoreCase(mime)) { ins = new GZIPInputStream(ins); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime) || "application/x-tar".equalsIgnoreCase(mime))) { kind = Kind.TAR_UPLOAD; TarInputStream tins = new TarInputStream(ins); TarEntry tarEntry = null; while ((tarEntry = tins.getNextEntry()) != null) { zos.putNextEntry(new ZipEntry(tarEntry.getName())); tins.copyEntryContents(zos); zos.closeEntry(); } tins.close(); } else { // Non-archive file type if (isSpecialSingleFile) kind = Kind.SPECIAL_ZIP_FILE; else kind = Kind.SINGLE_FILE; // Write bytes to a zip file ZipEntry zentry = new ZipEntry(fileName); zos.putNextEntry(zentry); zos.write(bytesForUpload); zos.closeEntry(); } zos.flush(); zos.close(); zipOutput = bos.toByteArray(); } // [END Buffer to ZIP Part] // ========================================================================================== } } } catch (NullPointerException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was a problem processing your submission. " + "You should submit files that are either zipped or jarred"); return; } finally { for (FileItem fItem : files) fItem.delete(); } if (webBasedUpload) { clientTool = "web"; clientVersion = kind.toString(); } Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request, submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(), getSubmitServerServletLog()); request.setAttribute("submission", submission); if (!webBasedUpload) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project " + project.getProjectNumber()); out.flush(); out.close(); return; } boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue(); // boolean // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission")); // set the successful submission as a request attribute String redirectUrl; if (fixedZip) { redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK=" + submission.getSubmissionPK(); } if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) { redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK=" + project.getProjectPK(); } else if (instructorUpload) { redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK=" + project.getProjectPK(); } else { redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK(); } response.sendRedirect(redirectUrl); }
From source file:com.github.podd.resources.UploadArtifactResourceImpl.java
private InferredOWLOntologyID uploadFileAndLoadArtifactIntoPodd(final Representation entity) throws ResourceException { List<FileItem> items;//from ww w. j a va 2s. com Path filePath = null; String contentType = null; // 1: Create a factory for disk-based file items final DiskFileItemFactory factory = new DiskFileItemFactory(1000240, this.tempDirectory.toFile()); // 2: Create a new file upload handler final RestletFileUpload upload = new RestletFileUpload(factory); final Map<String, String> props = new HashMap<String, String>(); try { // 3: Request is parsed by the handler which generates a list of // FileItems items = upload.parseRequest(this.getRequest()); for (final FileItem fi : items) { final String name = fi.getName(); if (name == null) { props.put(fi.getFieldName(), new String(fi.get(), StandardCharsets.UTF_8)); } else { // FIXME: Strip everything up to the last . out of the // filename so that // the filename can be used for content type determination // where // possible. // InputStream uploadedFileInputStream = // fi.getInputStream(); try { // Note: These are Java-7 APIs contentType = fi.getContentType(); props.put("Content-Type", fi.getContentType()); filePath = Files.createTempFile(this.tempDirectory, "ontologyupload-", name); final File file = filePath.toFile(); file.deleteOnExit(); fi.write(file); } catch (final IOException ioe) { throw ioe; } catch (final Exception e) { // avoid throwing a generic exception just because the // apache // commons library throws Exception throw new IOException(e); } } } } catch (final IOException | FileUploadException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e); } this.log.info("props={}", props.toString()); if (filePath == null) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Did not submit a valid file and filename"); } this.log.info("filename={}", filePath.toAbsolutePath().toString()); this.log.info("contentType={}", contentType); RDFFormat format = null; // If the content type was application/octet-stream then use the file // name instead // Browsers attach this content type when they are not sure what the // real type is if (MediaType.APPLICATION_OCTET_STREAM.getName().equals(contentType)) { format = Rio.getParserFormatForFileName(filePath.getFileName().toString()); this.log.info("octet-stream contentType filename format={}", format); } // Otherwise use the content type directly in preference to using the // filename else if (contentType != null) { format = Rio.getParserFormatForMIMEType(contentType); this.log.info("non-octet-stream contentType format={}", format); } // If the content type choices failed to resolve the type, then try the // filename if (format == null) { format = Rio.getParserFormatForFileName(filePath.getFileName().toString()); this.log.info("non-content-type filename format={}", format); } // Or fallback to RDF/XML which at minimum is able to detect when the // document is // structurally invalid if (format == null) { this.log.warn("Could not determine RDF format from request so falling back to RDF/XML"); format = RDFFormat.RDFXML; } try (final InputStream inputStream = new BufferedInputStream( Files.newInputStream(filePath, StandardOpenOption.READ));) { return this.uploadFileAndLoadArtifactIntoPodd(inputStream, format, DanglingObjectPolicy.REPORT, DataReferenceVerificationPolicy.DO_NOT_VERIFY); } catch (final IOException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "File IO error occurred", e); } }
From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java
public void handlePost(RequestContext context) throws ServletException, IOException { HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); if (!checkConfiguration(response)) return;/* w w w . j a va2 s . c o m*/ List<?> parameters = extractParameterList(request); String orgName = extractParameter("organisationName", parameters); String orgUrl = extractParameter("organisationUrl", parameters); String email = extractParameter("email", parameters); String entityId = extractParameter("entityId", parameters); final String password = extractParameter("keystorePassword", parameters); byte[] metadata = extractFile("metadata", parameters).get(); FileItem ksData = extractFile("keystore", parameters); byte[] keystore = null; if (ksData != null) { keystore = ksData.get(); } if (!checkNotNull(orgName, orgUrl, email, password, metadata, entityId) || metadata.length == 0 || (keystore == null && !Boolean.valueOf(extractParameter("createkeystore", parameters)))) { Map<String, Object> params = getStandardParameters(request); params.put("error", "All fields must be filled."); params.put("organisationName", orgName); params.put("organisationUrl", orgUrl); params.put("email", email); params.put("keystorePassword", password); params.put("entityId", entityId); log.info("Parameters not correct: " + params); log.info("Metadata: " + new String(metadata)); String res = renderTemplate("configure.vm", params, true); sendResponse(response, res); return; } Credential credential = context.getCredential(); if (keystore != null && keystore.length > 0) { credential = CredentialRepository.createCredential(new ByteArrayInputStream(keystore), password); } else if (Boolean.valueOf(extractParameter("createkeystore", parameters))) { try { BasicX509Credential cred = new BasicX509Credential(); KeyPair kp = dk.itst.oiosaml.security.SecurityHelper .generateKeyPairFromURI("http://www.w3.org/2001/04/xmlenc#rsa-1_5", 1024); cred.setPrivateKey(kp.getPrivate()); cred.setPublicKey(kp.getPublic()); credential = cred; KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); X509Certificate cert = dk.itst.oiosaml.security.SecurityHelper.generateCertificate(credential, getEntityId(request)); cred.setEntityCertificate(cert); ks.setKeyEntry("oiosaml", credential.getPrivateKey(), password.toCharArray(), new Certificate[] { cert }); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ks.store(bos, password.toCharArray()); keystore = bos.toByteArray(); bos.close(); } catch (Exception e) { log.error("Unable to generate credential", e); throw new RuntimeException("Unable to generate credential", e); } } EntityDescriptor descriptor = generateSPDescriptor(getBaseUrl(request), entityId, credential, orgName, orgUrl, email, Boolean.valueOf(extractParameter("enableArtifact", parameters)), Boolean.valueOf(extractParameter("enablePost", parameters)), Boolean.valueOf(extractParameter("enableSoap", parameters)), Boolean.valueOf(extractParameter("enablePostSLO", parameters)), Boolean.valueOf(extractParameter("supportOCESAttributeProfile", parameters))); File zipFile = generateZipFile(request.getContextPath(), password, metadata, keystore, descriptor); byte[] configurationContents = saveConfigurationInSession(request, zipFile); boolean written = writeConfiguration(getHome(servletContext), configurationContents); Map<String, Object> params = new HashMap<String, Object>(); params.put("home", getHome(servletContext)); params.put("written", written); sendResponse(response, renderTemplate("done.vm", params, true)); }
From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeFile.java
/** * Get a generic attributes response from a file item * @param fileItem The file item//from w w w.j av a2s.c o m * @param entry The entry * @param bCreatePhysicalFile True to create the physical file associated * with the file of the response, false otherwise. Note that the * physical file will never be saved in the database by this * method, like any other created object. * @return The created response */ private Response getResponseFromFile(FileItem fileItem, Entry entry, boolean bCreatePhysicalFile) { if (fileItem instanceof GenAttFileItem) { GenAttFileItem genAttFileItem = (GenAttFileItem) fileItem; if (genAttFileItem.getIdResponse() > 0) { Response response = ResponseHome.findByPrimaryKey(genAttFileItem.getIdResponse()); response.setEntry(entry); response.setFile(FileHome.findByPrimaryKey(response.getFile().getIdFile())); if (bCreatePhysicalFile) { response.getFile().getPhysicalFile().setValue(fileItem.get()); } return response; } } Response response = new Response(); response.setEntry(entry); File file = new File(); file.setTitle(fileItem.getName()); file.setSize((fileItem.getSize() < Integer.MAX_VALUE) ? (int) fileItem.getSize() : Integer.MAX_VALUE); if (bCreatePhysicalFile) { file.setMimeType(FileSystemUtil.getMIMEType(file.getTitle())); PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); file.setPhysicalFile(physicalFile); } response.setFile(file); return response; }
From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java
/** * Save the request parameters from the CV/Resume page *//*from w w w . jav a2 s .c o m*/ public static void saveCV(Vendor vendor, HttpServletRequest request) throws EnvoyServletException { // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); String radioValue = null; String resumeText = null; boolean doUpload = false; byte[] data = null; String filename = null; // Parse the request try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = EditUtil.utf8ToUnicode(item.getString()); if (name.equals("radioBtn")) { radioValue = value; } else if (name.equals("resumeText")) { resumeText = value; } } else { filename = item.getName(); if (filename == null || filename.equals("")) { // user hit done button but didn't modify the page continue; } else { doUpload = true; data = item.get(); } } } if (radioValue != null) { if (radioValue.equals("doc") && doUpload) { vendor.setResume(filename, data); try { ServerProxy.getVendorManagement().saveResumeFile(vendor); } catch (Exception e) { throw new EnvoyServletException(e); } } else if (radioValue.equals("text")) { vendor.setResume(resumeText); } } } catch (FileUploadException fe) { throw new EnvoyServletException(fe); } }