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
@Test public void testReadRetrybugWhenChannelThrowsAccessException() throws IOException, URISyntaxException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { final String tempPathPrefix = null; final Path tempDirectoryPath = Files.createTempDirectory(Paths.get("."), tempPathPrefix); final AtomicBoolean caughtException = new AtomicBoolean(false); try {// w w w . jav a2s . c o m final String DIR_NAME = "largeFiles/"; final String FILE_NAME = "lesmis-copies.txt"; final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME); final long bookSize = Files.size(objPath); final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize); final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client); final int maxNumBlockAllocationRetries = 1; final int maxNumObjectTransferAttempts = 3; final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim, maxNumBlockAllocationRetries, maxNumObjectTransferAttempts); final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj)); final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId())); assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue())); readJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { throw new AccessControlException(key); } }); } catch (final IOException e) { caughtException.set(true); assertTrue(e.getCause() instanceof AccessControlException); } finally { FileUtils.deleteDirectory(tempDirectoryPath.toFile()); } assertTrue(caughtException.get()); }
From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java
/** * Upload thesaurus.//from w w w . j ava2 s. com * * @param file the file * @param type the type * @param dir the dir * @param stylesheet the stylesheet * @param request the request * @return the element * @throws Exception the exception */ @ApiOperation(value = "Uploads a new thesaurus from a file", nickname = "uploadThesaurus", notes = "Uploads a new thesaurus.") @RequestMapping(method = RequestMethod.POST, produces = MediaType.TEXT_XML_VALUE) @ApiResponses(value = { @ApiResponse(code = 201, message = "Thesaurus uploaded in SKOS format."), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_REVIEWER) }) @PreAuthorize("hasRole('Reviewer')") @ResponseBody @ResponseStatus(value = HttpStatus.CREATED) public String uploadThesaurus( @ApiParam(value = "If set, do a file upload.") @RequestParam(value = "file", required = false) MultipartFile file, @ApiParam(value = "Local or external (default).") @RequestParam(value = "type", defaultValue = "external") String type, @ApiParam(value = "Type of thesaurus, usually one of the ISO thesaurus type codelist value. Default is theme.") @RequestParam(value = "dir", defaultValue = "theme") String dir, @ApiParam(value = "XSL to be use to convert the thesaurus before load. Default _none_.") @RequestParam(value = "stylesheet", defaultValue = "_none_") String stylesheet, HttpServletRequest request) throws Exception { long start = System.currentTimeMillis(); ServiceContext context = ApiUtils.createServiceContext(request); // Different options for upload boolean fileUpload = file != null && !file.isEmpty(); // Upload RDF file Path rdfFile = null; String fname = null; File tempDir = null; if (fileUpload) { Log.debug(Geonet.THESAURUS, "Uploading thesaurus file: " + file.getOriginalFilename()); tempDir = Files.createTempDirectory("thesaurus").toFile(); Path tempFilePath = tempDir.toPath().resolve(file.getOriginalFilename()); File convFile = tempFilePath.toFile(); file.transferTo(convFile); rdfFile = convFile.toPath(); fname = file.getOriginalFilename(); } else { Log.debug(Geonet.THESAURUS, "No file provided for thesaurus upload."); throw new MissingServletRequestParameterException("Thesaurus source not provided", "file"); } try { if (StringUtils.isEmpty(fname)) { throw new Exception("File upload from URL or file return null"); } long fsize; if (rdfFile != null && Files.exists(rdfFile)) { fsize = Files.size(rdfFile); } else { throw new MissingServletRequestParameterException("Thesaurus file doesn't exist", "file"); } // -- check that the archive actually has something in it if (fsize == 0) { throw new MissingServletRequestParameterException("Thesaurus file has zero size", "file"); } String extension = FilenameUtils.getExtension(fname); if (extension.equalsIgnoreCase("rdf") || extension.equalsIgnoreCase("xml")) { Log.debug(Geonet.THESAURUS, "Uploading thesaurus: " + fname); // Rename .xml to .rdf for all thesaurus fname = fname.replace(extension, "rdf"); uploadThesaurus(rdfFile, stylesheet, context, fname, type, dir); } else { Log.debug(Geonet.THESAURUS, "Incorrect extension for thesaurus named: " + fname); throw new Exception("Incorrect extension for thesaurus named: " + fname); } long end = System.currentTimeMillis(); long duration = (end - start) / 1000; return String.format("Thesaurus '%s' loaded in %d sec.", fname, duration); } finally { if (tempDir != null) { FileUtils.deleteQuietly(tempDir); } } }
From source file:com.sastix.cms.server.services.content.impl.hazelcast.HazelcastResourceServiceImpl.java
@Override @Transactional(readOnly = true)/*from w w w .j av a2s . co m*/ public ResponseEntity<InputStreamResource> getResponseInputStream(String uuid) throws ResourceAccessError, IOException { // Find Resource final Resource resource = resourceRepository.findOneByUid(uuid); if (resource == null) { return null; } InputStream inputStream; int size; //check cache first QueryCacheDTO queryCacheDTO = new QueryCacheDTO(resource.getUri()); CacheDTO cacheDTO = null; try { cacheDTO = cacheService.getCachedResource(queryCacheDTO); } catch (DataNotFound e) { LOG.warn("Resource '{}' is not cached.", resource.getUri()); } catch (Exception e) { LOG.error("Exception: {}", e.getLocalizedMessage()); } if (cacheDTO != null && cacheDTO.getCacheBlobBinary() != null) { LOG.info("Getting resource {} from cache", resource.getUri()); inputStream = new ByteArrayInputStream(cacheDTO.getCacheBlobBinary()); size = cacheDTO.getCacheBlobBinary().length; } else { try { final Path responseFile = hashedDirectoryService.getDataByURI(resource.getUri(), resource.getResourceTenantId()); inputStream = Files.newInputStream(responseFile); size = (int) Files.size(responseFile); // Adding resource to cache distributedCacheService.cacheIt(resource.getUri(), resource.getResourceTenantId()); } catch (IOException ex) { LOG.info("Error writing file to output stream. Filename was '{}'", resource.getUri(), ex); throw new RuntimeException("IOError writing file to output stream"); } catch (URISyntaxException e) { e.printStackTrace(); throw new RuntimeException("IOError writing file to output stream"); } } return ResponseEntity.ok().contentLength(size) .contentType(MediaType.parseMediaType(resource.getMediaType())) .body(new InputStreamResource(inputStream)); }
From source file:org.apache.tika.eval.AbstractProfiler.java
protected EvalFilePaths getPathsFromSrcCrawl(Metadata metadata, Path srcDir, Path extracts) { Path relativeSourceFilePath = Paths.get(metadata.get(FSProperties.FS_REL_PATH)); Path extractFile = findFile(extracts, relativeSourceFilePath); Path inputFile = srcDir.resolve(relativeSourceFilePath); long srcLen = -1l; //try to get the length of the source file in case there was an error //in both extracts try {/*ww w .j a v a 2s .c o m*/ srcLen = Files.size(inputFile); } catch (IOException e) { LOG.warn("Couldn't get length for: {}", inputFile.toAbsolutePath()); } return new EvalFilePaths(relativeSourceFilePath, extractFile, srcLen); }
From source file:de.qucosa.webapi.v1.DocumentResource.java
private void handleFileElement(String pid, int itemIndex, Element fileElement) throws URISyntaxException, IOException, FedoraClientException, XPathExpressionException { Node tempFile = fileElement.getElementsByTagName("TempFile").item(0); Node pathName = fileElement.getElementsByTagName("PathName").item(0); if (tempFile == null || pathName == null) { return;/*ww w . ja v a 2s . c o m*/ } String id = pid.substring("qucosa:".length()); String tmpFileName = tempFile.getTextContent(); String targetFilename = pathName.getTextContent(); URI fileUri = fileHandlingService.copyTempfileToTargetFileSpace(tmpFileName, targetFilename, id); Node labelNode = fileElement.getElementsByTagName("Label").item(0); String label = (labelNode != null) ? labelNode.getTextContent() : ""; final Path filePath = new File(fileUri).toPath(); String detectedContentType = Files.probeContentType(filePath); if (!(Boolean) xPath.evaluate("MimeType[text()!='']", fileElement, XPathConstants.BOOLEAN)) { if (detectedContentType != null) { Element mimeTypeElement = fileElement.getOwnerDocument().createElement("MimeType"); mimeTypeElement.setTextContent(detectedContentType); fileElement.appendChild(mimeTypeElement); } } if (!(Boolean) xPath.evaluate("FileSize[text()!='']", fileElement, XPathConstants.BOOLEAN)) { Element fileSizeElement = fileElement.getOwnerDocument().createElement("FileSize"); fileSizeElement.setTextContent(String.valueOf(Files.size(filePath))); fileElement.appendChild(fileSizeElement); } String dsid = DSID_QUCOSA_ATT + (itemIndex); String state = determineDatastreamState(fileElement); DatastreamProfile dsp = fedoraRepository.createExternalReferenceDatastream(pid, dsid, label, fileUri, detectedContentType, state); fileElement.setAttribute("id", String.valueOf(itemIndex)); addHashValue(fileElement, dsp); fileElement.removeChild(tempFile); }
From source file:org.apache.nifi.controller.repository.FileSystemRepository.java
private void removeIncompleteContent(final Path fileToRemove) { String fileDescription = null; try {/*from ww w . ja va 2 s . co m*/ fileDescription = fileToRemove.toFile().getAbsolutePath() + " (" + Files.size(fileToRemove) + " bytes)"; } catch (final IOException e) { fileDescription = fileToRemove.toFile().getAbsolutePath() + " (unknown file size)"; } LOG.info("Found unknown file {} in File System Repository; {} file", fileDescription, archiveData ? "archiving" : "removing"); try { if (archiveData) { archive(fileToRemove); } else { Files.delete(fileToRemove); } } catch (final IOException e) { final String action = archiveData ? "archive" : "remove"; LOG.warn("Unable to {} unknown file {} from File System Repository due to {}", action, fileDescription, e.toString()); LOG.warn("", e); } }
From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java
/** * {@inheritDoc}//from w w w. ja va2 s. c om */ @Override public long getSize(RepositoryFileReference ref) throws IOException { return Files.size(this.ref2AbsolutePath(ref)); }
From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java
@Test public void testReadRetryBugWhenDiskIsFull() throws IOException, URISyntaxException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { final String tempPathPrefix = null; final Path tempDirectoryPath = Files.createTempDirectory(Paths.get("."), tempPathPrefix); try {//from w ww. j a v a2 s. c o m final String DIR_NAME = "largeFiles/"; final String FILE_NAME = "lesmis-copies.txt"; final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME); final long bookSize = Files.size(objPath); final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize); final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client); final int maxNumBlockAllocationRetries = 1; final int maxNumObjectTransferAttempts = 3; final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim, maxNumBlockAllocationRetries, maxNumObjectTransferAttempts); final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj)); final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId())); assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue())); try { readJob.transfer(new FailingChannelBuilder()); } catch (final UnrecoverableIOException e) { assertEquals(DISK_FULL_MESSAGE, e.getCause().getMessage()); } } finally { FileUtils.deleteDirectory(tempDirectoryPath.toFile()); } }
From source file:org.roda.core.storage.fs.FSUtils.java
/** * Converts a path into a resource//from w w w. j a v a 2 s . c o m * * @param basePath * base path * @param path * relative path to base path * @throws RequestNotValidException * @throws NotFoundException * @throws GenericException */ public static Resource convertPathToResource(Path basePath, Path path) throws RequestNotValidException, NotFoundException, GenericException { Resource resource; // TODO support binary reference if (!FSUtils.exists(path)) { throw new NotFoundException("Cannot find file or directory at " + path); } // storage path StoragePath storagePath = FSUtils.getStoragePath(basePath, path); // construct if (FSUtils.isDirectory(path)) { resource = new DefaultDirectory(storagePath); } else { ContentPayload content = new FSPathContentPayload(path); long sizeInBytes; try { sizeInBytes = Files.size(path); Map<String, String> contentDigest = null; resource = new DefaultBinary(storagePath, content, sizeInBytes, false, contentDigest); } catch (IOException e) { throw new GenericException("Could not get file size", e); } } return resource; }
From source file:org.apache.tika.eval.AbstractProfiler.java
protected long getFileLength(Path p) { if (p != null && Files.isRegularFile(p)) { try {/* www.j av a2 s. co m*/ return Files.size(p); } catch (IOException e) { //swallow } } return NON_EXISTENT_FILE_LENGTH; }