List of usage examples for java.nio.file Files size
public static long size(Path path) throws IOException
From source file:dk.dma.msinm.common.repo.RepositoryService.java
/** * Streams the file specified by the path * @param path the path//from w w w.j a v a2 s .c om * @param request the servlet request * @return the response */ @GET @javax.ws.rs.Path("/file/{file:.+}") public Response streamFile(@PathParam("file") String path, @Context Request request) throws IOException { Path f = repoRoot.resolve(path); if (Files.notExists(f) || Files.isDirectory(f)) { log.warn("Failed streaming file: " + f); throw new WebApplicationException(404); } // Set expiry to cacheTimeout minutes Date expirationDate = new Date(System.currentTimeMillis() + 1000L * 60L * cacheTimeout); String mt = fileTypes.getContentType(f); // Check for an ETag match EntityTag etag = new EntityTag("" + Files.getLastModifiedTime(f).toMillis() + "_" + Files.size(f), true); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(etag); if (responseBuilder != null) { // Etag match log.trace("File unchanged. Return code 304"); return responseBuilder.expires(expirationDate).build(); } log.trace("Streaming file: " + f); return Response.ok(f.toFile(), mt).expires(expirationDate).tag(etag).build(); }
From source file:ddf.catalog.impl.operations.OperationsCrudSupport.java
void generateMetacardAndContentItems(StorageRequest storageRequest, List<ContentItem> incomingContentItems, Map<String, Metacard> metacardMap, List<ContentItem> contentItems, Map<String, Path> tmpContentPaths) throws IngestException { for (ContentItem contentItem : incomingContentItems) { try {//from ww w . j av a 2 s . c o m Path tmpPath = null; long size; try (InputStream inputStream = contentItem.getInputStream()) { if (inputStream == null) { throw new IngestException("Could not copy bytes of content message. Message was NULL."); } String sanitizedFilename = InputValidation.sanitizeFilename(contentItem.getFilename()); tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename), FilenameUtils.getExtension(sanitizedFilename)); Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING); size = Files.size(tmpPath); tmpContentPaths.put(contentItem.getId(), tmpPath); } catch (IOException e) { if (tmpPath != null) { FileUtils.deleteQuietly(tmpPath.toFile()); } throw new IngestException("Could not copy bytes of content message.", e); } String mimeTypeRaw = contentItem.getMimeTypeRawData(); mimeTypeRaw = guessMimeType(mimeTypeRaw, contentItem.getFilename(), tmpPath); if (!InputValidation.checkForClientSideVulnerableMimeType(mimeTypeRaw)) { throw new IngestException("Unsupported mime type."); } String fileName = updateFileExtension(mimeTypeRaw, contentItem.getFilename()); Metacard metacard = generateMetacard(mimeTypeRaw, contentItem.getId(), fileName, (Subject) storageRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT), tmpPath); metacardMap.put(metacard.getId(), metacard); ContentItem generatedContentItem = new ContentItemImpl(metacard.getId(), com.google.common.io.Files.asByteSource(tmpPath.toFile()), mimeTypeRaw, fileName, size, metacard); contentItems.add(generatedContentItem); } catch (Exception e) { tmpContentPaths.values().forEach(path -> FileUtils.deleteQuietly(path.toFile())); tmpContentPaths.clear(); throw new IngestException("Could not create metacard.", e); } } }
From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java
private static void putBeowulf() throws Exception { final String book1 = "beowulf.txt"; final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1); final Ds3Object obj = new Ds3Object(book1, Files.size(objPath1)); final Ds3ClientHelpers.Job job = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj)); final UUID jobId = job.getJobId(); final SeekableByteChannel book1Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME).buildChannel(book1); client.putObject(new PutObjectRequest(BUCKET_NAME, book1, book1Channel, jobId, 0, Files.size(objPath1))); ABMTestHelper.waitForJobCachedSizeToBeMoreThanZero(jobId, client, 20); }
From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java
@Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public String type(String identifier, String filename) throws BinaryStoreServiceException, DataNotFoundException { Path path = getPathForIdentifier(identifier); if (!Files.exists(path)) { throw new DataNotFoundException("Unable to find an object with id [" + identifier + "] in the storage"); }/*from w w w. j a v a2s . c om*/ try (InputStream is = Files.newInputStream(path)) { Tika tika = new Tika(); String type; if (Files.size(path) < 50000000) { LOGGER.log(Level.FINEST, "file size is not too large, trying to detect also containers"); try (TikaInputStream tis = TikaInputStream.get(is)) { type = tika.detect(tis, filename); } } else { LOGGER.log(Level.FINEST, "file size is TOO large, does not detect types inside containers"); type = tika.detect(is, filename); } return type; } catch (Exception e) { throw new BinaryStoreServiceException(e); } }
From source file:org.fim.internal.hash.FileHasherTest.java
private void checkFileHash(long fileSize, Range[] smallRanges, Range[] mediumRanges) throws IOException { Path fileToHash = createFileWithSize((int) fileSize); // Compute the expectedHash using a very simple algorithm and Guava Sha512 impl FileHash expectedHash = computeExpectedHash(fileToHash, smallRanges, mediumRanges); FileHash fileHash = cut.hashFile(fileToHash, Files.size(fileToHash)); assertRangesEqualsTo(smallRanges, mediumRanges); // displayFileHash(fileSize, fileHash); assertFileHashEqualsTo(fileSize, expectedHash, fileHash); }
From source file:org.apache.karaf.tooling.ArchiveMojo.java
private void addFileToTarGz(TarArchiveOutputStream tOut, Path f, String base) throws IOException { if (Files.isDirectory(f)) { String entryName = base + f.getFileName().toString() + "/"; TarArchiveEntry tarEntry = new TarArchiveEntry(entryName); tOut.putArchiveEntry(tarEntry);//from w w w . j a v a2 s . c o m tOut.closeArchiveEntry(); try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) { for (Path child : children) { addFileToTarGz(tOut, child, entryName); } } } else if (useSymLinks && Files.isSymbolicLink(f)) { String entryName = base + f.getFileName().toString(); TarArchiveEntry tarEntry = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK); tarEntry.setLinkName(Files.readSymbolicLink(f).toString()); tOut.putArchiveEntry(tarEntry); tOut.closeArchiveEntry(); } else { String entryName = base + f.getFileName().toString(); TarArchiveEntry tarEntry = new TarArchiveEntry(entryName); tarEntry.setSize(Files.size(f)); if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin/"))) { if (entryName.endsWith(".bat")) { tarEntry.setMode(0644); } else { tarEntry.setMode(0755); } } tOut.putArchiveEntry(tarEntry); Files.copy(f, tOut); tOut.closeArchiveEntry(); } }
From source file:io.undertow.server.handlers.SenderTestCase.java
@Test public void testSyncTransfer() throws Exception { StringBuilder sb = new StringBuilder(TXS); for (int i = 0; i < TXS; ++i) { sb.append("a"); }//from w ww . j a v a2s. c o m HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/transfer?blocking=true"); TestHttpClient client = new TestHttpClient(); try { HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Path file = Paths .get(SenderTestCase.class.getResource(SenderTestCase.class.getSimpleName() + ".class").toURI()); long length = Files.size(file); byte[] data = new byte[(int) length * TXS]; for (int i = 0; i < TXS; i++) { try (DataInputStream is = new DataInputStream(Files.newInputStream(file))) { is.readFully(data, (int) (i * length), (int) length); } } Assert.assertArrayEquals(data, HttpClientUtils.readRawResponse(result)); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.niord.web.aton.AtonTileRestService.java
/** * Computes an E-Tag for the file/*from ww w .j a v a 2s.co m*/ * @param file the file * @return the E-Tag for the file */ private EntityTag entityTagForFile(Path file) throws IOException { return new EntityTag("" + Files.getLastModifiedTime(file).toMillis() + "_" + Files.size(file), true); }
From source file:org.exist.storage.journal.JournalBinaryTest.java
@Override protected void readAndVerify(final DBBroker broker, final DocumentImpl doc, final Path file, final String dbFilename) throws IOException { final BinaryDocument binDoc = (BinaryDocument) doc; // verify the size, to ensure it is the correct content final long expectedSize = Files.size(file); assertEquals(expectedSize, binDoc.getContentLength()); // check the actual content too! final byte[] bdata = new byte[(int) binDoc.getContentLength()]; try (final CountingInputStream cis = new CountingInputStream(broker.getBinaryResource(binDoc))) { final int read = cis.read(bdata); assertEquals(bdata.length, read); final String data = new String(bdata); assertNotNull(data);/*from ww w . j av a 2 s . c om*/ assertEquals(expectedSize, cis.getByteCount()); } }
From source file:org.niord.core.repo.RepositoryService.java
/** * Streams the file specified by the path * @param path the path//from w w w . ja va 2s .c o m * @param request the servlet request * @return the response */ @GET @javax.ws.rs.Path("/file/{file:.+}") public Response streamFile(@PathParam("file") String path, @Context Request request) throws IOException { Path f = repoRoot.resolve(path); if (Files.notExists(f) || Files.isDirectory(f)) { log.warn("Failed streaming file: " + f); return Response.status(HttpServletResponse.SC_NOT_FOUND).entity("File not found: " + path).build(); } // Set expiry to cacheTimeout minutes Date expirationDate = new Date(System.currentTimeMillis() + 1000L * 60L * cacheTimeout); String mt = fileTypes.getContentType(f); // Check for an ETag match EntityTag etag = new EntityTag("" + Files.getLastModifiedTime(f).toMillis() + "_" + Files.size(f), true); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(etag); if (responseBuilder != null) { // Etag match log.trace("File unchanged. Return code 304"); return responseBuilder.expires(expirationDate).build(); } log.trace("Streaming file: " + f); return Response.ok(f.toFile(), mt).expires(expirationDate).tag(etag).build(); }