List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:org.paxle.tools.icon.impl.IconTool.java
/** * @param url the location of the resource, for which the favicon should be loaded * @param depth protection against endless loops, e.g. if the icon link returned by * a page is another html site. Maximum is 20. * @return the loaded image data.// w w w . ja va 2s . c o m */ private IconData getIcon(URL url, int depth) { if (url == null) return defaultIcon; else if (depth > 20) return defaultIcon; GetMethod method = null; try { /* * Handling of !http URLs */ if (!url.getProtocol().equals("http")) { String expectedType = URLConnection.guessContentTypeFromName(url.getFile()); byte[] data = readFileIconPng(expectedType); return data == null ? defaultIcon : new IconData(data); } /* * Handling of http URLs */ method = new GetMethod(url.toExternalForm()); int status = httpClient.executeMethod(method); if (status != 200) { // TODO: logging return defaultIcon; } // getting the mimetype and charset String contentMimeType = "unknown"; //to allow this to be null, the code below (like contentMimeType.equals("text/html")) must be refactored Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { contentMimeType = contentTypeHeader.getValue(); int idx = contentMimeType.indexOf(";"); if (idx != -1) contentMimeType = contentMimeType.substring(0, idx); } byte[] body = null; String iconType = "image/png"; if (contentMimeType.equals("text/html")) { if (url.getPath().equals("/favicon.ico")) { // the website returned the favicon.ico als html! return defaultHtmlIcon; } /* Download content until we get the * <LINK REL="SHORTCUT ICON" HREF="icons/matex.ico"> * header */ InputStream bodyStream = method.getResponseBodyAsStream(); HtmlReader reader = new HtmlReader(bodyStream); HtmlParserCallback theParser = new HtmlParserCallback(reader); new ParserDelegator().parse(reader, theParser, true); // get the parsed favicon url String urlString = theParser.getFaviconUrl(); URL faviconURL = null; if (urlString == null || urlString.length() == 0) { // website has no special icon, try to fetch the global favicon faviconURL = new URL(url, "/favicon.ico"); } else { faviconURL = new URL(url, urlString); } IconData faviconData = getIcon(faviconURL, ++depth); return (faviconData == null || faviconData == defaultIcon) ? defaultHtmlIcon : faviconData; } else if (contentMimeType.equals("image/x-icon") || contentMimeType.equals("image/vnd.microsoft.icon")) { byte[] data = method.getResponseBody(); Image icon = this.faviconReader.readIcoImage(data); if (icon != null) body = IconTool.toBytes(icon); } else if (contentMimeType.startsWith("image/")) { body = method.getResponseBody(); iconType = contentMimeType; } else { InputStream bodyStream = null; ByteArrayOutputStream bout = null; try { bodyStream = method.getResponseBodyAsStream(); bout = new ByteArrayOutputStream(); this.ioTool.copy(bodyStream, bout, 4); byte[] bodyPrefix = bout.toByteArray(); if ((bodyPrefix != null) && (bodyPrefix.length >= 4) && (bodyPrefix[0] == 0) && (bodyPrefix[1] == 0) && (bodyPrefix[2] == 1) && (bodyPrefix[3] == 0)) { this.ioTool.copy(bodyStream, bout); byte[] data = bout.toByteArray(); // trying to read icon Image icon = this.faviconReader.readIcoImage(data); if (icon != null) body = IconTool.toBytes(icon); } else { body = readFileIconPng(contentMimeType); iconType = "image/png"; } } catch (IOException e) { // TODO: logging } finally { if (bodyStream != null) bodyStream.close(); if (bout != null) bout.close(); } } return (body == null) ? defaultIcon : new IconData(iconType, body); } catch (Exception e) { // TODO: logging e.printStackTrace(); return defaultIcon; } finally { if (method != null) method.releaseConnection(); } }
From source file:org.shareok.data.webserv.JournalDataController.java
@RequestMapping(value = "/download/dspace/journal/{publisher}/{folderName}/{fileName}/") public void journalLoadingDataDownload(HttpServletResponse response, @PathVariable("publisher") String publisher, @PathVariable("folderName") String folderName, @PathVariable("fileName") String fileName) { String downloadPath = DspaceJournalDataUtil.getDspaceJournalDownloadFilePath(publisher, folderName, fileName);/*ww w. j a v a2s .c o m*/ try { File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { Logger.getLogger(JournalDataController.class.getName()).log(Level.SEVERE, null, ioex); } }
From source file:com.necl.core.controller.DownloadFileController.java
@RequestMapping(value = "/downloadManual", method = RequestMethod.GET) public void downloadFileManual(HttpServletResponse response) throws IOException, Exception { String keyFind = "PATH"; ConfigSystem configSystem = configSystemService.findByKey(keyFind); String saveDirectory = configSystem.getConfigText() + "Manual/"; File file = null;//from w ww . j av a 2 s .c o m String type = ".pdf"; String pathDirectory = saveDirectory + "ApprovalControlManual" + type; System.out.println("pthDi: " + pathDirectory); file = new File(pathDirectory); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { mimeType = "application/octet-stream"; } System.out.println("mimetype : " + mimeType); response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); }
From source file:com.t3.persistence.FileUtil.java
/** * Given a URL this method determines the content type of the URL (if possible) and * then returns a Reader with the appropriate character encoding. * /*w w w . j a v a 2 s.c om*/ * @param url the source of the data stream * @return String representing the data * @throws IOException */ public static Reader getURLAsReader(URL url) throws IOException { InputStreamReader isr = null; URLConnection conn = null; String encoding = "UTF-8"; // We're assuming character here, but it could be bytes. Perhaps we should // check the MIME type returned by the network server? conn = url.openConnection(); if (log.isDebugEnabled()) { String type = URLConnection.guessContentTypeFromName(url.getPath()); log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type); type = getContentType(conn.getInputStream()); // Now make a guess and change 'encoding' to match the content type... } isr = new InputStreamReader(conn.getInputStream(), encoding); return isr; }
From source file:org.caboclo.clients.GoogleDriveClient.java
@Override public void putFile(java.io.File file, String path) throws IOException { path = path.replace("\\", "/"); int pos = path.lastIndexOf("/"); if (pos > 0) { path = path.substring(0, pos);/*from ww w .ja v a2 s . com*/ } String parentId = this.getId(path); //The path does not exists! //FIXME-It is necessary to construct the path based on the last //valid id if (parentId.equals("root") && !path.equals("") && !path.equals("/") && !path.equals("\\")) { this.makedir(path); parentId = this.getId(path); } try { String mimeType = URLConnection.guessContentTypeFromName(file.getName()); mimeType = (mimeType == null) ? "application/octet-stream" : mimeType; File body = new File(); body.setTitle(getTitle(file.getName())); body.setMimeType(mimeType); if (parentId != null || !parentId.equals("")) { body.setParents(Arrays.asList(new ParentReference().setId(parentId))); } FileContent mediaContent = new FileContent(mimeType, file); File f = service.files().insert(body, mediaContent).execute(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.shareok.data.webserv.WebUtil.java
public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) { try {//from w w w. j a va 2s . co m File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { logger.error("Cannot download file responding to downloading resquest!", ioex); } }
From source file:org.jumpmind.symmetric.transport.http.HttpOutgoingTransport.java
public OutputStream openStream() { try {/*from www.j a va2 s. co m*/ connection = HttpTransportManager.openConnection(url, basicAuthUsername, basicAuthPassword); if (streamOutputEnabled) { connection.setChunkedStreamingMode(streamOutputChunkSize); } connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(httpTimeout); connection.setReadTimeout(httpTimeout); boundary = Long.toHexString(System.currentTimeMillis()); if (!fileUpload) { connection.setRequestMethod("PUT"); connection.setRequestProperty("Accept-Encoding", "gzip"); if (useCompression) { connection.addRequestProperty("Content-Type", "gzip"); // application/x-gzip? } } else { connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } os = connection.getOutputStream(); if (!fileUpload && useCompression) { os = new GZIPOutputStream(os) { { this.def.setLevel(compressionLevel); this.def.setStrategy(compressionStrategy); } }; } if (fileUpload) { final String fileName = "file.zip"; IOUtils.write("--" + boundary + CRLF, os); IOUtils.write( "Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + fileName + "\"" + CRLF, os); IOUtils.write("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + CRLF, os); IOUtils.write("Content-Transfer-Encoding: binary" + CRLF + CRLF, os); os.flush(); } return os; } catch (IOException ex) { throw new IoException(ex); } }
From source file:com.t3.persistence.FileUtil.java
/** * Given a URL this method determines the content type of the URL (if possible) and * then returns a Reader with the appropriate character encoding. * // w ww .j av a 2 s .c o m * @param url the source of the data stream * @return String representing the data * @throws IOException */ public static InputStream getURLAsInputStream(URL url) throws IOException { InputStream is = null; URLConnection conn = null; // We're assuming character here, but it could be bytes. Perhaps we should // check the MIME type returned by the network server? conn = url.openConnection(); if (log.isDebugEnabled()) { String type = URLConnection.guessContentTypeFromName(url.getPath()); log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type); type = getContentType(conn.getInputStream()); log.debug("result from getContentType(" + url.getPath() + ") is " + type); } is = conn.getInputStream(); return is; }
From source file:org.exoplatform.utils.ExoDocumentUtils.java
/** * Check if the device has an application to open this type of file. * /*from www . ja va 2 s. co m*/ * @param context Context (mandatory) * @param mimeType Mime Type to check (mandatory) * @param url file url to guess the mime type from (optional) * @return true if an application can open the given Mime Type */ public static boolean isCallable(Context context, String mimeType, String url) throws IllegalArgumentException { if (context == null || mimeType == null) throw new IllegalArgumentException("Context or mime-type cannot be null."); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType(mimeType.toLowerCase(Locale.US)); ComponentName activity = intent.resolveActivity(context.getPackageManager()); if (activity == null && url != null) { // Fallback on a guessed mime type if the first one doesn't work String guessedMimeType = URLConnection.guessContentTypeFromName(url); if (guessedMimeType != null) { intent = new Intent(Intent.ACTION_VIEW); intent.setType(guessedMimeType.toLowerCase(Locale.US)); activity = intent.resolveActivity(context.getPackageManager()); } } return activity != null; }
From source file:com.versacomllc.audit.network.sync.SyncAdapter.java
private String uploadFile(String path) { String downloadPath = Constants.FILE_CONTENT_PATH; if (TextUtils.isEmpty(path)) { Log.d(LOG_TAG, "File path is empty."); return null; }//from w w w . ja v a 2 s . com HttpClient httpclient = new DefaultHttpClient(); try { File file = new File(path); HttpPost httppost = new HttpPost(FILE_UPLOAD_PATH); String mimeType = URLConnection.guessContentTypeFromName(path); FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(file.getName(), bin); httppost.setEntity(reqEntity); Log.i(TAG, "executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { Log.i(TAG, "Response content length: " + resEntity.getContentLength()); } downloadPath = downloadPath + file.getName(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } return downloadPath; }