List of usage examples for java.nio.file StandardOpenOption APPEND
StandardOpenOption APPEND
To view the source code for java.nio.file StandardOpenOption APPEND.
Click Source Link
From source file:eu.itesla_project.security.SecurityAnalysisTool.java
@Override public void run(CommandLine line) throws Exception { Path caseFile = Paths.get(line.getOptionValue("case-file")); Set<LimitViolationType> limitViolationTypes = line.hasOption("limit-types") ? Arrays.stream(line.getOptionValue("limit-types").split(",")).map(LimitViolationType::valueOf) .collect(Collectors.toSet()) : EnumSet.allOf(LimitViolationType.class); Path csvFile = null;/*from w w w . j av a 2 s. com*/ if (line.hasOption("output-csv")) { csvFile = Paths.get(line.getOptionValue("output-csv")); } System.out.println("Loading network '" + caseFile + "'"); // load network Network network = Importers.loadNetwork(caseFile); if (network == null) { throw new RuntimeException("Case '" + caseFile + "' not found"); } network.getStateManager().allowStateMultiThreadAccess(true); ComponentDefaultConfig defaultConfig = new ComponentDefaultConfig(); SecurityAnalysisFactory securityAnalysisFactory = defaultConfig .findFactoryImplClass(SecurityAnalysisFactory.class).newInstance(); SecurityAnalysis securityAnalysis = securityAnalysisFactory.create(network, LocalComputationManager.getDefault(), 0); ContingenciesProviderFactory contingenciesProviderFactory = defaultConfig .findFactoryImplClass(ContingenciesProviderFactory.class).newInstance(); ContingenciesProvider contingenciesProvider = contingenciesProviderFactory.create(); // run security analysis on all N-1 lines SecurityAnalysisResult result = securityAnalysis.runAsync(contingenciesProvider).join(); if (!result.getPreContingencyResult().isComputationOk()) { System.out.println("Pre-contingency state divergence"); } LimitViolationFilter limitViolationFilter = new LimitViolationFilter(limitViolationTypes); if (csvFile != null) { System.out.println("Writing results to '" + csvFile + "'"); CsvTableFormatterFactory csvTableFormatterFactory = new CsvTableFormatterFactory(); Security.printPreContingencyViolations(result, Files.newBufferedWriter(csvFile, StandardCharsets.UTF_8), csvTableFormatterFactory, limitViolationFilter); Security.printPostContingencyViolations(result, Files.newBufferedWriter(csvFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND), csvTableFormatterFactory, limitViolationFilter); } else { SystemOutStreamWriter soutWriter = new SystemOutStreamWriter(); AsciiTableFormatterFactory asciiTableFormatterFactory = new AsciiTableFormatterFactory(); Security.printPreContingencyViolations(result, soutWriter, asciiTableFormatterFactory, limitViolationFilter); Security.printPostContingencyViolations(result, soutWriter, asciiTableFormatterFactory, limitViolationFilter); } }
From source file:sadl.utils.IoUtils.java
public static void writeToFile(double[] testSample, Path classificationTestFile) throws IOException { try (BufferedWriter bw = Files.newBufferedWriter(classificationTestFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { bw.append(Arrays.toString(testSample).replace('[', ' ').replace(']', ' ')); bw.append('\n'); }/*w ww . j av a 2 s . c om*/ }
From source file:uk.dsxt.voting.common.cryptoVote.CryptoVoteAcceptorWeb.java
private void sendNextVote() { if (!isNetworkOn) return;// w ww.j a va 2 s . c o m Map<String, String> parameters = unsentVoteMessages.poll(); int queueSize = unsentVoteMessages.size(); if (parameters == null) return; String result; try { result = httpHelper.request(acceptVoteUrl, parameters, RequestType.POST); } catch (IOException e) { log.warn("sendNextVote failed. url={} error={}", acceptVoteUrl, e); unsentVoteMessages.add(parameters); return; } catch (InternalLogicException e) { log.error("sendNextVote failed. url={}", acceptVoteUrl, e); unsentVoteMessages.add(parameters); return; } if (result == null || result.isEmpty()) { log.error("sendNextVote. result == null. url={}", acceptVoteUrl); unsentVoteMessages.add(parameters); return; } if (receiptsFile != null) { synchronized (receiptsFile) { try { Files.write(receiptsFile.toPath(), Collections.singletonList(result), Charset.forName("utf-8"), StandardOpenOption.APPEND, StandardOpenOption.CREATE); } catch (IOException e) { log.warn("sendNextVote. Couldn't save result to file: {}. result='{}' error={}", receiptsFile.getAbsolutePath(), result, e.getMessage()); } } } try { NodeVoteReceipt receipt = mapper.readValue(result, NodeVoteReceipt.class); log.debug( "sendNextVote. Vote sent, receipt.status={} clientPacketResidual={} packetSize={} queueSize={}", receipt.getStatus(), parameters.get("clientPacketResidual"), parameters.get("packetSize"), queueSize); } catch (IOException e) { log.error("sendNextVote. can not read receipt {}. error={}", result, e.getMessage()); } }
From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java
protected void appendToCsv(String[] data) throws IOException { String line = formatCsvLine(data); Files.write(Paths.get(CSV_TARGET_FILE.getPath()), line.getBytes(), StandardOpenOption.APPEND); }
From source file:com.codealot.textstore.FileStore.java
@Override public String storeText(final Reader reader) throws IOException { Objects.requireNonNull(reader, "No reader provided"); // make the digester final MessageDigest digester = getDigester(); // make temp file final Path textPath = Paths.get(this.storeRoot, UUID.randomUUID().toString()); // stream to file, building digest final ReaderInputStream readerAsBytes = new ReaderInputStream(reader, StandardCharsets.UTF_8); try {/*from w ww .ja va 2 s . c om*/ final byte[] bytes = new byte[1024]; int readLength = 0; long totalRead = 0L; while ((readLength = readerAsBytes.read(bytes)) > 0) { totalRead += readLength; digester.update(bytes, 0, readLength); final byte[] readBytes = Arrays.copyOf(bytes, readLength); Files.write(textPath, readBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND); } // check that something was read if (totalRead == 0L) { return this.storeText(""); } // make the hash final String hash = byteToHex(digester.digest()); // store the text, if new final Path finalPath = Paths.get(this.storeRoot, hash); if (Files.exists(finalPath)) { // already existed, so delete uuid named one Files.deleteIfExists(textPath); } else { // rename the file Files.move(textPath, finalPath); } return hash; } finally { if (readerAsBytes != null) { readerAsBytes.close(); } } }
From source file:sadl.utils.IoUtils.java
public static void writeToFile(List<double[]> testSamples, Path classificationTestFile) throws IOException { try (BufferedWriter bw = Files.newBufferedWriter(classificationTestFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { for (final double[] testSample : testSamples) { bw.append(Arrays.toString(testSample).replace('[', ' ').replace(']', ' ')); bw.append('\n'); }/*w w w . ja v a2 s . co m*/ } }
From source file:com.ikanow.aleph2.security.utils.LdifExportUtil.java
public void exportToLdif(String outPath) { // copy Template Path pOutPath = Paths.get(outPath); try {/* w w w.j a v a 2 s.c o m*/ Files.copy(this.getClass().getResourceAsStream("aleph2_template.ldif"), pOutPath, StandardCopyOption.REPLACE_EXISTING); String userEntries = createUserEntries(); Files.write(pOutPath, userEntries.getBytes(), StandardOpenOption.APPEND); } catch (Exception e) { logger.error(e); } }
From source file:com.liferay.sync.engine.document.library.handler.DownloadFileHandler.java
protected void copyFile(final SyncFile syncFile, Path filePath, InputStream inputStream, boolean append) throws Exception { OutputStream outputStream = null; Watcher watcher = WatcherManager.getWatcher(getSyncAccountId()); try {// w w w. j a v a2 s. c om Path tempFilePath = FileUtil.getTempFilePath(syncFile); boolean exists = FileUtil.exists(filePath); if (append) { outputStream = Files.newOutputStream(tempFilePath, StandardOpenOption.APPEND); IOUtils.copyLarge(inputStream, outputStream); } else { if (exists && (boolean) getParameterValue("patch")) { if (_logger.isDebugEnabled()) { _logger.debug("Patching {}", syncFile.getFilePathName()); } Files.copy(filePath, tempFilePath, StandardCopyOption.REPLACE_EXISTING); IODeltaUtil.patch(tempFilePath, inputStream); } else { Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING); } } watcher.addDownloadedFilePathName(filePath.toString()); if (GetterUtil.getBoolean(syncFile.getLocalExtraSettingValue("restoreEvent"))) { syncFile.unsetLocalExtraSetting("restoreEvent"); syncFile.setUiEvent(SyncFile.UI_EVENT_RESTORED_REMOTE); } else if (exists) { syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_UPDATE); } else { syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_NEW); } FileKeyUtil.writeFileKey(tempFilePath, String.valueOf(syncFile.getSyncFileId()), false); FileUtil.setModifiedTime(tempFilePath, syncFile.getModifiedTime()); if (MSOfficeFileUtil.isLegacyExcelFile(filePath)) { syncFile.setLocalExtraSetting("lastSavedDate", MSOfficeFileUtil.getLastSavedDate(tempFilePath)); } Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); ExecutorService executorService = SyncEngine.getExecutorService(); Runnable runnable = new Runnable() { @Override public void run() { IODeltaUtil.checksums(syncFile); syncFile.setState(SyncFile.STATE_SYNCED); SyncFileService.update(syncFile); } }; executorService.execute(runnable); } catch (FileSystemException fse) { if (fse instanceof AccessDeniedException) { _logger.error(fse.getMessage(), fse); syncFile.setState(SyncFile.STATE_ERROR); syncFile.setUiEvent(SyncFile.UI_EVENT_ACCESS_DENIED_LOCAL); SyncFileService.update(syncFile); return; } else if (fse instanceof NoSuchFileException) { if (isEventCancelled()) { SyncFileService.deleteSyncFile(syncFile); return; } } watcher.removeDownloadedFilePathName(filePath.toString()); String message = fse.getMessage(); _logger.error(message, fse); syncFile.setState(SyncFile.STATE_ERROR); if (message.contains("File name too long")) { syncFile.setUiEvent(SyncFile.UI_EVENT_FILE_NAME_TOO_LONG); } SyncFileService.update(syncFile); } finally { StreamUtil.cleanUp(outputStream); } }
From source file:business.services.FileService.java
public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk, Integer chunks, String flowIdentifier) { try {/*w w w . j a v a 2s .c o m*/ String identifier = user.getId().toString() + "_" + flowIdentifier; String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; log.info("File content-type: " + file.getContentType()); try { contentType = MediaType.valueOf(file.getContentType()).toString(); log.info("Media type: " + contentType); } catch (InvalidMediaTypeException e) { log.warn("Invalid content type: " + e.getMediaType()); //throw new FileUploadError("Invalid content type: " + e.getMediaType()); } InputStream input = file.getInputStream(); // Create temporary file for chunk Path path = fileSystem.getPath(uploadPath).normalize(); if (!path.toFile().exists()) { Files.createDirectory(path); } name = URLEncoder.encode(name, "utf-8"); String prefix = getBasename(name); String suffix = getExtension(name); Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize(); // filter path names that point to places outside the upload path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, f.getParent())) { // Path f is not in the upload path. Maybe 'name' contains '..'? throw new FileUploadError("Invalid file name"); } log.info("Copying file to " + f.toString()); // Copy chunk to temporary file Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING); // Save chunk location in chunk map SortedMap<Integer, Path> chunkMap; synchronized (uploadChunks) { // FIXME: perhaps use a better identifier? Not sure if this one // is unique enough... chunkMap = uploadChunks.get(identifier); if (chunkMap == null) { chunkMap = new TreeMap<Integer, Path>(); uploadChunks.put(identifier, chunkMap); } } chunkMap.put(chunk, f); log.info("Chunk " + chunk + " saved to " + f.toString()); // Assemble complete file if all chunks have been received if (chunkMap.size() == chunks.intValue()) { uploadChunks.remove(identifier); Path assembly = Files.createTempFile(path, prefix, suffix).normalize(); // filter path names that point to places outside the upload path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, assembly.getParent())) { // Path assembly is not in the upload path. Maybe 'name' contains '..'? throw new FileUploadError("Invalid file name"); } log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks..."); OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE, StandardOpenOption.APPEND); // Copy chunks to assembly file, delete chunk files for (int i = 1; i <= chunks; i++) { //log.info("Copying chunk " + i + "..."); Path source = chunkMap.get(new Integer(i)); if (source == null) { log.error("Cannot find chunk " + i); throw new FileUploadError("Cannot find chunk " + i); } Files.copy(source, out); Files.delete(source); } // Save assembled file name to database log.info("Saving attachment to database..."); File attachment = new File(); attachment.setName(URLDecoder.decode(name, "utf-8")); attachment.setType(type); attachment.setMimeType(contentType); attachment.setDate(new Date()); attachment.setUploader(user); attachment.setFilename(assembly.getFileName().toString()); attachment = fileRepository.save(attachment); return attachment; } return null; } catch (IOException e) { log.error(e); throw new FileUploadError(e.getMessage()); } }
From source file:org.linagora.linshare.webservice.uploadrequest.impl.FlowUploaderRestServiceImpl.java
@Path("/") @POST// w w w.java 2s . c o m @Consumes("multipart/form-data") @Override public Response uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber, @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize, @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(REQUEST_URL_UUID) String uploadRequestUrlUuid, @Multipart(PASSWORD) String password) throws BusinessException { logger.debug("upload chunk number : " + chunkNumber); identifier = cleanIdentifier(identifier); Validate.isTrue(isValid(chunkNumber, chunkSize, totalSize, identifier, filename)); try { logger.debug("writing chunk number : " + chunkNumber); java.nio.file.Path tempFile = getTempFile(identifier); FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND); byte[] byteArray = IOUtils.toByteArray(file); fc.write(ByteBuffer.wrap(byteArray), (chunkNumber - 1) * chunkSize); fc.close(); chunkedFiles.get(identifier).addChunk(chunkNumber); if (isUploadFinished(identifier, chunkSize, totalSize)) { logger.debug("upload finished "); InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ); File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename); try { uploadRequestUrlFacade.addUploadRequestEntry(uploadRequestUrlUuid, password, tempFile2, filename); } finally { deleteTempFile(tempFile2); } ChunkedFile remove = chunkedFiles.remove(identifier); Files.deleteIfExists(remove.getPath()); return Response.ok("upload success").build(); } else { logger.debug("upload pending "); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Response.ok("upload success").build(); }