List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName
String getFieldName();
From source file:com.zimbra.cs.service.UserServletContext.java
public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException { String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM; String filename = null;/* w w w .ja va2 s . c o m*/ InputStream is = null; final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024; if (limit == 0) { if (req.getParameter("lbfums") != null) { limit = Provisioning.getInstance().getLocalServer() .getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE); } else { limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE); } } boolean doCsrfCheck = false; if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) { doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload sfu = new ServletFileUpload(); try { FileItemIterator iter = sfu.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); if (fis.isFormField()) { is = fis.openStream(); params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8")); if (doCsrfCheck && !this.csrfAuthSucceeded) { String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN); if (UserServlet.log.isDebugEnabled()) { String paramValue = req.getParameter(UserServlet.QP_AUTH); UserServlet.log.debug( "CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue); } if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) { setCsrfAuthSucceeded(Boolean.FALSE); UserServlet.log.debug( "CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken); throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate)); } else { setCsrfAuthSucceeded(Boolean.TRUE); } } is.close(); is = null; } else { is = new UploadInputStream(fis.openStream(), limit); break; } } } catch (UserServletException e) { throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e); } catch (Exception e) { throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString()); } if (is == null) throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content"); } else { ContentType ctype = new ContentType(req.getContentType()); String contentEncoding = req.getHeader("Content-Encoding"); contentType = ctype.getContentType(); filename = ctype.getParameter("name"); if (filename == null || filename.trim().equals("")) filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit); } if (filename == null || filename.trim().equals("")) filename = "unknown"; else params.put(UserServlet.UPLOAD_NAME, filename); params.put(UserServlet.UPLOAD_TYPE, contentType); ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength()); return is; }
From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java
public void createFile(HttpServletRequest req, HttpServletResponse resp, Document buildDoc) throws IndelibleWebAccessException, IOException, ServletException, FileUploadException { boolean completedOK = false; boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); if (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); FilePath dirPath = null;// w w w . ja va 2 s .c o m if (fieldName.equals("upfile")) { try { connection.startTransaction(); String path = req.getPathInfo(); String fileName = item.getName(); if (fileName.indexOf('/') >= 0) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); dirPath = FilePath.getFilePath(path); FilePath reqPath = dirPath.getChild(fileName); if (reqPath == null || reqPath.getNumComponents() < 2) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); // Should be an absolute path reqPath = reqPath.removeLeadingComponent(); String fsIDStr = reqPath.getComponent(0); IndelibleFSVolumeIF volume = getVolume(fsIDStr); if (volume == null) throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null); FilePath createPath = reqPath.removeLeadingComponent(); FilePath parentPath = createPath.getParent(); FilePath childPath = createPath.getPathRelativeTo(parentPath); if (childPath.getNumComponents() != 1) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute()); if (!parentNode.isDirectory()) throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null); IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode; IndelibleFileNodeIF childNode = null; childNode = parentDirectory.getChildNode(childPath.getName()); if (childNode == null) { try { CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true); childNode = childInfo.getCreatedNode(); } catch (FileExistsException e) { // Probably someone else beat us to it... childNode = parentDirectory.getChildNode(childPath.getName()); } } else { } if (childNode.isDirectory()) throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null); IndelibleFSForkIF dataFork = childNode.getFork("data", true); dataFork.truncate(0); InputStream readStream = item.openStream(); byte[] writeBuffer = new byte[1024 * 1024]; int readLength; long bytesCopied = 0; int bufOffset = 0; while ((readLength = readStream.read(writeBuffer, bufOffset, writeBuffer.length - bufOffset)) > 0) { if (bufOffset + readLength == writeBuffer.length) { dataFork.appendDataDescriptor( new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length)); bufOffset = 0; } else bufOffset += readLength; bytesCopied += readLength; } if (bufOffset != 0) { // Flush out the final stuff dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset)); } connection.commit(); completedOK = true; } catch (PermissionDeniedException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e); } catch (IOException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e); } catch (ObjectNotFoundException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e); } catch (ForkNotFoundException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e); } finally { if (!completedOK) try { connection.rollback(); } catch (IOException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e); } } listPath(dirPath, buildDoc); return; } } throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); }
From source file:com.google.sampling.experiential.server.EventServlet.java
private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) { PrintWriter out = null;//from w w w . j a v a 2 s.com try { out = resp.getWriter(); } catch (IOException e1) { log.log(Level.SEVERE, "Cannot get an output PrintWriter!"); } try { boolean isDevInstance = isDevInstance(req); ServletFileUpload fileUploadTool = new ServletFileUpload(); fileUploadTool.setSizeMax(50000); resp.setContentType("text/html;charset=UTF-8"); FileItemIterator iterator = fileUploadTool.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = null; try { in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); String fileContents = null; fileContents = IOUtils.toString(in); out.println("length: " + fileContents.length()); out.println(fileContents); saveCSV(fileContents, isDevInstance); } } catch (ParseException e) { log.info("Parse Exception: " + e.getMessage()); out.println("Could not parse your csv upload: " + e.getMessage()); } finally { in.close(); } } } catch (SizeLimitExceededException e) { log.info("SizeLimitExceededException: " + e.getMessage()); out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); return; } catch (IOException e) { log.severe("IOException: " + e.getMessage()); out.println("Error in receiving file."); } catch (FileUploadException e) { log.severe("FileUploadException: " + e.getMessage()); out.println("Error in receiving file."); } }
From source file:act.data.ApacheMultipartParser.java
@Override public Map<String, String[]> parse(ActionContext context) { H.Request request = context.req(); InputStream body = request.inputStream(); Map<String, String[]> result = new HashMap<>(); try {// www. j a v a 2 s . c o m FileItemIteratorImpl iter = new FileItemIteratorImpl(body, request.header("content-type"), request.characterEncoding()); while (iter.hasNext()) { FileItemStream item = iter.next(); ISObject sobj = UploadFileStorageService.store(item, context.app()); if (sobj.getLength() == 0L) { continue; } String fieldName = item.getFieldName(); if (item.isFormField()) { // must resolve encoding String _encoding = request.characterEncoding(); // this is our default String _contentType = item.getContentType(); if (_contentType != null) { ContentTypeWithEncoding contentTypeEncoding = ContentTypeWithEncoding.parse(_contentType); if (contentTypeEncoding.encoding != null) { _encoding = contentTypeEncoding.encoding; } } mergeValueInMap(result, fieldName, sobj.asString(Charset.forName(_encoding))); } else { context.addUpload(item.getFieldName(), sobj); mergeValueInMap(result, fieldName, fieldName); } } } catch (FileUploadIOException e) { throw E.ioException("Error when handling upload", e); } catch (IOException e) { throw E.ioException("Error when handling upload", e); } catch (FileUploadException e) { throw E.ioException("Error when handling upload", e); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new UnexpectedException(e); } return result; }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data from request object (form, data and session) * // w w w . ja va2s . c om * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return all input fields into a service data * @throws ExilityException */ @SuppressWarnings("resource") public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); if (formIsSubmitted == false) { /** * most common call from client that uses serverAgent to send an * ajax request with serialized dc as data */ this.extractSerializedData(req, hasSerializedDc, inData); } else { /** * form is submitted. this is NOT from serverAgent.js. This call * would be from other .jsp files */ if (hasSerializedDc == false) { /** * client has submitted a form with form fields in that. * Traditional form submit **/ this.extractParametersAndFiles(req, inData); } else { /** * Logic got evolved over a period of time. several calling jsps * actually inspect the stream for file, and in the process they * would have extracted form fields into session. So, we extract * form fields, as well as dip into session */ HttpSession session = req.getSession(); if (ServletFileUpload.isMultipartContent(req) == false) { /** * Bit convoluted. the .jsp has already extracted files and * form fields into session. field. */ String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); } else { /** * jsp has not touched input stream, and it wants us to do * everything. */ try { ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); String fieldName = stream.getFieldName(); InputStream inStream = null; inStream = stream.openStream(); try { if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); /** * dc is a special name that contains * serialized DC */ if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { /** * it is a file. we assume that the files * are small, and hence we carry the content * in memory with a specific naming * convention */ String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } } catch (Exception e) { Spit.out("error whiel extracting data from request stream " + e.getMessage()); } IOUtils.closeQuietly(inStream); } } catch (Exception e) { // nothing to do here } /** * read session variables */ @SuppressWarnings("rawtypes") Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name.equals("dc")) { this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData); } String value = req.getSession().getAttribute(name).toString(); inData.addValue(name, value); System.out.println("name is: " + name + " value is: " + value); } } } } this.getStandardFields(req, inData); return inData; }
From source file:n3phele.service.rest.impl.CommandResource.java
@Consumes(MediaType.MULTIPART_FORM_DATA) @POST/*from www .ja v a 2s.co m*/ @Produces(MediaType.TEXT_PLAIN) @Path("import") @RolesAllowed("authenticated") public Response importer(@Context HttpServletRequest request) { try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); // JAXBContext jc = JAXBContext.newInstance(CommandDefinitions.class); // Unmarshaller u = jc.createUnmarshaller(); // CommandDefinitions a = (CommandDefinitions) u.unmarshal(stream); JSONJAXBContext jc = new JSONJAXBContext(CommandDefinitions.class); JSONUnmarshaller u = jc.createJSONUnmarshaller(); CommandDefinitions a = u.unmarshalFromJSON(stream, CommandDefinitions.class); StringBuilder response = new StringBuilder( "Processing " + a.getCommand().size() + " commands\n"); URI requestor = UserResource.toUser(securityContext).getUri(); for (CommandDefinition cd : a.getCommand()) { response.append(cd.getName()); response.append("....."); Command existing = null; try { if (cd.getUri() != null && cd.getUri().toString().length() != 0) { try { existing = dao.command().get(cd.getUri()); } catch (NotFoundException e1) { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; } else { if (c.isPreferred() && cd.isPreferred()) { c.setPreferred(false); dao.command().update(c); } } } } catch (Exception e) { // not found } } } else { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; break; } } } catch (Exception e) { // not found } } } catch (NotFoundException e) { } if (existing == null) { response.append(addCommand(cd)); } else { // update or illegal operation boolean isOwner = requestor.equals(existing.getOwner()); boolean mismatchedUri = (cd.getUri() != null && cd.getUri().toString().length() != 0) && !cd.getUri().equals(existing.getUri()); log.info("requestor is " + requestor + " owner is " + existing.getOwner() + " isOwner " + isOwner); log.info("URI in definition is " + cd.getUri() + " existing is " + existing.getUri() + " mismatchedUri " + mismatchedUri); if (!isOwner || mismatchedUri) { response.append("ignored: already exists"); } else { response.append(updateCommand(cd, existing)); response.append("\nupdated uri " + existing.getUri()); } } response.append("\n"); //response.append("</li>"); } //response.append("</ol>"); return Response.ok(response.toString()).build(); } } } catch (JAXBException e) { log.log(Level.WARNING, "JAXBException", e); } catch (FileUploadException e) { log.log(Level.WARNING, "FileUploadException", e); } catch (IOException e) { log.log(Level.WARNING, "IOException", e); } return Response.notModified().build(); }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * //from ww w .j a va 2s . co m * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return service data that contains all input fields * @throws ExilityException */ public ServiceData createInDataForStream(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); /** * this method is structured to handle simpler cases in the beginning if * form is not submitted, it has to be serialized data */ if (formIsSubmitted == false) { this.extractSerializedData(req, hasSerializedDc, inData); return inData; } if (hasSerializedDc == false) { this.extractParametersAndFiles(req, inData); return inData; } // it is a form submit with serialized DC in it HttpSession session = req.getSession(); try { if (ServletFileUpload.isMultipartContent(req) == false) { String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); return inData; } // complex case of file upload etc.. ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); InputStream inStream = null; try { inStream = stream.openStream(); String fieldName = stream.getFieldName(); if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } inStream.close(); } finally { IOUtils.closeQuietly(inStream); } } @SuppressWarnings("rawtypes") Enumeration e = req.getSession().getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name.equals("dc")) { this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData); } String value = req.getSession().getAttribute(name).toString(); inData.addValue(name, value); System.out.println("name is: " + name + " value is: " + value); } } catch (Exception ioEx) { // nothing to do here } return inData; }
From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.info("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try {//w w w . ja v a 2 s . co m // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.info("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.info("File field {} with file name detected.", name, item.getName()); log.info("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.info("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:hk.hku.cecid.corvus.http.PartnershipSenderUnitTest.java
/** * A Helper method which assert whether the HTTP content received in the HTTP monitor * is a multi-part form data, with basic-auth and well-formed partnership operation request. *//* www . ja v a 2s.c om*/ private void assertHttpRequestReceived() throws Exception { // Debug print information. Map headers = monitor.getHeaders(); // #0 Assertion assertFalse("No HTTP header found in the captured data.", headers.isEmpty()); Map.Entry tmp = null; Iterator itr = null; itr = headers.entrySet().iterator(); logger.info("Header information"); while (itr.hasNext()) { tmp = (Map.Entry) itr.next(); logger.info(tmp.getKey() + " : " + tmp.getValue()); } // #1 Check BASIC authentication value. String basicAuth = (String) headers.get("Authorization"); // #1 Assertion assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth); String[] authToken = basicAuth.split(" "); // There are 2 token, one is the "Basic" and another is the base64 auth value. assertTrue(authToken.length == 2); assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic")); // #1 Decode the base64 authentication value to see whether it is "corvus:corvus". String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8"); assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential); // #2 Check content Type String contentType = monitor.getContentType(); String mediaType = contentType.split(";")[0]; assertEquals("Invalid content type", "multipart/form-data", mediaType); // #3 Check the multi-part content. // Make a request context that bridge the content from our monitor to FileUpload library. RequestContext rc = new RequestContext() { public String getCharacterEncoding() { return "charset=ISO-8859-1"; } public int getContentLength() { return monitor.getContentLength(); } public String getContentType() { return monitor.getContentType(); } public InputStream getInputStream() { return monitor.getInputStream(); } }; FileUpload multipartParser = new FileUpload(); FileItemIterator item = multipartParser.getItemIterator(rc); FileItemStream fstream = null; /* * For each field in the partnership, we have to check the existence of the * associated field in the HTTP request. Also we check whether the content * of that web form field has same data to the field in the partnership. */ itr = this.target.getPartnershipMapping().entrySet().iterator(); Map data = ((KVPairData) this.target.properties).getProperties(); Map.Entry e; // an entry representing the partnership data to web form name mapping. String formParamName; // a temporary pointer pointing to the value in the entry. Object dataValue; // a temporary pointer pointing to the value in the partnership data. while (itr.hasNext()) { e = (Map.Entry) itr.next(); formParamName = (String) e.getValue(); // Add new part if the mapped key is not null. if (formParamName != null) { assertTrue("Insufficient number of web form parameter hit.", item.hasNext()); // Get the next multi-part element. fstream = item.next(); // Assert field name assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName()); // Assert field content dataValue = data.get(e.getKey()); if (dataValue instanceof String) { // Assert content equal. assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null)); } else if (dataValue instanceof byte[]) { byte[] expectedBytes = (byte[]) dataValue; byte[] actualBytes = IOHandler.readBytes(fstream.openStream()); // Assert byte length equal assertEquals(expectedBytes.length, actualBytes.length); for (int j = 0; j < expectedBytes.length; j++) assertEquals(expectedBytes[j], actualBytes[j]); } else { throw new IllegalArgumentException("Invalid content found in multipart."); } // Log information. logger.info("Field name found and verifed: " + fstream.getFieldName() + " content type:" + fstream.getContentType()); } } /* Check whether the partnership operation in the HTTP request is expected as i thought */ assertTrue("Missing request_action ?!", item.hasNext()); fstream = item.next(); assertEquals("request_action", fstream.getFieldName()); // Assert the request_action has same content the operation name. Map partnershipOpMap = this.target.getPartnershipOperationMapping(); assertEquals(partnershipOpMap.get(new Integer(this.target.getExecuteOperation())), IOHandler.readString(fstream.openStream(), null)); }
From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java
/** * Adds the resource content with language <code>language</code> to the * specified resource.//from ww w.j ava 2s.co m * * @param request * the request * @param resourceId * the resource identifier * @param languageId * the language identifier * @param is * the input stream * @return the resource */ @POST @Path("/{resource}/content/{language}") @Produces(MediaType.MEDIA_TYPE_WILDCARD) public Response addFileContent(@Context HttpServletRequest request, @PathParam("resource") String resourceId, @PathParam("language") String languageId) { Site site = getSite(request); // Check the parameters if (resourceId == null) throw new WebApplicationException(Status.BAD_REQUEST); // Extract the language Language language = LanguageUtils.getLanguage(languageId); if (language == null) { throw new WebApplicationException(Status.NOT_FOUND); } // Get the resource Resource<?> resource = loadResource(request, resourceId, null); if (resource == null || resource.contents().isEmpty()) { throw new WebApplicationException(Status.NOT_FOUND); } String fileName = null; String mimeType = null; File uploadedFile = null; try { // Multipart form encoding? if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload payload = new ServletFileUpload(); for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String fieldValue = Streams.asString(item.openStream()); if (StringUtils.isBlank(fieldValue)) continue; if (OPT_MIMETYPE.equals(fieldName)) { mimeType = fieldValue; } } else { // once the body gets read iter.hasNext must not be invoked // or the stream can not be read fileName = StringUtils.trim(item.getName()); mimeType = StringUtils.trim(item.getContentType()); uploadedFile = File.createTempFile("upload-", null); FileOutputStream fos = new FileOutputStream(uploadedFile); try { IOUtils.copy(item.openStream(), fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(fos); } } } } catch (FileUploadException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } } // Octet binary stream else { try { fileName = StringUtils.trimToNull(request.getHeader("X-File-Name")); mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE)); } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } InputStream is = null; FileOutputStream fos = null; try { is = request.getInputStream(); if (is == null) throw new WebApplicationException(Status.BAD_REQUEST); uploadedFile = File.createTempFile("upload-", null); fos = new FileOutputStream(uploadedFile); IOUtils.copy(is, fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } // Has there been a file in the request? if (uploadedFile == null) throw new WebApplicationException(Status.BAD_REQUEST); // A mime type would be nice as well if (StringUtils.isBlank(mimeType)) { mimeType = detectMimeTypeFromFile(fileName, uploadedFile); if (mimeType == null) throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } // Get the current user User user = securityService.getUser(); if (user == null) throw new WebApplicationException(Status.UNAUTHORIZED); // Make sure the user has editing rights if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR)) throw new WebApplicationException(Status.UNAUTHORIZED); // Try to create the resource content InputStream is = null; ResourceContent content = null; ResourceContentReader<?> reader = null; ResourceSerializer<?, ?> serializer = serializerService .getSerializerByType(resource.getURI().getType()); try { reader = serializer.getContentReader(); is = new FileInputStream(uploadedFile); content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType); } catch (IOException e) { logger.warn("Error reading resource content {} from request", resource.getURI()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (ParserConfigurationException e) { logger.warn("Error configuring parser to read resource content {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (SAXException e) { logger.warn("Error parsing udpated resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.BAD_REQUEST); } finally { IOUtils.closeQuietly(is); } URI uri = null; WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site, true); try { is = new FileInputStream(uploadedFile); resource = contentRepository.putContent(resource.getURI(), content, is); uri = new URI(resource.getURI().getIdentifier()); } catch (IOException e) { logger.warn("Error writing content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IllegalStateException e) { logger.warn("Illegal state while adding content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.PRECONDITION_FAILED); } catch (ContentRepositoryException e) { logger.warn("Error adding content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (URISyntaxException e) { logger.warn("Error creating a uri for resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); } // Create the response ResponseBuilder response = Response.created(uri); response.type(MediaType.MEDIA_TYPE_WILDCARD); response.tag(ResourceUtils.getETagValue(resource)); response.lastModified(ResourceUtils.getModificationDate(resource, language)); return response.build(); } finally { FileUtils.deleteQuietly(uploadedFile); } }