Example usage for java.nio.file Path getParent

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

Introduction

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

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:company.gonapps.loghut.dao.PostDao.java

public void createYearIndex() throws TemplateNotFoundException, IOException, MalformedTemplateNameException,
        ParseException, TemplateException {

    if (yearIndexTemplate == null)
        yearIndexTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/year_index.ftl");

    List<String> years = getYears();
    StringWriter temporaryBuffer = new StringWriter();
    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("settings", settingDao);
    modelMap.put("years", years);
    yearIndexTemplate.process(modelMap, temporaryBuffer);

    Path yearIndexPath = Paths.get(getYearIndexPathString());
    rrwl.writeLock().lock();//from w w  w.j  a  v a  2 s .  com
    Files.createDirectories(yearIndexPath.getParent());
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(yearIndexPath.toFile()))) {
        bufferedWriter.write(temporaryBuffer.toString());
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:company.gonapps.loghut.dao.PostDao.java

public void createMonthIndex(int year) throws IOException, TemplateException {

    if (monthIndexTemplate == null)
        monthIndexTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/month_index.ftl");

    List<String> months = getMonths(year);
    StringWriter temporaryBuffer = new StringWriter();
    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("settings", settingDao);
    modelMap.put("months", months);
    monthIndexTemplate.process(modelMap, temporaryBuffer);

    Path monthIndexPath = Paths.get(getMonthIndexPathString(year));
    rrwl.writeLock().lock();/*from w  w  w. j  a v a2  s  .c  o  m*/
    Files.createDirectories(monthIndexPath.getParent());
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(monthIndexPath.toFile()))) {
        bufferedWriter.write(temporaryBuffer.toString());
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:divconq.tool.Updater.java

static public boolean tryUpdate() {
    @SuppressWarnings("resource")
    final Scanner scan = new Scanner(System.in);

    FuncResult<RecordStruct> ldres = Updater.loadDeployed();

    if (ldres.hasErrors()) {
        System.out.println("Error reading deployed.json file: " + ldres.getMessage());
        return false;
    }/*  w  w  w  .j  a  v  a2 s .  c  o m*/

    RecordStruct deployed = ldres.getResult();

    String ver = deployed.getFieldAsString("Version");
    String packfolder = deployed.getFieldAsString("PackageFolder");
    String packprefix = deployed.getFieldAsString("PackagePrefix");

    if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) {
        System.out.println("Error reading deployed.json file: Missing Version or PackageFolder");
        return false;
    }

    if (StringUtil.isEmpty(packprefix))
        packprefix = "DivConq";

    System.out.println("Current Version: " + ver);

    Path packpath = Paths.get(packfolder);

    if (!Files.exists(packpath) || !Files.isDirectory(packpath)) {
        System.out.println("Error reading PackageFolder - it may not exist or is not a folder.");
        return false;
    }

    File pp = packpath.toFile();
    RecordStruct deployment = null;
    File matchpack = null;

    for (File f : pp.listFiles()) {
        if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip"))
            continue;

        System.out.println("Checking: " + f.getName());

        // if not a match before, clear this
        deployment = null;

        try {
            ZipFile zf = new ZipFile(f);

            Enumeration<ZipArchiveEntry> entries = zf.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();

                if (entry.getName().equals("deployment.json")) {
                    //System.out.println("crc: " + entry.getCrc());

                    FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry));

                    if (pres.hasErrors()) {
                        System.out.println("Error reading deployment.json file");
                        break;
                    }

                    deployment = (RecordStruct) pres.getResult();

                    break;
                }
            }

            zf.close();
        } catch (IOException x) {
            System.out.println("Error reading deployment.json file: " + x);
        }

        if (deployment != null) {
            String fndver = deployment.getFieldAsString("Version");
            String fnddependson = deployment.getFieldAsString("DependsOn");

            if (ver.equals(fnddependson)) {
                System.out.println("Found update: " + fndver);
                matchpack = f;
                break;
            }
        }
    }

    if ((matchpack == null) || (deployment == null)) {
        System.out.println("No updates found!");
        return false;
    }

    String fndver = deployment.getFieldAsString("Version");
    String umsg = deployment.getFieldAsString("UpdateMessage");

    if (StringUtil.isNotEmpty(umsg)) {
        System.out.println("========================================================================");
        System.out.println(umsg);
        System.out.println("========================================================================");
    }

    System.out.println();
    System.out.println("Do you want to install?  (y/n)");
    System.out.println();

    String p = scan.nextLine().toLowerCase();

    if (!p.equals("y"))
        return false;

    System.out.println();

    System.out.println("Intalling: " + fndver);

    Set<String> ignorepaths = new HashSet<>();

    ListStruct iplist = deployment.getFieldAsList("IgnorePaths");

    if (iplist != null) {
        for (Struct df : iplist.getItems())
            ignorepaths.add(df.toString());
    }

    ListStruct dflist = deployment.getFieldAsList("DeleteFiles");

    // deleting
    if (dflist != null) {
        for (Struct df : dflist.getItems()) {
            Path delpath = Paths.get(".", df.toString());

            if (Files.exists(delpath)) {
                System.out.println("Deleting: " + delpath.toAbsolutePath());

                try {
                    Files.delete(delpath);
                } catch (IOException x) {
                    System.out.println("Unable to Delete: " + x);
                }
            }
        }
    }

    // copying updates

    System.out.println("Checking for updated files: ");

    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(matchpack);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String entryname = entry.getName().replace('\\', '/');
            boolean xfnd = false;

            for (String exculde : ignorepaths)
                if (entryname.startsWith(exculde)) {
                    xfnd = true;
                    break;
                }

            if (xfnd)
                continue;

            System.out.print(".");

            Path localpath = Paths.get(".", entryname);

            if (entry.isDirectory()) {
                if (!Files.exists(localpath))
                    Files.createDirectories(localpath);
            } else {
                boolean hashmatch = false;

                if (Files.exists(localpath)) {
                    String local = null;
                    String update = null;

                    try (InputStream lin = Files.newInputStream(localpath)) {
                        local = HashUtil.getMd5(lin);
                    }

                    try (InputStream uin = zf.getInputStream(entry)) {
                        update = HashUtil.getMd5(uin);
                    }

                    hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update)
                            && local.equals(update));
                }

                if (!hashmatch) {
                    System.out.print("[" + entryname + "]");

                    try (InputStream uin = zf.getInputStream(entry)) {
                        Files.createDirectories(localpath.getParent());

                        Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (Exception x) {
                        System.out.println("Error updating: " + entryname + " - " + x);
                        return false;
                    }
                }
            }
        }

        zf.close();
    } catch (IOException x) {
        System.out.println("Error reading update package: " + x);
    }

    // updating local config
    deployed.setField("Version", fndver);

    OperationResult svres = Updater.saveDeployed(deployed);

    if (svres.hasErrors()) {
        System.out.println("Intalled: " + fndver
                + " but could not update deployed.json.  Repair the file before continuing.\nError: "
                + svres.getMessage());
        return false;
    }

    System.out.println("Intalled: " + fndver);

    return true;
}

From source file:company.gonapps.loghut.dao.PostDao.java

public void createPostIndex(int year, int month)
        throws IOException, TemplateException, InvalidTagNameException {

    if (postIndexTemplate == null)
        postIndexTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/post_index.ftl");

    List<PostDto> posts = getList(year, month);

    StringWriter temporaryBuffer = new StringWriter();
    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("settings", settingDao);
    modelMap.put("posts", posts);
    postIndexTemplate.process(modelMap, temporaryBuffer);

    Path postIndexPath = Paths.get(getPostIndexPathString(year, month));
    rrwl.writeLock().lock();/*w  w  w  . ja v  a 2  s  . c  om*/
    Files.createDirectories(postIndexPath.getParent());
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(postIndexPath.toFile()))) {
        bufferedWriter.write(temporaryBuffer.toString());
    } finally {
        rrwl.writeLock().unlock();
    }
}

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

/** Prepares to write out a file. This deletes existing files/directories */
private void prepareForFile(DirectoryCreator creator, Path target) throws IOException {
    ProjectFilesystem filesystem = creator.getFilesystem();
    if (filesystem.isFile(target, LinkOption.NOFOLLOW_LINKS)) {
        return;//from  w  w w.  j a v a 2s.com
    } else if (filesystem.exists(target, LinkOption.NOFOLLOW_LINKS)) {
        filesystem.deleteRecursivelyIfExists(target);
    } else if (target.getParent() != null) {
        creator.forcefullyCreateDirs(target.getParent());
    }
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGenerator.java

@VisibleForTesting
protected void writeSource(URI type, ClassName className, Buffer buffer) throws IOException {
    // Create the file based on the className in the mapping
    Path outputFile = getClassSourceFile(className);
    logger.info("{}: Writing {}", type, outputFile);

    // Write stuff into it
    Files.createDirectories(outputFile.getParent());
    Files.copy(buffer.getInputStream(), outputFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java

@Override
public void execute() throws MojoExecutionException {

    Path warExecFile = Paths.get(this.buildDirectory, this.finalName);
    try {/*from  w w  w .j ava  2s.c o m*/
        Files.deleteIfExists(warExecFile);
        Files.createDirectories(warExecFile.getParent());

        try (OutputStream os = Files.newOutputStream(warExecFile);
                ArchiveOutputStream aos = new ArchiveStreamFactory()
                        .createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) {

            // If project is a war project add the war to the project
            if ("war".equalsIgnoreCase(this.project.getPackaging())) {
                File projectArtifact = this.project.getArtifact().getFile();
                if (projectArtifact != null && Files.exists(projectArtifact.toPath())) {
                    aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName()));
                    try (InputStream is = Files.newInputStream(projectArtifact.toPath())) {
                        IOUtils.copy(is, aos);
                    }
                    aos.closeArchiveEntry();
                }
            }

            // Add extraWars into the jar
            if (this.extraWars != null) {
                for (Dependency extraWarDependency : this.extraWars) {
                    ArtifactRequest request = new ArtifactRequest();
                    request.setArtifact(new DefaultArtifact(extraWarDependency.getGroupId(),
                            extraWarDependency.getArtifactId(), extraWarDependency.getType(),
                            extraWarDependency.getVersion()));
                    request.setRepositories(this.projectRepos);
                    ArtifactResult result;
                    try {
                        result = this.repoSystem.resolveArtifact(this.repoSession, request);
                    } catch (ArtifactResolutionException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }

                    File extraWarFile = result.getArtifact().getFile();
                    aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName()));
                    try (InputStream is = Files.newInputStream(extraWarFile.toPath())) {
                        IOUtils.copy(is, aos);
                    }
                    aos.closeArchiveEntry();

                }
            }

            // Add extraResources into the jar. Folder /extra
            if (this.extraResources != null) {
                for (Resource extraResource : this.extraResources) {
                    DirectoryScanner directoryScanner = new DirectoryScanner();
                    directoryScanner.setBasedir(extraResource.getDirectory());

                    directoryScanner.setExcludes(extraResource.getExcludes()
                            .toArray(new String[extraResource.getExcludes().size()]));

                    if (!extraResource.getIncludes().isEmpty()) {
                        directoryScanner.setIncludes(extraResource.getIncludes()
                                .toArray(new String[extraResource.getIncludes().size()]));
                    } else {
                        // include everything by default
                        directoryScanner.setIncludes(new String[] { "**" });
                    }

                    directoryScanner.scan();
                    for (String includeFile : directoryScanner.getIncludedFiles()) {
                        aos.putArchiveEntry(
                                new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile));

                        Path extraFile = Paths.get(extraResource.getDirectory(), includeFile);
                        try (InputStream is = Files.newInputStream(extraFile)) {
                            IOUtils.copy(is, aos);
                        }
                        aos.closeArchiveEntry();
                    }

                }
            }

            Set<String> includeArtifacts = new HashSet<>();
            includeArtifacts.add("org.apache.tomcat:tomcat-jdbc");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-websocket");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli");
            includeArtifacts.add("org.yaml:snakeyaml");
            includeArtifacts.add("com.beust:jcommander");

            if (this.includeJSPSupport) {
                includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper");
                includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-el");
                includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj");
            }

            for (Artifact pluginArtifact : this.pluginArtifacts) {
                String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId();
                if (includeArtifacts.contains(artifactName)) {
                    try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) {
                        extractJarToArchive(jarFile, aos);
                    }
                }
            }

            if (this.extraDependencies != null) {
                for (Dependency dependency : this.extraDependencies) {

                    ArtifactRequest request = new ArtifactRequest();
                    request.setArtifact(new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(),
                            dependency.getType(), dependency.getVersion()));
                    request.setRepositories(this.projectRepos);
                    ArtifactResult result;
                    try {
                        result = this.repoSystem.resolveArtifact(this.repoSession, request);
                    } catch (ArtifactResolutionException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }

                    try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) {
                        extractJarToArchive(jarFile, aos);
                    }
                }
            }

            if (this.includeJSPSupport) {
                addFile(aos, "/conf/web.xml", "conf/web.xml");
            } else {
                addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml");
            }
            addFile(aos, "/conf/logging.properties", "conf/logging.properties");

            if (this.includeTcNativeWin32 != null) {
                aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32"));
                Files.copy(Paths.get(this.includeTcNativeWin32), aos);
                aos.closeArchiveEntry();
            }

            if (this.includeTcNativeWin64 != null) {
                aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64"));
                Files.copy(Paths.get(this.includeTcNativeWin64), aos);
                aos.closeArchiveEntry();
            }

            String[] runnerClasses = { "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions",
                    "ch.rasc.embeddedtc.runner.CheckConfig", "ch.rasc.embeddedtc.runner.Config",
                    "ch.rasc.embeddedtc.runner.Shutdown", "ch.rasc.embeddedtc.runner.Context",
                    "ch.rasc.embeddedtc.runner.DeleteDirectory",
                    "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions",
                    "ch.rasc.embeddedtc.runner.ObfuscateUtil", "ch.rasc.embeddedtc.runner.Runner$1",
                    "ch.rasc.embeddedtc.runner.Runner$2", "ch.rasc.embeddedtc.runner.Runner$StartOptions",
                    "ch.rasc.embeddedtc.runner.Runner$StopOptions",
                    "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook", "ch.rasc.embeddedtc.runner.Runner" };

            for (String rc : runnerClasses) {
                String classAsPath = rc.replace('.', '/') + ".class";

                try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) {
                    aos.putArchiveEntry(new JarArchiveEntry(classAsPath));
                    IOUtils.copy(is, aos);
                    aos.closeArchiveEntry();
                }
            }

            Manifest manifest = new Manifest();

            Manifest.Attribute mainClassAtt = new Manifest.Attribute();
            mainClassAtt.setName("Main-Class");
            mainClassAtt.setValue(Runner.class.getName());
            manifest.addConfiguredAttribute(mainClassAtt);

            aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
            manifest.write(aos);
            aos.closeArchiveEntry();

            aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME));
            aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8));
            aos.closeArchiveEntry();

        }
    } catch (IOException | ArchiveException | ManifestException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:at.tfr.securefs.client.SecurefsClient.java

public void run() {
    DateTime start = new DateTime();
    try (FileSystem fs = FileSystems.newFileSystem(new URI(baseDir), null)) {

        for (Path path : files) {

            Path sec = fs.getPath(path.toString() + (asyncTest ? "." + Thread.currentThread().getId() : ""));

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }// ww w.  ja  v  a2s  .com

                if (path.getParent() != null) {
                    fs.provider().createDirectory(fs.getPath(path.getParent().toString()));
                }
                final OutputStream secOs = Files.newOutputStream(sec);

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + sec);

                IOUtils.copyLarge(Files.newInputStream(path), secOs, new byte[128 * 1024]);
                secOs.close();
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                final InputStream secIs = Files.newInputStream(sec);
                IOUtils.copyLarge(secIs, Files.newOutputStream(out), new byte[128 * 1024]);
                secIs.close();
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());

                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = fs.provider().deleteIfExists(sec);
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

From source file:org.jmingo.query.watch.QuerySetWatchService.java

/**
 * Register watcher for specified path./*from  ww  w  .  j  a  v  a2  s  .c  o  m*/
 * If path references to a file then the parent folder of this file is registered.
 *
 * @param path the path to file or folder to watch
 */
public void regiser(Path path) {
    Validate.notNull(path, "path to watch cannot be null");
    try {
        lock.lock();
        if (!path.isAbsolute()) {
            path = path.toAbsolutePath();
        }
        Path dir = path;
        // check if specified path is referencing to file
        if (Files.isRegularFile(path)) {
            dir = path.getParent();//takes parent dir to register in watch service
        }
        if (needToRegister(path)) {
            LOGGER.debug("create watcher for dir: {}", dir);
            Watcher watcher = new Watcher(watchService, watchEventHandler, dir);
            executorService.submit(watcher);
        } else {
            LOGGER.debug("a watcher for dir: {} is already created", dir);
        }
        // add path to the registered collection event if this path wasn't registered in watchService
        // because we need to know for which files the new event should be posted in event bus and filter altered files properly
        registered.add(path);
    } finally {
        lock.unlock();
    }
}

From source file:org.apache.marmotta.platform.core.services.importer.ImportWatchServiceImpl.java

private Properties loadConfigFile(Path importFile) {
    // Check for a configFile
    final Path config = importFile.getParent()
            .resolve(configurationService.getStringConfiguration(CONFIG_KEY_CONF_FILE, "config"));
    if (Files.isReadable(config)) {
        try {/*from   w w w. j a v a2  s.com*/
            Properties prop = new Properties();
            final FileInputStream inStream = new FileInputStream(config.toFile());
            prop.load(inStream);
            inStream.close();
            return prop;
        } catch (IOException e) {
            log.warn("could not read dirConfigFile {}: {}", config, e.getMessage());
        }
    }
    return null;
}