List of usage examples for java.nio.file Path toAbsolutePath
Path toAbsolutePath();
From source file:org.tinymediamanager.core.entities.MediaFile.java
License:asdf
public Path getFileAsPath() { if (file == null) { Path f = Paths.get(this.path, this.filename); file = f.toAbsolutePath(); }//from w w w . j a v a 2s. co m return file; }
From source file:com.github.podd.example.ExamplePoddClient.java
public Map<Path, String> uploadToStorage(final List<Path> bagsToUpload, final String sshServerFingerprint, final String sshHost, final int portNo, final String username, final Path pathToPublicKey, final Path localRootPath, final Path remoteRootPath, final PasswordFinder keyExtractor) throws PoddClientException, NoSuchAlgorithmException, IOException { final Map<Path, String> results = new ConcurrentHashMap<>(); final ConcurrentMap<Path, ConcurrentMap<PoddDigestUtils.Algorithm, String>> digests = PoddDigestUtils .getDigests(bagsToUpload);/*from w w w .j ava 2 s . c om*/ try (SSHClient sshClient = new SSHClient(ExamplePoddClient.DEFAULT_CONFIG);) { sshClient.useCompression(); sshClient.addHostKeyVerifier(sshServerFingerprint); sshClient.connect(sshHost, portNo); if (!Files.exists(pathToPublicKey)) { throw new PoddClientException("Could not find public key: " + pathToPublicKey); } if (!SecurityUtils.isBouncyCastleRegistered()) { throw new PoddClientException("Bouncy castle needed"); } final FileKeyProvider rsa = new PKCS8KeyFile(); rsa.init(pathToPublicKey.toFile(), keyExtractor); sshClient.authPublickey(username, rsa); // Session session = sshClient.startSession(); try (SFTPClient sftp = sshClient.newSFTPClient();) { for (final Path nextBag : bagsToUpload) { // Check to make sure that the bag was under the local root path final Path localPath = nextBag.toAbsolutePath(); if (!localPath.startsWith(localRootPath)) { this.log.error( "Local bag path was not a direct descendant of the local root path: {} {} {}", localRootPath, nextBag, localPath); throw new PoddClientException( "Local bag path was not a direct descendant of the local root path: " + localPath + " " + localRootPath); } // Take the local root path out to get the subpath to use on the remote final Path remoteSubPath = localPath.subpath(localRootPath.getNameCount(), nextBag.getNameCount() - 1); this.log.info("Remote sub path: {}", remoteSubPath); final Path remoteDirPath = remoteRootPath.resolve(remoteSubPath); this.log.info("Remote dir path: {}", remoteDirPath); final Path remoteBagPath = remoteDirPath.resolve(nextBag.getFileName()); this.log.info("Remote bag path: {}", remoteBagPath); boolean fileFound = false; boolean sizeCorrect = false; try { // check details of a remote bag final FileAttributes attribs = sftp.lstat(remoteBagPath.toAbsolutePath().toString()); final long localSize = Files.size(nextBag); final long remoteSize = attribs.getSize(); if (localSize <= 0) { this.log.error("Local bag was empty: {}", nextBag); sizeCorrect = false; fileFound = false; } else if (remoteSize <= 0) { this.log.warn("Remote bag was empty: {} {}", nextBag, attribs); sizeCorrect = false; fileFound = false; } else if (localSize == remoteSize) { this.log.info("Found file on remote already with same size as local: {} {}", nextBag, remoteBagPath); sizeCorrect = true; fileFound = true; } else { sizeCorrect = false; fileFound = true; // We always assume that a non-zero local file is correct // The bags contain time-stamps that will be modified when they are // regenerated, likely changing the file-size, and hopefully changing // the digest checksums // throw new PoddClientException( // "Could not automatically compare file sizes (need manual intervention to delete one) : " // + nextBag + " " + remoteBagPath + " localSize=" + localSize // + " remoteSize=" + remoteSize); } } catch (final IOException e) { // lstat() throws an IOException if the file does not exist // Ignore sizeCorrect = false; fileFound = false; } final ConcurrentMap<Algorithm, String> bagDigests = digests.get(nextBag); if (bagDigests.isEmpty()) { this.log.error("No bag digests were generated for bag: {}", nextBag); } for (final Entry<Algorithm, String> entry : bagDigests.entrySet()) { final Path localDigestPath = localPath .resolveSibling(localPath.getFileName() + entry.getKey().getExtension()); // Create the local digest file Files.copy( new ReaderInputStream(new StringReader(entry.getValue()), StandardCharsets.UTF_8), localDigestPath); final Path remoteDigestPath = remoteBagPath .resolveSibling(remoteBagPath.getFileName() + entry.getKey().getExtension()); boolean nextDigestFileFound = false; boolean nextDigestCorrect = false; try { final Path tempFile = Files.createTempFile("podd-digest-", entry.getKey().getExtension()); final SFTPFileTransfer sftpFileTransfer = new SFTPFileTransfer(sftp.getSFTPEngine()); sftpFileTransfer.download(remoteBagPath.toAbsolutePath().toString(), tempFile.toAbsolutePath().toString()); nextDigestFileFound = true; final List<String> allLines = Files.readAllLines(tempFile, StandardCharsets.UTF_8); if (allLines.isEmpty()) { nextDigestCorrect = false; } else if (allLines.size() > 1) { nextDigestCorrect = false; } // Check if the digests match exactly else if (allLines.get(0).equals(entry.getValue())) { nextDigestCorrect = true; } else { nextDigestCorrect = false; } } catch (final IOException e) { nextDigestFileFound = false; nextDigestCorrect = false; } if (nextDigestFileFound && nextDigestCorrect) { this.log.info( "Not copying digest to remote as it exists and contains the same content as the local digest"); } else if (nextDigestFileFound && !nextDigestCorrect) { this.log.error("Found remote digest but content was not correct: {} {}", localDigestPath, remoteDigestPath); sftp.rm(remoteDigestPath.toString()); this.log.info("Copying digest to remote: {}", remoteDigestPath); sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString()); } else if (!nextDigestFileFound) { this.log.info("About to make directories on remote: {}", remoteDirPath); sftp.mkdirs(remoteDirPath.toString()); this.log.info("Copying digest to remote: {}", remoteDigestPath); sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString()); } } if (fileFound && sizeCorrect) { this.log.info("Not copying bag to remote as it exists and is the same size as local bag"); } else if (fileFound && !sizeCorrect) { this.log.error("Found remote bag but size was not correct: {} {}", nextBag, remoteBagPath); sftp.rm(remoteBagPath.toString()); this.log.info("Copying bag to remote: {}", remoteBagPath); sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString()); } else if (!fileFound) { this.log.info("About to make directories on remote: {}", remoteDirPath); sftp.mkdirs(remoteDirPath.toString()); this.log.info("Copying bag to remote: {}", remoteBagPath); sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString()); } } } } catch (final IOException e) { throw new PoddClientException("Could not copy a bag to the remote location", e); } return results; }
From source file:org.tinymediamanager.core.entities.MediaFile.java
License:asdf
public void setFile(Path file) { setFilename(file.getFileName().toString()); setPath(file.toAbsolutePath().getParent().toString()); this.file = file.toAbsolutePath(); }
From source file:org.tinymediamanager.core.entities.MediaFile.java
License:asdf
/** * (re)sets the path (when renaming MediaEntity folder).<br> * Exchanges the beginning MF path from oldPath with newPath<br> * <br>//from w ww . jav a 2 s .com * eg: <br> * Params: /movie/alien1/ & /movie/Alien 1/<br> * File: /movie/alien1/asdf/jklo/file.avi -> /movie/Alien 1/asdf/jklo/file.avi<br> * <br> * this id done by a simple string.replace() * * @param oldPath * the old path * @param newPath * the new path */ public void replacePathForRenamedFolder(Path oldPath, Path newPath) { String p = getPath(); p = p.replace(oldPath.toAbsolutePath().toString(), newPath.toAbsolutePath().toString()); setPath(p); }
From source file:org.fao.geonet.kernel.harvest.harvester.geonet.Aligner.java
private void removeOldFile(String id, Element infoFiles, String dir) { Path resourcesDir = Lib.resource.getDir(context, dir, id); try (DirectoryStream<Path> paths = Files.newDirectoryStream(resourcesDir)) { for (Path file : paths) { if (file != null && file.getFileName() != null && infoFiles != null && !existsFile(file.getFileName().toString(), infoFiles)) { if (log.isDebugEnabled()) { log.debug(" - Removing old " + dir + " file with name=" + file.getFileName()); }/* w w w. jav a 2 s .com*/ try { Files.delete(file); } catch (IOException e) { log.warning("Unable to delete file: " + file); } } } } catch (IOException e) { log.error(" - Cannot scan directory for " + dir + " files : " + resourcesDir.toAbsolutePath().normalize()); } }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Creates TestStructure Files in the filesystem of a fitnesse backend * system. This method doesn't use the api for that and does no * notifications to the test-editor or fitnsse server. * //w w w.j a va 2s . c o m * @param destinationTestStructure * full name of the new one * @return true on success * @throws IOException * on creation error. */ public boolean createTestStructureFiles(String destinationTestStructure) { String[] tsNameParts = destinationTestStructure.split("\\."); try { String destPath = getWorkspacePath() + File.separator + tsNameParts[0] + File.separator + "FitNesseRoot" + File.separator + destinationTestStructure.replaceAll("\\.", Matcher.quoteReplacement(File.separator)); Path tsDir = Files.createDirectories(Paths.get(destPath)); LOGGER.trace("Created: " + tsDir.toAbsolutePath()); String xml = "<?xml version=\"1.0\"?><properties><Edit>true</Edit><Files>true</Files><Properties>true</Properties><RecentChanges>true</RecentChanges><Refactor>true</Refactor><Search>true</Search><Test/><Versions>true</Versions><WhereUsed>true</WhereUsed></properties>"; Files.write(Paths.get(destPath, "properties.xml"), xml.getBytes()); return new File(tsDir.toFile(), "content.txt").createNewFile(); } catch (Exception e) { LOGGER.error("Error creating testobject from " + destinationTestStructure, e); } return false; }
From source file:com.vmware.photon.controller.deployer.xenon.task.CreateManagementVmTaskService.java
private void processConfigIso(State currentState, VmService.State vmState, HostService.State hostState) throws Throwable { checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK)); checkState(//from w w w . j av a 2s. c o m hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER)); String gateway = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY); String ipAddress = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP); String netmask = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK); String dnsEndpointList = hostState.metadata .get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER); String allowedServices = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_ALLOWED_SERVICES); if (!Strings.isNullOrEmpty(dnsEndpointList)) { dnsEndpointList = Stream.of(dnsEndpointList.split(",")).map((dnsServer) -> "DNS=" + dnsServer + "\n") .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); } DeployerContext deployerContext = HostUtils.getDeployerContext(this); String scriptDirectory = deployerContext.getScriptDirectory(); String domainName = DOMAIN_NAME; if (currentState.oAuthTenantName != null) { domainName = currentState.oAuthTenantName; } String userDataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "user-data.template")), StandardCharsets.UTF_8) .replace("$GATEWAY", gateway) .replace("$ADDRESS", new SubnetUtils(ipAddress, netmask).getInfo().getCidrSignature()) .replace("$DOMAIN_NAME", domainName); if (currentState.ntpEndpoint != null) { userDataConfigFileContent = userDataConfigFileContent.replace("$NTP", currentState.ntpEndpoint); } // If auth is enabled and this VM is the lightwave server, then set dns to its own address and add domain name. // If auth is enabled and this VM is not the lightwave server, then set dns to lightwave VM address and add // domain name. // If auth is not enabled, then use the default dns server, don't set domain. if (currentState.isAuthEnabled && vmState.ipAddress.equals(currentState.oAuthServerAddress)) { userDataConfigFileContent = userDataConfigFileContent.replace("$DNS", "DNS=" + vmState.ipAddress) .replace("$DOMAINS", "Domains=" + domainName); } else if (currentState.isAuthEnabled) { userDataConfigFileContent = userDataConfigFileContent .replace("$DNS", "DNS=" + currentState.oAuthServerAddress) .replace("$DOMAINS", "Domains=" + domainName); } else { userDataConfigFileContent = userDataConfigFileContent.replace("$DNS", dnsEndpointList) .replace("\n $DOMAINS", ""); } String metadataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "meta-data.template")), StandardCharsets.UTF_8) .replace("$INSTANCE_ID", vmState.name).replace("$LOCAL_HOSTNAME", vmState.name); Path vmConfigDirectoryPath = Files.createTempDirectory("iso-" + currentState.vmId).toAbsolutePath(); Path userDataConfigFilePath = vmConfigDirectoryPath.resolve("user-data.yml"); Files.write(userDataConfigFilePath, userDataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path metadataConfigFilePath = vmConfigDirectoryPath.resolve("meta-data.yml"); Files.write(metadataConfigFilePath, metadataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path isoFilePath = vmConfigDirectoryPath.resolve("config.iso"); List<String> command = new ArrayList<>(); command.add("./" + SCRIPT_NAME); command.add(isoFilePath.toAbsolutePath().toString()); command.add(userDataConfigFilePath.toAbsolutePath().toString()); command.add(metadataConfigFilePath.toAbsolutePath().toString()); command.add(currentState.serviceConfigDirectory); File scriptLogFile = new File(deployerContext.getScriptLogDirectory(), SCRIPT_NAME + "-" + vmState.vmId + "-" + ServiceUtils.getIDFromDocumentSelfLink(currentState.documentSelfLink) + ".log"); ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec()) .directory(deployerContext.getScriptDirectory()) .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build(); ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner); HostUtils.getListeningExecutorService(this).submit(futureTask); Futures.addCallback(futureTask, new FutureCallback<Integer>() { @Override public void onSuccess(@javax.validation.constraints.NotNull Integer result) { try { if (result != 0) { logScriptErrorAndFail(currentState, result, scriptLogFile); } else { State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null); patchState.vmConfigDirectory = vmConfigDirectoryPath.toAbsolutePath().toString(); TaskUtils.sendSelfPatch(CreateManagementVmTaskService.this, patchState); } } catch (Throwable t) { failTask(t); } } @Override public void onFailure(Throwable throwable) { failTask(throwable); } }); }
From source file:org.tinymediamanager.core.movie.MovieList.java
/** * create a new offline movie with the given title in the specified data source * /*from w w w .ja v a2 s . co m*/ * @param title * the given title * @param datasource * the data source to create the offline movie in * @param mediaSource * the media source to be set for the offline movie */ public void addOfflineMovie(String title, String datasource, MediaSource mediaSource) { // first crosscheck if the data source is in our settings if (!movieSettings.getMovieDataSource().contains(datasource)) { return; } // check if there is already an identical stub folder int i = 1; Path stubFolder = Paths.get(datasource, title); while (Files.exists(stubFolder)) { stubFolder = Paths.get(datasource, title + "(" + i++ + ")"); } Path stubFile = stubFolder.resolve(title + ".disc"); // create the stub file try { Files.createDirectory(stubFolder); Files.createFile(stubFile); } catch (IOException e) { LOGGER.error("could not create stub file: " + e.getMessage()); return; } // create a movie and set it as MF MediaFile mf = new MediaFile(stubFile); mf.gatherMediaInformation(); Movie movie = new Movie(); movie.setTitle(title); movie.setPath(stubFolder.toAbsolutePath().toString()); movie.setDataSource(datasource); movie.setMediaSource(mediaSource); movie.setDateAdded(new Date()); movie.addToMediaFiles(mf); movie.setOffline(true); movie.setNewlyAdded(true); addMovie(movie); movie.saveToDb(); }
From source file:org.craftercms.commons.mongo.MongoScriptRunner.java
private List<String> getCommands(final Path scriptPath) throws MongoDataException { List<String> commandList = new ArrayList<>(); if (SystemUtils.IS_OS_WINDOWS) { commandList.add("CMD"); commandList.add("/C"); }/*from ww w . j a v a 2s .co m*/ if (StringUtils.isBlank(mongoClientBin)) { throw new MongoDataException("Unable to run scripts, mongo client bin path is not set "); } String pwd = null; String authSource = null; String user = null; MongoClientURI uri = new MongoClientURI(connectionStr); if (uri.getCredentials() != null) { authSource = uri.getCredentials().getSource(); user = uri.getCredentials().getUserName(); if (uri.getCredentials().getPassword() != null) { pwd = new String(uri.getCredentials().getPassword()); } } String replicaSetName = ""; if (uri.getHosts().size() > 1) { replicaSetName = uri.getOptions().getRequiredReplicaSetName() + "/"; } final String host = StringUtils.trim(replicaSetName + StringUtils.join(uri.getHosts(), ",")); commandList.add(mongoClientBin); commandList.add("--host"); commandList.add(host); commandList.add(uri.getDatabase()); if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(pwd) && StringUtils.isNotBlank(authSource)) { commandList.add("-u"); commandList.add(user); commandList.add("-p"); commandList.add(pwd); commandList.add("--authenticationDatabase"); commandList.add(authSource); } commandList.add(scriptPath.toAbsolutePath().toString()); return commandList; }
From source file:org.tinymediamanager.core.entities.MediaFile.java
License:asdf
/** * Instantiates a new media file./* w ww .j a v a 2s.co m*/ * * @param f * the file * @param type * the MediaFileType */ public MediaFile(Path f, MediaFileType type) { this.path = f.getParent().toString(); // just path w/o filename this.filename = f.getFileName().toString(); this.file = f.toAbsolutePath(); if (type == null) { this.type = parseType(); } else { this.type = type; } // set containerformat for non MI files if (!isValidMediainfoFormat() && StringUtils.isBlank(getContainerFormat())) { setContainerFormat(getExtension()); } }