Java Code Examples for javax.activation.MimetypesFileTypeMap#getContentType()

The following examples show how to use javax.activation.MimetypesFileTypeMap#getContentType() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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));
}
 
Example 11
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 12
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 13
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 14
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 15
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 16
Source File: FileDropTargetListener.java    From magarena with GNU General Public License v3.0 4 votes vote down vote up
private String tryMimetypesFileTypeMap(File aFile) {
    final MimetypesFileTypeMap mtftp = new MimetypesFileTypeMap();
    mtftp.addMimeTypes("image " + IMAGE_FORMATS);
    mtftp.addMimeTypes("application/zip zip");
    return mtftp.getContentType(aFile);
}
 
Example 17
Source File: ExtractionHelper.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * the ip address is in a newline delimited string
 * @param assessment
 */
public String makeFCKAttachment(String text) {
 if (text == null) {
  return text;
 }
 String processedText = XmlUtil.processFormattedText(text);
 // if unzipLocation is null, there is no assessment attachment - no action is needed
 if (unzipLocation == null || processedText.equals("")) {
  return processedText;
 }

 String accessURL = ServerConfigurationService.getAccessUrl();
 String referenceRoot = AssessmentService.getContentHostingService().REFERENCE_ROOT;
 String prependString = accessURL + referenceRoot;
 StringBuffer updatedText = null;
 ContentResource contentResource = null;
 AttachmentHelper attachmentHelper = new AttachmentHelper();
 String resourceId = null;
  String importedPrependString = getImportedPrependString(processedText);
  if (importedPrependString == null) {
	  return processedText;
  }
  String[] splittedString = processedText.split("src=\""+importedPrependString);
  List<String> splittedList = new ArrayList<String>();
  String src = "";
  for (int i = 0; i < splittedString.length; i ++) {
	  	splittedString[i] = src + splittedString[i];
		String[] splittedRefString = splittedString[i].split("href=\""+importedPrependString);
		String href = "";
		for (int j = 0; j < splittedRefString.length; j++){ 
			splittedRefString[j] = href + splittedRefString[j];
			splittedList.add(splittedRefString[j]);
			href = "href=\"";
		}
		src = "src=\"";
  }
  splittedString = splittedList.toArray(splittedString);
  int endIndex = 0;
  String filename = null;
  String contentType = null;
  String fullFilePath = null;
  String oldResourceId = null;

  updatedText = new StringBuffer(splittedString[0]);
  for (int i = 1; i < splittedString.length; i++) {
	  log.debug("splittedString[" + i + "] = " + splittedString[i]);
	  // Here is an example, splittedString will be something like:
	  // /group/b917f0b9-e21d-4819-80ee-35feac91c9eb/Blue Hill.jpg" alt="...  or
	  // /user/ktsao/Blue Hill.jpg" alt="...
	  // oldResourceId = /group/b917f0b9-e21d-4819-80ee-35feac91c9eb/Blue Hill.jpg or /user/ktsao/Blue Hill.jpg
	  // oldSplittedResourceId[0] = ""
	  // oldSplittedResourceId[1] = group or user
	  // oldSplittedResourceId[2] = b917f0b9-e21d-4819-80ee-35feac91c9eb or ktsao
	  // oldSplittedResourceId[3] = Blue Hill.jpg
	  endIndex = splittedString[i].indexOf("\"",splittedString[i].indexOf("\"")+1);
	  oldResourceId = splittedString[i].substring(splittedString[i].indexOf("\"")+1, endIndex);
	  String[] oldSplittedResourceId = oldResourceId.split("/");
	  fullFilePath = unzipLocation + "/" + oldResourceId.replace(" ", "");
	  filename = oldSplittedResourceId[oldSplittedResourceId.length - 1];
	  MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
	  contentType = mimetypesFileTypeMap.getContentType(filename);
	  contentResource = attachmentHelper.createContentResource(fullFilePath, filename, contentType);

	  if (contentResource != null) {
		  resourceId = contentResource.getId();
		  updatedText.append(splittedString[i].substring(0,splittedString[i].indexOf("\"")+1));
		  updatedText.append(prependString);
		  updatedText.append(resourceId);
		  updatedText.append(splittedString[i].substring(endIndex));
	  }
	  else {
		  throw new RuntimeException("resourceId is null");
	  }

  }
  return updatedText.toString();	  
}
 
Example 18
Source File: ExtractionHelper.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * the ip address is in a newline delimited string
 * @param assessment
 */
public String makeFCKAttachment(String text) {
 if (text == null) {
  return text;
 }
 String processedText = XmlUtil.processFormattedText(text);
 // if unzipLocation is null, there is no assessment attachment - no action is needed
 if (unzipLocation == null || processedText.equals("")) {
  return processedText;
 }

 String accessURL = ServerConfigurationService.getAccessUrl();
 String referenceRoot = AssessmentService.getContentHostingService().REFERENCE_ROOT;
 String prependString = accessURL + referenceRoot;
 StringBuffer updatedText = null;
 ContentResource contentResource = null;
 AttachmentHelper attachmentHelper = new AttachmentHelper();
 String resourceId = null;
  String importedPrependString = getImportedPrependString(processedText);
  if (importedPrependString == null) {
	  return processedText;
  }
  String[] splittedString = processedText.split("src=\""+importedPrependString);
  List<String> splittedList = new ArrayList<String>();
  String src = "";
  for (int i = 0; i < splittedString.length; i ++) {
	  	splittedString[i] = src + splittedString[i];
		String[] splittedRefString = splittedString[i].split("href=\""+importedPrependString);
		String href = "";
		for (int j = 0; j < splittedRefString.length; j++){ 
			splittedRefString[j] = href + splittedRefString[j];
			splittedList.add(splittedRefString[j]);
			href = "href=\"";
		}
		src = "src=\"";
  }
  splittedString = splittedList.toArray(splittedString);
  int endIndex = 0;
  String filename = null;
  String contentType = null;
  String fullFilePath = null;
  String oldResourceId = null;

  updatedText = new StringBuffer(splittedString[0]);
  for (int i = 1; i < splittedString.length; i++) {
	  log.debug("splittedString[" + i + "] = " + splittedString[i]);
	  // Here is an example, splittedString will be something like:
	  // /group/b917f0b9-e21d-4819-80ee-35feac91c9eb/Blue Hill.jpg" alt="...  or
	  // /user/ktsao/Blue Hill.jpg" alt="...
	  // oldResourceId = /group/b917f0b9-e21d-4819-80ee-35feac91c9eb/Blue Hill.jpg or /user/ktsao/Blue Hill.jpg
	  // oldSplittedResourceId[0] = ""
	  // oldSplittedResourceId[1] = group or user
	  // oldSplittedResourceId[2] = b917f0b9-e21d-4819-80ee-35feac91c9eb or ktsao
	  // oldSplittedResourceId[3] = Blue Hill.jpg
	  endIndex = splittedString[i].indexOf("\"",splittedString[i].indexOf("\"")+1);
	  oldResourceId = splittedString[i].substring(splittedString[i].indexOf("\"")+1, endIndex);
	  String[] oldSplittedResourceId = oldResourceId.split("/");
	  fullFilePath = unzipLocation + "/" + oldResourceId.replace(" ", "");
	  filename = oldSplittedResourceId[oldSplittedResourceId.length - 1];
	  MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
	  contentType = mimetypesFileTypeMap.getContentType(filename);
	  contentResource = attachmentHelper.createContentResource(fullFilePath, filename, contentType);

	  if (contentResource != null) {
		  resourceId = contentResource.getId();
		  updatedText.append(splittedString[i].substring(0,splittedString[i].indexOf("\"")+1));
		  updatedText.append(prependString);
		  updatedText.append(resourceId);
		  updatedText.append(splittedString[i].substring(endIndex));
	  }
	  else {
		  throw new RuntimeException("resourceId is null");
	  }

  }
  return updatedText.toString();	  
}
 
Example 19
Source File: FileUtil.java    From qaf with MIT License 4 votes vote down vote up
public static String getContentType(File f) {
	MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
	FileNameMap fileNameMap = URLConnection.getFileNameMap();
	String ct = fileNameMap.getContentTypeFor(f.getName());
	return StringUtil.isBlank(ct) ? fileTypeMap.getContentType(f) : ct;
}