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:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public boolean delete(String backendPath) throws C5CException {
    Path file = buildRealPath(backendPath);
    boolean isDir = Files.isDirectory(file);
    if (!Files.exists(file)) {
        logger.error("Requested file not exits: {}", file.toAbsolutePath());
        FilemanagerException.Key key = (isDir) ? FilemanagerException.Key.DirectoryNotExist
                : FilemanagerException.Key.FileNotExists;
        throw new FilemanagerException(FilemanagerAction.DELETE, key, file.getFileName().toString());
    }//from  w w  w.java 2 s  .  c  o  m
    boolean success = false;
    if (isDir) {
        try {
            FileUtils.deleteDirectory(file.toFile());
            success = true;
        } catch (IOException e) {
        }
    } else {
        try {
            Files.delete(file);
            success = true;
        } catch (IOException e) {
        }
    }
    if (!success)
        throw new FilemanagerException(FilemanagerAction.DELETE,
                FilemanagerException.Key.InvalidDirectoryOrFile, FilenameUtils.getName(backendPath));
    return isDir;
}

From source file:com.github.ferstl.depgraph.AbstractGraphMojo.java

private void createGraphImage() throws IOException {
    String graphFileName = createGraphFileName();
    Path graphFile = this.outputFile.toPath().getParent().resolve(graphFileName);

    String dotExecutable = determineDotExecutable();
    String[] arguments = new String[] { "-T", this.imageFormat, "-o", graphFile.toAbsolutePath().toString(),
            this.outputFile.getAbsolutePath() };

    Commandline cmd = new Commandline();
    cmd.setExecutable(dotExecutable);/* www.  j a v  a  2  s  .c  o  m*/
    cmd.addArguments(arguments);

    getLog().info("Running Graphviz: " + dotExecutable + " " + Joiner.on(" ").join(arguments));

    StringStreamConsumer systemOut = new StringStreamConsumer();
    StringStreamConsumer systemErr = new StringStreamConsumer();
    int exitCode;

    try {
        exitCode = CommandLineUtils.executeCommandLine(cmd, systemOut, systemErr);
    } catch (CommandLineException e) {
        throw new IOException("Unable to execute Graphviz", e);
    }

    Splitter lineSplitter = Splitter.on(LINE_SEPARATOR_PATTERN).omitEmptyStrings().trimResults();
    Iterable<String> output = Iterables.concat(lineSplitter.split(systemOut.getOutput()),
            lineSplitter.split(systemErr.getOutput()));

    for (String line : output) {
        getLog().info("  dot> " + line);
    }

    if (exitCode != 0) {
        throw new IOException("Graphviz terminated abnormally. Exit code: " + exitCode);
    }

    getLog().info("Graph image created on " + graphFile.toAbsolutePath());
}

From source file:de.bbe_consulting.mavento.MagentoInfoMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    initMojo();//www  . jav a  2  s.co m
    getLog().info("Scanning: " + magentoPath);
    getLog().info("");
    if (mVersion != null) {
        getLog().info("Version: Magento " + mVersion.toString());
    }

    // parse sql properties from local.xml
    final Path localXmlPath = Paths.get(magentoPath + "/app/etc/local.xml");
    Document localXml = null;
    if (Files.exists(localXmlPath)) {
        localXml = MagentoXmlUtil.readXmlFile(localXmlPath.toAbsolutePath().toString());
    } else {
        throw new MojoExecutionException(
                "Could not read or parse /app/etc/local.xml." + " Use -DmagentoPath= to set Magento dir.");
    }
    final Map<String, String> dbSettings = MagentoXmlUtil.getDbValues(localXml);
    final String jdbcUrl = MagentoSqlUtil.getJdbcUrl(dbSettings.get("host"), dbSettings.get("port"),
            dbSettings.get("dbname"));

    // fetch installdate
    final String magentoInstallDate = MagentoXmlUtil.getMagentoInstallData(localXml);
    getLog().info("Installed: " + magentoInstallDate);
    getLog().info("");

    // read baseUrl
    MagentoCoreConfig baseUrl = null;
    try {
        baseUrl = new MagentoCoreConfig("web/unsecure/base_url");
    } catch (Exception e) {
        throw new MojoExecutionException("Error creating config entry. " + e.getMessage(), e);
    }

    String sqlError = SQL_CONNECTION_VALID;
    try {
        baseUrl = MagentoSqlUtil.getCoreConfigData(baseUrl, dbSettings.get("user"), dbSettings.get("password"),
                jdbcUrl, getLog());
        getLog().info("URL: " + baseUrl.getValue());
        getLog().info("");
    } catch (MojoExecutionException e) {
        sqlError = e.getMessage();
    }

    getLog().info("Database: " + dbSettings.get("dbname") + " via " + dbSettings.get("user") + "@"
            + dbSettings.get("host") + ":" + dbSettings.get("port"));
    getLog().info("Connection: " + sqlError);
    getLog().info("");

    if (!skipSize) {
        MutableLong rootSizeTotal = new MutableLong();
        try {
            FileSizeVisitor fs = new FileSizeVisitor(rootSizeTotal);
            Files.walkFileTree(Paths.get(magentoPath), fs);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
        getLog().info(
                "Magento files total: " + String.format("%,8d", rootSizeTotal.toLong()).trim() + " bytes");
        if (SQL_CONNECTION_VALID.equals(sqlError)) {
            try {
                final Map<String, Integer> dbDetails = MagentoSqlUtil.getDbSize(dbSettings.get("dbname"),
                        dbSettings.get("user"), dbSettings.get("password"), jdbcUrl, getLog());
                final List<MysqlTable> logTableDetails = MagentoSqlUtil.getLogTablesSize(
                        dbSettings.get("dbname"), dbSettings.get("user"), dbSettings.get("password"), jdbcUrl,
                        getLog());
                getLog().info("Database total: " + String.format("%,8d", dbDetails.get("totalRows")).trim()
                        + " entries / " + String.format("%,8d", dbDetails.get("totalSize")).trim() + "mb");
                int logSizeTotal = 0;
                int logRowsTotal = 0;
                for (MysqlTable t : logTableDetails) {
                    logSizeTotal += t.getTableSizeInMb();
                    logRowsTotal += t.getTableRows();
                    if (showDetails) {
                        getLog().info(" " + t.getTableName() + ": " + t.getFormatedTableEntries()
                                + " entries / " + t.getFormatedTableSizeInMb() + "mb");
                    }
                }
                getLog().info("Log tables total: " + String.format("%,8d", logRowsTotal).trim() + " entries / "
                        + String.format("%,8d", logSizeTotal).trim() + "mb");
            } catch (MojoExecutionException e) {
                getLog().info("Error: " + e.getMessage());
            }
        }
        getLog().info("");
    }
    // parse modules
    final Path modulesXmlPath = Paths.get(magentoPath + "/app/etc/modules");
    if (!Files.exists(modulesXmlPath)) {
        throw new MojoExecutionException("Could not find /app/etc/modules directory.");
    }

    DirectoryStream<Path> files = null;
    final ArrayList<MagentoModule> localModules = new ArrayList<MagentoModule>();
    final ArrayList<MagentoModule> communityModules = new ArrayList<MagentoModule>();
    try {
        files = Files.newDirectoryStream(modulesXmlPath);
        for (Path path : files) {
            if (!path.getFileName().toString().startsWith("Mage")) {
                MagentoModule m = new MagentoModule(path);
                if (m.getCodePool().equals("local")) {
                    localModules.add(m);
                } else {
                    communityModules.add(m);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Could not read modules directory. " + e.getMessage(), e);
    } finally {
        try {
            files.close();
        } catch (IOException e) {
            throw new MojoExecutionException("Error closing directory stream. " + e.getMessage(), e);
        }
    }

    // print module sorted module list
    final MagentoModuleComperator mmc = new MagentoModuleComperator();
    Collections.sort(localModules, mmc);
    Collections.sort(communityModules, mmc);

    getLog().info("Installed modules in..");

    getLog().info("..local: ");
    for (MagentoModule m : localModules) {
        getLog().info(m.getNamespace() + "_" + m.getName() + " version: " + m.getVersion() + " active: "
                + m.isActive());
    }
    if (localModules.size() == 0) {
        getLog().info("--none--");
    }
    getLog().info("");

    getLog().info("..community: ");
    for (MagentoModule m : communityModules) {
        getLog().info(m.getNamespace() + "_" + m.getName() + " version: " + m.getVersion() + " active: "
                + m.isActive());
    }
    if (communityModules.size() == 0) {
        getLog().info("--none--");
    }
    getLog().info("");

    // check local overlays for content
    getLog().info("Overlay status..");
    int fileCount = -1;
    final File localMage = new File(magentoPath + "/app/code/local/Mage");
    if (localMage.exists()) {
        fileCount = localMage.list().length;
        if (fileCount > 0) {
            getLog().info("local/Mage: " + localMage.list().length + " file(s)");
        }
    }
    final File localVarien = new File(magentoPath + "/app/code/local/Varien");

    if (localVarien.exists()) {
        fileCount = localVarien.list().length;
        if (fileCount > 0) {
            getLog().info("local/Varien: " + localVarien.list().length + " file(s)");
        }
    }

    if (fileCount == -1) {
        getLog().info("..not in use.");
    }

}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testDirectoryPathsOverwriteFiles() throws InterruptedException, IOException {
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        // It seems very unlikely that a zip file would contain ".." paths, but handle it anyways.
        zip.putArchiveEntry(new ZipArchiveEntry("foo/bar"));
        zip.closeArchiveEntry();/*w w w .  j  a  va2s. c  o m*/
    }

    Path extractFolder = tmpFolder.newFolder();
    Files.write(extractFolder.resolve("foo"), ImmutableList.of("whatever"));

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo")));
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar")));
}

From source file:dk.dma.msinm.common.repo.RepositoryService.java

/**
 * Handles upload of files to the "temp" repo root.
 * Only the "user" role is required to upload to the "temp" root
 *
 * @param path the folder to upload to//from   w  w  w.j  a  v  a2s  .  co m
 * @param request the request
 */
@POST
@javax.ws.rs.Path("/upload-temp/{folder:.+}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
@RolesAllowed({ "user" })
public List<String> uploadTempFile(@PathParam("folder") String path, @Context HttpServletRequest request)
        throws FileUploadException, IOException {

    // Check that the specified folder is indeed under the "temp" root
    Path folder = repoRoot.resolve(path);
    if (!folder.toAbsolutePath().startsWith(getTempRepoRoot().toAbsolutePath())) {
        log.warn("Failed streaming file to temp root folder: " + folder);
        throw new WebApplicationException("Invalid upload folder: " + path, 403);
    }

    return uploadFile(path, request);
}

From source file:it.polimi.diceH2020.launcher.Experiment.java

@PostConstruct
private void init() throws IOException {
    INPUTDATA_ENDPOINT = settings.getFullAddress() + port + "/inputdata";
    EVENT_ENDPOINT = settings.getFullAddress() + port + "/event";
    STATE_ENDPOINT = settings.getFullAddress() + port + "/state";
    UPLOAD_ENDPOINT = settings.getFullAddress() + port + "/upload";
    SOLUTION_ENDPOINT = settings.getFullAddress() + port + "/solution";
    //SETTINGS_ENDPOINT = settings.getFullAddress() + port +"/settings";
    Path result = Paths.get(settings.getResultDir());
    if (!Files.exists(result))
        Files.createDirectory(result);
    RESULT_FOLDER = result.toAbsolutePath().toString();
}

From source file:org.ng200.openolympus.cerberus.compilers.FPCCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    FPCCompiler.logger.debug("Compiling {} to {} using FPC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("ppcx64");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-o" + outputFile.toAbsolutePath().toString()); // Set
    // outuput/*from ww w  .  j  a v a  2  s. c  om*/
    // file
    commandLine.addArgument("-l-");
    commandLine.addArgument("-v0");
    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input
    // files

    FPCCompiler.logger.debug("Running FPC with arguments: {}", commandLine.toString());

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(errorStream, null, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        FPCCompiler.logger.error("Could not execute FPC: {}", e);
        throw new CompilationException("Could not execute FPC", e);
    }
    switch (result) {
    case 0:
        return;
    case 1:
        try {
            final String errorString = errorStream.toString("UTF-8");

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.getFileName().toString()))
                            .collect(Collectors.joining("|")) + ")",
                    Pattern.MULTILINE);

            FPCCompiler.logger.debug("Compilation error: {}", errorString);

            throw new CompilerError("fpc.wrote.stdout", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.sakuli.utils.SakuliPropertyPlaceholderConfigurerTest.java

@Test
public void testModifySahiProxyPortInPropertyFile() throws Exception {
    Path targetProps = Paths.get(this.getClass().getResource("properties-test/target.properties").toURI());

    Properties basicProps = new Properties();
    basicProps.put(SahiProxyProperties.PROXY_PORT, "9000");
    testling.modifySahiProxyPortPropertiesConfiguration(targetProps.toAbsolutePath().toString(), basicProps);
    PropertiesConfiguration targetProfConf = new PropertiesConfiguration(targetProps.toFile());
    assertEquals(targetProfConf.getString(SahiProxyProperties.SAHI_PROPERTY_PROXY_PORT_MAPPING), "9000");

    testling.restoreProperties();//from   ww  w  .  ja v a  2 s.  c o  m
    targetProfConf = new PropertiesConfiguration(targetProps.toFile());
    assertEquals(targetProfConf.getString(SahiProxyProperties.SAHI_PROPERTY_PROXY_PORT_MAPPING), null);
}

From source file:com.bancvue.mongomigrate.CreateCommand.java

public int execute() {
    int exitCode = 0;
    Path file = null;
    try {/*from   www  .j a  va2  s  .  co m*/
        // Ensure migrations folder exists.
        Path folder = Paths.get(migrationsFolder);
        if (!Files.exists(folder)) {
            Files.createDirectories(folder);
        }

        // Generate filename and ensure it doesn't already exist.
        file = Paths.get(migrationsFolder, generateMigrationFileName(migrationName));
        if (Files.exists(file))
            throw new FileAlreadyExistsException(file.toAbsolutePath().toString());

        // Write the file.
        BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("UTF-8"));
        writer.write("// Add migration javascript here.\n");
        writer.write("db.<collection_name>.update(\n");
        writer.write("    { <query> },\n");
        writer.write("    { <update> },\n");
        writer.write("    { multi: true }\n");
        writer.write(");\n");
        writer.flush();
        writer.close();

        System.out.println("Created migration file: " + file.toString());

    } catch (FileAlreadyExistsException e) {
        System.err.println("The specified migration file " + file.toString() + " already exists.");
        exitCode = 1;
    } catch (IOException e) {
        e.printStackTrace();
        exitCode = 1;
    }
    return exitCode;
}

From source file:org.tinymediamanager.core.movie.entities.MovieSet.java

@Override
public String getArtworkFilename(final MediaFileType type) {
    String artworkFilename = super.getArtworkFilename(type);

    // we did not find an image - get the cached file from the url
    if (StringUtils.isBlank(artworkFilename)) {
        final String artworkUrl = getArtworkUrl(type);
        if (StringUtils.isNotBlank(artworkUrl)) {
            Path artworkFile = ImageCache.getCacheDir().resolve(ImageCache.getMD5(artworkUrl));
            if (Files.exists(artworkFile)) {
                artworkFilename = artworkFile.toAbsolutePath().toString();
            }/*from ww w.j  a  v  a 2  s.  c o m*/
        }
    }

    return artworkFilename;
}