Java Code Examples for javax.activation.MimetypesFileTypeMap

The following examples show how to use javax.activation.MimetypesFileTypeMap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: JerryServer   Source File: JerryRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get Content-Type
 *
 * @return
 */
public String getContentType() {
    //利用JDK自带的类判断文件ContentType
    Path path = Paths.get(getUri());
    String content_type = null;
    try {
        content_type = Files.probeContentType(path);
    } catch (IOException e) {
        logger.error("Read File ContentType Error");
    }
    //若失败则调用另一个方法进行判断
    if (content_type == null) {
        content_type = new MimetypesFileTypeMap().getContentType(new File(getUri()));
    }
    return content_type;
}
 
Example 2
/**
 * Load MIME types
 */
public static void loadMimeTypes() {
	try {
		List<MimeType> mimeTypeList = MimeTypeDAO.findAll("mt.id");
		MimeTypeConfig.mimeTypes = new MimetypesFileTypeMap();

		for (MimeType mt : mimeTypeList) {
			String entry = mt.getName();

			for (String ext : mt.getExtensions()) {
				entry += " " + ext;
			}

			log.debug("loadMimeTypes => Add Entry: {}", entry);
			MimeTypeConfig.mimeTypes.addMimeTypes(entry);
		}
	} catch (DatabaseException e) {
		log.error(e.getMessage(), e);
	}
}
 
Example 3
Source Project: jplag   Source File: AccessStructure.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return A MimeMultipart object containing the zipped result files
 */
public MimeMultipart getResult() {

    File file = new File(JPLAG_RESULTS_DIRECTORY + File.separator
            + submissionID + getUsername() + ".zip");

    MimeMultipart mmp = new MimeMultipart();

    FileDataSource fds1 = new FileDataSource(file);
    MimetypesFileTypeMap mftp = new MimetypesFileTypeMap();
    mftp.addMimeTypes("multipart/zip zip ZIP");
    fds1.setFileTypeMap(mftp);

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(fds1));
        mbp.setFileName(file.getName());

        mmp.addBodyPart(mbp);
    } catch (MessagingException me) {
        me.printStackTrace();
    }
    return mmp;
}
 
Example 4
/**
 * Sets the content type header for the HTTP Response
 *
 * @param response
 *            HTTP response
 * @param file
 *            file to extract content type
 */
private static void setContentTypeHeader(HttpResponse response, String path) {
  String contentType = null;

  if(path.endsWith(".css")) {
    contentType = "text/css";
  }
  else if(path.endsWith(".js")) {
    contentType = "application/javascript";
  }
  else if(path.endsWith(".html")) {
    contentType = "text/html";
  }
  else {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    contentType = mimeTypesMap.getContentType(path);
  }

  response.headers().set(CONTENT_TYPE, contentType);
}
 
Example 5
/**
 * Return the mimetype of the file depending of his extension and the mime.types file
 * 
 * @param strFilename
 *            the file name
 * @return the file mime type
 */
public static String getMIMEType( String strFilename )
{
    try
    {
        MimetypesFileTypeMap mimeTypeMap = new MimetypesFileTypeMap( AppPathService.getWebAppPath( ) + File.separator + FILE_MIME_TYPE );

        return mimeTypeMap.getContentType( strFilename.toLowerCase( ) );
    }
    catch( IOException e )
    {
        AppLogService.error( e );

        return DEFAULT_MIME_TYPE;
    }
}
 
Example 6
Source Project: studio   Source File: ContentServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected void loadContentTypeProperties(String site, ContentItemTO item, String contentType) {
    // TODO: SJ: Refactor in 2.7.x
    if (item.isFolder()) {
        item.setContentType(CONTENT_TYPE_FOLDER);
    } else {
        if (contentType != null && !contentType.equals(CONTENT_TYPE_FOLDER) && !contentType.equals("asset") &&
                !contentType.equals(CONTENT_TYPE_UNKNOWN)) {
            ContentTypeConfigTO config = servicesConfig.getContentTypeConfig(site, contentType);
            if (config != null) {
                item.setForm(config.getForm());
                item.setFormPagePath(config.getFormPath());
                item.setPreviewable(config.isPreviewable());
                item.isPreviewable = item.previewable;
            }
        } else {
            MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            String mimeType = mimeTypesMap.getContentType(item.getName());
            if (mimeType != null && !StringUtils.isEmpty(mimeType)) {
                item.setPreviewable(ContentUtils.matchesPatterns(mimeType, servicesConfig
                        .getPreviewableMimetypesPaterns(site)));
                item.isPreviewable = item.previewable;
            }
        }
    }
    // TODO CodeRev:but what if the config is null?
}
 
Example 7
Source Project: studio   Source File: BinaryView.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {

    OutputStream out = response.getOutputStream();
    Map<String, Object> responseModelMap = (Map<String, Object>)model.get(RestScriptsController.DEFAULT_RESPONSE_BODY_MODEL_ATTR_NAME);
    if (responseModelMap != null) {
        InputStream contentStream = (InputStream) responseModelMap.get(DEFAULT_CONTENT_STREAM_MODEL_ATTR_NAME);
        String contentPath = (String) responseModelMap.get(DEFAULT_CONTENT_PATH_MODEL_ATTR_NAME);

        MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
        String contentType = mimetypesFileTypeMap.getContentType(contentPath);
        response.setContentType(contentType);
        if (contentStream != null) {
            IOUtils.write(IOUtils.toByteArray(contentStream), out);
        }
        out.flush();
        IOUtils.closeQuietly(contentStream);
        IOUtils.closeQuietly(out);
    }
}
 
Example 8
Source Project: arcusplatform   Source File: BridgeConfigModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides @Singleton
public MimetypesFileTypeMap provideMimeTypes() {
   try {
      InputStream clis = this.getClass().getResourceAsStream(MIMETYPES_LOCATION);
      if (clis != null) {
         return new MimetypesFileTypeMap(clis);
      } else {
         logger.error("Unable to find mime types in {}, no mime types will be supported", MIMETYPES_LOCATION);
      }
   }
   catch(Exception e) {
      logger.error("Unable to load mime types, no mime types will be supported", e);
   }
   return new MimetypesFileTypeMap();
}
 
Example 9
Source Project: arcusplatform   Source File: IpcdBridgeConfigModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides @Singleton
public MimetypesFileTypeMap provideMimeTypes() {
   try {
      InputStream clis = this.getClass().getResourceAsStream(MIMETYPES_LOCATION);
      if (clis != null) {
         return new MimetypesFileTypeMap(clis);
      } else {
         logger.error("Unable to find mime types in {}, no mime types will be supported", MIMETYPES_LOCATION);
      }
   }
   catch(Exception e) {
      logger.error("Unable to load mime types, no mime types will be supported", e);
   }
   return new MimetypesFileTypeMap();
}
 
Example 10
Source Project: Summer   Source File: FileView.java    License: Apache License 2.0 5 votes vote down vote up
public FileView(String fileName) throws IOException {
	File f = new File(fileName);
	file = new RandomAccessFile(f, "r");
	contentType = Files.probeContentType(Paths.get(f.getName()));
	if (contentType == null) {
		MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
		contentType = mimeTypesMap.getContentType(f.getName());
	}
}
 
Example 11
Source Project: domo-java-sdk   Source File: Transport.java    License: MIT License 5 votes vote down vote up
public Attachment uploadFile(HttpUrl url, String filePath){
    try {
        File file = new File(filePath);
        MediaType fileContentType = MediaType.parse(new MimetypesFileTypeMap().getContentType(file));
        MultipartBody multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(fileContentType, file)).build();

        Request request = new Request.Builder().url(url).post(multipartBody).build();
        Response response = httpClient.newCall(request).execute();
        return gson.fromJson(response.body().charStream(), Attachment.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source Project: eplmp   Source File: BinaryResourceDownloadMeta.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static void initFileTypeMap() {
    fileTypeMap = new MimetypesFileTypeMap();

    // Additional MIME types
    fileTypeMap.addMimeTypes("application/atom+xml atom");
    fileTypeMap.addMimeTypes("application/msword doc dot");
    fileTypeMap.addMimeTypes("application/mspowerpoint ppt pot");
    fileTypeMap.addMimeTypes("application/msexcel xls");
    fileTypeMap.addMimeTypes("application/pdf pdf");
    fileTypeMap.addMimeTypes("application/rdf+xml rdf rss");
    fileTypeMap.addMimeTypes("application/x-vnd.openxmlformat docx docm dotx dotm");
    fileTypeMap.addMimeTypes("application/x-vnd.openxmlformat xlsx xlsm");
    fileTypeMap.addMimeTypes("application/x-vnd.openxmlformat pptx pptm potx");
    fileTypeMap.addMimeTypes("application/x-javascript js");
    fileTypeMap.addMimeTypes("application/x-rar-compressed rar");
    fileTypeMap.addMimeTypes("application/x-textedit bat cmd");
    fileTypeMap.addMimeTypes("application/zip zip");
    fileTypeMap.addMimeTypes("audio/mpeg mp3");
    fileTypeMap.addMimeTypes("image/bmp bmp");
    fileTypeMap.addMimeTypes("image/gif gif");
    fileTypeMap.addMimeTypes("image/jpeg jpg jpeg jpe");
    fileTypeMap.addMimeTypes("image/png png");
    fileTypeMap.addMimeTypes("text/css css");
    fileTypeMap.addMimeTypes("text/csv csv");
    fileTypeMap.addMimeTypes("text/html htm html");
    fileTypeMap.addMimeTypes("text/xml xml");
    fileTypeMap.addMimeTypes("video/quicktime qt mov moov");
    fileTypeMap.addMimeTypes("video/mpeg mpeg mpg mpe mpv vbs mpegv");
    fileTypeMap.addMimeTypes("video/msvideo avi");
    fileTypeMap.addMimeTypes("video/mp4 mp4");
    fileTypeMap.addMimeTypes("video/ogg ogg");

    FileTypeMap.setDefaultFileTypeMap(fileTypeMap);
}
 
Example 13
Source Project: mycore   Source File: MCRXMLFunctions.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Determines the mime type for the file given by its name.
 *
 * @param f
 *            the name of the file
 * @return the mime type of the given file
 */
public static String getMimeType(String f) {
    if (f == null) {
        return "application/octet-stream";
    }
    MimetypesFileTypeMap mTypes = new MimetypesFileTypeMap();
    return mTypes.getContentType(f.toLowerCase(Locale.ROOT));
}
 
Example 14
/**
 * Introduced to dispel claims in a thread on Stack Overflow:
 * <a href="http://stackoverflow.com/questions/22986109/testing-spring-managed-servlet">Testing Spring managed servlet</a>
 */
@Test
public void getMimeTypeWithCustomConfiguredType() {
	FileTypeMap defaultFileTypeMap = FileTypeMap.getDefaultFileTypeMap();
	assertThat(defaultFileTypeMap, instanceOf(MimetypesFileTypeMap.class));
	MimetypesFileTypeMap mimetypesFileTypeMap = (MimetypesFileTypeMap) defaultFileTypeMap;
	mimetypesFileTypeMap.addMimeTypes("text/enigma    enigma");
	assertEquals("text/enigma", sc.getMimeType("filename.enigma"));
}
 
Example 15
private String getContentTypeByFileName(final String fileName) {
    if (fileName == null) {
        return "";
    } else if (fileName.endsWith(".png")) {
        return "image/png";
    }
    return MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
}
 
Example 16
private String getContentTypeByFileName(final String fileName) {
    if (fileName == null) {
        return "";
    } else if (fileName.endsWith(".png")) {
        return "image/png";
    }
    return MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
}
 
Example 17
Source Project: incubator-heron   Source File: FileResource.java    License: Apache License 2.0 5 votes vote down vote up
private Response getResponseByFile(String filePath) {

    File file = new File(filePath);
    if (!file.exists()) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }
    String mimeType = new MimetypesFileTypeMap().getContentType(file);
    Response.ResponseBuilder rb = Response.ok(file, mimeType);
    rb.header("content-disposition", "attachment; filename = "
        + file.getName());
    return rb.build();

  }
 
Example 18
Source Project: yes-cart   Source File: FileFilter.java    License: Apache License 2.0 5 votes vote down vote up
public FileFilter(final FileService fileService,
                  final SystemService systemService) {
    this.fileService = fileService;
    this.systemService = systemService;
    fileTypeMap = new MimetypesFileTypeMap();
    fileTypeMap.addMimeTypes("image/bmp bmp");
    fileTypeMap.addMimeTypes("application/x-shockwave-flash swf");
}
 
Example 19
Source Project: yes-cart   Source File: ImageFilter.java    License: Apache License 2.0 5 votes vote down vote up
public ImageFilter(final ImageService imageService,
                   final SystemService systemService) {
    this.imageService = imageService;
    this.systemService = systemService;
    fileTypeMap = new MimetypesFileTypeMap();
    fileTypeMap.addMimeTypes("image/bmp bmp");
    fileTypeMap.addMimeTypes("image/png png");
    fileTypeMap.addMimeTypes("application/x-shockwave-flash swf");
}
 
Example 20
private String getContentTypeByFileName(final String fileName) {
    if (fileName == null) {
        return "";
    } else if (fileName.endsWith(".png")) {
        return "image/png";
    }
    return MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
}
 
Example 21
private String getImage(String filename) {
    String filepath = "/themes/default/" + filename;
    try {
        byte[] image = IOUtils.toByteArray(this.getClass().getResourceAsStream(filepath));
        MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
        return "data:" + fileTypeMap.getContentType(filename) + ";base64," + Base64.getEncoder().encodeToString(image);
    } catch (IOException ex) {
        final String error = "Error while trying to load image from: " + filepath;
        LOGGER.error(error, ex);
        return null;
    }
}
 
Example 22
public String getMimetype(File inputFile) {
    try {
        final MagicMatch match = getMatch(inputFile);
        final String mimeType = match.getMimeType();
        if ("???".equals(mimeType)) {
            return guessMimeTypeFromDescription(match);
        }

        return mimeType;
    } catch (MagicMatchNotFoundException e) {
        LOGGER.debug("Failed to get Mime Type", e);
        final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        return mimeTypesMap.getContentType(inputFile);
    }
}
 
Example 23
/**
 * This will set the content types of files. If you want to support any
 * files add the content type and corresponding file extension here.
 *
 * @param response
 * @param file
 */
private static void setContentTypeHeader(HttpResponse response, File file) {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    mimeTypesMap.addMimeTypes("image png tif jpg jpeg bmp");
    mimeTypesMap.addMimeTypes("text/plain txt");
    mimeTypesMap.addMimeTypes("application/pdf pdf");

    String mimeType = mimeTypesMap.getContentType(file);

    response.headers().set(CONTENT_TYPE, mimeType);
}
 
Example 24
Source Project: sakai   Source File: ExtractionHelper.java    License: Educational Community License v2.0 5 votes vote down vote up
private ContentResource makeContentResource(String filename) {
 AttachmentHelper attachmentHelper = new AttachmentHelper();
 StringBuffer fullFilePath = new StringBuffer(unzipLocation);
 fullFilePath.append("/");
 fullFilePath.append(filename);
 MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
 String contentType = mimetypesFileTypeMap.getContentType(filename);
 ContentResource contentResource = attachmentHelper.createContentResource(fullFilePath.toString(), filename, contentType);
 
 return contentResource;
}
 
Example 25
Source Project: components   Source File: PropertiesControllerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<InputStreamResource> getIcon(String definitionName, DefinitionImageType imageType) {
    notNull(definitionName, "Definition name cannot be null.");
    notNull(imageType, "Definition image type cannot be null.");
    final Definition<?> definition = propertiesHelpers.getDefinition(definitionName);
    notNull(definition, "Could not find definition of name %s", definitionName);

    // Undefined and missing icon resources are simply 404.
    String imagePath = definition.getImagePath(imageType);
    if (imagePath == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    InputStream is = definition.getClass().getResourceAsStream(imagePath);
    if (is == null) {
        log.info("The image type %s should exist for %s at %s, but is missing. "
                + "The component should provide this resource.", imageType, definitionName, imagePath);
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    // At this point, we have enough information for a correct response.
    ResponseEntity.BodyBuilder response = ResponseEntity.ok();

    // Add the content type if it can be determined.
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String contentType = mimeTypesMap.getContentType(imagePath);
    if (contentType != null) {
        response = response.contentType(MediaType.parseMediaType(contentType));
    }

    return response.body(new InputStreamResource(is));
}
 
Example 26
private void handleStaticResource(final HttpServletRequest req, HttpServletResponse res, Site sites, String pageSlug)
        throws IOException, ServletException {
    pageSlug = pageSlug.replaceFirst("/", "");
    CMSTheme theme = sites.getTheme();
    if (theme != null) {
        byte[] bytes = theme.contentForPath(pageSlug);
        if (bytes != null) {
            CMSThemeFile templateFile = theme.fileForPath(pageSlug);
            String etag =
                    "W/\"" + bytes.length + "-" + (templateFile == null ? "na" : templateFile.getLastModified().getMillis())
                            + "\"";
            res.setHeader("ETag", etag);
            if (etag.equals(req.getHeader("If-None-Match"))) {
                res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
            res.setHeader("Expires", formatter.print(DateTime.now().plusHours(12)));
            res.setHeader("Cache-Control", "max-age=43200");
            res.setContentLength(bytes.length);
            if (templateFile != null) {
                res.setContentType(templateFile.getContentType());
            } else {
                res.setContentType(new MimetypesFileTypeMap().getContentType(pageSlug));
            }
            res.getOutputStream().write(bytes);
            return;
        }
    }
    res.sendError(404);
}
 
Example 27
Source Project: sakai   Source File: ExtractionHelper.java    License: Educational Community License v2.0 5 votes vote down vote up
private ContentResource makeContentResource(String filename) {
 AttachmentHelper attachmentHelper = new AttachmentHelper();
 StringBuffer fullFilePath = new StringBuffer(unzipLocation);
 fullFilePath.append("/");
 fullFilePath.append(filename);
 MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
 String contentType = mimetypesFileTypeMap.getContentType(filename);
 ContentResource contentResource = attachmentHelper.createContentResource(fullFilePath.toString(), filename, contentType);
 
 return contentResource;
}
 
Example 28
@Override
public String returnAvatarStream() {
	AvatarConfig config = this.getAvatarManager().getConfig();
	String stype = config.getStyle();
	if (null == stype || AvatarConfig.STYLE_DEFAULT.equals(stype)) {
		return super.returnAvatarStream();
	} else if (AvatarConfig.STYLE_GRAVATAR.equals(stype)) {
		return super.extractGravatar();
	}
	try {
		String url = this.getAvatarManager().getAvatarUrl(this.getUsername());
		if (null == url) {
			return this.extractDefaultAvatarStream();
		}
		MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
		this.setMimeType(mimeTypesMap.getContentType(url));
		File avatar = this.getAvatarManager().getAvatarResource(this.getUsername());
		if (null == avatar) {
			return this.extractDefaultAvatarStream();
		}
		this.setInputStream(new FileInputStream(avatar));
	} catch (Throwable t) {
		_logger.info("local avatar not available", t);
		return this.extractDefaultAvatarStream();
       }
	return SUCCESS;
}
 
Example 29
Source Project: mrgeo   Source File: TileMapServiceResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Category(UnitTest.class)
public void testMimetypesFileTypeMap()
{
  //MimetypesFileTypeMap foo = new MimetypesFileTypeMap();
  String type = new MimetypesFileTypeMap().getContentType("output.png");
  assertEquals("image/png", type);
  type = new MimetypesFileTypeMap().getContentType("output.jpg");
  assertEquals("image/jpeg", type);
  type = new MimetypesFileTypeMap().getContentType("output.tif");
  assertEquals("image/tiff", type);
}
 
Example 30
Source Project: studio   Source File: PluginController.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a single file for a given plugin
 */
@GetMapping("/file")
public ResponseEntity<Resource> getPluginFile(@RequestParam String siteId, @RequestParam String type,
                                              @RequestParam String name, @RequestParam String filename)
    throws ContentNotFoundException {

    Resource resource = configurationService.getPluginFile(siteId, type, name, filename);

    MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();
    String contentType = mimeMap.getContentType(filename);

    return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, contentType).body(resource);
}