List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:com.pari.nm.modules.jobs.PcbImportJob.java
private void pushToBackupServer() { File uploadFile = new File(pcbFileName); boolean isDeleteFile = true; String renamedFile = null;/*from w w w . j a va2 s.co m*/ if (profileName != null) { String finalProfileName = profileName; String[] profileNames = profileName.split("_"); if (profileNames.length == 2) { finalProfileName = profileNames[0] != null && !profileNames[0].equals("") ? profileNames[0] : "_" + profileNames[1]; } else if (profileNames.length > 2) { finalProfileName = profileName.substring(0, profileName.lastIndexOf("_")); } String cpName = finalProfileName; FtpServerDetails ftpServerDetails = ServerDBHelper.getFtpServerPreferences(cpName); if (ftpServerDetails != null) { int customJobId = nccmJobId != -1 ? nccmJobId : jobId; int customJobRunId = nccmJobRunId != -1 ? nccmJobRunId : jobRunId; JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), "File backup is configured for this Collection Profile")); String formatedName = cpName + "_" + jobId + "_" + jobRunId + "_" + System.currentTimeMillis() + ".zip"; Path path = Paths.get(uploadFile.getAbsolutePath()); renamedFile = path.getParent() + File.separator + formatedName; File formatedFile = new File(path.getParent() + File.separator + formatedName); uploadFile.renameTo(formatedFile); FTPServerType serverType = ftpServerDetails.getServerType(); String fileName = formatedFile.getName(); String successMsg = "Backup file: " + fileName + " uploaded successfully into " + serverType.toString() + " server: " + ftpServerDetails.getFtpServer(); successMsg += serverType.equals(FTPServerType.TFTP) ? "" : " and directory: " + ftpServerDetails.getDestDir(); String startMsg = "Backup file: " + fileName + " uploaded started"; String formatedMsg = CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), startMsg); JobRun.logJob(customJobId, customJobRunId, formatedMsg); if (serverType.equals(FTPServerType.SFTP)) { try { logger.info("Backup: LocalFile:" + formatedFile); logger.info( "Backup: DestFile:" + ftpServerDetails.getDestDir() + File.separator + fileName); PariSFTP pariSFTP = new PariSFTP(customJobId, customJobRunId); pariSFTP.uploadFileSFTP(ftpServerDetails.getFtpServer(), ftpServerDetails.getServerPort(), ftpServerDetails.getUserName(), ftpServerDetails.getPassword(), formatedFile.getAbsolutePath(), ftpServerDetails.getDestDir() + File.separator + fileName, this, serverType.equals(FTPServerType.SFTP)); JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), successMsg)); } catch (Exception ex) { String msg = "Failed to upload the backup file " + formatedFile + " Reason:" + ex.getMessage(); logger.warn(msg); JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), msg)); } } else if (serverType.equals(FTPServerType.FTP)) { PariFTP pftp = new PariFTP(ftpServerDetails.getFtpServer(), ftpServerDetails.getUserName(), ftpServerDetails.getPassword(), ftpServerDetails.getDestDir(), customJobId, customJobRunId); String errMsg = pftp.uploadFile(formatedFile.getAbsolutePath(), ftpServerDetails.getServerPort()); if (errMsg != null) { String msg = "Failed to upload the backup file to " + ftpServerDetails.getFtpServer() + " Reason :" + errMsg; logger.warn(msg); JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), msg)); } else { JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), successMsg)); } } else if (serverType.equals(FTPServerType.TFTP)) { TFTPHandler tftp = new TFTPHandler(ftpServerDetails.getFtpServer(), customJobId, customJobRunId); String errMsg = tftp.uploadFile(formatedFile.getAbsolutePath(), ftpServerDetails.getServerPort()); if (errMsg != null) { String msg = "Failed to upload the backup file to " + ftpServerDetails.getFtpServer() + " Reason :" + errMsg; logger.warn(msg); JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), msg)); } else { JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), successMsg)); } } else if (serverType.equals(FTPServerType.LOCAL)) { File backupFile = new File(ServerProperties.getCollectionProfileDir().getAbsolutePath() + File.separator + formatedFile.getName()); formatedFile.renameTo(backupFile); successMsg = "Backup file: " + fileName + " is available in the directory :" + backupFile.getAbsolutePath(); JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), successMsg)); isDeleteFile = false; } else if (serverType.equals(FTPServerType.SCP)) { SCPHandler scp = new SCPHandler(ftpServerDetails.getFtpServer(), customJobId, customJobRunId, ftpServerDetails.getUserName(), ftpServerDetails.getPassword(), ftpServerDetails.getDestDir()); String errMsg = scp.uploadFile(formatedFile.getAbsolutePath(), ftpServerDetails.getServerPort()); if (errMsg != null) { String msg = "Failed to upload the backup file to " + ftpServerDetails.getFtpServer() + " Reason :" + errMsg; logger.warn(msg); JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), msg)); } else { JobRun.logJob(customJobId, customJobRunId, CspcXMLUtils.logMsgInStdFormat("", null, "", System.currentTimeMillis(), successMsg)); } } } } if (isDeleteFile) { deletePCBFile(renamedFile != null ? renamedFile : pcbFileName); } }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void getIntermediate() throws Exception { UUID uuid = UUID.randomUUID(); Path inter = DataBundles.getIntermediate(dataBundle, uuid); assertFalse(Files.exists(inter)); DataBundles.setStringValue(inter, "intermediate"); Path parent = inter.getParent(); assertEquals(dataBundle.getRoot().resolve("intermediates"), parent.getParent()); String parentName = parent.getFileName().toString(); assertEquals(2, parentName.length()); assertTrue(uuid.toString().startsWith(parentName)); // Filename is a valid string String interFileName = inter.getFileName().toString(); assertTrue(interFileName.startsWith(parentName)); assertEquals(uuid, UUID.fromString(interFileName)); }
From source file:org.opencb.cellbase.app.transform.GeneParser.java
@Deprecated private void connect(Path genomeSequenceFilePath) throws ClassNotFoundException, SQLException, IOException { logger.info("Connecting to reference genome sequence database ..."); Class.forName("org.sqlite.JDBC"); sqlConn = DriverManager.getConnection( "jdbc:sqlite:" + genomeSequenceFilePath.getParent().toString() + "/reference_genome.db"); if (!Files.exists(Paths.get(genomeSequenceFilePath.getParent().toString(), "reference_genome.db")) || Files.size(genomeSequenceFilePath.getParent().resolve("reference_genome.db")) == 0) { logger.info("Genome sequence database doesn't exists and will be created"); Statement createTable = sqlConn.createStatement(); createTable.executeUpdate("CREATE TABLE if not exists " + "genome_sequence (sequenceName VARCHAR(50), chunkId VARCHAR(30), start INT, end INT, sequence VARCHAR(2000))"); indexReferenceGenomeFasta(genomeSequenceFilePath); }/*from ww w .j av a 2 s . c om*/ indexedSequences = getIndexedSequences(); sqlQuery = sqlConn.prepareStatement("SELECT sequence from genome_sequence WHERE chunkId = ? "); //AND start <= ? AND end >= ? logger.info("Genome sequence database connected"); }
From source file:duthientan.mmanm.com.Main.java
private void BntGenerationKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntGenerationKeyActionPerformed // TODO add your handling code here: if (filePath.size() != 0) { progressBarCipher.setIndeterminate(true); new Thread(new Runnable() { @Override// w w w .j a v a 2s . c om public void run() { try { Path path = Paths.get(filePath.get(0)); String srcParent = path.getParent().toString(); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); final KeyPair key = keyGen.generateKeyPair(); File privateKeyFile = new File(srcParent + "/private.key"); File publicKeyFile = new File(srcParent + "/public.key"); publicKeyFile.createNewFile(); publicKeyFile.createNewFile(); ObjectOutputStream publicKeyOS = new ObjectOutputStream( new FileOutputStream(publicKeyFile)); publicKeyOS.writeObject(key.getPublic()); publicKeyOS.close(); ObjectOutputStream privateKeyOS = new ObjectOutputStream( new FileOutputStream(privateKeyFile)); privateKeyOS.writeObject(key.getPrivate()); privateKeyOS.close(); progressBarCipher.setIndeterminate(false); JFrame frame = new JFrame("COMPLETED"); JOptionPane.showMessageDialog(frame, "Greneration Key File Completed"); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } else { JFrame frame = new JFrame("ERROR"); JOptionPane.showMessageDialog(frame, "Please Choice File To Cipher Before Greneration Key"); } }
From source file:org.opencb.opencga.storage.variant.sqlite.VariantSqliteDBAdaptor.java
private Path getMetaDir(Path file) { String inputName = file.getFileName().toString(); return file.getParent().resolve(".meta_" + inputName); }
From source file:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java
protected boolean isInErrorState(Path filePath) { while (true) { if (filePath == null) { return false; }//from ww w . j a v a2 s .c o m SyncFile syncFile = SyncFileService.fetchSyncFile(filePath.toString()); if (syncFile != null) { if (syncFile.isSystem()) { break; } if (syncFile.getState() == SyncFile.STATE_ERROR) { return true; } } filePath = filePath.getParent(); } return false; }
From source file:org.dhus.store.datastore.DefaultDataStoreManager.java
/** May return null. */ private Path prepareDestinationPath(Product productData, Destination destination) throws IOException { ConfigurationManager configManager = ApplicationContextProvider.getBean(ConfigurationManager.class); Path destinationPath = null; switch (destination) { case ERROR://from w w w.j a v a 2s .c o m String errorPath = configManager.getErrorPath(); if (errorPath != null && !errorPath.isEmpty()) { destinationPath = Paths.get(errorPath, productData.getName()); } break; case TRASH: String trashPath = configManager.getTrashPath(); if (trashPath != null && !trashPath.isEmpty()) { destinationPath = Paths.get(trashPath, productData.getName()); } break; case NONE: default: return null; } if (destinationPath != null) { Path directory = destinationPath.getParent(); if (Files.notExists(directory)) { Files.createDirectory(directory); } } return destinationPath; }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
public boolean createGlobalRepo() { boolean toReturn = false; Path globalConfigRepoPath = buildRepoPath(GitRepositories.GLOBAL).resolve(GIT_ROOT); if (!Files.exists(globalConfigRepoPath)) { // Git repository doesn't exist for global, but the folder might be present, let's delete if exists Path globalConfigPath = globalConfigRepoPath.getParent(); // Create the global repository folder try {/*from w w w. j ava2 s .c o m*/ Files.deleteIfExists(globalConfigPath); logger.info("Bootstrapping repository..."); Files.createDirectories(globalConfigPath); globalRepo = createGitRepository(globalConfigPath); toReturn = true; } catch (IOException e) { // Something very wrong has happened logger.error("Bootstrapping repository failed", e); } } else { logger.info("Detected existing global repository, will not create new one."); toReturn = false; } return toReturn; }
From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java
/** * Indexes all the documents in the path provided. Will also remove anything from the index if not on disk * Generally this is a slow update used only for the inital clone of a repository * NB this can be used for updates but it will be much slower as it needs to to walk the contents of the disk *///from www . j a v a 2 s . c o m public void indexDocsByPath(Path path, String repoName, String repoLocations, String repoRemoteLocation, boolean existingRepo) { SearchcodeLib scl = Singleton.getSearchCodeLib(); // Should have data object by this point List<String> fileLocations = new ArrayList<>(); Queue<CodeIndexDocument> codeIndexDocumentQueue = Singleton.getCodeIndexQueue(); // Convert once outside the main loop String fileRepoLocations = FilenameUtils.separatorsToUnix(repoLocations); boolean lowMemory = this.LOWMEMORY; try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { while (CodeIndexer.shouldPauseAdding()) { Singleton.getLogger().info("Pausing parser."); try { Thread.sleep(SLEEPTIME); } catch (InterruptedException ex) { } } // Convert Path file to unix style that way everything is easier to reason about String fileParent = FilenameUtils.separatorsToUnix(file.getParent().toString()); String fileToString = FilenameUtils.separatorsToUnix(file.toString()); String fileName = file.getFileName().toString(); String md5Hash = Values.EMPTYSTRING; if (fileParent.endsWith("/.svn") || fileParent.contains("/.svn/")) { return FileVisitResult.CONTINUE; } List<String> codeLines; try { codeLines = Helpers.readFileLines(fileToString, MAXFILELINEDEPTH); } catch (IOException ex) { return FileVisitResult.CONTINUE; } try { FileInputStream fis = new FileInputStream(new File(fileToString)); md5Hash = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis); fis.close(); } catch (IOException ex) { Singleton.getLogger().warning("Unable to generate MD5 for " + fileToString); } // is the file minified? if (scl.isMinified(codeLines)) { Singleton.getLogger().info("Appears to be minified will not index " + fileToString); return FileVisitResult.CONTINUE; } String languageName = scl.languageGuesser(fileName, codeLines); String fileLocation = fileToString.replace(fileRepoLocations, Values.EMPTYSTRING) .replace(fileName, Values.EMPTYSTRING); String fileLocationFilename = fileToString.replace(fileRepoLocations, Values.EMPTYSTRING); String repoLocationRepoNameLocationFilename = fileToString; String newString = getBlameFilePath(fileLocationFilename); String codeOwner = getInfoExternal(codeLines.size(), repoName, fileRepoLocations, newString) .getName(); // If low memory don't add to the queue, just index it directly if (lowMemory) { CodeIndexer.indexDocument(new CodeIndexDocument(repoLocationRepoNameLocationFilename, repoName, fileName, fileLocation, fileLocationFilename, md5Hash, languageName, codeLines.size(), StringUtils.join(codeLines, " "), repoRemoteLocation, codeOwner)); } else { Singleton.incrementCodeIndexLinesCount(codeLines.size()); codeIndexDocumentQueue.add(new CodeIndexDocument(repoLocationRepoNameLocationFilename, repoName, fileName, fileLocation, fileLocationFilename, md5Hash, languageName, codeLines.size(), StringUtils.join(codeLines, " "), repoRemoteLocation, codeOwner)); } fileLocations.add(fileLocationFilename); return FileVisitResult.CONTINUE; } }); } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } if (existingRepo) { CodeSearcher cs = new CodeSearcher(); List<String> indexLocations = cs.getRepoDocuments(repoName); for (String file : indexLocations) { if (!fileLocations.contains(file)) { Singleton.getLogger().info("Missing from disk, removing from index " + file); try { CodeIndexer.deleteByFileLocationFilename(file); } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } } } } }