Example usage for java.nio.file Path toString

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

Introduction

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

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:istata.web.HtmlController.java

@RequestMapping(value = { "/edit \"**", "/edit \"**/**" })
@ResponseBody/*from   w w  w . j av  a 2 s  . co m*/
public String edit(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model)
        throws IOException {

    String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    stataService.saveCmd(path);

    path = path.substring(7, path.length() - 1);

    Path dofile = Paths.get(path).toAbsolutePath();

    if (dofile.toString().equals(path) && dofile.toFile().exists()) {
        model.put("content", stataService.loadDoFile(path).getContent());
        model.put("title", path);

        return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "edit.vm", "UTF-8", model);
    } else {
        path = stataService.expandPath(path);

        dofile = Paths.get(path).toAbsolutePath();

        if (dofile.toFile().exists()) {
            response.sendRedirect("/edit \"" + dofile.toAbsolutePath().toString() + "\"");
            return null;
        } else {
            // TODO maybe this can be done more graceful
            throw new NoSuchFileException(path);
        }
    }

}

From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallPropertiesTask.java

@Override
public void run(MicroServiceTask task) throws InvalidInstallationException {
    Path msVersionFolder = helper.targetDirOf(task.getMs());

    byte[] content = msService.getContentOfProperties(task.getMs().getName());
    Path applicationProp = Paths.get(msVersionFolder.toString(), "application.properties");
    try {/* ww w. j a  va2  s .c om*/
        Files.write(applicationProp, content);
        LOG.info("Cration du fichier de proprits {}", applicationProp.toAbsolutePath());
    } catch (IOException ex) {
        throw new InvalidInstallationException("Impossible d'installer le fichier de properties", ex);
    }
}

From source file:com.dickthedeployer.dick.web.service.CommandService.java

public String invoke(Path workingDir, String... command) throws RuntimeException {
    try {// ww w  .  ja  v  a  2  s.c om
        log.info("Executing command {} in path {}", Arrays.toString(command), workingDir.toString());
        StringBuilder text = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(workingDir.toFile());
        builder.redirectErrorStream(true);

        Process process = builder.start();

        try (Scanner s = new Scanner(process.getInputStream())) {
            while (s.hasNextLine()) {
                text.append(s.nextLine());
            }
            int result = process.waitFor();
            log.info("Process exited with result {} and output {}", result, text);

            if (result != 0) {
                throw new CommandExecutionException();
            }
            return text.toString();
        }
    } catch (IOException | InterruptedException ex) {
        throw new CommandExecutionException(ex);
    }
}

From source file:gumga.framework.application.template.GumgaFreemarkerTemplateEngineTest.java

@Before
public void startup() throws Exception {
    URL resourceUrl = getClass().getResource("/templates");
    Path resourcePath = Paths.get(resourceUrl.toURI());
    gumgaFreemarkerTemplateEngineService = new GumgaFreemarkerTemplateEngineService(resourcePath.toString(),
            "UTF-8");
    gumgaFreemarkerTemplateEngineService.init();
    assertNotNull(gumgaFreemarkerTemplateEngineService);
    gumgaFreemarkerTemplateEngineService.init();
    createOutputFolder(OUTPUT_FOLDER);// www  . j  a  va  2 s .c  o m
}

From source file:org.balloon_project.overflight.task.importer.ImporterFileListener.java

@Override
public void run() {
    // TODO initial import start
    // initial import of existing file
    logger.info("Scanning for files to import");
    File importDir = new File(configuration.getDatabaseImportDirectory());
    if (importDir.exists() && importDir.isDirectory()) {
        for (File file : importDir.listFiles()) {
            if (file.isFile() && file.getPath().endsWith(IndexingTask.N_TRIPLES_EXTENSION)) {
                logger.info("File event: Adding " + file.toString() + " to importer queue");
                importer.startImporting(file);
            }//from  ww w.  j a v  a2  s.c om
        }
    }

    // starting file watch service for future files
    try {
        String path = configuration.getDatabaseImportDirectory();
        logger.info("Starting import file listener for path " + path);
        Path tmpPath = Paths.get(path);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        for (;;) {
            WatchKey key = watchService.take();

            for (WatchEvent event : key.pollEvents()) {
                if (event.kind().name() == "OVERFLOW") {
                    continue;
                } else {
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    logger.info("File event: Adding " + filename.toString() + " to importer queue");
                    importer.startImporting(tmpPath.resolve(filename).toFile());
                }
            }

            // Reset the key -- this step is critical if you want to
            // receive further watch events.  If the key is no longer valid,
            // the directory is inaccessible so exit the loop.
            boolean valid = key.reset();
            if (!valid) {
                break;
            }

        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        logger.debug("Stopping import file listener");
    }
}

From source file:com.yahoo.parsec.gradle.ParsecInitTask.java

/**
 * Execute.//from   w  w w .jav a  2  s  . c o m
 *
 * @throws TaskExecutionException TaskExecutionException
 */
@TaskAction
public void executeTask() throws TaskExecutionException {

    try {
        // Create ${buildDir}/bin
        fileUtils.checkAndCreateDirectory(pathUtils.getBinPath());
        String rdlBinSuffix = System.getProperty("os.name").equals("Mac OS X") ? "darwin" : "linux";

        // Extract rdl to ${buildDir}/bin
        File file = fileUtils.getFileFromResource("/rdl-bin/rdl-bin.zip");
        try (ZipFile zipFile = new ZipFile(file);
                InputStream inputStream = zipFile
                        .getInputStream(zipFile.getEntry(PathUtils.RDL_BINARY + "-" + rdlBinSuffix))) {
            fileUtils.writeResourceAsExecutable(inputStream, pathUtils.getRdlBinaryPath());
        }

        extractParsecRdlGenerator(rdlBinSuffix,
                Arrays.asList("java-model", "java-server", "java-client", "swagger"));

        // Create ${baseDir}/parsec-bin
        fileUtils.checkAndCreateDirectory(pathUtils.getBinPath());

        // Copy all scripts under resource/scripts to ${baseDir}/parsec-bin
        for (Path scriptPath : fileUtils.listDirFilePaths("scripts")) {
            String scriptPathString = scriptPath.toString();
            if (scriptPathString.endsWith(".sh") || scriptPathString.endsWith(".rb")) {
                fileUtils.writeResourceAsExecutable(scriptPath.toString(),
                        pathUtils.getBinPath() + "/" + scriptPath.getFileName());
            }
        }
        String test = pathUtils.getBinPath();
        if (pluginExtension.isGenerateSwagger()) {
            String swaggerUIPath = pathUtils.getSwaggerUIPath();

            // Create ${buildDir}/generated-resources/swagger-ui
            fileUtils.checkAndCreateDirectory(swaggerUIPath);

            // Extract swagger-ui archive if ${buildDir}/generated-resources/swagger-ui is empty
            if (new File(swaggerUIPath).list().length <= 0) {
                fileUtils.unTarZip("/swagger-ui/swagger-ui.tgz", swaggerUIPath, true);
            }
        }
    } catch (IOException e) {
        throw new TaskExecutionException(this, e);
    }
}

From source file:com.rptools.io.TableFileParser.java

/**
 * Save new json file if it doesn't exist. Delete the text file.
 *
 * @param file Path to file//from  w  w w  . j ava  2 s . com
 * @param builder RPTable builder to print to JSON file
 * @return Boolean: If the .json file already existed and will be parsed separately
 */
private boolean updateResourceFiles(Path file, RPTable.Builder builder) throws IOException {
    File json = new File(file.toString().replace(EXT_TXT, EXT_JSON));
    Files.delete(file);
    boolean isNew = json.createNewFile();
    Files.write(json.toPath(), Lists.newArrayList(JsonFormat.printer().print(builder)), UTF_8);
    return isNew;
}

From source file:net.mindengine.dashserver.compiler.GlobalAssetsFileWatcher.java

@Override
public void run() {
    copyAllAssets();/*from w w w . j  a  v a 2s . com*/

    Path path = Paths.get(this.assetsFolderPath);
    FileSystem fileSystem = path.getFileSystem();
    try (WatchService service = fileSystem.newWatchService()) {
        path.register(service, ENTRY_MODIFY, ENTRY_CREATE);

        while (true) {
            WatchKey watchKey = service.take();

            for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
                Path watchEventPath = (Path) watchEvent.context();
                String fileName = watchEventPath.toString();
                copyFileAsset(fileName);
            }

            if (!watchKey.reset()) {
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.StartTask.java

/**
 * Syntaxe : java [-options] class [args...] (pour l'excution d'une classe)
 * ou java [-options] -jar jarfile [args...] (pour l'excution d'un fichier
 * JAR//from w  w  w  .  j av a2 s  .  co m
 *
 * @param task
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FailStartedException
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FileMsNotFoundException
 */
@Override
public void run(MicroServiceTask task) throws FailStartedException, FileMsNotFoundException {
    LOG.info("Dmarrage du micro service {}", task.getMs().getName());

    Path jar = helper.targetJarOf(task.getMs());
    Path workingDir = helper.targetDirOf(task.getMs());

    if (!Files.exists(jar)
            || !Files.exists(Paths.get(workingDir.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt"))) {
        throw new FileMsNotFoundException("Jar inexistant ou invalide");
    }

    String javaEx = this.javaExec.isEmpty() ? System.getProperty("java.home") + "/bin/java" : this.javaExec;

    ProcessBuilder ps = new ProcessBuilder(javaEx, "-jar", helper.targetJarOf(task.getMs()).toString(), "&");
    ps.directory(workingDir.toFile());

    try {
        Path consoleLog = Paths.get(workingDir.toString(), "console.log");
        ps.redirectOutput(consoleLog.toFile());
        ps.redirectError(consoleLog.toFile());

        LOG.info("Run de {}", ps.command().toString());
        ps.start();
    } catch (IOException ex) {
        throw new FailStartedException("Impossible de dmarrer le programme java : " + task.getMs().getId(),
                ex);
    }

    LOG.info("Micro service {} dmarr", task.getMs().getName());
}

From source file:com.dancorder.Archiverify.FileHashGenerator.java

String calculateMd5(Path file) throws IOException {
    if (!Files.exists(file)) {
        return null;
    }/*from w ww . j a v a  2s . c o m*/

    FileInputStream stream = null;
    try {
        stream = new FileInputStream(file.toString());
        return DigestUtils.md5Hex(stream);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}