List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java
/** * invokeProcessEngine./*from w w w .j a va 2 s. co m*/ * * @param req * @param res * @param httpSession * @param pathInfo * @param embeddedInvocation TODO * @throws IOException * @throws ServletException */ private void invokeProcessEngine(HttpServletRequest req, HttpServletResponse res, HttpSession httpSession, String pathInfo, Map<Object, Object> variableValues, @SuppressWarnings("rawtypes") Map<String, String[]> parameterValues, boolean embeddedInvocation) throws IOException, ServletException { boolean newSession = false; Integer depth = (Integer) httpSession.getAttribute("connector.depth"); if (depth == null) { depth = new Integer(0); } String prefix = "connector.attributes."; String fullPrefix = prefix + depth.intValue() + "."; if (embeddedInvocation) httpSession.setAttribute(fullPrefix + "fragment", "true"); Deployment deployment = null; String brand = null; String entryName = null; boolean subdialog = false; if (!pathInfo.startsWith(PATH_PREFIX)) { System.out.println("invoking process engine for new session: " + pathInfo); newSession = true; synchronized (this) { for (String path : deploymentsByPath.keySet()) { System.out.println("Comparing to deployment: " + path); if (pathInfo.equals(path) || pathInfo.startsWith(path) && pathInfo.length() > path.length() && pathInfo.charAt(path.length()) == '/') { deployment = deploymentsByPath.get(path); System.out.println("Matching deployment found: " + deployment); brand = req.getParameter("BRAND"); if (req.getParameter("SUBDIALOG") != null) subdialog = Boolean.parseBoolean(req.getParameter("SUBDIALOG")); if (pathInfo.length() > path.length() + 1) { entryName = pathInfo.substring(path.length() + 1); System.out.println("Entry point name: " + entryName); } break; } } } if (deployment == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (entryName == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } pathInfo = NEXT_PATH; httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deployment.getProcessID()); } else if (pathInfo.equals(LOG_PATH)) { if (req.getParameter("cmd") != null && req.getParameter("cmd").equals("set")) { String level = req.getParameter("level"); if (level == null || (!level.equalsIgnoreCase("ERROR") && !level.equalsIgnoreCase("WARN") && !level.equalsIgnoreCase("INFO") && !level.equalsIgnoreCase("DEBUG"))) level = "INFO"; System.setProperty("org.eclipse.vtp.loglevel", level); } writeLogging(req, res); return; } else { String deploymentID = (String) httpSession.getAttribute(fullPrefix + DEPLOYMENT_ID); synchronized (this) { deployment = deploymentsByID.get(deploymentID); } if (deployment == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (subdialog) httpSession.setAttribute(fullPrefix + "subdialog", "true"); if (pathInfo.equals(INDEX_PATH)) { writeIndex(res, deployment); return; } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); if (ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) { System.out.println( "ServletFileUpload.isMultipartContent(new ServletRequestContext(httpRequest)) is true"); try { List items = upload.parseRequest(req); for (int i = 0; i < items.size(); i++) { FileItem fui = (FileItem) items.get(i); if (fui.isFormField() || "text/plain".equals(fui.getContentType())) { System.out.println("Form Field: " + fui.getFieldName() + " | " + fui.getString()); parameterValues.put(fui.getFieldName(), new String[] { fui.getString() }); } else { File temp = File.createTempFile(Guid.createGUID(), ".tmp"); fui.write(temp); parameterValues.put(fui.getFieldName(), new String[] { temp.getAbsolutePath() }); fui.delete(); System.out.println("File Upload: " + fui.getFieldName()); System.out.println("\tTemp file name: " + temp.getAbsolutePath()); System.out.println("\tContent Type: " + fui.getContentType()); System.out.println("\tSize: " + fui.getSize()); } } } catch (Exception e) { e.printStackTrace(); } } for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); parameterValues.put(key, req.getParameterValues(key)); } for (String key : parameterValues.keySet()) { String[] values = parameterValues.get(key); if (values == null || values.length == 0) System.out.println(key + " empty"); else { System.out.println(key + " " + values[0]); for (int i = 1; i < values.length; i++) System.out.println("\t" + values[i]); } } IDocument document = null; if (pathInfo.equals(ABORT_PATH)) document = deployment.abort(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else if (pathInfo.equals(NEXT_PATH)) { if (brand == null && !newSession) document = deployment.next(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else document = deployment.start(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues, entryName, brand, subdialog); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (document == null) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else if (document instanceof ControllerDocument) { ControllerDocument cd = (ControllerDocument) document; if (cd.getTarget() == null) { @SuppressWarnings("unchecked") Map<String, Map<String, Object>> outgoing = (Map<String, Map<String, Object>>) httpSession .getAttribute(fullPrefix + "outgoing-data"); int newDepth = depth.intValue() - 1; if (newDepth == 0) httpSession.removeAttribute("connector.depth"); else httpSession.setAttribute("connector.depth", new Integer(newDepth)); String oldFullPrefix = fullPrefix; fullPrefix = prefix + newDepth + "."; Object[] params = (Object[]) httpSession.getAttribute(fullPrefix + "exitparams"); if (params != null) for (int i = 0; i < params.length; i += 2) parameterValues.put((String) params[i], (String[]) params[i + 1]); String[] paramNames = cd.getParameterNames(); for (int i = 0; i < paramNames.length; ++i) parameterValues.put(paramNames[i], cd.getParameterValues(paramNames[i])); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); if (outgoing != null) { Map<String, Object> map = outgoing.get(cd.getParameterValues("exit")[0]); if (map != null) { for (int i = 0; i < variableNames.length; ++i) { Object mapping = map.get(variableNames[i]); if (mapping != null) variables.put(mapping, cd.getVariableValue(variableNames[i])); } } } deployment.end(httpSession, prefix, depth.intValue()); for (@SuppressWarnings("rawtypes") Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); if (name.startsWith(oldFullPrefix)) httpSession.removeAttribute(name); } invokeProcessEngine(req, res, httpSession, NEXT_PATH, variables, parameterValues, newDepth > 0); return; } else { String[] paramNames = cd.getParameterNames(); Object[] params = new Object[paramNames.length * 2]; for (int i = 0; i < params.length; i += 2) { params[i] = paramNames[i / 2]; params[i + 1] = cd.getParameterValues(paramNames[i / 2]); } httpSession.setAttribute(fullPrefix + "exitparams", params); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); for (int i = 0; i < variableNames.length; ++i) variables.put(variableNames[i], cd.getVariableValue(variableNames[i])); httpSession.setAttribute("connector.depth", new Integer(depth.intValue() + 1)); fullPrefix = prefix + (depth.intValue() + 1) + "."; String deploymentId = cd.getTarget().substring(0, cd.getTarget().lastIndexOf('(') - 1); String entryPointName = cd.getTarget().substring(cd.getTarget().lastIndexOf('(') + 1, cd.getTarget().length() - 1); httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deploymentId); httpSession.setAttribute(fullPrefix + ENTRY_POINT_NAME, entryPointName); Map<String, Map<String, Object>> outgoing = new HashMap<String, Map<String, Object>>(); String[] outPaths = cd.getOutgoingPaths(); for (int i = 0; i < outPaths.length; ++i) { Map<String, Object> map = new HashMap<String, Object>(); String[] names = cd.getOutgoingDataNames(outPaths[i]); for (int j = 0; j < names.length; ++j) map.put(names[j], cd.getOutgoingDataValue(outPaths[i], names[j])); outgoing.put(outPaths[i], map); } httpSession.setAttribute(fullPrefix + "outgoing-data", outgoing); invokeProcessEngine(req, res, httpSession, "/" + deploymentId + "/" + entryPointName, variables, parameterValues, true); return; } } res.setStatus(HttpServletResponse.SC_OK); if (!document.isCachable()) res.setHeader("Cache-Control", "max-age=0, no-cache"); res.setContentType(document.getContentType()); OutputStream writer = res.getOutputStream(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); if (reporter.isSeverityEnabled(IReporter.SEVERITY_INFO) && !document.isSecured()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); xmlWriter = new XMLWriter(baos); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); System.out.println(new String(baos.toByteArray(), "UTF-8")); } } catch (TransformerException e) { throw new ServletException(e); } writer.flush(); writer.close(); }
From source file:org.entermedia.upload.FileUpload.java
protected void readParameters(WebPageRequest inContext, ServletFileUpload uploadreader, UploadRequest upload, String encoding) throws UnsupportedEncodingException { List fileItems;//from w w w. ja v a 2s . c o m FileItemIterator itemIterator; try { fileItems = uploadreader.parseRequest(inContext.getRequest()); // This is a multipart MIME-encoded request, so the request // parameters must all be parsed from the POST body, not // gotten directly off the HttpServletRequest. for (int i = 0; i < fileItems.size(); i++) { org.apache.commons.fileupload.FileItem tmp = (org.apache.commons.fileupload.FileItem) fileItems .get(i); int count = 0; if (!tmp.isFormField()) { if (tmp.getContentType() != null && tmp.getContentType().toLowerCase().contains("json")) { JsonSlurper slurper = new JsonSlurper(); String content = tmp.getString(encoding).trim(); Map jsonRequest = (Map) slurper.parseText(content); //this is real, the other way is just for t inContext.setJsonRequest(jsonRequest); } else { FileUploadItem foundUpload = new FileUploadItem(); foundUpload.setFileItem(tmp); String name = tmp.getName(); if (name != null && name.contains("\\")) { name = name.substring(name.lastIndexOf("\\") + 1); } foundUpload.setName(name); //String num = "0"; //int index = tmp.getFieldName().indexOf("."); // if( index > -1) // { // num = tmp.getFieldName().substring(index+1); // } foundUpload.setCount(count); count++; upload.addUploadItem(foundUpload); } } } } catch (Exception e) { throw new OpenEditException(e); } //TODO: Find out why Apache creates tmp files for each parameter attached to the body of the upload Map arguments = inContext.getParameterMap(); for (int i = 0; i < fileItems.size(); i++) { org.apache.commons.fileupload.FileItem tmp = (org.apache.commons.fileupload.FileItem) fileItems.get(i); if (tmp.isFormField()) { Object vals = arguments.get(tmp.getFieldName()); String[] values = null;//(String[]) if (vals instanceof String) { values = new String[1]; values[0] = (String) vals; //the old value? } else if (vals != null) { values = (String[]) vals; } if (values == null) { values = new String[1]; } else { //grow by one String[] newvalues = new String[values.length + 1]; System.arraycopy(values, 0, newvalues, 0, values.length); values = newvalues; } values[values.length - 1] = tmp.getString(encoding).trim(); arguments.put(tmp.getFieldName(), values); } } for (Iterator iterator = arguments.keySet().iterator(); iterator.hasNext();) { String param = (String) iterator.next(); Object vals = arguments.get(param); if (vals instanceof String[]) { String[] existing = (String[]) vals; inContext.setRequestParameter(param, existing); if (param.equals("jsonrequest") && existing.length > 0) { JsonSlurper slurper = new JsonSlurper(); String content = existing[0]; Map jsonRequest = (Map) slurper.parseText(content); //this is real, the other way is just for t inContext.setJsonRequest(jsonRequest); } } } addAlreadyUploaded(inContext, upload); }
From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java
/** * {@inheritDoc}/* w w w. ja v a 2s . co m*/ */ public Reference addAttachment(String application, String context, String prefix, NameConflictResolution onConflict, FileItem file, boolean makeThumb, String altRef) { pushAdvisor(); try { String name = file.getName(); if (name != null) { name = massageName(name); } String type = file.getContentType(); // TODO: change to file.getInputStream() for after Sakai 2.3 more efficient support // InputStream body = file.getInputStream(); byte[] body = file.get(); long size = file.getSize(); // detect no file selected if ((name == null) || (type == null) || (body == null) || (size == 0)) { // TODO: if using input stream, close it // if (body != null) body.close(); return null; } Reference rv = addAttachment(name, name, application, context, prefix, onConflict, type, body, size, makeThumb, altRef); return rv; } finally { popAdvisor(); } }
From source file:org.etudes.tool.melete.AddResourcesPage.java
public String addItems() { byte[] secContentData; String secResourceName;/* www. j a v a 2 s.c om*/ String secContentMimeType; FacesContext context = FacesContext.getCurrentInstance(); ResourceLoader bundle = new ResourceLoader("org.etudes.tool.melete.bundle.Messages"); String addCollId = getMeleteCHService().getUploadCollectionId(); //Code that validates required fields int emptyCounter = 0; String linkValue, titleValue; boolean emptyLinkFlag = false; boolean emptyTitleFlag = false; err_fields = null; if (this.fileType.equals("upload")) { for (int i = 1; i <= 10; i++) { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get("file" + i); if (fi == null || fi.getName() == null || fi.getName().length() == 0) { emptyCounter = emptyCounter + 1; } } if (emptyCounter == 10) { FacesContext ctx = FacesContext.getCurrentInstance(); ValueBinding binding = Util.getBinding("#{manageResourcesPage}"); ManageResourcesPage manResPage = (ManageResourcesPage) binding.getValue(ctx); manResPage.resetValues(); return "manage_content"; } /* try { if (emptyCounter == 10) throw new MeleteException("all_uploads_empty"); } catch (MeleteException mex) { String errMsg = bundle.getString(mex.getMessage()); context.addMessage (null, new FacesMessage(FacesMessage.SEVERITY_ERROR,mex.getMessage(),errMsg)); return "failure"; } */ for (int i = 1; i <= 10; i++) { try { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get("file" + i); if (fi != null && fi.getName() != null && fi.getName().length() != 0) { //validate fileName Util.validateUploadFileName(fi.getName()); validateFileSize(fi.getSize()); // filename on the client secResourceName = fi.getName(); if (secResourceName.indexOf("/") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/") + 1); } if (secResourceName.indexOf("\\") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\") + 1); } if (logger.isDebugEnabled()) logger.debug("Rsrc name is " + secResourceName); if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int) fi.getSize()); secContentData = new byte[(int) fi.getSize()]; InputStream is = fi.getInputStream(); is.read(secContentData); secContentMimeType = fi.getContentType(); if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType); if (logger.isDebugEnabled()) logger.debug( "new names for upload content is" + secContentMimeType + "," + secResourceName); addItem(secResourceName, secContentMimeType, addCollId, secContentData); if (success_fields == null) success_fields = new ArrayList<String>(); success_fields.add(new Integer(i).toString()); success_fields.add(bundle.getString("add_item_success") + secResourceName); } else { logger.debug("File being uploaded is NULL"); continue; } } catch (MeleteException mex) { String mexMsg = mex.getMessage(); if (mex.getMessage().equals("embed_img_bad_filename")) mexMsg = "img_bad_filename"; String errMsg = bundle.getString(mexMsg); // context.addMessage ("FileUploadForm:chooseFile"+i, new FacesMessage(FacesMessage.SEVERITY_ERROR,mex.getMessage(),errMsg)); // logger.error("error in uploading multiple files" + errMsg); if (err_fields == null) err_fields = new ArrayList<String>(); err_fields.add(new Integer(i).toString()); err_fields.add(errMsg); //return "failure"; } catch (Exception e) { logger.debug("file upload FAILED" + e.toString()); } } if (err_fields != null) { logger.debug("err found in fields" + err_fields.toString()); return "file_upload_view"; } } if (this.fileType.equals("link")) { Iterator utIterator = utList.iterator(); //Finish validating here int count = -1; while (utIterator.hasNext()) { count++; try { UrlTitleObj utObj = (UrlTitleObj) utIterator.next(); if (utObj.title != null) utObj.title = utObj.title.trim(); String linkUrl = utObj.getUrl(); if (linkUrl != null) linkUrl = linkUrl.trim(); String checkUrl = linkUrl; if (checkUrl != null) { checkUrl = checkUrl.replace("http://", ""); checkUrl = checkUrl.replace("https://", ""); } if ((utObj.title == null || utObj.title.length() == 0) && (checkUrl == null || checkUrl.length() == 0)) { utIterator.remove(); continue; } if (utObj.title == null || utObj.title.length() == 0) { context.addMessage("LinkUploadForm:utTable:" + count + ":title", new FacesMessage( FacesMessage.SEVERITY_ERROR, "URL_title_reqd", bundle.getString("URL_title_reqd"))); return "#"; } if (checkUrl == null || checkUrl.length() == 0) { context.addMessage("LinkUploadForm:utTable:" + count + ":url", new FacesMessage( FacesMessage.SEVERITY_ERROR, "URL_reqd", bundle.getString("URL_reqd"))); return "#"; } Util.validateLink(linkUrl); } catch (UserErrorException uex) { String errMsg = bundle.getString(uex.getMessage()); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "add_section_bad_url_formats", bundle.getString("add_section_bad_url_formats"))); return "failure"; } catch (Exception e) { logger.debug("link upload FAILED" + e.toString()); } } utIterator = utList.iterator(); while (utIterator.hasNext()) { UrlTitleObj utObj = (UrlTitleObj) utIterator.next(); try { secContentMimeType = getMeleteCHService().MIME_TYPE_LINK; String linkUrl = utObj.getUrl(); secResourceName = utObj.getTitle(); if ((linkUrl != null) && (linkUrl.trim().length() > 0) && (secResourceName != null) && (secResourceName.trim().length() > 0)) { secContentData = new byte[linkUrl.length()]; secContentData = linkUrl.getBytes(); addItem(secResourceName, secContentMimeType, addCollId, secContentData); } } catch (MeleteException mex) { String errMsg = bundle.getString(mex.getMessage()); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, mex.getMessage(), errMsg)); return "failure"; } catch (Exception e) { logger.debug("link upload FAILED" + e.toString()); } } } FacesContext ctx = FacesContext.getCurrentInstance(); ValueBinding binding = Util.getBinding("#{manageResourcesPage}"); ManageResourcesPage manResPage = (ManageResourcesPage) binding.getValue(ctx); manResPage.resetValues(); return "manage_content"; }
From source file:org.etudes.tool.melete.SectionPage.java
public String uploadSectionContent(String fieldname) throws Exception { try {//from w ww.j a v a2s . c o m FacesContext context = FacesContext.getCurrentInstance(); org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get(fieldname); if (fi != null && fi.getName() != null && fi.getName().length() != 0) { Util.validateUploadFileName(fi.getName()); // filename on the client secResourceName = fi.getName(); if (secResourceName.indexOf("/") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/") + 1); } if (secResourceName.indexOf("\\") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\") + 1); } if (logger.isDebugEnabled()) logger.debug("Rsrc name is " + secResourceName); if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int) fi.getSize()); this.secContentData = new byte[(int) fi.getSize()]; InputStream is = fi.getInputStream(); is.read(this.secContentData); String secContentMimeType = fi.getContentType(); if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType); return secContentMimeType; } else { logger.debug("File being uploaded is NULL"); return null; } } catch (MeleteException me) { logger.debug("file upload FAILED" + me.toString()); throw me; } catch (Exception e) { logger.error("file upload FAILED" + e.toString()); return null; } }
From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java
@Override public List<Document> parseHttpRequest(HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (logger.isDebugEnabled()) { logger.info("Parse file item form HTTP servlet request."); }//from w w w.ja v a 2 s .c om Document document = null; List<Document> documents = new ArrayList<Document>(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) return documents; File repository = FileUtils.forceMkdir(FilePathUtils.REPOSITORY_PATH); if (repository != null) logger.info("The" + FilePathUtils.REPOSITORY_PATH + " Directory is created"); if (FileUtils.forceMkdir(FilePathUtils.RESOURCE_PATH) != null) logger.info("To create specified sub-folder under " + FilePathUtils.ROOT_PATH + " top-level folder"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_CACHE_SIZE); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAXIMUM_FILE_SIZE); try { List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem fileItem = iterator.next(); if (!fileItem.isFormField()) { // Write file items to disk-based String absolutePath = writeFiles(fileItem, fileItem.getName()); document = Document.getInstance(); document.setFilename(fileItem.getName()); document.setContentType(fileItem.getContentType()); document.setSize(fileItem.getSize()); document.setUrl(absolutePath); document.setReadOnly(false); document.setArchive(false); document.setDirectory(false); document.setHidden(false); document.setSystem(false); document.setOther(false); document.setRegularFile(false); Date time = Calendar.getInstance().getTime(); document.setCreationTime(time); document.setLastAccessTime(time); document.setLastModifiedTime(time); documents.add(document); logger.info("File(s) " + document.getFilename() + " was/were uploaded successfully"); } } } catch (SizeLimitExceededException slee) { throw new SizeLimitExceededException( "The request was rejected because its size exceeds (" + slee.getActualSize() + "bytes) the configured maximum (" + slee.getPermittedSize() + "bytes)"); } catch (FileUploadException fue) { throw new FileUploadException("Upload file stream was been cancelled", fue.getCause()); } finally { try { FileUtils.cleanDirectory(factory.getRepository()); logger.info("Cleans a directory without deleting it"); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } } return documents; }
From source file:org.exoplatform.frameworks.jcr.command.web.fckeditor.UploadFileCommand.java
public boolean execute(Context context) throws Exception { GenericWebAppContext webCtx = (GenericWebAppContext) context; HttpServletResponse response = webCtx.getResponse(); HttpServletRequest request = webCtx.getRequest(); PrintWriter out = response.getWriter(); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); String type = (String) context.get("Type"); if (type == null) { type = ""; }//from ww w . jav a 2 s . c o m // // To limit browsing set Servlet init param "digitalAssetsPath" // // with desired JCR path // String rootFolderStr = // (String)context.get("org.exoplatform.frameworks.jcr.command.web.fckeditor.digitalAssetsPath" // ); // // if(rootFolderStr == null) // rootFolderStr = "/"; // // // set current folder // String currentFolderStr = (String)context.get("CurrentFolder"); // if(currentFolderStr == null) // currentFolderStr = ""; // else if(currentFolderStr.length() < rootFolderStr.length()) // currentFolderStr = rootFolderStr; // // String jcrMapping = (String)context.get(GenericWebAppContext.JCR_CONTENT_MAPPING); // if(jcrMapping == null) // jcrMapping = DisplayResourceCommand.DEFAULT_MAPPING; // // String digitalWS = (String)webCtx.get(AppConstants.DIGITAL_ASSETS_PROP); // if(digitalWS == null) // digitalWS = AppConstants.DEFAULT_DIGITAL_ASSETS_WS; String workspace = (String) webCtx.get(AppConstants.DIGITAL_ASSETS_PROP); if (workspace == null) { workspace = AppConstants.DEFAULT_DIGITAL_ASSETS_WS; } String currentFolderStr = getCurrentFolderPath(webCtx); webCtx.setCurrentWorkspace(workspace); Node parentFolder = (Node) webCtx.getSession().getItem(currentFolderStr); DiskFileUpload upload = new DiskFileUpload(); List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { fields.put(item.getFieldName(), item); } } FileItem uplFile = (FileItem) fields.get("NewFile"); // On IE, the file name is specified as an absolute path. String fileName = uplFile.getName(); if (fileName != null) { int lastUnixPos = fileName.lastIndexOf("/"); int lastWindowsPos = fileName.lastIndexOf("\\"); int index = Math.max(lastUnixPos, lastWindowsPos); fileName = fileName.substring(index + 1); } Node file = JCRCommandHelper.createResourceFile(parentFolder, fileName, uplFile.getInputStream(), uplFile.getContentType()); parentFolder.save(); int retVal = 0; out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + "');"); out.println("</script>"); out.flush(); out.close(); return false; }
From source file:org.exoplatform.platform.portlet.juzu.branding.BrandingController.java
/** * method save() records an image in BrandingDataStorageService * /*from ww w. j a va2 s.c o m*/ * @param httpContext * @param file * @return Response.Content * @throws IOException */ @Resource public Response.Content uploadFile(HttpContext httpContext, FileItem file, String browser) throws IOException { if (browser != null && browser.equals("html5")) { if (file != null && file.getContentType().contains("png")) { dataStorageService.saveLogoPreview(file); } JSONObject result = new JSONObject(); try { result.put("logoUrl", getLogoUrl(httpContext, false)); } catch (JSONException ex) { if (LOG.isErrorEnabled()) { LOG.error("Can not put logoUrl value", ex); } } return Response.ok(result.toString()).with(PropertyType.MIME_TYPE, "application/json"); } else { if (file != null && file.getContentType().contains("png")) { dataStorageService.saveLogoPreview(file); return Response.ok(getLogoUrl(httpContext, false)); } else { return Response.ok("false"); } } }
From source file:org.exoplatform.platform.portlet.juzu.branding.models.BrandingDataStorageService.java
/** * Save logo file in the jcr/*from ww w .ja v a 2 s .c om*/ * * @param item, item file */ public void saveLogoPreview(FileItem item) { SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { Session session = sessionProvider.getSession("collaboration", repositoryService.getCurrentRepository()); Node rootNode = session.getRootNode(); if (!rootNode.hasNode("Application Data")) { rootNode.addNode("Application Data", "nt:folder"); session.save(); } Node applicationDataNode = rootNode.getNode("Application Data"); if (!applicationDataNode.hasNode("logos")) { applicationDataNode.addNode("logos", "nt:folder"); session.save(); } Node logosNode = applicationDataNode.getNode("logos"); Node fileNode = null; if (logosNode.hasNode(logo_preview_name)) { fileNode = logosNode.getNode(logo_preview_name); fileNode.remove(); session.save(); } fileNode = logosNode.addNode(logo_preview_name, "nt:file"); Node jcrContent = fileNode.addNode("jcr:content", "nt:resource"); jcrContent.setProperty("jcr:data", resizeImage(item.getInputStream())); jcrContent.setProperty("jcr:lastModified", Calendar.getInstance()); jcrContent.setProperty("jcr:encoding", "UTF-8"); jcrContent.setProperty("jcr:mimeType", item.getContentType()); logosNode.save(); session.save(); } catch (Exception e) { LOG.error("Branding - Error while saving the logo: ", e.getMessage()); } finally { sessionProvider.close(); ConversationState state = ConversationState.getCurrent(); String userId = (state != null) ? state.getIdentity().getUserId() : null; if (userId != null) { // LOG.info("Branding - A new logo on the navigation bar has been saved by user :" + userId); } } }
From source file:org.exoplatform.services.xmpp.rest.FileExchangeService.java
@POST public Response upload() throws IOException { EnvironmentContext env = EnvironmentContext.getCurrent(); HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class); HttpServletResponse resp = (HttpServletResponse) env.get(HttpServletResponse.class); String description = req.getParameter("description"); String username = req.getParameter("username"); String requestor = req.getParameter("requestor"); String isRoom = req.getParameter("isroom"); boolean isMultipart = FileUploadBase.isMultipartContent(req); if (isMultipart) { // FileItemFactory factory = new DiskFileUpload(); // Create a new file upload handler // ServletFileUpload upload = new ServletFileUpload(factory); DiskFileUpload upload = new DiskFileUpload(); // Parse the request try {//from ww w . j av a 2 s. c o m List<FileItem> items = upload.parseRequest(req); XMPPMessenger messenger = (XMPPMessenger) PortalContainer.getInstance() .getComponentInstanceOfType(XMPPMessenger.class); for (FileItem fileItem : items) { XMPPSessionImpl session = (XMPPSessionImpl) messenger.getSession(username); String fileName = fileItem.getName(); String fileType = fileItem.getContentType(); if (session != null) { if (fileName != null) { // TODO Check this for compatible or not // It's necessary because IE posts full path of uploaded files fileName = FilenameUtils.getName(fileName); fileType = FilenameUtils.getExtension(fileName); File file = new File(tmpDir); if (file.isDirectory()) { String uuid = UUID.randomUUID().toString(); boolean success = (new File(tmpDir + "/" + uuid)).mkdir(); if (success) { String path = tmpDir + "/" + uuid + "/" + fileName; File f = new File(path); success = f.createNewFile(); if (success) { // File did not exist and was created InputStream inputStream = fileItem.getInputStream(); OutputStream out = new FileOutputStream(f); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); if (log.isDebugEnabled()) log.debug("File " + path + "is created"); session.sendFile(requestor, path, description, Boolean.parseBoolean(isRoom)); } } else { if (log.isDebugEnabled()) log.debug("File already exists"); } } } } else { if (log.isDebugEnabled()) log.debug("XMPPSession for user " + username + " is null!"); } } } catch (Exception e) { if (log.isDebugEnabled()) e.printStackTrace(); return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build(); } } return Response.ok().build(); }