List of usage examples for java.nio.file Files deleteIfExists
public static boolean deleteIfExists(Path path) throws IOException
From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java
@Override public void run() { Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile; // Path lockMarker; Process process;//from ww w . j av a 2 s . co m int exitValue; Set<JsonReportEntry> report; JsonReportEntry entry; String line; StringBuffer buf; Path srcPath, destPath; ProcessBuilder processBuilder; Ticket ticket; String script, stdOut, stdErr; long tic, toc; JSONObject obj; Message msg; Charset cs; int trial; boolean suc; Exception ex; if (log.isDebugEnabled()) log.debug("Starting up local thread for ticket " + invoc.getTicketId() + "."); if (invoc == null) throw new NullPointerException("Invocation must not be null."); ticket = invoc.getTicket(); process = null; stdOut = null; stdErr = null; // lockMarker = null; script = null; successMarker = null; cs = Charset.forName("UTF-8"); try { callLocation = Paths.get(System.getProperty("user.dir")); location = buildDir.resolve(String.valueOf(invoc.getTicketId())); // lockMarker = location.resolve( Invocation.LOCK_FILENAME ); successMarker = location.resolve(Invocation.SUCCESS_FILENAME); reportFile = location.resolve(Invocation.REPORT_FILENAME); script = invoc.toScript(); // if( Files.exists( lockMarker ) ) // throw new IOException( "Lock held on ticket "+invoc.getTicketId() ); if (!Files.exists(successMarker)) { deleteIfExists(location); Files.createDirectories(location); // Files.createFile( lockMarker ); scriptFile = invoc.getExecutablePath(location); Files.createFile(scriptFile, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---"))); // write executable script try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) { writer.write(script); } // write executable log entry try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) { writer.write(ticket.getExecutableLogEntry().toString()); writer.write('\n'); } for (String filename : invoc.getStageInList()) { if (filename.charAt(0) == '/') throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'."); srcPath = centralRepo.resolve(filename); destPath = location.resolve(filename); if (!Files.exists(srcPath)) { srcPath = callLocation.resolve(filename); if (log.isTraceEnabled()) log.trace("Resolving relative path '" + srcPath + "'."); } else if (log.isTraceEnabled()) log.trace("Resolving path to central repository '" + srcPath + "'."); if (log.isTraceEnabled()) log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'."); if (!Files.exists(destPath.getParent())) Files.createDirectories(destPath.getParent()); Files.createSymbolicLink(destPath, srcPath); } // run script processBuilder = new ProcessBuilder(invoc.getCmd()); processBuilder.directory(location.toFile()); stdOutFile = location.resolve(Invocation.STDOUT_FILENAME); stdErrFile = location.resolve(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile.toFile()); processBuilder.redirectError(stdErrFile.toFile()); trial = 1; suc = false; ex = null; tic = System.currentTimeMillis(); do { try { process = processBuilder.start(); suc = true; } catch (IOException e) { ex = e; if (log.isWarnEnabled()) log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL + "ms: " + e.getMessage()); Thread.sleep(WAIT_INTERVAL); } } while (suc == false && trial <= MAX_TRIALS); if (process == null) { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null)); // Files.delete( lockMarker ); return; } exitValue = process.waitFor(); toc = System.currentTimeMillis(); try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) { obj = new JSONObject(); obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic); entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj); writer.write(entry.toString()); writer.write('\n'); try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdOut = buf.toString(); if (!stdOut.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut); writer.write(entry.toString()); writer.write('\n'); } } try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdErr = buf.toString(); if (!stdErr.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr); writer.write(entry.toString()); writer.write('\n'); } } if (exitValue == 0) Files.createFile(successMarker); else { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr)); // Files.delete( lockMarker ); return; } } } // gather report report = new HashSet<>(); try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) { while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; entry = new JsonReportEntry(line); // If the report comes from the hard cache then the run id // is different from the run id of this invocation. This is // corrected here. entry.setRunId(invoc.getRunId()); report.add(entry); } } invoc.evalReport(report); // create link in central data repository for (String f : invoc.getStageOutList()) { srcPath = location.resolve(f); destPath = centralRepo.resolve(f); if (Files.exists(destPath)) continue; if (log.isTraceEnabled()) log.trace("Creating link from " + srcPath + " to " + destPath + "."); Files.createSymbolicLink(destPath, srcPath); } ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report)); if (log.isTraceEnabled()) log.trace("Local thread ran through without exception."); // Files.deleteIfExists( lockMarker ); } catch (InterruptedException e) { if (log.isTraceEnabled()) log.trace("Local thread has been interrupted."); } catch (Exception e) { if (log.isTraceEnabled()) log.trace("Something went wrong. Deleting success marker if present."); if (successMarker != null) try { Files.deleteIfExists(successMarker); } catch (IOException e1) { e1.printStackTrace(); } msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr); ticketSrc.sendMsg(msg); } finally { if (process != null) { if (log.isDebugEnabled()) log.debug("Stopping local thread for ticket " + invoc.getTicketId() + "."); process.destroy(); } } }
From source file:org.digidoc4j.main.DigiDoc4JTest.java
@Test @Ignore("Requires a physical smart card") public void createContainer_andSignIt_withPkcs11() throws Exception { Files.deleteIfExists(Paths.get(testBdocContainer)); String[] params = new String[] { "-in", testBdocContainer, "-add", "testFiles/test.txt", "text/plain", "-pkcs11", "/usr/local/lib/opensc-pkcs11.so", "22975", "2" }; callMainWithoutSystemExit(params);//from w ww.ja va 2 s . c om Container container = ContainerOpener.open(testBdocContainer); assertEquals(1, container.getDataFiles().size()); assertEquals("test.txt", container.getDataFiles().get(0).getName()); assertEquals(1, container.getSignatures().size()); assertTrue(container.validate().isValid()); }
From source file:net.solarnetwork.node.setup.s3.S3SetupManager.java
/** * Apply sync rules to a specific directory. * // w w w .java2 s. com * <p> * This method will delete any file found in {@code dir} that is <b>not</b> * also in {@code installedFiles}. * </p> * * @param dir * the directory to delete files from * @param installedFiles * the list of files to keep (these must be absolute paths) * @return the set of deleted files, or an empty set if nothing deleted * @throws IOException * if an IO error occurs */ private Set<Path> applySetupSyncPath(Path dir, Set<Path> installedFiles) throws IOException { if (!Files.isDirectory(dir)) { return Collections.emptySet(); } Set<Path> deleted = new LinkedHashSet<>(); Files.walk(dir) .filter(p -> !Files.isDirectory(p) && !installedFiles.contains(p.toAbsolutePath().normalize())) .forEach(p -> { try { log.trace("Deleting syncPath {} file {}", dir, p); if (Files.deleteIfExists(p)) { deleted.add(p); } } catch (IOException e) { log.warn("Error deleting syncPath {} file {}: {}", dir, p, e.getMessage()); } }); return deleted; }
From source file:de.elomagic.carafile.client.CaraFileClient.java
/** * Downloads a file into a {@link OutputStream}. * * @param md {@link MetaData} of the file. * @param out The output stream. It's not recommended to use a buffered stream. * @throws IOException Thrown when unable to write file into the output stream or the SHA-1 validation failed. *//* ww w . ja va 2 s . com*/ public void downloadFile(final MetaData md, final OutputStream out) throws IOException { if (md == null) { throw new IllegalArgumentException("Parameter 'md' must not be null!"); } if (out == null) { throw new IllegalArgumentException("Parameter 'out' must not be null!"); } Map<String, Path> downloadedChunks = new HashMap<>(); Set<String> chunksToDownload = new HashSet<>(); for (ChunkData chunkData : md.getChunks()) { chunksToDownload.add(chunkData.getId()); } try { while (!chunksToDownload.isEmpty()) { PeerChunk pc = peerChunkSelector.getNext(md, chunksToDownload); if (pc == null || pc.getPeerURI() == null) { throw new IOException("No peer found or selected for download"); } Path chunkFile = Files.createTempFile("fs_", ".tmp"); try (OutputStream chunkOut = Files.newOutputStream(chunkFile, StandardOpenOption.APPEND)) { downloadShunk(pc, md, chunkOut); downloadedChunks.put(pc.getChunkId(), chunkFile); chunksToDownload.remove(pc.getChunkId()); chunkOut.flush(); } catch (Exception ex) { Files.deleteIfExists(chunkFile); throw ex; } } MessageDigest messageDigest = DigestUtils.getSha1Digest(); // Write chunk on correct order to file. try (DigestOutputStream dos = new DigestOutputStream(out, messageDigest); BufferedOutputStream bos = new BufferedOutputStream(dos, md.getChunkSize())) { for (ChunkData chunk : md.getChunks()) { Path chunkPath = downloadedChunks.get(chunk.getId()); Files.copy(chunkPath, bos); } } String sha1 = Hex.encodeHexString(messageDigest.digest()); if (!sha1.equalsIgnoreCase(md.getId())) { throw new IOException( "SHA1 validation of file failed. Expected " + md.getId() + " but was " + sha1); } } finally { for (Path path : downloadedChunks.values()) { try { Files.deleteIfExists(path); } catch (IOException ex) { LOG.error("Unable to delete chunk " + path.toString() + "; " + ex.getMessage(), ex); } } } }
From source file:org.opencb.opencga.server.ws.FileWSServer.java
@POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @ApiOperation(httpMethod = "POST", position = 4, value = "Resource to upload a file by chunks", response = QueryResponse.class) public Response chunkUpload(@FormDataParam("chunk_content") byte[] chunkBytes, @FormDataParam("chunk_content") FormDataContentDisposition contentDisposition, @DefaultValue("") @FormDataParam("chunk_id") String chunk_id, @DefaultValue("false") @FormDataParam("last_chunk") String last_chunk, @DefaultValue("") @FormDataParam("chunk_total") String chunk_total, @DefaultValue("") @FormDataParam("chunk_size") String chunk_size, @DefaultValue("") @FormDataParam("chunk_hash") String chunkHash, @DefaultValue("false") @FormDataParam("resume_upload") String resume_upload, @ApiParam(value = "filename", required = true) @DefaultValue("") @FormDataParam("filename") String filename, @ApiParam(value = "fileFormat", required = true) @DefaultValue("") @FormDataParam("fileFormat") String fileFormat, @ApiParam(value = "bioFormat", required = true) @DefaultValue("") @FormDataParam("bioFormat") String bioFormat, @ApiParam(value = "userId", required = true) @DefaultValue("") @FormDataParam("userId") String userId, // @ApiParam(defaultValue = "projectId", required = true) @DefaultValue("") @FormDataParam("projectId") String projectId, @ApiParam(value = "studyId", required = true) @FormDataParam("studyId") String studyIdStr, @ApiParam(value = "relativeFilePath", required = true) @DefaultValue("") @FormDataParam("relativeFilePath") String relativeFilePath, @ApiParam(value = "description", required = true) @DefaultValue("") @FormDataParam("description") String description, @ApiParam(value = "parents", required = true) @DefaultValue("true") @FormDataParam("parents") boolean parents) { long t = System.currentTimeMillis(); java.nio.file.Path filePath = null; final int studyId; try {/*w w w . jav a2 s . c o m*/ studyId = catalogManager.getStudyId(studyIdStr); } catch (Exception e) { return createErrorResponse(e); } try { filePath = Paths.get(catalogManager.getFileUri(studyId, relativeFilePath)); System.out.println(filePath); } catch (CatalogIOException e) { System.out.println("catalogManager.getFilePath"); e.printStackTrace(); } catch (CatalogException e) { e.printStackTrace(); } java.nio.file.Path completedFilePath = filePath.getParent().resolve("_" + filename); java.nio.file.Path folderPath = filePath.getParent().resolve("__" + filename); logger.info(relativeFilePath + ""); logger.info(folderPath + ""); logger.info(filePath + ""); boolean resume = Boolean.parseBoolean(resume_upload); try { logger.info("---resume is: " + resume); if (resume) { logger.info("Resume ms :" + (System.currentTimeMillis() - t)); return createOkResponse(getResumeFileJSON(folderPath)); } int chunkId = Integer.parseInt(chunk_id); int chunkSize = Integer.parseInt(chunk_size); boolean lastChunk = Boolean.parseBoolean(last_chunk); logger.info("---saving chunk: " + chunkId); logger.info("lastChunk: " + lastChunk); // WRITE CHUNK TYPE_FILE if (!Files.exists(folderPath)) { logger.info("createDirectory(): " + folderPath); Files.createDirectory(folderPath); } logger.info("check dir " + Files.exists(folderPath)); // String hash = StringUtils.sha1(new String(chunkBytes)); // logger.info("bytesHash: " + hash); // logger.info("chunkHash: " + chunkHash); // hash = chunkHash; if (chunkBytes.length == chunkSize) { Files.write(folderPath.resolve(chunkId + "_" + chunkBytes.length + "_partial"), chunkBytes); } else { String errorMessage = "Chunk content size (" + chunkBytes.length + ") " + "!= chunk_size (" + chunk_size + ")."; logger.error(errorMessage); return createErrorResponse(new IOException(errorMessage)); } if (lastChunk) { logger.info("lastChunk is true..."); Files.deleteIfExists(completedFilePath); Files.createFile(completedFilePath); List<java.nio.file.Path> chunks = getSortedChunkList(folderPath); logger.info("----ordered chunks length: " + chunks.size()); for (java.nio.file.Path partPath : chunks) { logger.info(partPath.getFileName().toString()); Files.write(completedFilePath, Files.readAllBytes(partPath), StandardOpenOption.APPEND); } IOUtils.deleteDirectory(folderPath); try { QueryResult queryResult = catalogManager.createFile(studyId, File.Format.valueOf(fileFormat.toUpperCase()), File.Bioformat.valueOf(bioFormat.toUpperCase()), relativeFilePath, completedFilePath.toUri(), description, parents, sessionId); return createOkResponse(queryResult); } catch (Exception e) { logger.error(e.toString()); return createErrorResponse(e); } } } catch (IOException e) { System.out.println("e = " + e); // TODO Auto-generated catch block e.printStackTrace(); } logger.info("chunk saved ms :" + (System.currentTimeMillis() - t)); return createOkResponse("ok"); }
From source file:org.openhab.binding.fems.FEMSCore.java
/** * Checks if modbus connection to storage system is working * @param ess "dess" or "cess"/*from w w w .ja v a 2 s .co m*/ * @return */ public static boolean isModbusWorking(Log log, String ess) { // remove old lock file try { if (Files.deleteIfExists(Paths.get("/var/lock/LCK..ttyUSB0"))) { log.info("Deleted old lock file"); } } catch (IOException e) { log.error("Error deleting old lock file: " + e.getMessage()); e.printStackTrace(); } // find first matching device String modbusDevice = "ttyUSB*"; String portName = "/dev/ttyUSB0"; // if no file found: use default try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/dev"), modbusDevice)) { for (Path file : files) { portName = file.toAbsolutePath().toString(); log.info("Set modbus portname: " + portName); } } catch (Exception e) { log.info("Error trying to find " + modbusDevice + ": " + e.getMessage()); e.printStackTrace(); } // default: DESS int baudRate = 9600; int socAddress = 10143; int unit = 4; if (ess.compareTo("cess") == 0) { baudRate = 19200; socAddress = 0x1402; unit = 100; } SerialParameters params = new SerialParameters(); params.setPortName(portName); params.setBaudRate(baudRate); params.setDatabits(8); params.setParity("None"); params.setStopbits(1); params.setEncoding(Modbus.SERIAL_ENCODING_RTU); params.setEcho(false); params.setReceiveTimeout(Constants.MODBUS_TIMEOUT); SerialConnection serialConnection = new SerialConnection(params); try { serialConnection.open(); } catch (Exception e) { log.error("Modbus connection error: " + e.getMessage()); serialConnection.close(); return false; } ModbusSerialTransaction modbusSerialTransaction = null; ReadMultipleRegistersRequest req = new ReadMultipleRegistersRequest(socAddress, 1); req.setUnitID(unit); req.setHeadless(); modbusSerialTransaction = new ModbusSerialTransaction(serialConnection); modbusSerialTransaction.setRequest(req); modbusSerialTransaction.setRetries(1); try { modbusSerialTransaction.execute(); } catch (ModbusException e) { log.error("Modbus execution error: " + e.getMessage()); serialConnection.close(); return false; } ModbusResponse res = modbusSerialTransaction.getResponse(); serialConnection.close(); if (res instanceof ReadMultipleRegistersResponse) { return true; } else if (res instanceof ExceptionResponse) { log.error("Modbus read error: " + ((ExceptionResponse) res).getExceptionCode()); } else { log.error("Modbus read undefined response"); } return false; }
From source file:org.digidoc4j.main.DigiDoc4JTest.java
@Test public void itShouldNotBePossible_ToSignWithBoth_Pkcs11AndPkcs12() throws Exception { exit.expectSystemExitWithStatus(5);/*from w w w. java2 s . c o m*/ Files.deleteIfExists(Paths.get(testBdocContainer)); String[] params = new String[] { "-in", testBdocContainer, "-add", "testFiles/test.txt", "text/plain", "-pkcs11", "/usr/local/lib/opensc-pkcs11.so", "01497", "2", "-pkcs12", "testFiles/signout.p12", "test" }; DigiDoc4J.main(params); }
From source file:org.n52.wps.server.database.PostgresDatabase.java
@Override public synchronized void updateResponse(String id, InputStream stream) { Path tempFilePath = null;/* w w w. j a v a 2 s . com*/ FileInputStream fis = null; try { tempFilePath = Files.createTempFile(UUID.randomUUID().toString(), null); Files.copy(stream, tempFilePath, StandardCopyOption.REPLACE_EXISTING); fis = new FileInputStream(tempFilePath.toFile()); AbstractDatabase.updateSQL.setString(UPDATE_COLUMN_REQUEST_ID, id); AbstractDatabase.updateSQL.setAsciiStream(UPDATE_COLUMN_RESPONSE, fis, (int) tempFilePath.toFile().length()); AbstractDatabase.updateSQL.executeUpdate(); getConnection().commit(); } catch (SQLException e) { LOGGER.error("Could not insert Response into database", e); } catch (IOException e) { LOGGER.error("Could not insert Response into database", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { LOGGER.error("Could not close file input stream", e); } } if (tempFilePath != null) { try { Files.deleteIfExists(tempFilePath); } catch (IOException e) { LOGGER.error("Could not delete file: " + tempFilePath.toString(), e); } } } }
From source file:org.corehunter.services.simple.SimpleCoreHunterRunServices.java
private void removeResult(CoreHunterRunResult coreHunterRunResult) { Path path = Paths.get(getPath().toString(), RESULTS_PATH, coreHunterRunResult.getUniqueIdentifier()); logger.info("Removing result for {} with id {} to path {}", coreHunterRunResult.getName(), coreHunterRunResult.getUniqueIdentifier(), path.toString()); try {/* w ww . ja v a 2s . com*/ Files.deleteIfExists(path); } catch (IOException e) { logger.error("Can not remove result to path {} due to {}", path, e.getMessage()); logger.error("Full error ", e); e.printStackTrace(); } }
From source file:org.ballerinalang.stdlib.system.FileSystemTest.java
@Test(description = "Test for copying a file to new location") public void testCopyFile() throws IOException, InterruptedException { try {/*from w w w . j a va 2 s .c om*/ BValue[] args = { new BString(srcFilePath.toString()), new BString(tempDestPath.toString()), new BBoolean(false) }; BRunUtil.invoke(compileResult, "testCopy", args); assertTrue(Files.exists(tempDestPath)); assertTrue(Files.exists(srcFilePath)); assertEquals(tempDestPath.toFile().length(), srcFilePath.toFile().length()); // Execute same with replaceExist false long modifiedTime = tempDestPath.toFile().lastModified(); BRunUtil.invoke(compileResult, "testCopy", args); long modifiedTimeWithoutReplace = tempDestPath.toFile().lastModified(); assertEquals(modifiedTimeWithoutReplace, modifiedTime); // Execute same with replaceExist true BValue[] args1 = { new BString(srcFilePath.toString()), new BString(tempDestPath.toString()), new BBoolean(true) }; Thread.sleep(1000); BRunUtil.invoke(compileResult, "testCopy", args1); long modifiedTimeWithReplace = tempDestPath.toFile().lastModified(); assertNotEquals(modifiedTimeWithReplace, modifiedTime); } finally { Files.deleteIfExists(tempDestPath); } }