javax.activation.MimetypesFileTypeMap Java Examples

The following examples show how to use javax.activation.MimetypesFileTypeMap. 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 File: HttpClasspathServerHandler.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #2
Source File: MimeTypeConfig.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 File: JerryRequest.java    From JerryServer with 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 #4
Source File: ContentServiceImpl.java    From studio with 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 #5
Source File: BinaryView.java    From studio with 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 #6
Source File: FileSystemUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #7
Source File: AccessStructure.java    From jplag with 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 #8
Source File: FileView.java    From Summer with 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 #9
Source File: IpcdBridgeConfigModule.java    From arcusplatform with 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 File: BridgeConfigModule.java    From arcusplatform with 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 #11
Source File: ContentServiceImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
protected ContentItemTO loadContentItem(String site, String path) {
    // TODO: SJ: Refactor such that the populate of non-XML is also a method in 3.1+
    ContentItemTO item = createNewContentItemTO(site, path);

    if (item.uri.endsWith(".xml") && !item.uri.startsWith("/config/")) {

        try {
            item = populateContentDrivenProperties(site, item);
        } catch (Exception err) {
            logger.debug("error constructing item for object at site '{}' path '{}'", err, site, path);
        }
    } else {
        item.setLevelDescriptor(item.name.equals(servicesConfig.getLevelDescriptorName(site)));
        item.page = ContentUtils.matchesPatterns(item.getUri(), servicesConfig.getPagePatterns(site));
        item.isPage = item.page;
        item.previewable = item.page;
        item.isPreviewable = item.previewable;
        item.asset = ContentUtils.matchesPatterns(item.getUri(), servicesConfig.getAssetPatterns(site)) ||
                ContentUtils.matchesPatterns(item.getUri(), servicesConfig.getRenderingTemplatePatterns(site)) ||
                ContentUtils.matchesPatterns(item.getUri(), servicesConfig.getScriptsPatterns(site));
        item.isAsset = item.asset;
        item.component = ContentUtils.matchesPatterns(item.getUri(), servicesConfig.getComponentPatterns(site)) ||
                item.isLevelDescriptor() || item.asset;
        item.isComponent = item.component;
        item.document = ContentUtils.matchesPatterns(item.getUri(), servicesConfig.getDocumentPatterns(site));
        item.isDocument = item.document;
        item.browserUri =item.getUri();
        item.setContentType(getContentTypeClass(site, path));
    }

    loadContentTypeProperties(site, item, item.contentType);

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String mimeType = mimeTypesMap.getContentType(item.getName());
    if (StringUtils.isNotEmpty(mimeType)) {
        item.setMimeType(mimeType);
    }
    return item;
}
 
Example #12
Source File: TaskResource.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Inject
public TaskResource(
  TaskRequestManager taskRequestManager,
  TaskManager taskManager,
  SlaveManager slaveManager,
  MesosClient mesosClient,
  SingularityTaskMetadataConfiguration taskMetadataConfiguration,
  SingularityAuthorizer authorizationHelper,
  RequestManager requestManager,
  SingularityValidator validator,
  DisasterManager disasterManager,
  AsyncHttpClient httpClient,
  LeaderLatch leaderLatch,
  @Singularity ObjectMapper objectMapper,
  RequestHelper requestHelper,
  MesosConfiguration configuration,
  SingularityMesosSchedulerClient mesosSchedulerClient
) {
  super(httpClient, leaderLatch, objectMapper);
  this.taskManager = taskManager;
  this.taskRequestManager = taskRequestManager;
  this.taskMetadataConfiguration = taskMetadataConfiguration;
  this.slaveManager = slaveManager;
  this.mesosClient = mesosClient;
  this.requestManager = requestManager;
  this.authorizationHelper = authorizationHelper;
  this.validator = validator;
  this.disasterManager = disasterManager;
  this.requestHelper = requestHelper;
  this.httpClient = httpClient;
  this.configuration = configuration;
  this.fileTypeMap = new MimetypesFileTypeMap();
  this.mesosSchedulerClient = mesosSchedulerClient;
}
 
Example #13
Source File: FileBasedCollection.java    From rome with Apache License 2.0 5 votes vote down vote up
private void updateMediaEntryAppLinks(final Entry entry, final String fileName, final boolean singleEntry) {

        // TODO: figure out why PNG is missing from Java MIME types
        final FileTypeMap map = FileTypeMap.getDefaultFileTypeMap();
        if (map instanceof MimetypesFileTypeMap) {
            try {
                ((MimetypesFileTypeMap) map).addMimeTypes("image/png png PNG");
            } catch (final Exception ignored) {
            }
        }
        entry.setId(getEntryMediaViewURI(fileName));
        entry.setTitle(fileName);
        entry.setUpdated(new Date());

        final List<Link> otherlinks = new ArrayList<Link>();
        entry.setOtherLinks(otherlinks);

        final Link editlink = new Link();
        editlink.setRel("edit");
        editlink.setHref(getEntryEditURI(fileName, relativeURIs, singleEntry));
        otherlinks.add(editlink);

        final Link editMedialink = new Link();
        editMedialink.setRel("edit-media");
        editMedialink.setHref(getEntryMediaEditURI(fileName, relativeURIs, singleEntry));
        otherlinks.add(editMedialink);

        final Content content = entry.getContents().get(0);
        content.setSrc(getEntryMediaViewURI(fileName));
        final List<Content> contents = new ArrayList<Content>();
        contents.add(content);
        entry.setContents(contents);
    }
 
Example #14
Source File: UserAvatarAction.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #15
Source File: MimeTypeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of 
 * MIME type.
 * 
 */
@Test
public void whenUsingMimeTypesFileTypeMap_thenSuccess() {
    final File file = new File(FILE_LOC);
    final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
    final String mimeType = fileTypeMap.getContentType(file.getName());
    assertEquals(mimeType, PNG_EXT);
}
 
Example #16
Source File: MCRXMLFunctions.java    From mycore with 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 #17
Source File: EmailServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private String getContentTypeByFileName(final String fileName) {
    if (fileName == null) {
        return "";
    } else if (fileName.endsWith(".png")) {
        return "image/png";
    }
    return MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
}
 
Example #18
Source File: EmailServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private String getContentTypeByFileName(final String fileName) {
    if (fileName == null) {
        return "";
    } else if (fileName.endsWith(".png")) {
        return "image/png";
    }
    return MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
}
 
Example #19
Source File: PluginController.java    From studio with 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);
}
 
Example #20
Source File: ExtractionHelper.java    From sakai with 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 #21
Source File: FileResource.java    From incubator-heron with 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 #22
Source File: FileFilter.java    From yes-cart with 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 #23
Source File: ImageFilter.java    From yes-cart with 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 #24
Source File: EmailServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private String getContentTypeByFileName(final String fileName) {
    if (fileName == null) {
        return "";
    } else if (fileName.endsWith(".png")) {
        return "image/png";
    }
    return MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
}
 
Example #25
Source File: ThemeServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: FileAnalyser.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #27
Source File: HttpStaticFileServerHandler.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #28
Source File: CMSURLHandler.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #29
Source File: ExtractionHelper.java    From sakai with 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 #30
Source File: PropertiesControllerImpl.java    From components with 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));
}