List of usage examples for java.nio.file Files probeContentType
public static String probeContentType(Path path) throws IOException
From source file:SecurityWatch.java
public void watchVideoCamera(Path path) throws IOException, InterruptedException { watchService = FileSystems.getDefault().newWatchService(); register(path, StandardWatchEventKinds.ENTRY_CREATE); OUTERMOST: while (true) { final WatchKey key = watchService.poll(); if (key == null) { System.out.println("The video camera is jammed - security watch system is canceled!"); break; } else {/* w ww . j a va2 s .co m*/ for (WatchEvent<?> watchEvent : key.pollEvents()) { final Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); final Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { //print it out the video capture time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); System.out.println("Video capture successfully at: " + dateFormat.format(new Date())); } else { System.out.println("The video camera capture format failed! This could be a virus!"); break OUTERMOST; } } } boolean valid = key.reset(); if (!valid) { break; } } } watchService.close(); }
From source file:SecurityWatch.java
public void watchVideoCamera(Path path) throws IOException, InterruptedException { watchService = FileSystems.getDefault().newWatchService(); register(path, StandardWatchEventKinds.ENTRY_CREATE); OUTERMOST: while (true) { final WatchKey key = watchService.poll(11, TimeUnit.SECONDS); if (key == null) { System.out.println("The video camera is jammed - security watch system is canceled!"); break; } else {//from w w w .j a v a2 s . c o m for (WatchEvent<?> watchEvent : key.pollEvents()) { final Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); final Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { //print it out the video capture time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); System.out.println("Video capture successfully at: " + dateFormat.format(new Date())); } else { System.out.println("The video camera capture format failed! This could be a virus!"); break OUTERMOST; } } } boolean valid = key.reset(); if (!valid) { break; } } } watchService.close(); }
From source file:io.redlink.solrlib.SolrCoreDescriptor.java
static void unpackSolrCoreZip(Path solrCoreBundle, Path solrHome, ClassLoader classLoader) throws IOException { final String contentType = Files.probeContentType(solrCoreBundle); if ("application/zip".equals(contentType) || //fallback if Files.probeContentType(..) fails (such as on Max OS X) (contentType == null/*from w w w . j a v a 2 s.co m*/ && StringUtils.endsWithAny(solrCoreBundle.getFileName().toString(), ".zip", ".jar"))) { LoggerFactory.getLogger(SolrCoreDescriptor.class).debug("Unpacking SolrCore zip {} to {}", solrCoreBundle, solrHome); try (FileSystem fs = FileSystems.newFileSystem(solrCoreBundle, classLoader)) { unpackSolrCoreDir(fs.getPath("/"), solrHome); } } else { throw new IllegalArgumentException( "Packaged solrCoreBundle '" + solrCoreBundle + "' has unsupported type: " + contentType); } }
From source file:foam.nanos.blob.HttpBlobService.java
protected void download(X x) { OutputStream os = null;//from www .j av a 2 s.com HttpServletRequest req = x.get(HttpServletRequest.class); HttpServletResponse resp = x.get(HttpServletResponse.class); try { String path = req.getRequestURI(); String id = path.replaceFirst("/service/" + nspec_.getName() + "/", ""); Blob blob = getDelegate().find(id); if (blob == null) { resp.setStatus(resp.SC_NOT_FOUND); return; } long size = blob.getSize(); resp.setStatus(resp.SC_OK); if (blob instanceof FileBlob) { File file = ((FileBlob) blob).getFile(); resp.setContentType(Files.probeContentType(Paths.get(file.toURI()))); } else { resp.setContentType("application/octet-stream"); } resp.setHeader("Content-Length", Long.toString(size, 10)); resp.setHeader("ETag", id); resp.setHeader("Cache-Control", "public"); os = resp.getOutputStream(); blob.read(os, 0, size); os.close(); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { IOUtils.closeQuietly(os); } }
From source file:org.mitre.mpf.mvc.util.NIOUtils.java
public static String getPathContentType(Path path) { String contentType = null;//from w w w .j av a 2s . c o m if (path != null && Files.isRegularFile(path)) { try { contentType = Files.probeContentType(path); } catch (IOException e) { log.error("Error determining the content type of file '{}'", path.toAbsolutePath().toString()); } } return contentType; }
From source file:org.ado.musicdroid.service.MediaConverterService.java
private boolean isAudio(File file) { try {/*from w w w . j a va2 s . c om*/ return Files.probeContentType(file.toPath()).startsWith("audio"); } catch (IOException e) { return false; } }
From source file:com.tango.BucketSyncer.S32GCSTestFile.java
public static S32GCSTestFile create(String key, Storage client, List<StorageAsset> stuffToCleanup, Copy copy, Clean clean) throws Exception { S32GCSTestFile s32GCSTestFile = new S32GCSTestFile(); Storage.Objects.Insert insertObject = null; StorageObject objectMetadata = null; InputStream inputStream = new FileInputStream(s32GCSTestFile.file); Path source = Paths.get(s32GCSTestFile.file.getPath()); String type = Files.probeContentType(source); InputStreamContent mediaContent = new InputStreamContent(type, inputStream); switch (clean) { case SOURCE:// w w w . j ava 2 s . c o m stuffToCleanup.add(new StorageAsset(S32GCSMirrorTest.SOURCE, key)); break; case DEST: stuffToCleanup.add(new StorageAsset(S32GCSMirrorTest.DESTINATION, key)); break; case SOURCE_AND_DEST: stuffToCleanup.add(new StorageAsset(S32GCSMirrorTest.SOURCE, key)); stuffToCleanup.add(new StorageAsset(S32GCSMirrorTest.DESTINATION, key)); break; } switch (copy) { case SOURCE: insertObject = client.objects().insert(S32GCSMirrorTest.SOURCE, objectMetadata, mediaContent); insertObject.setName(key); insertObject.execute(); break; case DEST: insertObject = client.objects().insert(S32GCSMirrorTest.DESTINATION, objectMetadata, mediaContent); insertObject.setName(key); insertObject.execute(); break; case SOURCE_AND_DEST: insertObject = client.objects().insert(S32GCSMirrorTest.SOURCE, objectMetadata, mediaContent); insertObject.setName(key); insertObject.execute(); insertObject = client.objects().insert(S32GCSMirrorTest.DESTINATION, objectMetadata, mediaContent); insertObject.setName(key); insertObject.execute(); break; } return s32GCSTestFile; }
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 ww w . ja v a 2 s . co m * @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:com.qatickets.service.TicketFileAttachmentService.java
@Transactional(readOnly = false) public void save(File incomingFile, int ticketId, UserProfile user) { log.debug("Save attachment: " + incomingFile); Ticket ticket = ticketService.findById(ticketId); if (ticket != null) { // save attachment TicketFileAttachment a = new TicketFileAttachment(); a.setDate(new Date()); a.setFileName(spamService.clean(incomingFile.getName(), 200)); a.setImage(false);/* ww w.j av a2s. c om*/ a.setTicket(ticket); a.setUser(user); try { a.setContentType(Files.probeContentType(new File(incomingFile.getName()).toPath())); } catch (IOException e1) { a.setContentType(new MimetypesFileTypeMap().getContentType(incomingFile.getName())); } a.setSize(incomingFile.length()); log.debug("Saved attachment: " + a); this.dao.save(a); // attach to body ticket.addAttachment(a); this.ticketService.save(ticket); // upload to aws /* File file = new File(SystemUtils.getJavaIoTmpDir(), UUID.randomUUID().toString()); try { multpartFile.transferTo(file); s3client.save(a, user, file); } catch (Exception e) { log.error("Error: ", e); } finally { FileUtils.deleteQuietly(file); } */ } }
From source file:ca.viaware.dlna.streamserver.StreamServer.java
private void streamMedia(HttpExchange exchange) throws IOException { final int entryId = Integer.parseInt(StringUtils.cleanNumber(exchange.getRequestURI().getPath())); Log.info("STREAM-SERVER: Got request for library item %0", entryId); HttpUtils.emptyStream(exchange.getRequestBody()); LibraryEntry entry = (LibraryEntry) Library.runInstance(new LibraryInstanceRunner() { @Override// www . j a v a 2 s.c o m public Object run(LibraryFactory factory) { return factory.get(entryId); } }); if (entry != null) { File file = entry.getLocation(); String mime = Files.probeContentType(file.toPath().toAbsolutePath()); Log.info("STREAM-SERVER: Entry is %0 %1", file.getAbsolutePath(), mime); Headers headers = exchange.getResponseHeaders(); headers.set("CONTENT-TYPE", mime); headers.set("USER-AGENT", Globals.SERVER); headers.set("CONTENT-LANGUAGE", "en"); if (exchange.getRequestMethod().equals("GET")) { Log.info("Starting stream upload."); exchange.sendResponseHeaders(200, 0); InputStream fileIn = new FileInputStream(file); OutputStream output = exchange.getResponseBody(); byte[] buffer = new byte[1024]; int read; while ((read = fileIn.read(buffer)) != -1) { output.write(buffer, 0, read); } output.close(); } else { exchange.sendResponseHeaders(200, -1); exchange.getResponseBody().close(); Log.info("Not streaming to HEAD request."); } Log.info("STREAM-SERVER: Finished stream transaction."); } else { String html = ""; html += "<!DOCTYPE html><html>"; html += "<head><title>ViaWare UPnP - Stream Server</title></head>"; html += "<body>"; html += "<h1>ViaWare UPnP Server v" + ViaWareDLNA.VERSION + " - Stream Server</h1><hr>"; html += "Unable to find the specified stream<br>"; html += "Copyright 2015 Seth Traverse"; html += "</body></html>"; byte[] bytes = html.getBytes("UTF-8"); Headers headers = exchange.getResponseHeaders(); headers.set("CONTENT-TYPE", "text/html"); headers.set("CONTENT-LANGUAGE", "en"); exchange.sendResponseHeaders(404, bytes.length); exchange.getResponseBody().write(bytes); exchange.getResponseBody().close(); } }