List of usage examples for java.net FileNameMap getContentTypeFor
public String getContentTypeFor(String fileName);
From source file:org.openstatic.http.HttpResponse.java
/** Determine the content type of a local file */ public static String getContentTypeFor(String filename) { String lc_file = filename.toLowerCase(); if (lc_file.endsWith(".html") || lc_file.endsWith(".htm")) { return "text/html"; } else if (lc_file.endsWith(".txt")) { return "text/plain"; } else if (lc_file.endsWith(".css")) { return "text/css"; } else if (lc_file.endsWith(".js")) { return "text/javascript"; } else if (lc_file.endsWith(".jpg") || lc_file.endsWith(".jpe") || lc_file.endsWith(".jpeg")) { return "image/jpeg"; } else if (lc_file.endsWith(".gif")) { return "image/gif"; } else {/*from www. jav a 2 s . co m*/ FileNameMap fnm = URLConnection.getFileNameMap(); return fnm.getContentTypeFor(filename); } }
From source file:org.yes.cart.service.vo.impl.VoIOSupportImpl.java
static String getMimeType(String fileName) { final FileNameMap mimeTypes = URLConnection.getFileNameMap(); final String contentType = mimeTypes.getContentTypeFor(fileName); // 2. nothing found -> lookup our in extension map to find types like ".doc" or ".docx" if (contentType == null) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()); ;// w w w .j ava 2 s .c om return EXT_MIMETYPE_MAP.get(extension); } return contentType; }
From source file:com.whiuk.philip.opensmime.PathConverter.java
private static FileInformation handleFileScheme(Context context, Uri uri) { FileInputStream fileInputStream = null; final String filePath = uri.getPath(); try {//from w ww. j a va2 s . c om File srcFile = new File(filePath); fileInputStream = new FileInputStream(srcFile); File tmpFile = copyToTempFile(context, fileInputStream); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(filePath); String fileName = FilenameUtils.getName(filePath); return new FileInformation(tmpFile, fileName, mimeType); } catch (IOException e) { Log.e(OpenSMIME.LOG_TAG, "error acquiring FileInforamtion in handleFileScheme", e); } return null; }
From source file:de.fau.cs.mad.smile.android.encryption.PathConverter.java
private static FileInformation handleFileScheme(Context context, Uri uri) { FileInputStream fileInputStream = null; final String filePath = uri.getPath(); try {//from w w w.jav a 2 s. c om File srcFile = new File(filePath); fileInputStream = new FileInputStream(srcFile); File tmpFile = copyToTempFile(context, fileInputStream); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(filePath); String fileName = FilenameUtils.getName(filePath); return new FileInformation(tmpFile, fileName, mimeType); } catch (IOException e) { Log.e(SMileCrypto.LOG_TAG, "error acquiring FileInforamtion in handleFileScheme", e); } return null; }
From source file:com.qmetry.qaf.automation.util.FileUtil.java
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; }
From source file:se.mithlond.services.content.model.articles.media.BitmapImage.java
/** * Creates a BitmapImage originating from a File. * * @param imageFile The File pointing to an Image. * @return The converted and created BitmapImage. *//*from www . ja v a2 s . co m*/ public static BitmapImage createFromFile(final File imageFile) { // Check sanity final File file = Validate.notNull(imageFile, "imageFile"); // Replace whitespace with '_' and make the name lowercase. final String harmonizedFileName = validateAndHarmonizeName(file.getName()); // Read the data, and convert it to a BufferedImage. final byte[] bytes; final BufferedImage bufferedImage; try { bytes = Files.readAllBytes(file.toPath()); bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes)); } catch (IOException e) { // Complain. throw new IllegalArgumentException("Could not create a BufferedImage from file [" + imageFile.getName() + "] with the harmonized name [" + harmonizedFileName + "]", e); } // Find the Mime type of the image. final FileNameMap fileNameMap = URLConnection.getFileNameMap(); final String mimeType = fileNameMap.getContentTypeFor(harmonizedFileName); // All Done. return new BitmapImage(harmonizedFileName, bufferedImage.getWidth(), bufferedImage.getHeight(), mimeType, bytes); }
From source file:se.mithlond.services.content.model.articles.media.BitmapImage.java
/** * Creates a BitmapImage originating from a File. * * @param resourcePath The resource path to an image file. * @return The converted and created BitmapImage. *///w w w. ja va 2 s .c om public static BitmapImage createFromResourcePath(final String resourcePath) { // Check sanity Validate.notEmpty(resourcePath, "resourcePath"); final URL resource = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (resource == null) { throw new IllegalArgumentException("No resource found for resourcePath " + resourcePath); } // We will only handle "JAR" or "FILE" protocols. if (FILE_PROTOCOL.equalsIgnoreCase(resource.getProtocol())) { // Delegate return createFromFile(new File(resource.getPath())); } if (!JAR_PROTOCOL.equalsIgnoreCase(resource.getProtocol())) { throw new IllegalArgumentException("Will only handle 'JAR' protocol URLs."); } // // Ensure that the URI targets a single image file. // The typical URI should look like the following: // // jar:file:/some/path/to/images.jar!/images/example_png.png // final String jarProtocolStart = JAR_PROTOCOL + ":"; final String innerProtocolStringForm = resource.toString() .substring(resource.toString().indexOf(jarProtocolStart) + jarProtocolStart.length()); if (!innerProtocolStringForm.trim().toLowerCase().startsWith(FILE_PROTOCOL + ":")) { throw new IllegalArgumentException( "Expected sub-protocol 'file:' within the JAR file., but got: " + innerProtocolStringForm); } final String internalJarPath = innerProtocolStringForm.substring(innerProtocolStringForm.indexOf("!") + 1); // Harmonize and validate the image file name. final String fileName = internalJarPath.substring(internalJarPath.lastIndexOf("/") + 1); final String harmonizedFileName = validateAndHarmonizeName(fileName); // Find the Mime type of the image. final FileNameMap fileNameMap = URLConnection.getFileNameMap(); final String mimeType = fileNameMap.getContentTypeFor(harmonizedFileName); // Read the image data from the JarEntry final byte[] data; final BufferedImage bufferedImage; try { data = IOUtils.toByteArray(resource.openStream()); bufferedImage = ImageIO.read(new ByteArrayInputStream(data)); } catch (IOException e) { throw new IllegalArgumentException("Could not read image data from [" + resource.toString() + "]", e); } // All Done. return new BitmapImage(harmonizedFileName, bufferedImage.getWidth(), bufferedImage.getHeight(), mimeType, data); }
From source file:com.openmeap.http.FileHandlingHttpRequestExecuterImpl.java
@Override public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException { // test to determine whether this is a file upload or not. Boolean isFileUpload = false; for (Object o : postParams.values()) { if (o instanceof File) { isFileUpload = true;//from w w w. j a v a2 s . c o m break; } } if (isFileUpload) { try { HttpPost httpPost = new HttpPost(createUrl(url, getParams)); httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Object o : postParams.entrySet()) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o; if (entry.getValue() instanceof File) { // For File parameters File file = (File) entry.getValue(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(file.toURL().toString()); entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type)); } else { // For usual String parameters entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT))); } } httpPost.setEntity(entity); return execute(httpPost); } catch (Exception e) { throw new HttpRequestException(e); } } else { return super.postData(url, getParams, postParams); } }
From source file:org.jboss.dashboard.ui.controller.responses.SendStreamResponse.java
/** * Send a file as response./*from w w w .j a va 2 s . co m*/ * * @param f File to send */ public SendStreamResponse(File f) { try { init(new FileInputStream(f), "inline; filename=" + URLEncoder.encode(f.getName()) + ";"); FileNameMap fileNameMap = URLConnection.getFileNameMap(); contentType = fileNameMap.getContentTypeFor(f.getName()); } catch (FileNotFoundException e) { log.error("Error:", e); errorCode = HttpServletResponse.SC_NOT_FOUND; } }
From source file:com.openmeap.admin.web.servlet.WebViewServlet.java
@SuppressWarnings("unchecked") @Override//w w w . j a va2 s. c o m public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { logger.trace("in service"); ModelManager mgr = getModelManager(); GlobalSettings settings = mgr.getGlobalSettings(); String validTempPath = settings.validateTemporaryStoragePath(); if (validTempPath != null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath); } String pathInfo = request.getPathInfo(); String[] pathParts = pathInfo.split("[/]"); if (pathParts.length < 4) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3]; String fileRelative = pathInfo.replace(remove, ""); String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT); String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT); Application app = mgr.getModelService().findApplicationByName(applicationNameString); ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash, "MD5"); String authSalt = app.getProxyAuthSalt(); String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT); try { if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } } catch (DigestException e1) { throw new GenericRuntimeException(e1); } File fileFull = new File( arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative); try { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString()); response.setContentType(mimeType); response.setContentLength(Long.valueOf(fileFull.length()).intValue()); InputStream inputStream = null; OutputStream outputStream = null; try { //response.setStatus(HttpServletResponse.SC_FOUND); inputStream = new FileInputStream(fileFull); outputStream = response.getOutputStream(); Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream); } finally { if (inputStream != null) { inputStream.close(); } response.getOutputStream().flush(); response.getOutputStream().close(); } } catch (FileNotFoundException e) { logger.error("Exception {}", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException ioe) { logger.error("Exception {}", ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }