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.tinymediamanager.ui.TmmUIHelper.java

public static void openFile(Path file) throws Exception {
    String fileType = "." + FilenameUtils.getExtension(file.getFileName().toString());
    String abs = file.toAbsolutePath().toString();

    if (StringUtils.isNotBlank(Globals.settings.getMediaPlayer())
            && Globals.settings.getAllSupportedFileTypes().contains(fileType)) {
        if (SystemUtils.IS_OS_MAC_OSX) {
            Runtime.getRuntime()//  w  w w  .  j a v  a 2s .  c  o m
                    .exec(new String[] { "open", Globals.settings.getMediaPlayer(), "--args", abs });
        } else {
            Runtime.getRuntime().exec(new String[] { Globals.settings.getMediaPlayer(), abs });
        }
    } else if (SystemUtils.IS_OS_WINDOWS) {
        // use explorer directly - ship around access exceptions and the unresolved network bug
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6780505
        Runtime.getRuntime().exec(new String[] { "explorer", abs });
    } else if (SystemUtils.IS_OS_LINUX) {
        // try all different starters
        boolean started = false;
        try {
            Runtime.getRuntime().exec(new String[] { "gnome-open", abs });
            started = true;
        } catch (IOException e) {
        }

        if (!started) {
            try {
                Runtime.getRuntime().exec(new String[] { "kde-open", abs });
                started = true;
            } catch (IOException e) {
            }
        }

        if (!started) {
            try {
                Runtime.getRuntime().exec(new String[] { "xdg-open", abs });
                started = true;
            } catch (IOException e) {
            }
        }

        if (!started && Desktop.isDesktopSupported()) {
            Desktop.getDesktop().open(file.toFile());
        }
    } else if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().open(file.toFile());

    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.external339.AFConfigurationProcessor.java

static Path resolvePath(Path file, String workingDirectory) {
    return file == null ? null
            : (file.isAbsolute() ? file//from w ww.  j a  v  a 2 s . co  m
                    : (file.getFileName().startsWith(File.separator) ? file.toAbsolutePath()
                            : (Paths.get(workingDirectory, file.getFileName().toString()))));
}

From source file:abfab3d.shapejs.Project.java

/**
 * Load a project/*from   w  w  w  . j a  v a2s . c  o m*/
 *
 * @param file
 * @throws IOException
 */
public static Project load(String file) throws IOException {
    Path workingDirName = Files.createTempDirectory("loadScript");
    String resultDirPath = workingDirName.toAbsolutePath().toString();

    Project ret_val = new Project();
    Map<String, String> sceneFiles = new HashMap<String, String>();
    List<String> m_resources = new ArrayList<String>();

    if (file.endsWith(".zip")) {
        extractZip(file, resultDirPath, sceneFiles, m_resources);
    } else if (file.endsWith(".js")) {
        sceneFiles.put("scriptFile", file);
    } else {
        throw new IllegalArgumentException("File type must be .js or .zip");
    }

    String scriptFilePath = sceneFiles.get("scriptFile");
    String paramFilePath = sceneFiles.get("paramFile");
    System.out.println("scriptFilePath: " + scriptFilePath);
    System.out.println("paramFilePath: " + paramFilePath);

    if (scriptFilePath == null) {
        throw new IllegalArgumentException("Missing script file");
    }

    File scriptFile = new File(scriptFilePath);
    String code = FileUtils.readFileToString(scriptFile, "UTF-8");
    EvaluatedScript evalResult = null;
    ShapeJSEvaluator evaluator = new ShapeJSEvaluator();

    if (paramFilePath != null) {
        Gson gson = JSONParsing.getJSONParser();
        String paramsJson = FileUtils.readFileToString(new File(paramFilePath), "UTF-8");
        Map<String, Object> scriptParams = gson.fromJson(paramsJson, Map.class);

        evalResult = evaluator.evalScript(code, null, scriptParams);
    } else {
        evalResult = evaluator.evalScript(code, null, null);
    }

    URI uri = new File(file).toURI();
    Script script = new Script(uri, evalResult);
    Map<String, Parameter> scriptParams = evalResult.getParamMap();

    ret_val.setScript(script);

    return ret_val;
}

From source file:org.ng200.openolympus.FileAccess.java

public static void rsync(final Path from, final Path to) throws IOException {
    final CommandLine commandLine = new CommandLine("/usr/bin/rsync");
    commandLine.addArgument("-r");
    commandLine.addArgument("--ignore-errors");
    commandLine.addArgument(from.toAbsolutePath().toString());
    commandLine.addArgument(to.toAbsolutePath().toString());
    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete//from   w w  w  .  j a  va2 s  . c  o  m
    final ByteArrayOutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));
    executor.setExitValues(new int[] { 0 });
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        throw new IOException("Rsync failed:\n" + outAndErr.toString(), e);
    }
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

private static Path pack(final Path folder, JsonObject graph, String tkName)
        throws IOException, URISyntaxException {
    String namespace = splAppNamespace(graph);
    String name = splAppName(graph);

    Path zipFilePath = Paths.get(folder.toAbsolutePath().toString() + ".zip");
    String workingDir = zipFilePath.getParent().toString();

    Path topologyToolkit = TkInfo.getTopologyToolkitRoot().getAbsoluteFile().toPath();

    // Paths to copy into the toolkit
    Map<Path, String> paths = new HashMap<>();

    // tkManifest is the list of toolkits contained in the archive
    try (PrintWriter tkManifest = new PrintWriter("manifest_tk.txt", "UTF-8")) {
        tkManifest.println(tkName);/*  w  w w.  j  a  v  a  2s  .  c o  m*/
        tkManifest.println("com.ibm.streamsx.topology");

        JsonObject configSpl = object(graph, CONFIG, "spl");
        if (configSpl != null) {
            objectArray(configSpl, "toolkits", tk -> {
                File tkRoot = new File(jstring(tk, "root"));
                String tkRootName = tkRoot.getName();
                tkManifest.println(tkRootName);
                paths.put(tkRoot.toPath(), tkRootName);
            });
        }
    }

    // mainComposite is a string of the namespace and the main composite.
    // This is used by the Makefile
    try (PrintWriter mainComposite = new PrintWriter("main_composite.txt", "UTF-8")) {
        mainComposite.print(namespace + "::" + name);
    }

    Path manifest = Paths.get(workingDir, "manifest_tk.txt");
    Path mainComp = Paths.get(workingDir, "main_composite.txt");
    Path makefile = topologyToolkit
            .resolve(Paths.get("opt", "python", "templates", "common", "Makefile.template"));

    paths.put(topologyToolkit, topologyToolkit.getFileName().toString());
    paths.put(manifest, "manifest_tk.txt");
    paths.put(mainComp, "main_composite.txt");
    paths.put(makefile, "Makefile");
    paths.put(folder, folder.getFileName().toString());

    addAllToZippedArchive(paths, zipFilePath);
    manifest.toFile().delete();
    mainComp.toFile().delete();

    return zipFilePath;
}

From source file:omm.OMMEnhancer.java

public static Path unpack(InputStream zipStream) throws IOException {
    Path unpackedApplication = Files.createTempDirectory("unpacked");

    File file = File.createTempFile("gate", "zip");
    FileUtils.copyInputStreamToFile(zipStream, file);

    try {//  w  w w  .  j  a  va  2 s  .  com
        ZipFile zipFile = new ZipFile(file);
        zipFile.extractAll(unpackedApplication.toAbsolutePath().toString());
    } catch (ZipException e) {
        e.printStackTrace();
    }
    log.info("unpacked gate to " + unpackedApplication.toString());
    return unpackedApplication;
}

From source file:org.sonar.java.it.JavaRulingTest.java

private static void prepareDumpOldFolder() {
    Path allRulesFolder = Paths.get("src/test/resources");
    if (SUBSET_OF_ENABLED_RULES.isEmpty()) {
        effectiveDumpOldFolder = allRulesFolder.toAbsolutePath();
    } else {//ww w.  j  a va2  s .co m
        effectiveDumpOldFolder = TMP_DUMP_OLD_FOLDER.getRoot().toPath().toAbsolutePath();
        Try.of(() -> Files.list(allRulesFolder)).orElseThrow(Throwables::propagate)
                .filter(p -> p.toFile().isDirectory()).forEach(srcProjectDir -> copyDumpSubset(srcProjectDir,
                        effectiveDumpOldFolder.resolve(srcProjectDir.getFileName())));
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.app.Main.java

private static void loadConfiguration() {
    Path defaultConfigPath = workingDirectory.resolve(CONFIGURATION_FILENAME);
    logger.debug("Searching for config in default filepath: " + defaultConfigPath.toAbsolutePath().toString());

    try {//from   w  w w  .j  ava  2  s  .  c  om
        logger.debug("Loading configuration.");

        config = new PropertiesConfiguration(defaultConfigPath.toFile());

    } catch (ConfigurationException e) {
        logger.error(e.getMessage(), e);
        logger.error("Configuration could not be loaded. Exiting...");
        System.exit(-1);
    }

    if (!(defaultConfigPath.toFile().exists() && defaultConfigPath.toFile().isFile())) {
        try {
            logger.info("Creating empty config file in working directory...");
            config.save();
            logger.debug("Saved empty configuration: " + defaultConfigPath.toAbsolutePath().toString());
        } catch (ConfigurationException e) {
            logger.error("Default configuration file could not be saved!");
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.esa.s2tbx.dataio.openjpeg.OpenJpegUtils.java

/**
 * Get the tile layout with opj_dump/*from  w  ww  . j  a  v  a2  s .  c om*/
 *
 * @param opjdumpPath path to opj_dump
 * @param jp2FilePath the path to the jpeg file
 * @return the tile layout for the openjpeg file
 * @throws IOException
 * @throws InterruptedException
 */
public static TileLayout getTileLayoutWithOpenJPEG(String opjdumpPath, Path jp2FilePath)
        throws IOException, InterruptedException {

    if (opjdumpPath == null) {
        throw new IllegalStateException("Cannot retrieve tile layout, opj_dump cannot be found");
    }

    TileLayout tileLayout;

    String pathToImageFile = jp2FilePath.toAbsolutePath().toString();
    if (SystemUtils.IS_OS_WINDOWS) {
        pathToImageFile = Utils.GetIterativeShortPathName(pathToImageFile);
    }

    ProcessBuilder builder = new ProcessBuilder(opjdumpPath, "-i", pathToImageFile);
    builder.redirectErrorStream(true);

    CommandOutput exit = OpenJpegUtils.runProcess(builder);

    if (exit.getErrorCode() != 0) {
        StringBuilder sbu = new StringBuilder();
        for (String fragment : builder.command()) {
            sbu.append(fragment);
            sbu.append(' ');
        }

        throw new IOException(
                String.format("Command [%s] failed with error code [%d], stdoutput [%s] and stderror [%s]",
                        sbu.toString(), exit.getErrorCode(), exit.getTextOutput(), exit.getErrorOutput()));
    }
    tileLayout = OpenJpegUtils.parseOpjDump(exit.getTextOutput());

    return tileLayout;
}

From source file:org.audiveris.omr.log.LogUtil.java

/**
 * Start a specific file logging, typically for the processing of a given book.
 *
 * @param name      appender name (typically the book radix)
 * @param logFolder target folder where the log file is to be written
 *//*from  w  ww. j  a  va 2 s. co m*/
public static void addAppender(String name, Path logFolder) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    FileAppender fileAppender = new FileAppender();
    PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder();
    fileAppender.setName(name);
    fileAppender.setContext(loggerContext);
    fileAppender.setAppend(false);

    String now = new SimpleDateFormat("yyyyMMdd'T'HHmm").format(new Date());
    Path logFile = logFolder.resolve(name + "-" + now + ".log");
    fileAppender.setFile(logFile.toAbsolutePath().toString());
    fileEncoder.setContext(loggerContext);
    fileEncoder.setPattern("%date %level [%X{BOOK}%X{SHEET}] %25file:%-4line | %msg%n%ex");
    fileEncoder.start();
    fileAppender.setEncoder(fileEncoder);
    fileAppender.start();
    root.addAppender(fileAppender);
}