Example usage for java.nio.file Path toAbsolutePath

List of usage examples for java.nio.file Path toAbsolutePath

Introduction

In this page you can find the example usage for java.nio.file Path toAbsolutePath.

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:org.roda.core.RodaCoreFactory.java

public static InputStream getConfigurationFileAsStream(String configurationFile) {
    Path config = getConfigPath().resolve(configurationFile);
    InputStream inputStream = null;
    try {//from  w w  w  . j a  v  a2s .  c o  m
        if (FSUtils.exists(config) && !FSUtils.isDirectory(config)
                && config.toAbsolutePath().startsWith(getConfigPath().toAbsolutePath().toString())) {
            inputStream = Files.newInputStream(config);
            LOGGER.trace("Loading configuration from file {}", config);
        }
    } catch (IOException e) {
        // do nothing
    }
    if (inputStream == null) {
        inputStream = RodaCoreFactory.class
                .getResourceAsStream("/" + RodaConstants.CORE_CONFIG_FOLDER + "/" + configurationFile);
        LOGGER.trace("Loading configuration from classpath {}", configurationFile);
    }
    return inputStream;
}

From source file:org.tinymediamanager.core.movie.MovieRenamer.java

/**
 * Rename movie.//from w w  w.ja v a 2  s  .  co m
 * 
 * @param movie
 *          the movie
 */
public static void renameMovie(Movie movie) {
    // FIXME: what? when?
    boolean posterRenamed = false;
    boolean fanartRenamed = false;
    boolean downloadMissingArtworks = false;

    // check if a datasource is set
    if (StringUtils.isEmpty(movie.getDataSource())) {
        LOGGER.error("no Datasource set");
        return;
    }

    // if (!movie.isScraped()) {
    if (movie.getTitle().isEmpty()) {
        LOGGER.error("won't rename movie '" + movie.getPathNIO() + "' / '" + movie.getTitle()
                + "' not even title is set?");
        return;
    }

    // all the good & needed mediafiles
    ArrayList<MediaFile> needed = new ArrayList<>();
    ArrayList<MediaFile> cleanup = new ArrayList<>();

    LOGGER.info("Renaming movie: " + movie.getTitle());
    LOGGER.debug("movie year: " + movie.getYear());
    LOGGER.debug("movie path: " + movie.getPathNIO());
    LOGGER.debug("movie isDisc?: " + movie.isDisc());
    LOGGER.debug("movie isMulti?: " + movie.isMultiMovieDir());
    if (movie.getMovieSet() != null) {
        LOGGER.debug("movieset: " + movie.getMovieSet().getTitle());
    }
    LOGGER.debug("path expression: " + MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname());
    LOGGER.debug("file expression: " + MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerFilename());

    String newPathname = createDestinationForFoldername(
            MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname(), movie);
    String oldPathname = movie.getPathNIO().toString();

    if (!newPathname.isEmpty()) {
        newPathname = movie.getDataSource() + File.separator + newPathname;
        Path srcDir = movie.getPathNIO();
        Path destDir = Paths.get(newPathname);
        if (!srcDir.toAbsolutePath().equals(destDir.toAbsolutePath())) {

            boolean newDestIsMultiMovieDir = false;
            // re-evaluate multiMovieDir based on renamer settings
            // folder MUST BE UNIQUE, we need at least a T/E-Y combo or IMDBid
            // so if renaming just to a fixed pattern (eg "$S"), movie will downgrade to a MMD
            if (!isFolderPatternUnique(MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerPathname())) {
                // FIXME: if we already in a normal dir - keep it?
                newDestIsMultiMovieDir = true;
            }
            // FIXME: add warning to GUI if downgrade!!!!!!
            LOGGER.debug("movie willBeMulti?: " + newDestIsMultiMovieDir);

            // ######################################################################
            // ## 1) old = separate movie dir, and new too -> move folder
            // ######################################################################
            if (!movie.isMultiMovieDir() && !newDestIsMultiMovieDir) {
                boolean ok = false;
                try {
                    ok = Utils.moveDirectorySafe(srcDir, destDir);
                    if (ok) {
                        movie.setMultiMovieDir(false);
                        movie.updateMediaFilePath(srcDir, destDir);
                        movie.setPath(newPathname);
                        movie.saveToDb(); // since we moved already, save it
                    }
                } catch (Exception e) {
                    LOGGER.error("error moving folder: ", e);
                    MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, srcDir,
                            "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
                }
                if (!ok) {
                    // FIXME: when we were not able to rename folder, display error msg and abort!!!
                    LOGGER.error("Could not move to destination '" + destDir + "' - NOT renaming folder");
                    return;
                }
            } else if (movie.isMultiMovieDir() && !newDestIsMultiMovieDir) {
                // ######################################################################
                // ## 2) MMD movie -> normal movie (upgrade)
                // ######################################################################
                LOGGER.trace("Upgrading movie into it's own dir :) " + newPathname);
                try {
                    Files.createDirectories(destDir);
                } catch (Exception e) {
                    LOGGER.error("Could not create destination '" + destDir
                            + "' - NOT renaming folder ('upgrade' movie)");
                    // well, better not to rename
                    return;
                }
                movie.setMultiMovieDir(false);
                downloadMissingArtworks = true; // yay - we upgraded our movie, so we could try to get additional artworks :)
            } else {
                // ######################################################################
                // ## Can be
                // ## 3) MMD movie -> MMD movie (but foldername possible changed)
                // ## 4) normal movie -> MMD movie (downgrade)
                // ## either way - check & create dest folder
                // ######################################################################
                LOGGER.trace("New movie path is a MMD :( " + newPathname);
                if (!Files.exists(destDir)) { // if existent, all is good -> MMD (FIXME: kinda, we *might* have another full movie in there)
                    try {
                        Files.createDirectories(destDir);
                    } catch (Exception e) {
                        LOGGER.error("Could not create destination '" + destDir
                                + "' - NOT renaming folder ('MMD' movie)");
                        // well, better not to rename
                        return;
                    }
                }
                movie.setMultiMovieDir(true);
            }
        } // src == dest
    } // folder pattern empty
    else {
        LOGGER.info("Folder rename settings were empty - NOT renaming folder");
        // set it to current for file renaming
        newPathname = movie.getPathNIO().toString();
    }

    // ######################################################################
    // ## mark ALL existing and known files for cleanup (clone!!)
    // ######################################################################
    for (MovieNfoNaming s : MovieNfoNaming.values()) {
        String nfoFilename = movie.getNfoFilename(s);
        if (StringUtils.isBlank(nfoFilename)) {
            continue;
        }
        // mark all known variants for cleanup
        MediaFile del = new MediaFile(movie.getPathNIO().resolve(nfoFilename), MediaFileType.NFO);
        cleanup.add(del);
    }
    for (MoviePosterNaming s : MoviePosterNaming.values()) {
        MediaFile del = new MediaFile(
                movie.getPathNIO()
                        .resolve(replaceInvalidCharacters(MovieArtworkHelper.getPosterFilename(s, movie))),
                MediaFileType.POSTER);
        cleanup.add(del);
    }
    for (MovieFanartNaming s : MovieFanartNaming.values()) {
        MediaFile del = new MediaFile(
                movie.getPathNIO()
                        .resolve(replaceInvalidCharacters(MovieArtworkHelper.getFanartFilename(s, movie))),
                MediaFileType.FANART);
        cleanup.add(del);
    }
    // cleanup ALL MFs
    for (MediaFile del : movie.getMediaFiles()) {
        cleanup.add(new MediaFile(del));
    }
    cleanup.removeAll(Collections.singleton(null)); // remove all NULL ones!

    // update movie path at end of renaming - we need the old one here!!
    // movie.setPath(newPathname);
    // movie.saveToDb();

    // BASENAME
    String newVideoBasename = "";
    if (!isFilePatternValid()) {
        // Template empty or not even title set, so we are NOT renaming any files
        // we keep the same name on renaming ;)
        newVideoBasename = movie.getVideoBasenameWithoutStacking();
        LOGGER.warn("Filepattern is not valid - NOT renaming files!");
    } else {
        // since we rename, generate the new basename
        MediaFile ftr = generateFilename(movie, movie.getMediaFiles(MediaFileType.VIDEO).get(0),
                newVideoBasename).get(0); // there can be only one
        newVideoBasename = FilenameUtils.getBaseName(ftr.getFilenameWithoutStacking());
    }
    LOGGER.debug("Our new basename for renaming: " + newVideoBasename);

    // unneeded / more reliable with with java 7?
    // // ######################################################################
    // // ## test VIDEO rename
    // // ######################################################################
    // for (MediaFile vid : movie.getMediaFiles(MediaFileType.VIDEO)) {
    // LOGGER.debug("testing file " + vid.getFileAsPath());
    // Path f = vid.getFileAsPath();
    // boolean testRenameOk = false;
    // for (int i = 0; i < 5; i++) {
    // testRenameOk = f.renameTo(f); // haahaa, try to rename to itself :P
    // if (testRenameOk) {
    // break; // ok it worked, step out
    // }
    // // we had the case, that the renaemoTo didn't work,
    // // and even the exists did not work!
    // // so we skip this additional check, which results in not removing the movie file
    // // if (!f.exists()) {
    // // LOGGER.debug("Hmmm... file " + f + " does not even exists; delete from DB");
    // // // delete from MF or ignore for later cleanup (but better now!)
    // // movie.removeFromMediaFiles(vid);
    // // testRenameOk = true; // we "tested" this ok
    // // break;
    // // }
    // try {
    // LOGGER.debug("rename did not work - sleep a while and try again...");
    // Thread.sleep(1000);
    // }
    // catch (InterruptedException e) {
    // LOGGER.warn("I'm so excited - could not sleep");
    // }
    // }
    // if (!testRenameOk) {
    // LOGGER.warn("File " + vid.getFileAsPath() + " is not accessible!");
    // MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, vid.getFilename(), "message.renamer.failedrename"));
    // return;
    // }
    // }

    // ######################################################################
    // ## rename VIDEO (move 1:1)
    // ######################################################################
    for (MediaFile vid : movie.getMediaFiles(MediaFileType.VIDEO)) {
        LOGGER.trace("Rename 1:1 " + vid.getType() + " " + vid.getFileAsPath());
        MediaFile newMF = generateFilename(movie, vid, newVideoBasename).get(0); // there can be only one
        boolean ok = moveFile(vid.getFileAsPath(), newMF.getFileAsPath());
        if (ok) {
            vid.setFile(newMF.getFileAsPath()); // update
        }
        needed.add(vid); // add vid, since we're updating existing MF object
    }

    // ######################################################################
    // ## rename POSTER, FANART (copy 1:N)
    // ######################################################################
    // we can have multiple ones, just get the newest one and copy(overwrite) them to all needed
    ArrayList<MediaFile> mfs = new ArrayList<>();
    mfs.add(movie.getNewestMediaFilesOfType(MediaFileType.FANART));
    mfs.add(movie.getNewestMediaFilesOfType(MediaFileType.POSTER));
    mfs.removeAll(Collections.singleton(null)); // remove all NULL ones!
    for (MediaFile mf : mfs) {
        LOGGER.trace("Rename 1:N " + mf.getType() + " " + mf.getFileAsPath());
        ArrayList<MediaFile> newMFs = generateFilename(movie, mf, newVideoBasename); // 1:N
        for (MediaFile newMF : newMFs) {
            posterRenamed = true;
            fanartRenamed = true;
            boolean ok = copyFile(mf.getFileAsPath(), newMF.getFileAsPath());
            if (ok) {
                needed.add(newMF);
            }
        }
    }

    // ######################################################################
    // ## rename NFO (copy 1:N) - only TMM NFOs
    // ######################################################################
    // we need to find the newest, valid TMM NFO
    MediaFile nfo = new MediaFile();
    for (MediaFile mf : movie.getMediaFiles(MediaFileType.NFO)) {
        if (mf.getFiledate() >= nfo.getFiledate() && MovieConnectors.isValidNFO(mf.getFileAsPath())) {
            nfo = new MediaFile(mf);
        }
    }

    if (nfo.getFiledate() > 0) { // one valid found? copy our NFO to all variants
        ArrayList<MediaFile> newNFOs = generateFilename(movie, nfo, newVideoBasename); // 1:N
        if (newNFOs.size() > 0) {
            // ok, at least one has been set up
            for (MediaFile newNFO : newNFOs) {
                boolean ok = copyFile(nfo.getFileAsPath(), newNFO.getFileAsPath());
                if (ok) {
                    needed.add(newNFO);
                }
            }
        } else {
            // list was empty, so even remove this NFO
            cleanup.add(nfo);
        }
    } else {
        LOGGER.trace("No valid NFO found for this movie");
    }

    // now iterate over all non-tmm NFOs, and add them for cleanup or not
    for (MediaFile mf : movie.getMediaFiles(MediaFileType.NFO)) {
        if (MovieConnectors.isValidNFO(mf.getFileAsPath())) {
            cleanup.add(mf);
        } else {
            if (MovieModuleManager.MOVIE_SETTINGS.isMovieRenamerNfoCleanup()) {
                cleanup.add(mf);
            } else {
                needed.add(mf);
            }
        }
    }

    // ######################################################################
    // ## rename all other types (copy 1:1)
    // ######################################################################
    mfs = new ArrayList<>();
    mfs.addAll(movie.getMediaFilesExceptType(MediaFileType.VIDEO, MediaFileType.NFO, MediaFileType.POSTER,
            MediaFileType.FANART, MediaFileType.SUBTITLE));
    mfs.removeAll(Collections.singleton(null)); // remove all NULL ones!
    for (MediaFile other : mfs) {
        LOGGER.trace("Rename 1:1 " + other.getType() + " " + other.getFileAsPath());

        ArrayList<MediaFile> newMFs = generateFilename(movie, other, newVideoBasename); // 1:N
        newMFs.removeAll(Collections.singleton(null)); // remove all NULL ones!
        for (MediaFile newMF : newMFs) {
            boolean ok = copyFile(other.getFileAsPath(), newMF.getFileAsPath());
            if (ok) {
                needed.add(newMF);
            } else {
                // FIXME: what to do? not copied/exception... keep it for now...
                needed.add(other);
            }
        }
    }

    // ######################################################################
    // ## rename subtitles later, but ADD it to not clean up
    // ######################################################################
    needed.addAll(movie.getMediaFiles(MediaFileType.SUBTITLE));

    // ######################################################################
    // ## invalidade image cache
    // ######################################################################
    for (MediaFile gfx : movie.getMediaFiles()) {
        if (gfx.isGraphic()) {
            ImageCache.invalidateCachedImage(gfx.getFileAsPath());
        }
    }

    // remove duplicate MediaFiles
    Set<MediaFile> newMFs = new LinkedHashSet<>(needed);
    needed.clear();
    needed.addAll(newMFs);

    movie.removeAllMediaFiles();
    movie.addToMediaFiles(needed);
    movie.setPath(newPathname);

    // update .actors
    for (MovieActor actor : movie.getActors()) {
        actor.setEntityRoot(newPathname);
    }

    movie.saveToDb();

    // cleanup & rename subtitle files
    renameSubtitles(movie);

    movie.gatherMediaFileInformation(false);

    // rewrite NFO if it's a MP NFO and there was a change with poster/fanart
    if (MovieModuleManager.MOVIE_SETTINGS.getMovieConnector() == MovieConnectors.MP
            && (posterRenamed || fanartRenamed)) {
        movie.writeNFO();
    }

    movie.saveToDb();

    // ######################################################################
    // ## CLEANUP - delete all files marked for cleanup, which are not "needed"
    // ######################################################################
    LOGGER.info("Cleanup...");
    for (int i = cleanup.size() - 1; i >= 0; i--) {
        // cleanup files which are not needed
        if (!needed.contains(cleanup.get(i))) {
            MediaFile cl = cleanup.get(i);
            if (cl.getFileAsPath().equals(Paths.get(movie.getDataSource()))
                    || cl.getFileAsPath().equals(movie.getPathNIO())
                    || cl.getFileAsPath().equals(Paths.get(oldPathname))) {
                LOGGER.warn("Wohoo! We tried to remove complete datasource / movie folder. Nooo way...! "
                        + cl.getType() + ": " + cl.getFileAsPath());
                // happens when iterating eg over the getNFONaming and we return a "" string.
                // then the path+filename = movie path and we want to delete :/
                // do not show an error anylonger, just silently ignore...
                // MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, cl.getFile(), "message.renamer.failedrename"));
                // return; // rename failed
                continue;
            }

            if (Files.exists(cl.getFileAsPath())) { // unneeded, but for not displaying wrong deletes in logger...
                LOGGER.debug("Deleting " + cl.getFileAsPath());
                Utils.deleteFileWithBackup(cl.getFileAsPath(), movie.getDataSource());
            }

            try (DirectoryStream<Path> directoryStream = Files
                    .newDirectoryStream(cl.getFileAsPath().getParent())) {
                if (!directoryStream.iterator().hasNext()) {
                    // no iterator = empty
                    LOGGER.debug("Deleting empty Directory " + cl.getFileAsPath().getParent());
                    Files.delete(cl.getFileAsPath().getParent()); // do not use recursive her
                }
            } catch (IOException ex) {
            }
        }
    }

    if (downloadMissingArtworks) {
        LOGGER.debug("Yay - movie upgrade :) download missing artworks");
        MovieArtworkHelper.downloadMissingArtwork(movie);
    }
}

From source file:org.apache.tika.batch.fs.FSBatchTestBase.java

public String[] getDefaultCommandLineArgsArr(String inputSubDir, Path outputDir,
        Map<String, String> commandLine) throws Exception {
    List<String> args = new ArrayList<>();
    //need to include "-" because these are going to the commandline!
    if (inputSubDir != null) {
        args.add("-inputDir");
        args.add(getInputRoot(inputSubDir).toAbsolutePath().toString());
    }/*w  w  w . ja  va2  s.c o m*/
    if (outputDir != null) {
        args.add("-outputDir");
        args.add(outputDir.toAbsolutePath().toString());
    }
    if (commandLine != null) {
        for (Map.Entry<String, String> e : commandLine.entrySet()) {
            args.add(e.getKey());
            args.add(e.getValue());
        }
    }
    return args.toArray(new String[args.size()]);
}

From source file:org.carcv.impl.core.io.FFMPEGVideoHandlerIT.java

@Test
public void testCreateVideoInternal() throws IOException, InterruptedException {
    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);

    DirectoryStream<Path> testpaths = Files.newDirectoryStream(videoDir);
    int counterTest = 0;
    for (Path p : testpaths) {
        assertTrue(Files.exists(p));
        counterTest++;//from www  . java2  s . c o m
    }
    assertEquals(2, counterTest);

    DirectoryStream<Path> paths = Files.newDirectoryStream(videoDir);
    String imageSuffix = ".invalid";
    for (Path p : paths) {
        imageSuffix = FFMPEGVideoHandler.getSuffix(p);
        if (imageSuffix != null)
            break;
    }

    Path output = Paths.get("/tmp",
            "video-" + new Random().nextInt() + "-" + System.currentTimeMillis() + "." + "mjpeg");

    String command = "ffmpeg -y -f image2 -pattern_type glob -i \"" + videoDir.toAbsolutePath().toString()
            + File.separator + "*." + imageSuffix + "\" -r " + 2 + " " + output.toAbsolutePath().toString();

    LOGGER.info("Executing: " + command);
    Process p = Runtime.getRuntime().exec(command);
    LOGGER.debug(getErrorMessage(p.getErrorStream()));

    LOGGER.debug("Return value: {}", p.waitFor());

    assertTrue(Files.exists(output));
    LOGGER.debug("Path of created video: {}", output);
}

From source file:com.yahoo.rdl.maven.RdlExecutableFileProviderImpl.java

@Override
public Path getRdlExecutableFile() throws MojoExecutionException {
    if (configuredExecutableFile != null) {
        return configuredExecutableFile;
    }/*w  ww. j  a  v  a  2 s  . c o  m*/
    if (actualExecutableFile != null) {
        return actualExecutableFile;
    }
    File binFolder = new File(scratchSpace.toFile(), "bin");
    if (!binFolder.mkdirs() && !binFolder.exists()) {
        throw new MojoExecutionException("Unable to create folder for rdl executable: " + binFolder);
    }

    Path rdlBinaryPath = scratchSpace.resolve(Paths.get("bin", "rdl"));
    try (OutputStream os = Files.newOutputStream(rdlBinaryPath, StandardOpenOption.CREATE)) {
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("bin/" + osName + "/rdl")) {
            IOUtils.copy(is, os);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to write rdl binary to " + rdlBinaryPath, e);
    }
    if (!rdlBinaryPath.toFile().setExecutable(true) && !rdlBinaryPath.toFile().canExecute()) {
        throw new MojoExecutionException("Unable to chmod +x executable: " + rdlBinaryPath.toAbsolutePath());
    }

    Path rdlGenSwaggerBinaryPath = scratchSpace.resolve(Paths.get("bin", "rdl-gen-swagger"));
    try (OutputStream os = Files.newOutputStream(rdlGenSwaggerBinaryPath, StandardOpenOption.CREATE)) {
        try (InputStream is = getClass().getClassLoader()
                .getResourceAsStream("bin/" + osName + "/rdl-gen-swagger")) {
            IOUtils.copy(is, os);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to write rdl-gen-swagger binary to " + rdlBinaryPath, e);
    }
    if (!rdlGenSwaggerBinaryPath.toFile().setExecutable(true)
            && !rdlGenSwaggerBinaryPath.toFile().canExecute()) {
        throw new MojoExecutionException("Unable to chmod +x executable: " + rdlBinaryPath.toAbsolutePath());
    }

    actualExecutableFile = rdlBinaryPath;
    return rdlBinaryPath;
}

From source file:org.talend.dataprep.cache.file.FileSystemContentCache.java

private Path findEntry(ContentCacheKey key) {
    final Path path = computeEntryPath(key, null);
    final File[] files = path.getParent().toFile().listFiles();
    if (files != null) {
        for (File file : files) {
            if (!StringUtils.startsWith(file.getName(), key.getKey())) {
                LOGGER.trace("file {} does not match key {}", file.getName(), key.getKey());
                continue;
            }//from w  ww. j a va2  s.co m
            if (Paths.get(file.toURI()).equals(path.toAbsolutePath())) {
                LOGGER.debug("cache entry for #{} is {}", key, file.toPath());
                return file.toPath();
            }
            final String suffix = StringUtils.substringAfterLast(file.getName(), ".");
            if (isLiveEntry(suffix)) {
                LOGGER.debug("cache entry for #{} is {}", key, file.toPath());
                return file.toPath();
            }
        }
    }
    LOGGER.debug("No cache for entry #{}", key);
    return null;
}

From source file:org.n52.movingcode.runtime.coderepository.LocalVersionedFileRepository.java

private final synchronized void reloadContent() {

    PackageInventory newInventory = new PackageInventory();

    // obtain all immediate subfolders
    Path repoRoot = FileSystems.getDefault().getPath(directory.getAbsolutePath());
    Collection<Path> packageFolders = listSubdirs(repoRoot);

    LOGGER.info("Scanning directory: " + directory.getAbsolutePath());

    for (Path currentFolder : packageFolders) {

        // attempt to read packageDescription XML
        File packageDescriptionFile = new File(currentFolder.toFile(), Constants.PACKAGE_DESCRIPTION_XML);
        // deal with empty inventory folders
        if (!packageDescriptionFile.exists()) {
            // TODO: remove such invalid folders?
            LOGGER.warn("Found empty inventory folder: " + currentFolder.toAbsolutePath());
            continue; // skip this and immediately jump to the next iteration
        }/*from   ww  w  .ja  v  a 2  s  .c o m*/

        PackageDescriptionDocument pd;
        try {
            pd = PackageDescriptionDocument.Factory.parse(packageDescriptionFile);
        } catch (XmlException e) {
            // silently skip this and immediately jump to the next iteration
            continue;
        } catch (IOException e) {
            // silently skip this and immediately jump to the next iteration
            continue;
        }

        // packageID = absolute path
        LOGGER.info(
                "Found package: " + currentFolder + "; using ID: " + RepositoryUtils.extractId(pd).toString());

        // attempt to access workspace root folder
        String workspace = pd.getPackageDescription().getWorkspace().getWorkspaceRoot();
        if (workspace.startsWith("./")) {
            workspace = workspace.substring(2); // remove leading "./" if it exists
        }

        File workspaceDir = new File(currentFolder.toFile(), workspace);
        if (!workspaceDir.exists()) {
            continue; // skip this and immediately jump to the next iteration
        }

        MovingCodePackage mcPackage = new MovingCodePackage(workspaceDir, pd);

        // validate
        // and add to package map
        // and add current file to zipFiles map
        if (mcPackage.isValid()) {
            newInventory.add(mcPackage);
            LOGGER.info(
                    "Found package: " + currentFolder + "; using ID: " + mcPackage.getPackageId().toString());
        } else {
            LOGGER.error(currentFolder + " is an invalid package.");
        }
    }

    // announce new content scan
    updateInventory(newInventory);
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkGrantedUsingSpecificFiltersWithDirectoryListingEnabled()
        throws IOException, URISyntaxException {

    HttpParams params = new SyncBasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    HttpConnectionParams.setSoTimeout(params, 300000);

    TestHttpClient client = new TestHttpClient(params);

    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {//from w w  w .  ja  v  a  2s . com
        DefaultServer.setRootHandler(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true,
                        rootPath.toAbsolutePath().toString().concat("/newDir")))
                                .setDirectoryListingEnabled(false).addWelcomeFiles("page.html")));
        /**
         * This request should return a 200 code as rootPath + "/newDir" is used in the safePaths
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/.");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());
        Assert.assertTrue(response, response.contains("A web page"));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.roda.core.RodaCoreFactory.java

public static InputStream getDefaultFileAsStream(String defaultFile, ClassLoader... extraClassLoaders) {
    Path defaultPath = getDefaultPath().resolve(defaultFile);
    InputStream inputStream = null;
    try {//ww w .j ava2 s  .c o  m
        if (FSUtils.exists(defaultPath) && !FSUtils.isDirectory(defaultPath)
                && defaultPath.toAbsolutePath().startsWith(getDefaultPath().toAbsolutePath().toString())) {
            inputStream = Files.newInputStream(defaultPath);
            LOGGER.debug("Trying to load default from file {}", defaultPath);
        }
    } catch (IOException e) {
        // do nothing
    }

    if (inputStream == null) {
        String fileClassPath = "/" + RodaConstants.CORE_DEFAULT_FOLDER + "/" + defaultFile;
        inputStream = RodaCoreFactory.class.getResourceAsStream(fileClassPath);
        LOGGER.debug("Trying to load default file from classpath {}", fileClassPath);
    }

    if (inputStream == null) {
        String fileClassPath = RodaConstants.CORE_DEFAULT_FOLDER + "/" + defaultFile;
        for (ClassLoader classLoader : extraClassLoaders) {
            LOGGER.debug("Trying to load default file from extra class loader {}", fileClassPath);
            inputStream = classLoader.getResourceAsStream(fileClassPath);
            if (inputStream != null) {
                break;
            }
        }
    }

    return inputStream;
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private void commitUpdates(StorageRequest request) throws StorageException {
    try {//from ww w  .ja v  a 2s  .c om
        for (String contentUri : updateMap.get(request.getId())) {
            Path contentIdDir = getTempContentItemDir(request.getId(), new URI(contentUri));
            Path target = getContentItemDir(new URI(contentUri));
            try {
                if (Files.exists(contentIdDir)) {
                    if (Files.exists(target)) {
                        List<Path> files = listPaths(target);
                        for (Path file : files) {
                            if (!Files.isDirectory(file)) {
                                Files.deleteIfExists(file);
                            }
                        }
                    }
                    Files.createDirectories(target.getParent());
                    Files.move(contentIdDir, target, StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (IOException e) {
                LOGGER.debug(
                        "Unable to move files by simple rename, resorting to copy. This will impact performance.",
                        e);
                try {
                    Path createdTarget = Files.createDirectories(target);
                    List<Path> files = listPaths(contentIdDir);
                    Files.copy(files.get(0), Paths.get(createdTarget.toAbsolutePath().toString(),
                            files.get(0).getFileName().toString()));
                } catch (IOException e1) {
                    throw new StorageException("Unable to commit changes for request: " + request.getId(), e1);
                }
            }
        }
    } catch (URISyntaxException e) {
        throw new StorageException(e);
    } finally {
        rollback(request);
    }
}