List of usage examples for java.nio.file Files size
public static long size(Path path) throws IOException
From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java
private static void putBigFiles() throws IOException, URISyntaxException { final String DIR_NAME = "largeFiles/"; final String[] FILE_NAMES = new String[] { "lesmis.txt", "lesmis-copies.txt", "GreatExpectations.txt" }; final Path dirPath = ResourceUtils.loadFileResource(DIR_NAME); final List<String> bookTitles = new ArrayList<>(); final List<Ds3Object> objects = new ArrayList<>(); for (final String book : FILE_NAMES) { final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + book); final long bookSize = Files.size(objPath); final Ds3Object obj = new Ds3Object(book, bookSize); bookTitles.add(book);//from www . ja va 2 s .c o m objects.add(obj); } final int maxNumBlockAllocationRetries = 1; final int maxNumObjectTransferAttempts = 3; final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(client, maxNumBlockAllocationRetries, maxNumObjectTransferAttempts); final Ds3ClientHelpers.Job writeJob = ds3ClientHelpers.startWriteJob(BUCKET_NAME, objects); writeJob.transfer(new FileObjectPutter(dirPath)); }
From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java
private long size(Path p) { try {/*from www . j a v a 2 s .c om*/ return Files.size(p); } catch (Exception e) { return 0; } }
From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java
@Test public void testFileChangeThatDoesNotModifyAbiAvoidsRebuild() throws IOException { setUpProjectWorkspaceForScenario("rulekey_changed_while_abi_stable"); // Run `buck build`. BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); BuildTarget utilTarget = BuildTargetFactory.newInstance("//:util"); ProcessResult buildResult = workspace.runBuckCommand("build", bizTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); Path utilRuleKeyPath = BuildTargetPaths.getScratchPath(filesystem, utilTarget, ".%s/metadata/build/RULE_KEY"); String utilRuleKey = getContents(utilRuleKeyPath); Path utilAbiRuleKeyPath = BuildTargetPaths.getScratchPath(filesystem, utilTarget, ".%s/metadata/build/INPUT_BASED_RULE_KEY"); String utilAbiRuleKey = getContents(utilAbiRuleKeyPath); Path bizRuleKeyPath = BuildTargetPaths.getScratchPath(filesystem, bizTarget, ".%s/metadata/build/RULE_KEY"); String bizRuleKey = getContents(bizRuleKeyPath); Path bizAbiRuleKeyPath = BuildTargetPaths.getScratchPath(filesystem, bizTarget, ".%s/metadata/build/INPUT_BASED_RULE_KEY"); String bizAbiRuleKey = getContents(bizAbiRuleKeyPath); Path utilOutputPath = BuildTargetPaths.getGenPath(filesystem, utilTarget, "lib__%s__output/" + utilTarget.getShortName() + ".jar"); long utilJarSize = Files.size(workspace.getPath(utilOutputPath)); Path bizOutputPath = BuildTargetPaths.getGenPath(filesystem, bizTarget, "lib__%s__output/" + bizTarget.getShortName() + ".jar"); FileTime bizJarLastModified = Files.getLastModifiedTime(workspace.getPath(bizOutputPath)); // TODO(mbolin): Run uber-biz.jar and verify it prints "Hello World!\n". // Edit Util.java in a way that does not affect its ABI. workspace.replaceFileContents("Util.java", "Hello World", "Hola Mundo"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:biz"); buildResult2.assertSuccess("Successful build should exit with 0."); assertThat(utilRuleKey, not(equalTo(getContents(utilRuleKeyPath)))); assertThat(utilAbiRuleKey, not(equalTo(getContents(utilAbiRuleKeyPath)))); workspace.getBuildLog().assertTargetBuiltLocally(utilTarget); assertThat(bizRuleKey, not(equalTo(getContents(bizRuleKeyPath)))); assertEquals(bizAbiRuleKey, getContents(bizAbiRuleKeyPath)); workspace.getBuildLog().assertTargetHadMatchingInputRuleKey(bizTarget); assertThat("util.jar should have been rewritten, so its file size should have changed.", utilJarSize, not(equalTo(Files.size(workspace.getPath(utilOutputPath))))); assertEquals("biz.jar should not have been rewritten, so its last-modified time should be the same.", bizJarLastModified, Files.getLastModifiedTime(workspace.getPath(bizOutputPath))); // TODO(mbolin): Run uber-biz.jar and verify it prints "Hola Mundo!\n". // TODO(mbolin): This last scenario that is being tested would be better as a unit test. // Run `buck build` one last time. This ensures that a dependency java_library() rule (:util) // that is built via BuildRuleSuccess.Type.MATCHING_INPUT_BASED_RULE_KEY does not // explode when its dependent rule (:biz) invokes the dependency's getAbiKey() method as part of // its own getAbiKeyForDeps(). ProcessResult buildResult3 = workspace.runBuckCommand("build", "//:biz"); buildResult3.assertSuccess("Successful build should exit with 0."); }
From source file:com.spectralogic.ds3client.integration.PutJobManagement_Test.java
@Test public void truncateAllJobs() throws Exception { final int testTimeOutSeconds = 5; final String book1 = "beowulf.txt"; final Path objPath1 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book1); final String book2 = "ulysses.txt"; final Path objPath2 = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, Files.size(objPath1)); final Ds3Object obj2 = new Ds3Object("place_holder_1", 5000000); final Ds3Object obj3 = new Ds3Object(book2, Files.size(objPath2)); final Ds3Object obj4 = new Ds3Object("place_holder_2", 5000000); try {/* w ww .j a v a 2s . c om*/ final Ds3ClientHelpers.Job putJob1 = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj1, obj2)); final UUID jobId1 = putJob1.getJobId(); final SeekableByteChannel book1Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME) .buildChannel(book1); client.putObject(new PutObjectRequest(BUCKET_NAME, book1, book1Channel, jobId1.toString(), 0, Files.size(objPath1))); final Ds3ClientHelpers.Job putJob2 = HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(obj3, obj4)); final UUID jobId2 = putJob2.getJobId(); final SeekableByteChannel book2Channel = new ResourceObjectPutter(RESOURCE_BASE_NAME) .buildChannel(book2); client.putObject(new PutObjectRequest(BUCKET_NAME, book2, book2Channel, jobId2.toString(), 0, Files.size(objPath2))); HELPERS.startWriteJob(BUCKET_NAME, Lists.newArrayList(new Ds3Object("place_holder_3", 1000000))); ABMTestHelper.waitForJobCachedSizeToBeMoreThanZero(jobId1, client, 20); ABMTestHelper.waitForJobCachedSizeToBeMoreThanZero(jobId2, client, 20); final TruncateAllJobsSpectraS3Response truncateAllJobsSpectraS3Response = client .truncateAllJobsSpectraS3(new TruncateAllJobsSpectraS3Request()); assertThat(truncateAllJobsSpectraS3Response.getStatusCode(), is(204)); final GetJobSpectraS3Response truncatedJob1 = client .getJobSpectraS3(new GetJobSpectraS3Request(jobId1.toString())); assertEquals(truncatedJob1.getMasterObjectListResult().getOriginalSizeInBytes(), Files.size(objPath1)); final GetJobSpectraS3Response truncatedJob2 = client .getJobSpectraS3(new GetJobSpectraS3Request(jobId2.toString())); assertEquals(truncatedJob2.getMasterObjectListResult().getOriginalSizeInBytes(), Files.size(objPath2)); assertThat(client.getActiveJobsSpectraS3(new GetActiveJobsSpectraS3Request()).getActiveJobListResult() .getActiveJobs().size(), is(2)); } finally { deleteAllContents(client, BUCKET_NAME); } }
From source file:org.codice.ddf.catalog.content.plugin.video.VideoThumbnailPluginTest.java
private ContentItem createMockVideoContentItemFromResource(final String resource) throws Exception { final Path tmpPath = Paths.get(getClass().getResource(resource).toURI()); final ContentItem mockContentItem = createMockVideoContentItemWithSizeBytes(Files.size(tmpPath)); HashMap<String, Path> contentItemPaths = new HashMap<>(); contentItemPaths.put(null, tmpPath); tmpContentPaths.put(mockContentItem.getId(), contentItemPaths); return mockContentItem; }
From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java
@Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<BinaryStoreContent> systemBrowse(String name, String prefix) throws BinaryStoreServiceException { if (name == null || name.length() == 0) { List<BinaryStoreContent> vinfos = new ArrayList<BinaryStoreContent>(); List<String> vnames = new ArrayList<String>(); vnames.addAll(BinaryStoreVolumeMapper.listVolumes()); vnames.add(WORK);/* w w w . j ava2s . co m*/ for (String vname : vnames) { try { BinaryStoreContent volume = new BinaryStoreContent(); Path vpath = Paths.get(base.toString(), vname); FileStore vstore = Files.getFileStore(vpath); volume.setPath(vname); volume.setType(Type.VOLUME); volume.setFsName(vstore.name()); volume.setFsType(vstore.type()); volume.setFsTotalSize(vstore.getTotalSpace()); volume.setFsFreeSize(vstore.getUsableSpace()); volume.setSize(Files.size(vpath)); volume.setLastModificationDate(Files.getLastModifiedTime(vpath).toMillis()); vinfos.add(volume); } catch (IOException e) { LOGGER.log(Level.WARNING, "Unable to retrieve binary store volume information for volume: " + vname); } } return vinfos; } else { try { if (prefix == null) { prefix = ""; } Path vpath = Paths.get(base.toString(), name, prefix); if (!Files.exists(vpath)) { throw new BinaryStoreServiceException( "volume name does not point to an existing file or a directory"); } return Files.list(vpath).map(this::pathToContent).collect(Collectors.toList()); } catch (IOException e) { throw new BinaryStoreServiceException(e); } } }
From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java
private void removeExistingPathAndRecalculateSpaceAndChecksum(Path path, OwncloudLocalQuotaImpl quota) { try {//from ww w . ja v a 2 s . co m if (Files.isDirectory(path)) { log.debug("Remove Directory {} with all its Content and reduce the used Space of User {}", path.toAbsolutePath().normalize(), quota.getUsername()); Files.walkFileTree(path, new DeleteFileVisitor(quota::reduceUsed)); } else { log.debug("Remove File {} and reduce the used Space of User {}", path.toAbsolutePath().normalize(), quota.getUsername()); quota.reduceUsed(Files.size(path)); Files.delete(path); } } catch (IOException e) { val logMessage = String.format("Cannot remove Path %s", path.toAbsolutePath().normalize()); log.error(logMessage, e); throw new OwncloudLocalResourceException(logMessage, e); } finally { checksumService.recalculateChecksum(path); } }
From source file:org.fao.geonet.api.records.MetadataApi.java
@ApiOperation(value = "Get a metadata record as ZIP", notes = "Metadata Exchange Format (MEF) is returned. MEF is a ZIP file containing " + "the metadata as XML and some others files depending on the version requested. " + "See http://geonetwork-opensource.org/manuals/trunk/eng/users/annexes/mef-format.html.", nickname = "getRecordAsZip") @RequestMapping(value = "/{metadataUuid}/formatters/zip", method = RequestMethod.GET, consumes = { MediaType.ALL_VALUE }, produces = { "application/zip", MEF_V1_ACCEPT_TYPE, MEF_V2_ACCEPT_TYPE }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Return the record."), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW) }) public @ResponseBody void getRecordAsZip( @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid, @ApiParam(value = "MEF file format.", required = false) @RequestParam(required = false, defaultValue = "FULL") MEFLib.Format format, @ApiParam(value = "With related records (parent and service).", required = false) @RequestParam(required = false, defaultValue = "true") boolean withRelated, @ApiParam(value = "Resolve XLinks in the records.", required = false) @RequestParam(required = false, defaultValue = "true") boolean withXLinksResolved, @ApiParam(value = "Preserve XLink URLs in the records.", required = false) @RequestParam(required = false, defaultValue = "false") boolean withXLinkAttribute, @RequestParam(required = false, defaultValue = "true") boolean addSchemaLocation, @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = "application/x-gn-mef-2-zip") String acceptHeader, HttpServletResponse response, HttpServletRequest request) throws Exception { ApplicationContext appContext = ApplicationContextHolder.get(); GeonetworkDataDirectory dataDirectory = appContext.getBean(GeonetworkDataDirectory.class); AbstractMetadata metadata;//w ww .j av a 2 s. co m try { metadata = ApiUtils.canViewRecord(metadataUuid, request); } catch (SecurityException e) { Log.debug(API.LOG_MODULE_NAME, e.getMessage(), e); throw new NotAllowedException(ApiParams.API_RESPONSE_NOT_ALLOWED_CAN_VIEW); } Path stylePath = dataDirectory.getWebappDir().resolve(Geonet.Path.SCHEMAS); Path file = null; ServiceContext context = ApiUtils.createServiceContext(request); MEFLib.Version version = MEFLib.Version.find(acceptHeader); if (version == MEFLib.Version.V1) { // This parameter is deprecated in v2. boolean skipUUID = false; file = MEFLib.doExport(context, metadataUuid, format.toString(), skipUUID, withXLinksResolved, withXLinkAttribute, addSchemaLocation); } else { Set<String> tmpUuid = new HashSet<String>(); tmpUuid.add(metadataUuid); // MEF version 2 support multiple metadata record by file. if (withRelated) { // Adding children in MEF file // Creating request for services search Element childRequest = new Element("request"); childRequest.addContent(new Element("parentUuid").setText(metadataUuid)); childRequest.addContent(new Element("to").setText("1000")); // Get children to export - It could be better to use GetRelated service TODO Set<String> childs = MetadataUtils.getUuidsToExport(metadataUuid, request, childRequest); if (childs.size() != 0) { tmpUuid.addAll(childs); } // Creating request for services search Element servicesRequest = new Element(Jeeves.Elem.REQUEST); servicesRequest .addContent(new Element(org.fao.geonet.constants.Params.OPERATES_ON).setText(metadataUuid)); servicesRequest.addContent(new Element(org.fao.geonet.constants.Params.TYPE).setText("service")); // Get linked services for export Set<String> services = MetadataUtils.getUuidsToExport(metadataUuid, request, servicesRequest); if (services.size() != 0) { tmpUuid.addAll(services); } } Log.info(Geonet.MEF, "Building MEF2 file with " + tmpUuid.size() + " records."); file = MEFLib.doMEF2Export(context, tmpUuid, format.toString(), false, stylePath, withXLinksResolved, withXLinkAttribute, false, addSchemaLocation); } response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("inline; filename=\"%s.zip\"", metadata.getUuid())); response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(Files.size(file))); response.setContentType(acceptHeader); FileUtils.copyFile(file.toFile(), response.getOutputStream()); }
From source file:com.liferay.sync.engine.document.library.util.FileEventUtil.java
public static void updateFile(Path filePath, long syncAccountId, SyncFile syncFile, Path deltaFilePath, String name, String sourceChecksum, String sourceFileName, long sourceVersionId, String targetChecksum) throws IOException { Map<String, Object> parameters = new HashMap<>(); parameters.put("changeLog", getChangeLog()); parameters.put("checksum", targetChecksum); parameters.put("description", syncFile.getDescription()); parameters.put("fileEntryId", syncFile.getTypePK()); parameters.put("majorVersion", false); parameters.put("mimeType", syncFile.getMimeType()); parameters.put("sourceFileName", name); parameters.put("syncFile", syncFile); parameters.put("title", name); if (FileUtil.checksumsEqual(sourceChecksum, targetChecksum)) { parameters.put("-file", null); } else {//w ww . j a va2s . c o m if ((deltaFilePath != null) && (sourceVersionId != 0) && ((Files.size(filePath) / Files.size(deltaFilePath)) >= PropsValues.SYNC_FILE_PATCHING_THRESHOLD_SIZE_RATIO)) { parameters.put("deltaFilePath", deltaFilePath); parameters.put("sourceFileName", sourceFileName); parameters.put("sourceVersionId", sourceVersionId); PatchFileEntryEvent patchFileEntryEvent = new PatchFileEntryEvent(syncAccountId, parameters); patchFileEntryEvent.run(); return; } parameters.put("filePath", filePath); } UpdateFileEntryEvent updateFileEntryEvent = new UpdateFileEntryEvent(syncAccountId, parameters); updateFileEntryEvent.run(); }
From source file:org.roda.core.storage.AbstractStorageServiceTest.java
@Test(enabled = false) protected void testBinaryContent(Binary binary, ContentPayload providedPayload) throws IOException, GenericException { // check if content is the same assertTrue(IOUtils.contentEquals(providedPayload.createInputStream(), binary.getContent().createInputStream())); Path tempFile = Files.createTempFile("test", ".tmp"); Files.copy(binary.getContent().createInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING); // check size in bytes assertEquals(Long.valueOf(Files.size(tempFile)), binary.getSizeInBytes()); if (binary.getContentDigest() != null) { for (Entry<String, String> entry : binary.getContentDigest().entrySet()) { String digest = FSUtils.computeContentDigest(tempFile, entry.getKey()); assertEquals(digest, entry.getValue()); }//www . j a v a2 s.com } // delete temp file Files.delete(tempFile); }