List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream) throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException { ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream()); ZipEntry zipEntry;/*from w ww . j a v a2 s . c o m*/ boolean hasOriginSigsRels = false; while (null != (zipEntry = zipInputStream.getNextEntry())) { LOG.debug("copy ZIP entry: " + zipEntry.getName()); ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); if ("[Content_Types].xml".equals(zipEntry.getName())) { Document contentTypesDocument = loadDocumentNoClose(zipInputStream); Element typesElement = contentTypesDocument.getDocumentElement(); /* * We need to add an Override element. */ Element overrideElement = contentTypesDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/content-types", "Override"); overrideElement.setAttribute("PartName", "/" + signatureZipEntryName); overrideElement.setAttribute("ContentType", "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"); typesElement.appendChild(overrideElement); Element nsElement = contentTypesDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/content-types"); NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument, "/tns:Types/tns:Default[@Extension='sigs']", nsElement); if (0 == nodeList.getLength()) { /* * Add Default element for 'sigs' extension. */ Element defaultElement = contentTypesDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/content-types", "Default"); defaultElement.setAttribute("Extension", "sigs"); defaultElement.setAttribute("ContentType", "application/vnd.openxmlformats-package.digital-signature-origin"); typesElement.appendChild(defaultElement); } writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false); } else if ("_rels/.rels".equals(zipEntry.getName())) { Document relsDocument = loadDocumentNoClose(zipInputStream); Element nsElement = relsDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/relationships"); NodeList nodeList = XPathAPI.selectNodeList(relsDocument, "/tns:Relationships/tns:Relationship[@Target='_xmlsignatures/origin.sigs']", nsElement); if (0 == nodeList.getLength()) { Element relationshipElement = relsDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString()); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"); relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs"); relsDocument.getDocumentElement().appendChild(relationshipElement); } writeDocumentNoClosing(relsDocument, zipOutputStream, false); } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) { hasOriginSigsRels = true; Document originSignRelsDocument = loadDocumentNoClose(zipInputStream); Element relationshipElement = originSignRelsDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); String relationshipId = "rel-" + UUID.randomUUID().toString(); relationshipElement.setAttribute("Id", relationshipId); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); String target = FilenameUtils.getName(signatureZipEntryName); LOG.debug("target: " + target); relationshipElement.setAttribute("Target", target); originSignRelsDocument.getDocumentElement().appendChild(relationshipElement); writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false); } else { IOUtils.copy(zipInputStream, zipOutputStream); } } if (false == hasOriginSigsRels) { /* * Add signature relationships document. */ addOriginSigsRels(signatureZipEntryName, zipOutputStream); addOriginSigs(zipOutputStream); } /* * Return. */ zipInputStream.close(); return zipOutputStream; }
From source file:ddf.catalog.resource.impl.URLResourceReader.java
private ResourceResponse retrieveFileProduct(URI resourceURI, String productName, String bytesToSkip) throws ResourceNotFoundException { URLConnection connection = null; try {/*from w w w . ja va2 s. com*/ LOGGER.debug("Opening connection to: {}", resourceURI.toString()); connection = resourceURI.toURL().openConnection(); productName = StringUtils.defaultIfBlank( handleContentDispositionHeader(connection.getHeaderField(HttpHeaders.CONTENT_DISPOSITION)), productName); String mimeType = getMimeType(resourceURI, productName); InputStream is = connection.getInputStream(); skipBytes(is, bytesToSkip); return new ResourceResponseImpl( new ResourceImpl(new BufferedInputStream(is), mimeType, FilenameUtils.getName(productName))); } catch (MimeTypeResolutionException | IOException e) { LOGGER.error("Error retrieving resource", e); throw new ResourceNotFoundException("Unable to retrieve resource at: " + resourceURI.toString(), e); } }
From source file:com.shangde.common.util.FCKConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /* w ww . ja va 2 s .co m*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = null; String typeDirPath = null; String otherFilePath = this.getServletConfig().getServletContext().getRealPath("/"); System.out.println("===========" + otherFilePath); String fckSavePath = (String) request.getSession().getAttribute("fckSavePath"); if (fckSavePath != null && !fckSavePath.trim().equals("")) { typeDirPath = otherFilePath + "/upload/" + fckSavePath + "/"; } else { typeDirPath = otherFilePath + "/upload/public/"; } // if("article".equals((request.getSession().getAttribute("fckSavePath")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // }else if("exam".equals((request.getSession().getAttribute("exam")))){//? feceditor.properties // typeDirPath = otherFilePath + "/static/images/"; // } // else{ // typeDirPath = otherFilePath + "/back/upload/fckimage/"; // } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time, FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID() + "." + extension;// if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) {//???? newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_OK, temp); } } else {//???? if (fckSavePath != null && !fckSavePath.trim().equals("")) { String temp = "http://import.highso.org.cn/upload" + "/" + fckSavePath + "/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } else { String temp = "http://import.highso.org.cn/upload/public/" + filename; ur = new UploadResponse(UploadResponse.SC_RENAMED, temp); } } // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { logger.error(e.getMessage()); ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:edu.ku.brc.specify.tools.AppendHelp.java
/** * /* ww w. j ava 2 s . com*/ */ @SuppressWarnings({ "unchecked" }) public AppendHelp() { super(); StringBuilder sb = new StringBuilder(); String path = "help/SpecifyHelp"; File spHelpDir = new File(path); getMapEntries(spHelpDir); sb.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); //sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); sb.append("<head>\n"); //sb.append("<base href=\"help/SpecifyHelp/Workbench\">\n"); sb.append("<style>body { font-family: sans-serif; }</style>\n"); sb.append("<link href=\"../../main.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\"></link>\n"); sb.append("<title>Specify Help</title>\n"); sb.append("</head>\n"); sb.append("<body bgcolor=\"#ffffff\">\n"); sb.append("<H1>"); sb.append("Specify Help"); sb.append("</H1>\n"); try { List<TOCItem> tocList = getTOCList(spHelpDir, sb); Vector<String> fileNameList = new Vector<String>(); Hashtable<String, Boolean> fileNameHash = new Hashtable<String, Boolean>(); for (TOCItem item : tocList) { String fName = targetToUrlHash.get(item.getTarget()); if (fName != null) { if (fName.indexOf('#') > -1) { String[] toks = StringUtils.split(fName, "#"); item.setFileName("help/" + toks[0]); item.setAnchor(toks[1]); } else { item.setFileName("help/" + fName); } String fullName = item.getFileName(); if (fileNameHash.get(fullName) == null) { fileNameList.add(fullName); fileNameHash.put(fullName, false); } //sb.append(getContents(new File(fileName), p.first, toks.length > 1 ? toks[1] : null)); } } int i = 0; for (TOCItem item : tocList) { if (item.getFileName() != null) { System.out.println(item.getTarget() + " " + item.getFileName()); Boolean used = fileNameHash.get(item.getFileName()); if (used != null && !used) { if (i > 0) { sb.append("<HR>\n"); } sb.append(getContents(new File(item.getFileName()), item.getTarget(), null)); fileNameHash.put(item.getFileName(), true); i++; } } else { System.err.println("File Name is null for target[" + item.getTarget() + "]"); } } Hashtable<String, Boolean> fNameHash = new Hashtable<String, Boolean>(); for (String url : urlToTargetHash.keySet()) { fNameHash.put(FilenameUtils.getName(url), true); } for (File file : (Collection<File>) FileUtils.listFiles(new File(path), new String[] { "html" }, true)) { try { String fName = FilenameUtils.getName(file.getAbsolutePath()); if (fNameHash.get(fName) == null) { if (i > 0) { sb.append("<HR>\n"); } sb.append(getContents(file, fName, null)); i++; } } catch (Exception ex) { ex.printStackTrace(); } } sb.append("</body></html>"); FileUtils.writeStringToFile(new File("SpecifyHelp.html"), sb.toString()); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:it.geosolutions.tools.compress.file.Compressor.java
/** * This function zip the input file./*w w w. j av a 2 s . com*/ * * @param file * The input file to be zipped. * @param out * The zip output stream. * @throws IOException */ public static void zipFile(final File file, final ZipOutputStream out) throws IOException { if (file != null && out != null) { // /////////////////////////////////////////// // Create a buffer for reading the files // /////////////////////////////////////////// byte[] buf = new byte[4096]; FileInputStream in = null; try { in = new FileInputStream(file); // ////////////////////////////////// // Add ZIP entry to output stream. // ////////////////////////////////// out.putNextEntry(new ZipEntry(FilenameUtils.getName(file.getAbsolutePath()))); // ////////////////////////////////////////////// // Transfer bytes from the file to the ZIP file // ////////////////////////////////////////////// int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // ////////////////////// // Complete the entry // ////////////////////// out.closeEntry(); } catch (IOException e) { if (LOGGER.isErrorEnabled()) LOGGER.error(e.getLocalizedMessage(), e); if (out != null) out.close(); } finally { if (in != null) in.close(); } } else throw new IOException("One or more input parameters are null!"); }
From source file:de.uzk.hki.da.grid.IrodsCommandLineConnector.java
/** * Iquests ICAT for the given AVU//from w w w . j ava2 s. c o m * @author Jens Peters * @param dao * @param avufield * @return */ public String iquestDataObjectForAVU(String dao, String avufield) { String coll_name = FilenameUtils.getFullPath(dao); String data_name = FilenameUtils.getName(dao); coll_name = coll_name.substring(0, coll_name.length() - 1); String commandAsArray[] = new String[] { "iquest", "\"SELECT DATA_NAME, COLL_NAME, META_DATA_ATTR_NAME, META_DATA_ATTR_VALUE where COLL_NAME = \'" + coll_name + "\' and DATA_NAME = \'" + data_name + "\' and META_DATA_ATTR_NAME = \'" + avufield + "\'" }; String iquest = executeIcommand(commandAsArray); try { return parseResultForAVUField(iquest, "META_DATA_ATTR_VALUE"); } catch (IOException e) { logger.error("Error in parsing Resultlist searching for " + avufield, e); } return ""; }
From source file:com.zhoujian.fckeditor.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * //from w w w . j a v a 2s. c om * @param request * the current request instance * @return the upload response instance associated with this request */ UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) uploadResponse = UploadResponse.getOK(fileUrl); else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } // if (uplFile.getSize() > 1024 * 500) { uploadResponse = new UploadResponse(204); } uplFile.delete(); } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:com.safetys.framework.fckeditor.connector.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands. * /*ww w.j a v a 2 s.c o m*/ * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { Dispatcher.logger.debug("Entering Dispatcher#doPost"); final Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) { uploadResponse = UploadResponse.getFileUploadDisabledError(); } else if (!Command.isValidForPost(context.getCommandStr())) { uploadResponse = UploadResponse.getInvalidCommandError(); } else if (!ResourceType.isValidType(context.getTypeStr())) { uploadResponse = UploadResponse.getInvalidResourceTypeError(); } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } else { // call the Connector#fileUpload final ResourceType type = context.getDefaultResourceType(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); try { final List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time final FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename final String fileName = FilenameUtils.getName(uplFile.getName()); Dispatcher.logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); final String newFileName = this.connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) { uploadResponse = UploadResponse.getOK(fileUrl); } else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (final InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (final WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } Dispatcher.logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:com.windy.zfxy.fck.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * //from w w w . ja v a 2s. c om * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); fileName = java.util.UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName); logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); // this.setPhotoPath(fileUrl); if (sanitizedFileName.equals(newFileName)) { uploadResponse = UploadResponse.getOK(fileUrl); } else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:com.astamuse.asta4d.web.builtin.StaticResourceHandler.java
/** * The header value of Content-Type/*w w w .j a v a 2 s . c om*/ * * @param path * @return a guess of the content type by file name extension, "application/octet-stream" when not matched */ protected String judgContentType(String path) { Context context = Context.getCurrentThreadContext(); String forceContentType = context.getData(WebApplicationContext.SCOPE_PATHVAR, VAR_CONTENT_TYPE); if (forceContentType != null) { return forceContentType; } String fileName = FilenameUtils.getName(path); // guess the type by file name extension String type = URLConnection.guessContentTypeFromName(fileName); if (type == null) { type = MimeTypeMap.get(FilenameUtils.getExtension(fileName)); } if (type == null) { type = "application/octet-stream"; } return type; }