List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException
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;/*from w ww .j a va2 s.com*/ 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.glaf.core.web.servlet.FileUploadServlet.java
public void upload(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html;charset=UTF-8"); LoginContext loginContext = RequestUtils.getLoginContext(request); if (loginContext == null) { return;//from w w w . j a v a 2 s . c o m } String serviceKey = request.getParameter("serviceKey"); String type = request.getParameter("type"); if (StringUtils.isEmpty(type)) { type = "0"; } Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap:" + paramMap); String rootDir = SystemProperties.getConfigRootPath(); InputStream inputStream = null; try { DiskFileItemFactory diskFactory = new DiskFileItemFactory(); // threshold ???? 8M diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE); // repository diskFactory.setRepository(new File(rootDir + "/temp")); ServletFileUpload upload = new ServletFileUpload(diskFactory); int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0); if (maxUploadSize == 0) { maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB } maxUploadSize = maxUploadSize * FileUtils.MB_SIZE; logger.debug("maxUploadSize:" + maxUploadSize); upload.setHeaderEncoding("UTF-8"); upload.setSizeMax(maxUploadSize); upload.setFileSizeMax(maxUploadSize); String uploadDir = Constants.UPLOAD_PATH; if (ServletFileUpload.isMultipartContent(request)) { logger.debug("#################start upload process#########################"); FileItemIterator iter = upload.getItemIterator(request); PrintWriter out = response.getWriter(); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { // ???? String autoCreatedDateDirByParttern = "yyyy/MM/dd"; String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern); File savePath = new File(rootDir + uploadDir + autoCreatedDateDir); if (!savePath.exists()) { savePath.mkdirs(); } String fileId = UUID32.getUUID(); String fileName = savePath + "/" + fileId; BlobItem dataFile = new BlobItemEntity(); dataFile.setLastModified(System.currentTimeMillis()); dataFile.setCreateBy(loginContext.getActorId()); dataFile.setFileId(fileId); dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId); dataFile.setFilename(item.getName()); dataFile.setName(item.getName()); dataFile.setContentType(item.getContentType()); dataFile.setType(type); dataFile.setStatus(0); dataFile.setServiceKey(serviceKey); getBlobService().insertBlob(dataFile); inputStream = item.openStream(); FileUtils.save(fileName, inputStream); logger.debug(fileName + " save ok."); out.print(fileId); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { IOUtils.close(inputStream); } }
From source file:lucee.runtime.type.scope.FormImpl.java
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory(); Resource tempFile;//ww w . j av a 2 s .c o m // Create a new file upload handler final String encoding = getEncoding(); FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list = new ArrayList<URLItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); is = IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false)); } else { tempFile = tempDir.getRealResource(getFileName()); fileItems.put(item.getFieldName().toLowerCase(), new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName())); String value = tempFile.toString(); IOUtil.copy(is, tempFile, true); list.add(new URLItem(item.getFieldName(), value, false)); } } raw = list.toArray(new URLItem[list.size()]); fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException = e; } }
From source file:com.netflix.zuul.scriptManager.FilterScriptManagerServlet.java
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); org.apache.commons.fileupload.FileItemIterator it = null; try {//from w ww . j av a 2s . c o m it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream stream = it.next(); InputStream input = stream.openStream(); // NOTE: we are going to pull the entire stream into memory // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger byte[] uploadedBytes = getBytesFromInputStream(input); input.close(); if (uploadedBytes.length == 0) { setUsageError(400, "ERROR: Body contained no data.", response); return null; } return new String(uploadedBytes); } } catch (FileUploadException e) { throw new IOException(e.getMessage()); } return null; }
From source file:n3phele.service.rest.impl.CommandResource.java
@Consumes(MediaType.MULTIPART_FORM_DATA) @POST/*from w ww . jav a2 s.c om*/ @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 w w w . java2 s . com * @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.sonicle.webtop.core.app.AbstractEnvironmentService.java
public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { ServletFileUpload upload = null; WebTopSession.UploadedFile uploadedFile = null; HashMap<String, String> multipartParams = new HashMap<>(); try {/* ww w.ja v a 2 s. co m*/ String service = ServletUtils.getStringParameter(request, "service", true); String cntx = ServletUtils.getStringParameter(request, "context", true); String tag = ServletUtils.getStringParameter(request, "tag", null); if (!ServletFileUpload.isMultipartContent(request)) throw new Exception("No upload request"); IServiceUploadStreamListener istream = getUploadStreamListener(cntx); if (istream != null) { try { MapItem data = new MapItem(); // Empty response data // Defines the upload object upload = new ServletFileUpload(); FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { InputStream is = null; try { is = fis.openStream(); String key = fis.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(), tag, fis.getName(), -1, findMediaType(fis)); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("editable", isFileEditableInDocEditor(fis.getName())); // Handle listener, its implementation can stop // file upload throwing a UploadException. InputStream is = null; try { getEnv().getSession().addUploadedFile(uploadedFile); is = fis.openStream(); istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data); } finally { IOUtils.closeQuietly(is); getEnv().getSession().removeUploadedFile(uploadedFile, false); } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(false, ex1.getMessage()).printTo(out); } catch (Exception ex1) { throw ex1; } } else { try { MapItem data = new MapItem(); // Empty response data IServiceUploadListener iupload = getUploadListener(cntx); // Defines the upload object DiskFileItemFactory factory = new DiskFileItemFactory(); //TODO: valutare come imporre i limiti //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); upload = new ServletFileUpload(factory); List<FileItem> files = upload.parseRequest(request); // Plupload component (client-side) will upload multiple file // each in its own request. So we can skip loop on files. Iterator it = files.iterator(); while (it.hasNext()) { FileItem fi = (FileItem) it.next(); if (fi.isFormField()) { InputStream is = null; try { is = fi.getInputStream(); String key = fi.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Writes content into a temp file File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX); fi.write(file); // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag, fi.getName(), fi.getSize(), findMediaType(fi)); getEnv().getSession().addUploadedFile(uploadedFile); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("uploadId", uploadedFile.getUploadId()); data.add("editable", isFileEditableInDocEditor(fi.getName())); // Handle listener (if present), its implementation can stop // file upload throwing a UploadException. if (iupload != null) { try { iupload.onUpload(cntx, request, multipartParams, uploadedFile, data); } catch (UploadException ex2) { getEnv().getSession().removeUploadedFile(uploadedFile, true); throw ex2; } } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(ex1).printTo(out); } } } catch (Exception ex) { WebTopApp.logger.error("Error uploading", ex); new JsonResult(ex).printTo(out); } }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data from request object (form, data and session) * /* w w w .ja v a 2 s. com*/ * @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: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 {//from w w w . j a 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:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java
/** * Adds the resource content with language <code>language</code> to the * specified resource./*from w w w. j a va 2 s . 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); } }