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:org.roda.core.storage.fs.FSUtils.java

public static BinaryVersion convertPathToBinaryVersion(Path historyDataPath, Path historyMetadataPath,
        Path path) throws RequestNotValidException, NotFoundException, GenericException {
    DefaultBinaryVersion ret;//  www . j ava2s  .c  o m

    if (!FSUtils.exists(path)) {
        throw new NotFoundException("Cannot find file version at " + path);
    }

    // storage path
    Path relativePath = historyDataPath.relativize(path);
    String fileName = relativePath.getFileName().toString();
    int lastIndexOfDot = fileName.lastIndexOf(VERSION_SEP);

    if (lastIndexOfDot <= 0 || lastIndexOfDot == fileName.length() - 1) {
        throw new RequestNotValidException("Bad name for versioned file: " + path);
    }

    String id = fileName.substring(lastIndexOfDot + 1);
    String realFileName = fileName.substring(0, lastIndexOfDot);
    Path realFilePath = relativePath.getParent().resolve(realFileName);
    Path metadataPath = historyMetadataPath
            .resolve(relativePath.getParent().resolve(fileName + METADATA_SUFFIX));

    StoragePath storagePath = FSUtils.getStoragePath(realFilePath);

    // construct
    ContentPayload content = new FSPathContentPayload(path);
    long sizeInBytes;
    try {
        sizeInBytes = Files.size(path);
        Map<String, String> contentDigest = null;
        Binary binary = new DefaultBinary(storagePath, content, sizeInBytes, false, contentDigest);

        if (FSUtils.exists(metadataPath)) {
            ret = JsonUtils.readObjectFromFile(metadataPath, DefaultBinaryVersion.class);
            ret.setBinary(binary);
        } else {
            Date createdDate = new Date(
                    Files.readAttributes(path, BasicFileAttributes.class).creationTime().toMillis());
            Map<String, String> defaultProperties = new HashMap<>();
            ret = new DefaultBinaryVersion(binary, id, createdDate, defaultProperties);
        }

    } catch (IOException e) {
        throw new GenericException("Could not get file size", e);
    }

    return ret;
}

From source file:com.liferay.sync.engine.document.library.handler.DownloadFileHandler.java

protected boolean isUnsynced(SyncFile syncFile) {
    if (syncFile != null) {
        syncFile = SyncFileService.fetchSyncFile(syncFile.getSyncFileId());
    }/*  ww  w .  j av  a2  s .c o m*/

    if (syncFile == null) {
        return true;
    }

    if (syncFile.getState() == SyncFile.STATE_UNSYNCED) {
        if (_logger.isDebugEnabled()) {
            _logger.debug("Skipping file {}. File is unsynced.", syncFile.getName());
        }

        return true;
    }

    Path filePath = Paths.get(syncFile.getFilePathName());

    if (FileUtil.notExists(filePath.getParent())) {
        if (_logger.isDebugEnabled()) {
            _logger.debug("Skipping file {}. Missing parent file path {}.", syncFile.getName(),
                    filePath.getParent());
        }

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_PARENT_MISSING);

        SyncFileService.update(syncFile);

        return true;
    }

    return false;
}

From source file:com.kumarvv.setl.Setl.java

/**
 * load dataSources from default db.json file when def file skips them
 *
 * @param def//from   w w w .  j av a 2 s. c o  m
 */
protected void loadDataStores(final Def def) {
    if (def == null || def.getFilePath() == null) {
        return;
    }

    Path dbPath = def.getFilePath().resolveSibling("db.json");
    if (dbPath == null || !dbPath.toFile().exists()) {
        // resolve from parent folders
        Path parent = def.getFilePath().getParent();
        while (parent != null) {
            dbPath = parent.resolveSibling("db.json");
            if (dbPath != null && dbPath.toFile().exists()) {
                break;
            }
            parent = parent.getParent();
        }
        if (dbPath == null || !dbPath.toFile().exists()) {
            return;
        }
    }

    try {
        Def dbDef = new ObjectMapper().readValue(dbPath.toFile(), Def.class);

        if (def.getFromDS() == null && dbDef.getFromDS() != null) {
            def.setFromDS(new DS());
            def.getFromDS().setUrl(dbDef.getFromDS().getUrl());
            def.getFromDS().setUsername(dbDef.getFromDS().getUsername());
            def.getFromDS().setPassword(dbDef.getFromDS().getPassword());
        }
        if (def.getToDS() == null && dbDef.getToDS() != null) {
            def.setToDS(new DS());
            def.getToDS().setUrl(dbDef.getToDS().getUrl());
            def.getToDS().setUsername(dbDef.getToDS().getUsername());
            def.getToDS().setPassword(dbDef.getToDS().getPassword());
        }
    } catch (Exception e) {
        Logger.error("DB.json error: {}", e.getMessage());
        // just ignore
    }
}

From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * {@inheritDoc}//w  w w .  j  a  va 2  s  . c o m
 */
@Override
// TODO: We should be careful about how large the byte[] is. Perhaps we should have precondition to protect memory
//       or we should wrap calls to this in something that chunks it off an input stream or just take this in as
//       input stream
public void updateFile(final String jobId, final String relativePath, final long startByte, final byte[] data)
        throws IOException {
    log.debug("Attempting to write {} bytes from position {} into log file {} for job {}", data.length,
            startByte, relativePath, jobId);
    final Path jobFile = this.jobsDirRoot.resolve(jobId).resolve(relativePath);

    if (Files.notExists(jobFile)) {
        // Make sure all the directories exist on disk
        final Path logFileParent = jobFile.getParent();
        if (logFileParent != null) {
            this.createOrCheckDirectory(logFileParent);
        }
    } else if (Files.isDirectory(jobFile)) {
        // TODO: Perhaps this should be different exception
        throw new IllegalArgumentException(relativePath + " is a directory not a file. Unable to update");
    }

    try (FileChannel fileChannel = FileChannel.open(jobFile,
            EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.SPARSE))) {
        // Move the byteChannel to the start byte
        fileChannel.position(startByte);

        // The size and length are ignored in this implementation as we just assume we're writing everything atm
        // TODO: Would it be better to provide an input stream and buffer the output?
        final ByteBuffer byteBuffer = ByteBuffer.wrap(data);

        while (byteBuffer.hasRemaining()) {
            fileChannel.write(byteBuffer);
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java

private void extract(ActionDescription aAction, Path aArchive, ArchiveInputStream aAStream, Path aTarget)
        throws IOException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aArchive.getFileName().toString());

    Map<String, Object> cfg = aAction.getConfiguration();
    int strip = cfg.containsKey("strip") ? (int) cfg.get("strip") : 0;

    AntFileFilter filter = new AntFileFilter(coerceToList(cfg.get("includes")),
            coerceToList(cfg.get("excludes")));

    ArchiveEntry entry = null;/*from w  w w .j  a v  a2s.  c o m*/
    while ((entry = aAStream.getNextEntry()) != null) {
        String name = stripLeadingFolders(entry.getName(), strip);

        if (name == null) {
            // Stripped to null - nothing left to extract - continue;
            continue;
        }

        if (filter.accept(name)) {
            Path out = aTarget.resolve(base).resolve(name);
            if (entry.isDirectory()) {
                Files.createDirectories(out);
            } else {
                Files.createDirectories(out.getParent());
                Files.copy(aAStream, out);
            }
        }
    }
}

From source file:org.roda.core.common.monitor.TransferredResourcesScanner.java

public void updateTransferredResource(Optional<String> folderRelativePath, ContentPayload payload, String name,
        boolean waitToFinish)
        throws NotFoundException, GenericException, IOException, IsStillUpdatingException {
    if (folderRelativePath.isPresent()) {
        Path path = basePath.resolve(folderRelativePath.get());
        Path parent = path.getParent();
        Path parentToBase = basePath.relativize(parent);
        FSUtils.deletePath(path);/* w  w w.j  a  v a  2  s.  c  o m*/

        payload.writeToPath(parent.resolve(name));
        updateTransferredResources(Optional.ofNullable(parentToBase.toString()), waitToFinish);
    }
}

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

public void createYearIndex(String tagName) throws IOException, TemplateException {

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

    List<String> years = getYears(tagName);
    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(settingDao.getSetting("tags.directory") + "/" + tagName + "/index.html");

    rrwl.writeLock().lock();//from   ww w. j  a  va 2 s  .c o m
    Files.createDirectories(yearIndexPath.getParent());
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(yearIndexPath.toFile()))) {
        bufferedWriter.write(temporaryBuffer.toString());
    } finally {
        rrwl.writeLock().unlock();
    }
}

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

@Before
public void createSymlinksScenario() throws IOException, URISyntaxException {
    Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("windows"));

    /**//from w  w w. ja  v a2  s  . c om
     * Creating following structure for test:
     *
     * $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/page.html
     * $ROOT_PATH/newDir/innerDir/
     * $ROOT_PATH/newDir/innerDir/page.html
     * $ROOT_PATH/newSymlink -> $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/innerSymlink -> $ROOT_PATH/newDir/innerDir/
     *
     */
    Path filePath = Paths.get(getClass().getResource("page.html").toURI());
    Path rootPath = filePath.getParent();

    Path newDir = rootPath.resolve("newDir");
    Files.createDirectories(newDir);

    Path innerDir = newDir.resolve("innerDir");
    Files.createDirectories(innerDir);

    Files.copy(filePath, newDir.resolve(filePath.getFileName()));
    Files.copy(filePath, innerDir.resolve(filePath.getFileName()));

    Path newSymlink = rootPath.resolve("newSymlink");

    Files.createSymbolicLink(newSymlink, newDir);

    Path innerSymlink = newDir.resolve("innerSymlink");

    Files.createSymbolicLink(innerSymlink, innerDir);
}

From source file:org.everit.i18n.propsxlsconverter.internal.I18nConverterImpl.java

@Override
public void importFromXls(final String xlsFileName, final String workingDirectory) {

    validateImportParameters(xlsFileName, workingDirectory);
    WorkbookReader workbookReader = new WorkbookReader(xlsFileName);
    System.out.println("lines: " + workbookReader.getLastRowNumber());
    Map<String, Properties> langProperties = new HashMap<String, Properties>();

    String[] languages = workbookReader.getLanguages();
    Set<String> fileNames = workbookReader.getFileNames();
    for (String fileName : fileNames) {
        langProperties.put(fileName, new Properties());
    }//from ww w .  jav a 2 s.  c o  m
    for (String lang : languages) {
        for (String fileName : fileNames) {
            langProperties.put(getFilenameForLang(fileName, lang), new Properties());
        }
    }
    int lastRowNumber = workbookReader.getLastRowNumber();
    for (int i = 1; i < lastRowNumber; i++) {
        WorkbookRowDTO nextRow = workbookReader.getNextRow();
        String propertiesFile = nextRow.propertiesFile;
        langProperties.get(propertiesFile).setProperty(nextRow.propKey, nextRow.defaultLangValue);
        for (String lang : languages) {
            ofNullable(nextRow.langValues.get(lang)).map(String::trim).filter(s -> !s.isEmpty())
                    .ifPresent(v -> {
                        langProperties.get(getFilenameForLang(propertiesFile, lang))
                                .setProperty(nextRow.propKey, v);
                    });
        }
    }
    langProperties.entrySet().stream().forEach(e -> {
        if (e.getValue().isEmpty()) {
            return;
        }
        Path filePath = Paths.get(workingDirectory, e.getKey());
        filePath.getParent().toFile().mkdirs();
        File file = filePath.toFile();
        try {
            file.createNewFile();
            try (PrintWriter pw = new PrintWriter(file, "UTF-8")) {
                e.getValue().keySet().stream().sorted().forEach(key -> pw
                        .write(String.format("%s=%s\n", key, e.getValue().getProperty(key.toString()))));
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    });
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java

private void extractRar(ActionDescription aAction, Path aCachedFile, Path aTarget)
        throws IOException, RarException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aCachedFile.getFileName().toString());

    Map<String, Object> cfg = aAction.getConfiguration();
    int strip = cfg.containsKey("strip") ? (int) cfg.get("strip") : 0;

    AntFileFilter filter = new AntFileFilter(coerceToList(cfg.get("includes")),
            coerceToList(cfg.get("excludes")));

    try (Archive archive = new Archive(new FileVolumeManager(aCachedFile.toFile()))) {
        FileHeader fh = archive.nextFileHeader();
        while (fh != null) {
            String name = stripLeadingFolders(fh.getFileNameString(), strip);

            if (name == null) {
                // Stripped to null - nothing left to extract - continue;
                continue;
            }//from   w  ww.  j a  v a2  s  .  c o  m

            if (filter.accept(name)) {
                Path out = aTarget.resolve(base).resolve(name);
                if (fh.isDirectory()) {
                    Files.createDirectories(out);
                } else {
                    Files.createDirectories(out.getParent());
                    try (OutputStream os = Files.newOutputStream(out)) {
                        archive.extractFile(fh, os);
                    }
                }
            }

            fh = archive.nextFileHeader();
        }
    }
}