List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:org.activiti.rest.api.process.BaseExecutionVariableResource.java
protected RestVariable setBinaryVariable(Representation representation, Execution execution, boolean isNew) { try {/*from ww w.j av a2 s.co m*/ RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(representation); String variableScope = null; String variableName = null; String variableType = null; FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("scope".equals(fileItem.getFieldName())) { variableScope = fileItem.getString("UTF-8"); } else if ("name".equals(fileItem.getFieldName())) { variableName = fileItem.getString("UTF-8"); } else if ("type".equals(fileItem.getFieldName())) { variableType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } // Validate input and set defaults if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } if (variableName == null) { throw new ActivitiIllegalArgumentException("No variable name was found in request body."); } if (variableType != null) { if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) { throw new ActivitiIllegalArgumentException( "Only 'binary' and 'serializable' are supported as variable type."); } } else { variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE; } RestVariableScope scope = RestVariableScope.LOCAL; if (variableScope != null) { scope = RestVariable.getScopeFromString(variableScope); } if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) { // Use raw bytes as variable value ByteArrayOutputStream variableOutput = new ByteArrayOutputStream( ((Long) uploadItem.getSize()).intValue()); IOUtils.copy(uploadItem.getInputStream(), variableOutput); setVariable(execution, variableName, variableOutput.toByteArray(), scope, isNew); } else { // Try deserializing the object ObjectInputStream stream = new ObjectInputStream(uploadItem.getInputStream()); Object value = stream.readObject(); setVariable(execution, variableName, value, scope, isNew); stream.close(); } if (execution instanceof ProcessInstance) { return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, null, null, execution.getId()); } else { return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, null, execution.getId(), null); } } catch (FileUploadException fue) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, fue); } catch (IOException ioe) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, ioe); } catch (ClassNotFoundException ioe) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage(), null, null); } }
From source file:org.activiti.rest.api.repository.BaseModelSourceResource.java
@Put public InputRepresentation setModelSource(Representation representation) { if (authenticate() == false) return null; Model model = getModelFromRequest(); if (!MediaType.MULTIPART_FORM_DATA.isCompatible(representation.getMediaType())) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The request should be of type 'multipart/form-data'.", null, null); }//from ww w . j av a 2 s. c o m RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); try { FileItem uploadItem = null; List<FileItem> items = upload.parseRepresentation(representation); for (FileItem fileItem : items) { uploadItem = fileItem; } if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } int size = ((Long) uploadItem.getSize()).intValue(); // Copy file-body in a bytearray as the engine requires this ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size); IOUtils.copy(uploadItem.getInputStream(), bytesOutput); byte[] byteArray = bytesOutput.toByteArray(); setModelSource(model, byteArray); return new InputRepresentation(new ByteArrayInputStream(byteArray), MediaType.APPLICATION_OCTET_STREAM); } catch (FileUploadException e) { throw new ActivitiException("Error with uploaded file: " + e.getMessage(), e); } catch (IOException e) { throw new ActivitiException("Error while reading uploaded file: " + e.getMessage(), e); } }
From source file:org.activiti.rest.api.runtime.process.BaseExecutionVariableResource.java
protected RestVariable setBinaryVariable(Representation representation, Execution execution, boolean isNew) { try {/* w w w . j a v a2 s . c o m*/ RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(representation); String variableScope = null; String variableName = null; String variableType = null; FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("scope".equals(fileItem.getFieldName())) { variableScope = fileItem.getString("UTF-8"); } else if ("name".equals(fileItem.getFieldName())) { variableName = fileItem.getString("UTF-8"); } else if ("type".equals(fileItem.getFieldName())) { variableType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } // Validate input and set defaults if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } if (variableName == null) { throw new ActivitiIllegalArgumentException("No variable name was found in request body."); } if (variableType != null) { if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) { throw new ActivitiIllegalArgumentException( "Only 'binary' and 'serializable' are supported as variable type."); } } else { variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE; } RestVariableScope scope = RestVariableScope.LOCAL; if (variableScope != null) { scope = RestVariable.getScopeFromString(variableScope); } if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) { // Use raw bytes as variable value ByteArrayOutputStream variableOutput = new ByteArrayOutputStream( ((Long) uploadItem.getSize()).intValue()); IOUtils.copy(uploadItem.getInputStream(), variableOutput); setVariable(execution, variableName, variableOutput.toByteArray(), scope, isNew); } else { // Try deserializing the object ObjectInputStream stream = new ObjectInputStream(uploadItem.getInputStream()); Object value = stream.readObject(); setVariable(execution, variableName, value, scope, isNew); stream.close(); } if (execution instanceof ProcessInstance && allowProcessInstanceUrl()) { return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, null, null, execution.getId()); } else { return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, null, execution.getId(), null); } } catch (FileUploadException fue) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, fue); } catch (IOException ioe) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, ioe); } catch (ClassNotFoundException ioe) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage(), null, null); } }
From source file:org.activiti.rest.api.runtime.task.TaskVariableBaseResource.java
protected RestVariable setBinaryVariable(Representation representation, Task task, boolean isNew) { try {/*from w ww . java 2s . com*/ RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(representation); String variableScope = null; String variableName = null; String variableType = null; FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("scope".equals(fileItem.getFieldName())) { variableScope = fileItem.getString("UTF-8"); } else if ("name".equals(fileItem.getFieldName())) { variableName = fileItem.getString("UTF-8"); } else if ("type".equals(fileItem.getFieldName())) { variableType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } // Validate input and set defaults if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } if (variableName == null) { throw new ActivitiIllegalArgumentException("No variable name was found in request body."); } if (variableType != null) { if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) { throw new ActivitiIllegalArgumentException( "Only 'binary' and 'serializable' are supported as variable type."); } } else { variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE; } RestVariableScope scope = RestVariableScope.LOCAL; if (variableScope != null) { scope = RestVariable.getScopeFromString(variableScope); } if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) { // Use raw bytes as variable value ByteArrayOutputStream variableOutput = new ByteArrayOutputStream( ((Long) uploadItem.getSize()).intValue()); IOUtils.copy(uploadItem.getInputStream(), variableOutput); setVariable(task, variableName, variableOutput.toByteArray(), scope, isNew); } else { // Try deserializing the object ObjectInputStream stream = new ObjectInputStream(uploadItem.getInputStream()); Object value = stream.readObject(); setVariable(task, variableName, value, scope, isNew); stream.close(); } return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, task.getId(), null, null); } catch (FileUploadException fue) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, fue); } catch (IOException ioe) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, ioe); } catch (ClassNotFoundException ioe) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage(), null, null); } }
From source file:org.activiti.rest.api.task.BaseTaskVariableResource.java
protected RestVariable setBinaryVariable(Representation representation, Task task, boolean isNew) { try {/*from www . jav a 2s.c o m*/ RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(representation); String variableScope = null; String variableName = null; String variableType = null; FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("scope".equals(fileItem.getFieldName())) { variableScope = fileItem.getString("UTF-8"); } else if ("name".equals(fileItem.getFieldName())) { variableName = fileItem.getString("UTF-8"); } else if ("type".equals(fileItem.getFieldName())) { variableType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } // Validate input and set defaults if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } if (variableName == null) { throw new ActivitiIllegalArgumentException("No variable name was found in request body."); } if (variableType != null) { if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) { throw new ActivitiIllegalArgumentException( "Only 'binary' and 'serializable' are supported as variable type."); } } else { variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE; } RestVariableScope scope = RestVariableScope.LOCAL; if (variableScope != null) { scope = RestVariable.getScopeFromString(variableScope); } if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) { // Use raw bytes as variable value ByteArrayOutputStream variableOutput = new ByteArrayOutputStream( ((Long) uploadItem.getSize()).intValue()); IOUtils.copy(uploadItem.getInputStream(), variableOutput); setVariable(task, variableName, variableOutput.toByteArray(), scope, isNew); } else { // Try deserializing the object ObjectInputStream stream = new ObjectInputStream(uploadItem.getInputStream()); Object value = stream.readObject(); setVariable(task, variableName, value, scope, isNew); stream.close(); } return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, task.getId(), null); } catch (FileUploadException fue) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, fue); } catch (IOException ioe) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, ioe); } catch (ClassNotFoundException ioe) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage(), null, null); } }
From source file:org.activiti.rest.service.api.identity.UserPictureResource.java
@Put public void updateUserPicture(Representation representation) { if (authenticate() == false) return;//from w w w. j a va2s .c o m User user = getUserFromRequest(); if (!MediaType.MULTIPART_FORM_DATA.isCompatible(representation.getMediaType())) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The request should be of type 'multipart/form-data'.", null, null); } RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); try { FileItem uploadItem = null; List<FileItem> items = upload.parseRepresentation(representation); String mimeType = MediaType.IMAGE_JPEG.toString(); for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("mimeType".equals(fileItem.getFieldName())) { mimeType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } int size = ((Long) uploadItem.getSize()).intValue(); // Copy file-body in a bytearray as the engine requires this ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size); IOUtils.copy(uploadItem.getInputStream(), bytesOutput); Picture newPicture = new Picture(bytesOutput.toByteArray(), mimeType); ActivitiUtil.getIdentityService().setUserPicture(user.getId(), newPicture); } catch (FileUploadException e) { throw new ActivitiException("Error with uploaded file: " + e.getMessage(), e); } catch (IOException e) { throw new ActivitiException("Error while reading uploaded file: " + e.getMessage(), e); } }
From source file:org.activityinfo.server.attachment.AttachmentServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w . jav a 2 s .c o m String key = request.getParameter("blobId"); Integer siteId = Integer.valueOf(request.getParameter("siteId")); FileItem fileItem = getFirstUploadFile(request); String fileName = fileItem.getName(); InputStream uploadingStream = fileItem.getInputStream(); service.upload(key, fileItem, uploadingStream); CreateSiteAttachment siteAttachment = new CreateSiteAttachment(); siteAttachment.setSiteId(siteId); siteAttachment.setBlobId(key); siteAttachment.setFileName(fileName); siteAttachment.setBlobSize(fileItem.getSize()); siteAttachment.setContentType(fileItem.getContentType()); dispatcher.execute(siteAttachment); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error handling upload", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.alfresco.web.app.servlet.UploadFileServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w. ja va 2 s .c o m @SuppressWarnings("unchecked") protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uploadId = null; String returnPage = null; final RequestContext requestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext); try { AuthenticationStatus status = servletAuthenticate(request, response); if (status == AuthenticationStatus.Failure) { return; } if (!isMultipart) { throw new AlfrescoRuntimeException( "This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data"); } if (logger.isDebugEnabled()) logger.debug("Uploading servlet servicing..."); FacesContext context = FacesContext.getCurrentInstance(); Map<Object, Object> session = context.getExternalContext().getSessionMap(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // ensure that the encoding is handled correctly upload.setHeaderEncoding("UTF-8"); List<FileItem> fileItems = upload.parseRequest(request); FileUploadBean bean = new FileUploadBean(); for (FileItem item : fileItems) { if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("return-page")) { returnPage = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("upload-id")) { uploadId = item.getString(); } } else { String filename = item.getName(); if (filename != null && filename.length() != 0) { if (logger.isDebugEnabled()) { logger.debug("Processing uploaded file: " + filename); } // ADB-41: Ignore non-existent files i.e. 0 byte streams. if (allowZeroByteFiles() == true || item.getSize() > 0) { // workaround a bug in IE where the full path is returned // IE is only available for Windows so only check for the Windows path separator filename = FilenameUtils.getName(filename); final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload"); item.write(tempFile); bean.setFile(tempFile); bean.setFileName(filename); bean.setFilePath(tempFile.getAbsolutePath()); if (logger.isDebugEnabled()) { logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename); } } else { if (logger.isWarnEnabled()) logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client."); } } } } session.put(FileUploadBean.getKey(uploadId), bean); if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) { logger.warn("no file uploaded for upload id: " + uploadId); } if (returnPage == null || returnPage.length() == 0) { throw new AlfrescoRuntimeException("return-page parameter has not been supplied"); } JSONObject json; try { json = new JSONObject(returnPage); if (json.has("id") && json.has("args")) { // finally redirect if (logger.isDebugEnabled()) { logger.debug("Sending back javascript response " + returnPage); } response.setContentType(MimetypeMap.MIMETYPE_HTML); response.setCharacterEncoding("utf-8"); // work-around for WebKit protection against embedded javascript on POST body response response.setHeader("X-XSS-Protection", "0"); final PrintWriter out = response.getWriter(); out.println("<html><body><script type=\"text/javascript\">"); out.println("window.parent.upload_complete_helper("); out.println("'" + json.getString("id") + "'"); out.println(", "); out.println(json.getJSONObject("args")); out.println(");"); out.println("</script></body></html>"); out.close(); } } catch (JSONException e) { // finally redirect if (logger.isDebugEnabled()) logger.debug("redirecting to: " + returnPage); response.sendRedirect(returnPage); } if (logger.isDebugEnabled()) logger.debug("upload complete"); } catch (Throwable error) { handleUploadException(request, response, error, returnPage); } }
From source file:org.apache.hupa.server.utils.TestUtils.java
/** * Creates a client side mock smtp message. * It is possible to say the number of attachments we want. * * @param registry/*ww w . j a v a2 s. com*/ * @param nfiles * @return * @throws AddressException * @throws MessagingException * @throws IOException */ public static SmtpMessage createMockSMTPMessage(FileItemRegistry registry, int nfiles) throws AddressException, MessagingException, IOException { ArrayList<MessageAttachment> attachments = new ArrayList<MessageAttachment>(); for (int i = 1; i <= nfiles; i++) { FileItem fileItem; fileItem = TestUtils.createMockFileItem("uploadedFile_" + i + ".bin"); registry.add(fileItem); MessageAttachment msgAttach = new MessageAttachmentImpl(); msgAttach.setName(fileItem.getFieldName()); msgAttach.setContentType(fileItem.getContentType()); msgAttach.setSize((int) fileItem.getSize()); attachments.add(msgAttach); } SmtpMessage smtpMessage = new SmtpMessageImpl(); smtpMessage.setFrom("Test user <from@dom.com>"); smtpMessage.setTo(Arrays.asList("to@dom.com")); smtpMessage.setCc(Arrays.asList("cc@dom.com")); smtpMessage.setBcc(Arrays.asList("bcc@dom.com")); smtpMessage.setSubject("Subject"); smtpMessage.setText("<div>Body</div>"); smtpMessage.setMessageAttachments(attachments); return smtpMessage; }
From source file:org.apache.jackrabbit.demo.blog.servlet.BlogAddControllerServlet.java
/** * This methods handles POST requests and adds the blog entries according to the parameters in the * request. Request must be multi-part encoded. *//*from ww w.j av a 2 s .co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List parameters = null; String title = null; String content = null; FileItem image = null; FileItem video = null; // Check whether the request is multipart encoded if (ServletFileUpload.isMultipartContent(request)) { DefaultFileItemFactory fileItemFactory = new DefaultFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); try { // Parse the request and get the paramter set parameters = fileUpload.parseRequest(request); Iterator paramIter = parameters.iterator(); // Resolve the parameter set while (paramIter.hasNext()) { FileItem item = (FileItem) paramIter.next(); if (item.getFieldName().equalsIgnoreCase("title")) { title = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("content")) { content = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("image")) { image = item; } else if (item.getFieldName().equalsIgnoreCase("video")) { video = item; } } } catch (FileUploadException e) { throw new ServletException("Error occured in processing the multipart request", e); } } else { throw new ServletException("Request is not a multi-part encoded request"); } try { //log in to the repository and aquire a session Session session = repository.login(new SimpleCredentials("username", "password".toCharArray())); String username = (String) request.getSession().getAttribute("username"); // Only logged in users are allowed to create blog entries if (username == null) { //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Authentication Required"); request.setAttribute("msgBody", "Only logged in users are allowed to add blog entries."); request.setAttribute("urlText", "go back to login page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/index.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } Node blogRootNode = session.getRootNode().getNode("blogRoot"); Node userNode = blogRootNode.getNode(username); // Node to hold the current year Node yearNode; // Node to hold the current month Node monthNode; // Node to hold the blog entry to be added Node blogEntryNode; // Holds the name of the blog entry node String nodeName; // createdOn property of the blog entry is set to the current time. Calendar calendar = Calendar.getInstance(); String year = calendar.get(Calendar.YEAR) + ""; String month = calendar.get(Calendar.MONTH) + ""; // check whether node exists for current year under usernode and creates a one if not exist if (userNode.hasNode(year)) { yearNode = userNode.getNode(year); } else { yearNode = userNode.addNode(year, "nt:folder"); } // check whether node exists for current month under the current year and creates a one if not exist if (yearNode.hasNode(month)) { monthNode = yearNode.getNode(month); } else { monthNode = yearNode.addNode(month, "nt:folder"); } if (monthNode.hasNode(title)) { nodeName = createUniqueName(title, monthNode); } else { nodeName = title; } // creates a blog entry under the current month blogEntryNode = monthNode.addNode(nodeName, "blog:blogEntry"); blogEntryNode.setProperty("blog:title", title); blogEntryNode.setProperty("blog:content", content); Value date = session.getValueFactory().createValue(Calendar.getInstance()); blogEntryNode.setProperty("blog:created", date); blogEntryNode.setProperty("blog:rate", 0); // If the blog entry has an image if (image.getSize() > 0) { if (image.getContentType().startsWith("image")) { Node imageNode = blogEntryNode.addNode("image", "nt:file"); Node contentNode = imageNode.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", image.getInputStream()); contentNode.setProperty("jcr:mimeType", image.getContentType()); contentNode.setProperty("jcr:lastModified", date); } else { session.refresh(false); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Unsupported image format"); request.setAttribute("msgBody", "The image you attached in not supported"); request.setAttribute("urlText", "go back to new blog entry page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } } // If the blog entry has a video if (video.getSize() > 0) { if (video.getName().endsWith(".flv") || video.getName().endsWith(".FLV")) { Node imageNode = blogEntryNode.addNode("video", "nt:file"); Node contentNode = imageNode.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", video.getInputStream()); contentNode.setProperty("jcr:mimeType", video.getContentType()); contentNode.setProperty("jcr:lastModified", date); } else { session.refresh(false); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Unsupported video format"); request.setAttribute("msgBody", "Only Flash videos (.flv) are allowed as video attachement. click <a href=\"www.google.com\">here</a> to covert the videos online."); request.setAttribute("urlText", "go back to new blog entry page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } } // persist the changes done session.save(); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Blog entry added succesfully"); request.setAttribute("msgBody", "Blog entry titled \"" + title + "\" was successfully added to your blog space"); request.setAttribute("urlText", "go back to my blog page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/view"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); } catch (RepositoryException e) { throw new ServletException("Repository error occured", e); } finally { if (session != null) { session.logout(); } } }