List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:com.joyent.manta.http.ContentTypeLookup.java
/** * Finds the content type set in {@link MantaHttpHeaders} and returns that if it * is not null. Otherwise, it will return the specified default content type. * * @param headers headers to parse for content type * @param filename path to the destination file * @param file file that is being probed for content type * @param defaultContentType content type to default to * @return content type object//from w ww . j av a 2s . c om * @throws IOException thrown when we can't access the file being analyzed */ public static ContentType findOrDefaultContentType(final MantaHttpHeaders headers, final String filename, final File file, final ContentType defaultContentType) throws IOException { final String headerContentType; if (headers != null) { headerContentType = headers.getContentType(); } else { headerContentType = null; } String type = ObjectUtils.firstNonNull( // Use explicitly set headers if available headerContentType, // Detect based on destination and then source // filename. URLConnection uses a property list // bundled with the JVM and is expected to be // consistent on all platforms. As implied by the // method name, the contents of the file are not // considered. URLConnection.guessContentTypeFromName(filename), URLConnection.guessContentTypeFromName(file.getName()), // Probe using the JVM default detection method. The // detection methods vary across platforms and may // rely on /etc/mime.types or include native libraries // such as libgio or libreal. The contents of the // file may be inspected. This check is ordered last // both for cross-platform consistency. See // https://github.com/joyent/java-manta/issues/276 for // further context. Files.probeContentType(file.toPath())); if (type == null) { return defaultContentType; } return ContentType.parse(type); }
From source file:org.springframework.social.twitter.api.impl.ton.TonTemplateTest.java
@Test public void uploadChunk() throws IOException { mockServer.expect(requestTo("https://ton.twitter.com/1.1/ton/bucket/ta_partner")).andExpect(method(POST)) .andRespond(withCreatedEntity(URI.create(RESPONSE_URI))); Resource resource = dataResource("hashed_twitter.txt"); InputStream is = resource.getInputStream(); String contentType = URLConnection.guessContentTypeFromName(resource.getFilename()); byte[] data = bufferObj(is); ZonedDateTime expiry = ZonedDateTime.now().plusDays(7); URI uri = twitter.tonOperations().uploadSingleChunk(BUCKET_NAME, data, contentType, expiry); assertEquals(uri.toString(), RESPONSE_URI); }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
/** * Uploads file with public read access. Will try to determine content type. * * @param url upload url.//from w w w . j a va 2 s .c o m * @param file file for upload. */ public static void uploadPublicFile(final URL url, final File file) throws IOException { String contentType = URLConnection.guessContentTypeFromName(file.getName()); uploadPublicFile(url, contentType, file); }
From source file:org.jboss.tools.livereload.core.internal.server.jetty.WorkspaceFileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final HttpServletResponse httpServletResponse = (HttpServletResponse) response; final String requestURI = request.getRequestURI(); Logger.info("Serving " + requestURI); if (requestURI == null) { httpServletResponse.setStatus(400); } else {//from w ww . j a v a 2s . co m final IResource resource = ResourceUtils.retrieveResource(requestURI); if (resource != null && resource.getType() == IResource.FILE) { try { final byte[] scriptContent = IOUtils.toByteArray(((IFile) resource).getContents()); httpServletResponse.getOutputStream().write(scriptContent); httpServletResponse.setStatus(200); httpServletResponse.setContentType(URLConnection.guessContentTypeFromName(resource.getName())); // httpServletResponse.setContentType("text/javascript"); } catch (CoreException e) { Logger.error("Error occurred while returning content at location: " + requestURI, e); httpServletResponse.setStatus(500); } } else if (resource != null && resource.getType() == IResource.FOLDER) { Logger.debug("Forbidden location: {} is a folder", requestURI); httpServletResponse.setStatus(403); } else { Logger.debug("Unknown location: {} ", requestURI); httpServletResponse.setStatus(404); } } }
From source file:de.dominikschadow.javasecurity.controller.IndexController.java
@GetMapping("download") @ResponseBody/* w ww . j a v a2s . co m*/ public ResponseEntity<Resource> download(@RequestParam("name") String name) { try { String originalName = resourceService.getFileByIndirectReference(name).getName(); String contentType = URLConnection.guessContentTypeFromName(originalName); Resource resource = resourceService.loadAsResource(originalName); return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).body(resource); } catch (MalformedURLException | AccessControlException ex) { log.error(ex.getMessage(), ex); } return ResponseEntity.notFound().build(); }
From source file:com.necl.core.controller.DownloadFileController.java
@RequestMapping(value = "/download", method = RequestMethod.GET) public void downloadFile(HttpServletResponse response, @RequestParam String id) throws IOException, Exception { String pre_year = "20"; String post_year = id.substring(3, 5); String full_year = pre_year + post_year + "/"; String keyFind = "PATH"; ConfigSystem configSystem = configSystemService.findByKey(keyFind); String saveDirectory = configSystem.getConfigText() + full_year; File file = null;/*w w w . j a va2 s. c o m*/ String name = id.replace("/", "_"); String type = ".pdf"; String pathDirectory = saveDirectory + name + type; System.out.println("path:" + pathDirectory); file = new File(pathDirectory); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; 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"; } 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.orpheusdroid.screenrecorder.VideosListFragment.java
/** * Method to check if the file's meme type is video * * @param path String - path to the file * @return boolean// w w w . j a va2s . c om */ private static boolean isVideoFile(String path) { String mimeType = URLConnection.guessContentTypeFromName(path); return mimeType != null && mimeType.startsWith("video"); }
From source file:com.agiletec.plugins.jacms.apsadmin.resource.ResourceFinderAction.java
public String getMimetype(String filename) { return URLConnection.guessContentTypeFromName(filename); }
From source file:at.tomtasche.reader.background.UpLoader.java
@Override public Document loadInBackground() { if (uri == DocumentLoader.URI_INTRO) { cancelLoad();// w ww. j ava 2 s .co m return null; } String type = getContext().getContentResolver().getType(uri); if (type == null) type = URLConnection.guessContentTypeFromName(uri.toString()); if (type == null) { try { InputStream stream = getContext().getContentResolver().openInputStream(uri); try { type = URLConnection.guessContentTypeFromStream(stream); } finally { stream.close(); } } catch (Exception e) { e.printStackTrace(); } } if (type != null && (type.equals("text/html") || type.equals("text/plain") || type.equals("image/png") || type.equals("image/jpeg"))) { try { document = new Document(null); document.addPage(new Page("Document", new URI(uri.toString()), 0)); return document; } catch (URISyntaxException e) { e.printStackTrace(); } } String name = uri.getLastPathSegment(); try { name = URLEncoder.encode(name, "UTF-8"); type = URLEncoder.encode(type, "UTF-8"); } catch (Exception e) { } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(SERVER_URL + "file?name=" + name + "&type=" + type); InputStream stream = null; try { stream = getContext().getContentResolver().openInputStream(uri); InputStreamEntity reqEntity = new InputStreamEntity(stream, -1); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { Map<String, Object> container = new Gson().fromJson(EntityUtils.toString(response.getEntity()), Map.class); String key = container.get("key").toString(); URI viewerUri = URI.create("https://docs.google.com/viewer?embedded=true&url=" + URLEncoder.encode(SERVER_URL + "file?key=" + key, "UTF-8")); document = new Document(null); document.addPage(new Page("Document", viewerUri, 0)); } else { throw new RuntimeException("server couldn't handle request"); } } catch (Throwable e) { e.printStackTrace(); lastError = e; } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { } httpclient.getConnectionManager().shutdown(); } return document; }
From source file:com.example.dlp.Redact.java
private static void redactImage(String filePath, Likelihood minLikelihood, List<InfoType> infoTypes, String outputPath) throws Exception { // [START dlp_redact_image] // Instantiate the DLP client try (DlpServiceClient dlpClient = DlpServiceClient.create()) { // The path to a local file to inspect. Can be a JPG or PNG image file. // filePath = 'path/to/image.png' // detect file mime type, default to application/octet-stream String mimeType = URLConnection.guessContentTypeFromName(filePath); if (mimeType == null) { mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filePath); }/*from w ww. ja v a 2s . c o m*/ if (mimeType == null) { mimeType = "application/octet-stream"; } byte[] data = Files.readAllBytes(Paths.get(filePath)); // The minimum likelihood required before redacting a match // minLikelihood = 'LIKELIHOOD_UNSPECIFIED' // The infoTypes of information to redact // infoTypes = [{ name: 'EMAIL_ADDRESS' }, { name: 'PHONE_NUMBER' }] // The local path to save the resulting image to. // outputPath = 'result.png' InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes) .setMinLikelihood(minLikelihood).build(); ContentItem contentItem = ContentItem.newBuilder().setType(mimeType).setData(ByteString.copyFrom(data)) .build(); List<ImageRedactionConfig> imageRedactionConfigs = new ArrayList<>(); for (InfoType infoType : infoTypes) { // clear the specific info type if detected in the image // use .setRedactionColor to color detected info type without clearing ImageRedactionConfig imageRedactionConfig = ImageRedactionConfig.newBuilder().setInfoType(infoType) .clearTarget().build(); imageRedactionConfigs.add(imageRedactionConfig); } RedactContentRequest redactContentRequest = RedactContentRequest.newBuilder() .setInspectConfig(inspectConfig).addAllImageRedactionConfigs(imageRedactionConfigs) .addItems(contentItem).build(); RedactContentResponse contentResponse = dlpClient.redactContent(redactContentRequest); for (ContentItem responseItem : contentResponse.getItemsList()) { // redacted image data ByteString redactedImageData = responseItem.getData(); FileOutputStream outputStream = new FileOutputStream(outputPath); outputStream.write(redactedImageData.toByteArray()); outputStream.close(); } // [END dlp_redact_image] } }