List of usage examples for java.nio.channels FileChannel open
public static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException
From source file:org.linagora.linshare.webservice.userv2.impl.FlowDocumentUploaderRestServiceImpl.java
@Path("/") @POST/* w w w . j av a 2 s.c o m*/ @Consumes("multipart/form-data") @Override public FlowDto uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber, @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize, @Multipart(CURRENT_CHUNK_SIZE) long currentChunkSize, @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier, @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath, @Multipart(FILE) InputStream file, MultipartBody body, @Multipart(value = WORK_GROUP_UUID, required = false) String workGroupUuid, @Multipart(value = WORK_GROUP_FOLDER_UUID, required = false) String workGroupFolderUuid, @Multipart(value = ASYNC_TASK, required = false) boolean async) throws BusinessException { logger.debug("upload chunk number : " + chunkNumber); identifier = cleanIdentifier(identifier); boolean isValid = FlowUploaderUtils.isValid(chunkNumber, chunkSize, totalSize, identifier, filename); Validate.isTrue(isValid); checkIfMaintenanceIsEnabled(); FlowDto flow = new FlowDto(chunkNumber); try { logger.debug("writing chunk number : " + chunkNumber); java.nio.file.Path tempFile = FlowUploaderUtils.getTempFile(identifier, chunkedFiles); ChunkedFile currentChunkedFile = chunkedFiles.get(identifier); if (!currentChunkedFile.hasChunk(chunkNumber)) { FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(file, output); fc.write(ByteBuffer.wrap(output.toByteArray()), (chunkNumber - 1) * chunkSize); fc.close(); if (sizeValidation) { if (output.size() != currentChunkSize) { String msg = String.format("File size does not match, found : %1$d, announced : %2$d", output.size(), currentChunkSize); logger.error(msg); flow.setChunkUploadSuccess(false); flow.setErrorMessage(msg); return flow; } } currentChunkedFile.addChunk(chunkNumber); } else { logger.error("currentChunkedFile.hasChunk(chunkNumber) !!! " + currentChunkedFile); logger.error("chunkedNumber skipped : " + chunkNumber); } logger.debug("nb uploading files : " + chunkedFiles.size()); logger.debug("current chuckedfile uuid : " + identifier); logger.debug("current chuckedfiles" + chunkedFiles.toString()); if (FlowUploaderUtils.isUploadFinished(identifier, chunkSize, totalSize, chunkedFiles)) { flow.setLastChunk(true); logger.debug("upload finished : " + chunkNumber + " : " + identifier); InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ); File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename); if (sizeValidation) { long currSize = tempFile2.length(); if (currSize != totalSize) { String msg = String.format("File size does not match, found : %1$d, announced : %2$d", currSize, totalSize); logger.error(msg); flow.setChunkUploadSuccess(false); flow.setErrorMessage(msg); return flow; } } EntryDto uploadedDocument = new EntryDto(); flow.setIsAsync(async); boolean isWorkGroup = !Strings.isNullOrEmpty(workGroupUuid); if (async) { logger.debug("Async mode is used"); // Asynchronous mode AccountDto actorDto = documentFacade.getAuthenticatedAccountDto(); AsyncTaskDto asyncTask = null; try { if (isWorkGroup) { ThreadEntryTaskContext threadEntryTaskContext = new ThreadEntryTaskContext(actorDto, actorDto.getUuid(), workGroupUuid, tempFile2, filename, workGroupFolderUuid); asyncTask = asyncTaskFacade.create(totalSize, getTransfertDuration(identifier), filename, null, AsyncTaskType.THREAD_ENTRY_UPLOAD); ThreadEntryUploadAsyncTask task = new ThreadEntryUploadAsyncTask(threadEntryAsyncFacade, threadEntryTaskContext, asyncTask); taskExecutor.execute(task); flow.completeAsyncTransfert(asyncTask); } else { DocumentTaskContext documentTaskContext = new DocumentTaskContext(actorDto, actorDto.getUuid(), tempFile2, filename, null, null); asyncTask = asyncTaskFacade.create(totalSize, getTransfertDuration(identifier), filename, null, AsyncTaskType.DOCUMENT_UPLOAD); DocumentUploadAsyncTask task = new DocumentUploadAsyncTask(documentAsyncFacade, documentTaskContext, asyncTask); taskExecutor.execute(task); flow.completeAsyncTransfert(asyncTask); } } catch (Exception e) { logAsyncFailure(asyncTask, e); deleteTempFile(tempFile2); ChunkedFile remove = chunkedFiles.remove(identifier); Files.deleteIfExists(remove.getPath()); throw e; } } else { try { if (isWorkGroup) { uploadedDocument = threadEntryFacade.create(null, workGroupUuid, workGroupFolderUuid, tempFile2, filename); } else { uploadedDocument = documentFacade.create(tempFile2, filename, "", null); } flow.completeTransfert(uploadedDocument); } finally { deleteTempFile(tempFile2); ChunkedFile remove = chunkedFiles.remove(identifier); if (remove != null) { Files.deleteIfExists(remove.getPath()); } else { logger.error("Should not happen !!!"); logger.error("chunk number: " + chunkNumber); logger.error("chunk identifier: " + identifier); logger.error("chunk filename: " + filename); logger.error("chunks : " + chunkedFiles.toString()); } } } return flow; } else { logger.debug("upload pending "); flow.setChunkUploadSuccess(true); } } catch (BusinessException e) { logger.error(e.getMessage()); logger.debug("Exception : ", e); flow.setChunkUploadSuccess(false); flow.setErrorMessage(e.getMessage()); flow.setErrCode(e.getErrorCode().getCode()); } catch (Exception e) { logger.error(e.getMessage()); logger.debug("Exception : ", e); flow.setChunkUploadSuccess(false); flow.setErrorMessage(e.getMessage()); } return flow; }
From source file:org.roda.core.plugins.plugins.base.InventoryReportPluginUtils.java
public static void mergeFiles(List<Path> files, Path mergedFile) throws IOException { try (FileChannel out = FileChannel.open(mergedFile, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) { for (Path path : files) { try (FileChannel in = FileChannel.open(path, StandardOpenOption.READ)) { for (long p = 0, l = in.size(); p < l;) p += in.transferTo(p, l - p, out); }//from www . j a va 2 s . co m } } catch (IOException e) { throw e; } }
From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java
@Override public long createFile(String fileName, InputStream inputStream) throws IOException { long fileSize; Path filePath = this.directory.resolve(fileName); try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream); FileChannel fc = FileChannel.open(filePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) { fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); }//w ww.j a v a 2 s.c o m return fileSize; }
From source file:record.wave.WaveWriter.java
/** * Opens the file and writes a wave header. *//*from w w w .j av a2 s . co m*/ private void open() throws IOException { int version = 2; while (Files.exists(mFile)) { mFile = Paths.get(mFile.toFile().getAbsolutePath().replace(".wav", "_" + version + ".wav")); version++; } mFileChannel = (FileChannel.open(mFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)); ByteBuffer header = WaveUtils.getWaveHeader(mAudioFormat); header.flip(); while (header.hasRemaining()) { mFileChannel.write(header); } }