List of usage examples for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap
public MimetypesFileTypeMap()
From source file:org.silverpeas.mobile.server.servlets.MediaServlet.java
private String createMedia(HttpServletRequest request, HttpServletResponse response, String name, String userId, String componentId, String albumId, File file, boolean watermark, String watermarkHD, String watermarkOther, boolean download) throws Exception { // cration de la photo String type = new MimetypesFileTypeMap().getContentType(file); List<FileItem> parameters = new ArrayList<FileItem>(); LocalDiskFileItem item = new LocalDiskFileItem(file, type); parameters.add(item);/* www . java 2s.com*/ MediaDataCreateDelegate delegate = null; if (type.contains("image")) { delegate = new MediaDataCreateDelegate(MediaType.Photo, "fr", albumId, parameters); } if (type.contains("audio")) { delegate = new MediaDataCreateDelegate(MediaType.Sound, "fr", albumId, parameters); } else if (type.contains("video")) { parameters.clear(); parameters.add(new LocalDiskFileItem( MediaHelper.optimizeVideoForWeb(file, request.getSession().getId()), type)); delegate = new MediaDataCreateDelegate(MediaType.Video, "fr", albumId, parameters); } else if (type.contains("octet-stream")) { if (file.getName().endsWith(".mp3")) { delegate = new MediaDataCreateDelegate(MediaType.Sound, "fr", albumId, parameters); } else if (file.getName().endsWith(".mp4")) { parameters.clear(); parameters.add(new LocalDiskFileItem( MediaHelper.optimizeVideoForWeb(file, request.getSession().getId()), type)); delegate = new MediaDataCreateDelegate(MediaType.Video, "fr", albumId, parameters); } } //TODO : use right language if (delegate == null) { response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return null; } Media newMedia = getGalleryService().createMedia(getUserInSession(request), componentId, GalleryComponentSettings.getWatermark(componentId), delegate); return newMedia.getId(); }
From source file:org.craftercms.studio.impl.repository.mongodb.services.impl.ContentServiceImpl.java
private Item nodeToItem(final Node newNode, String ticket, String site, final InputStream inputStream) throws RepositoryException { CoreMetadata core = newNode.getCore(); Item item = new Item(); item.setPath(pathService.getPathByItemId(ticket, site, newNode.getId())); item.setId(new ItemId(newNode.getId())); item.setLastModifiedDate(core.getLastModifiedDate()); item.setModifiedBy(core.getCreator()); item.setCreatedBy(core.getCreator()); item.setCreationDate(core.getCreateDate()); item.setFolder(nodeService.isNodeFolder(newNode)); item.setModifiedBy(core.getModifier()); item.setRepoId(newNode.getId());//from w ww .ja v a 2 s . c o m item.setLabel(core.getLabel()); item.setFileName(core.getNodeName()); if (nodeService.isNodeFile(newNode)) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); item.setMimeType(mimeTypesMap.getContentType(item.getFileName())); } item.setInputStream(inputStream); return item; }
From source file:org.bonitasoft.console.common.server.servlet.ResourceServlet.java
/** * Get resource file//from w w w .j av a2 s .c o m * * @param request * @param response * @param resourceName * @param fileName * @throws ServletException * @throws UnsupportedEncodingException */ protected void getResourceFile(final HttpServletRequest request, final HttpServletResponse response, String resourceName, String fileName) throws ServletException, UnsupportedEncodingException { byte[] content = null; String contentType = null; if (resourceName == null) { final String errorMessage = "Error while using the servlet to get a resource: the parameter " + getResourceParameterName() + " is null."; if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, errorMessage); } throw new ServletException(errorMessage); } if (fileName == null) { final String errorMessage = "Error while using the servlet to get a resource: the parameter " + LOCATION_PARAM + " is null."; if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, errorMessage); } throw new ServletException(errorMessage); } resourceName = URLDecoder.decode(resourceName, "UTF-8"); fileName = URLDecoder.decode(fileName, "UTF-8"); response.setCharacterEncoding("UTF-8"); final File resourcesParentFolder = getResourcesParentFolder(request); final String subFolderName = getSubFolderName(); String subFolderSuffix; if (subFolderName != null) { subFolderSuffix = File.separator + subFolderName; } else { subFolderSuffix = ""; } try { final File resourceFolder = new File(resourcesParentFolder, resourceName + subFolderSuffix); final File file = new File(resourceFolder, fileName); final BonitaHomeFolderAccessor tenantFolder = new BonitaHomeFolderAccessor(); if (!tenantFolder.isInFolder(resourceFolder, resourcesParentFolder)) { throw new ServletException("For security reasons, access to this file paths" + resourceFolder.getAbsolutePath() + " is restricted."); } if (!tenantFolder.isInFolder(file, resourceFolder)) { throw new ServletException("For security reasons, access to this file paths" + file.getAbsolutePath() + " is restricted."); } final String lowerCaseFileName = fileName.toLowerCase(); if (lowerCaseFileName.endsWith(".jpg")) { contentType = "image/jpeg"; } else if (lowerCaseFileName.endsWith(".jpeg")) { contentType = "image/jpeg"; } else if (lowerCaseFileName.endsWith(".gif")) { contentType = "image/gif"; } else if (lowerCaseFileName.endsWith(".png")) { contentType = "image/png"; } else if (lowerCaseFileName.endsWith(".css") || lowerCaseFileName.endsWith(".less")) { contentType = "text/css"; } else if (lowerCaseFileName.endsWith(".js")) { contentType = "application/x-javascript"; } else if (lowerCaseFileName.endsWith(".html")) { contentType = "text/html; charset=UTF-8"; } else if (lowerCaseFileName.endsWith(".htc")) { contentType = "text/x-component"; } else if (lowerCaseFileName.endsWith(".svg")) { contentType = "image/svg+xml"; } else if (lowerCaseFileName.endsWith(".eot")) { contentType = "application/vnd.ms-fontobject"; } else if (lowerCaseFileName.endsWith(".woff")) { contentType = "application/x-font-woff"; } else if (lowerCaseFileName.endsWith(".ttf")) { contentType = "application/x-font-ttf"; } else if (lowerCaseFileName.endsWith(".otf")) { contentType = "application/x-font-opentype"; } else { final FileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap(); contentType = mimetypesFileTypeMap.getContentType(file); } if (contentType == null) { contentType = "application/octet-stream"; } content = FileUtils.readFileToByteArray(file); response.setContentType(contentType); response.setContentLength(content.length); response.setBufferSize(content.length); final OutputStream out = response.getOutputStream(); out.write(content, 0, content.length); response.flushBuffer(); out.close(); } catch (final IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Error while generating the response.", e); } throw new ServletException(e.getMessage(), e); } }
From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java
public static void downloadToBrowser(String filename, String realpath, HttpServletRequest request, HttpServletResponse response) {// ww w.jav a 2s . co m // ?MIME TYPE? //try { // mimetypesMap=new MimetypesFileTypeMap(request.getSession().getServletContext().getRealPath("WEB-INF/my.mime.types")); mimetypesMap = new MimetypesFileTypeMap(); //} catch (IOException e1) { // e1.printStackTrace(); //} // response.setCharacterEncoding("UTF-8"); response.setContentType(mimetypesMap.getContentType(filename)); response.addHeader("Content-Disposition", "attachment;filename=" + toUTF8(filename)); FileInputStream in = null; OutputStream out = null; try { /* ???? BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(new File(realpath)))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter( response.getOutputStream())); int length = -1; char[] chs = new char[1024]; while ((length = in.read(chs)) != -1) { out.write(chs, 0, length); } */ in = new FileInputStream(new File(realpath)); out = response.getOutputStream(); int length = -1; byte[] bs = new byte[1024]; while ((length = in.read(bs)) != -1) { out.write(bs, 0, length); } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (Exception ex) { } } }
From source file:ome.services.blitz.repo.CheckedPath.java
/** * Get the mimetype for a file.//from w w w. j a v a2 s . c o m * * @return A String representing the mimetype. */ public String getMimetype() { if (mime == null) { mime = new MimetypesFileTypeMap().getContentType(file); } return mime; }
From source file:org.silverpeas.mobile.server.services.ServiceMediaImpl.java
private String createPhoto(String name, String userId, String componentId, String albumId, File file, boolean watermark, String watermarkHD, String watermarkOther, boolean download) throws Exception { // cration de la photo List<FileItem> parameters = new ArrayList<FileItem>(); String type = new MimetypesFileTypeMap().getContentType(file); LocalDiskFileItem item = new LocalDiskFileItem(file, type); parameters.add(item);// w w w.ja v a 2 s. c o m MediaDataCreateDelegate delegate = new MediaDataCreateDelegate(MediaType.Photo, "fr", albumId, parameters); Media newMedia = getGalleryService().createMedia(getUserInSession(), componentId, GalleryComponentSettings.getWatermark(componentId), delegate); return newMedia.getId(); }
From source file:com.emc.ecs.sync.target.FilesystemTarget.java
@Override public SyncObject reverseFilter(SyncObject obj) { File destFile = createFile(targetRoot.getPath(), obj.getRelativePath()); obj.setTargetIdentifier(destFile.getPath()); return new FileSyncObject(this, new MimetypesFileTypeMap(), createFile(targetRoot.getPath(), obj.getRelativePath()), obj.getRelativePath(), followLinks); }
From source file:org.ala.harvester.BiocacheHarvester.java
private void processJsonDynaBean(DynaBean dynaBean) throws Exception { List<String> imageUrls = null; String identifier = null;/*from w w w . j a v a 2 s . co m*/ String mediaURL = "/data/biocache-media/"; if (dynaBean != null && dynaBean.getOther().get("occurrences") != null) { List occurrences = (List) dynaBean.getOther().get("occurrences"); for (int i = 0; i < occurrences.size(); i++) { try { logger.info("\n ------------------- \n*** record ctr: " + (ctr++) + "\n -------------------"); ParsedDocument imageDoc = new ParsedDocument(); List<Triple<String, String, String>> triples = imageDoc.getTriples(); Map<String, String> dcs = imageDoc.getDublinCore(); Map<String, Object> occurrence = (Map<String, Object>) occurrences.get(i); imageUrls = (List<String>) occurrence.get("images"); //load all the images for (String imageUrl : imageUrls) { if (imageUrl.length() > 4) { imageDoc.setContentType(new MimetypesFileTypeMap().getContentType(imageUrl)); } if (imageUrl != null && imageUrl.trim().startsWith(mediaURL)) { imageUrl = imageUrl.trim().replaceFirst(mediaURL, BIOCACHE_MEDIA_URL); String occurrenceID = (String) occurrence.get("occurrenceID"); //Fix so that if occurrenceId starts with http or https it is treated as the identifier for the image. This will allow the BIE images to retain the same identifiers thus rankings are preserved. if (occurrenceID != null && occurrenceID.trim().startsWith("http://") || occurrenceID.trim().startsWith("https://")) { identifier = occurrenceID.trim(); } else { identifier = imageUrl; } } else { identifier = imageUrl; } logger.info("imageUrl: " + imageUrl + ", occurrence: " + occurrence); imageDoc.setGuid(identifier); imageDoc.setContent(getContent(imageUrl)); dcs.put(Predicates.DC_TITLE.toString(), (String) occurrence.get("scientificName")); dcs.put(Predicates.DC_IDENTIFIER.toString(), identifier); String licence = (String) occurrence.get("rights"); if (licence != null) { dcs.put(Predicates.DC_LICENSE.toString(), licence); } String dataResourceUid = (String) occurrence.get("dataResourceUid"); String occurrenceDetails = (String) occurrence.get("occurrenceDetails"); if (occurrenceDetails != null) { dcs.put(Predicates.DC_IS_PART_OF.toString(), occurrenceDetails); } else { String collectionPageURL = MessageFormat.format(COLLECTION_PUBLIC_PAGE_TEMPLATE, dataResourceUid); dcs.put(Predicates.DC_IS_PART_OF.toString(), collectionPageURL); } String photographer = (String) occurrence.get("photographer"); String collector = (String) occurrence.get("collector"); if (photographer != null) { dcs.put(Predicates.DC_CREATOR.toString(), photographer); } else if (collector != null) { dcs.put(Predicates.DC_CREATOR.toString(), collector); } String subject = MappingUtils.getSubject(); String sname = (String) occurrence.get("scientificName"); if (sname == null) { sname = (String) occurrence.get("raw_scientificName"); } triples.add(new Triple<String, String, String>(subject, Predicates.SCIENTIFIC_NAME.toString(), sname)); triples.add(new Triple<String, String, String>(subject, Predicates.IMAGE_URL.toString(), imageUrl)); //bie image link back to biocache occurrence triples.add(new Triple<String, String, String>(subject, Predicates.OCCURRENCE_UID.toString(), (String) occurrence.get("uuid"))); triples.add(new Triple<String, String, String>(subject, Predicates.OCCURRENCE_ROW_KEY.toString(), (String) occurrence.get("rowKey"))); if (imageDoc != null && imageDoc.getGuid() != null) { debugParsedDoc(imageDoc); this.repository.storeDocument(dataResourceUid, imageDoc); } } } catch (Exception ex) { //do nothing...continue on next logger.error("processJsonDynaBean: " + ex); } } } }
From source file:cc.kune.core.server.manager.file.EntityLogoDownloadManager.java
/** * Gets the mime./*from w w w . ja v a2 s .c o m*/ * * @param file * the file * @return the mime */ private String getMime(final File file) { return new MimetypesFileTypeMap().getContentType(file); }
From source file:org.betaconceptframework.astroboa.resourceapi.filter.BinaryChannelLoaderFilter.java
private void loadAndReturnContentOfBinaryChannel(String fileAccessInfo, HttpServletResponse httpServletResponse) throws IOException { BinaryChannelFileAccessInfoProcessor fileAccessInfoProcessor = new BinaryChannelFileAccessInfoProcessor( fileAccessInfo);// www .j a v a 2 s . com if (!fileAccessInfoProcessor.processFileAccessInfo()) { logger.warn("Invalid file access info " + fileAccessInfo); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { String repositoryId = fileAccessInfoProcessor.getRepositoryId(); String fileName = fileAccessInfoProcessor.getFileName(); String mimeType = fileAccessInfoProcessor.getMimeType(); String width = fileAccessInfoProcessor.getWidth(); String height = fileAccessInfoProcessor.getHeight(); String contentDispositionType = fileAccessInfoProcessor.getContentDispositionType(); String relativePathToStream = fileAccessInfoProcessor.getRelativePathToStream(); //Check that repository home directory exists if (MapUtils.isEmpty(repositoryHomeDirectoriesPerRepositoryId) || StringUtils.isBlank(repositoryId) || !repositoryHomeDirectoriesPerRepositoryId.containsKey(repositoryId)) { logger.error("No available home directory exists for repository " + repositoryId); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { logger.debug("Ready to serve binary channel : path {}, mime-type: {}, filename :{}", new Object[] { relativePathToStream, mimeType, fileName }); File resource = null; try { //Load file resource = new File(repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator + relativePathToStream); if (!resource.exists()) { logger.warn("Could not locate resource " + repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator + relativePathToStream); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { //It may well be the case where filename and mime type are not provided //in file access info (especially if binary channel is unmanaged). //In this cases obtain filename and mime type from resource if (StringUtils.isBlank(fileName)) { fileName = resource.getName(); } if (StringUtils.isBlank(mimeType)) { mimeType = new MimetypesFileTypeMap().getContentType(resource); } ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); httpServletResponse.setDateHeader("Last-Modified", resource.lastModified()); httpServletResponse.setContentType(mimeType); String processedFilename = org.betaconceptframework.utility.FilenameUtils .convertFilenameGreekCharactersToEnglishAndReplaceInvalidCharacters(fileName); // byte[] resourceByteArray = FileUtils.readFileToByteArray(resource); if (StringUtils.isNotBlank(mimeType) && mimeType.startsWith("image/")) { resourceByteArray = resizeImageResource(resourceByteArray, mimeType, width, height); httpServletResponse.setHeader("Content-Disposition", contentDispositionType + ";filename=" + (width != null ? "W" + width : "") + (height != null ? "H" + height : "") + (width != null || height != null ? "-" : "") + processedFilename); } else { //Resource is not an image. Set charset encoding httpServletResponse.setCharacterEncoding("UTF-8"); } if (!httpServletResponse.containsHeader("Content-Disposition")) { httpServletResponse.setHeader("Content-Disposition", contentDispositionType + ";filename=" + processedFilename); } httpServletResponse.setHeader("ETag", ContentApiUtils.createETag(resource.lastModified(), resourceByteArray.length)); httpServletResponse.setContentLength(resourceByteArray.length); try { IOUtils.write(resourceByteArray, servletOutputStream); servletOutputStream.flush(); } catch (Exception e) { //Something went wrong while writing data to stream. //Just log to debug and not to warn logger.debug("", e); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } } catch (Exception e) { logger.error("", e); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } } }