Example usage for java.nio.file Path startsWith

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

Introduction

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

Prototype

default boolean startsWith(String other) 

Source Link

Document

Tests if this path starts with a Path , constructed by converting the given path string, in exactly the manner specified by the #startsWith(Path) startsWith(Path) method.

Usage

From source file:cn.edu.zjnu.acm.judge.controller.CKFinderController.java

@Nullable
@ToDownload//www.ja v  a 2s. c  o m
@GetMapping("/support/ckfinder")
public Path ckfinder(@RequestParam("path") String path) {
    log.info(path);
    try {
        int indexOf = path.indexOf('?');
        Path parent = judgeConfiguration.getUploadDirectory();
        Path imagePath = parent.getFileSystem()
                .getPath(parent.toString(), indexOf > 0 ? path.substring(0, indexOf) : path).normalize();
        if (!imagePath.startsWith(parent)) {
            log.debug("absolute path parent='{}' path='{}'", parent, imagePath);
            return null;
        }
        return imagePath;
    } catch (IllegalArgumentException ex) {
        return null;
    }
}

From source file:net.mozq.picto.core.ProcessCore.java

public static void findFiles(ProcessCondition processCondition, Consumer<ProcessData> processDataSetter,
        BooleanSupplier processStopper) throws IOException {

    Set<FileVisitOption> fileVisitOptionSet;
    if (processCondition.isFollowLinks()) {
        fileVisitOptionSet = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    } else {//from w  ww  . j  a  va  2s . c o m
        fileVisitOptionSet = Collections.emptySet();
    }

    Files.walkFileTree(processCondition.getSrcRootPath(), fileVisitOptionSet, processCondition.getDept(),
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (processStopper.getAsBoolean()) {
                        return FileVisitResult.TERMINATE;
                    }

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                    if (attrs.isDirectory()) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    if (processStopper.getAsBoolean()) {
                        return FileVisitResult.TERMINATE;
                    }

                    if (!processCondition.getPathFilter().accept(file, attrs)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    Path rootRelativeSubPath = processCondition.getSrcRootPath().relativize(file.getParent());

                    ImageMetadata imageMetadata = getImageMetadata(file);

                    Date baseDate;
                    if (processCondition.isChangeFileCreationDate()
                            || processCondition.isChangeFileModifiedDate()
                            || processCondition.isChangeFileAccessDate()
                            || processCondition.isChangeExifDate()) {
                        baseDate = getBaseDate(processCondition, file, attrs, imageMetadata);
                    } else {
                        baseDate = null;
                    }

                    String destSubPathname = processCondition.getDestSubPathFormat().format(varName -> {
                        try {
                            switch (varName) {
                            case "Now":
                                return new Date();
                            case "ParentSubPath":
                                return rootRelativeSubPath.toString();
                            case "FileName":
                                return file.getFileName().toString();
                            case "BaseName":
                                return FileUtilz.getBaseName(file.getFileName().toString());
                            case "Extension":
                                return FileUtilz.getExt(file.getFileName().toString());
                            case "Size":
                                return Long.valueOf(Files.size(file));
                            case "CreationDate":
                                return (processCondition.isChangeFileCreationDate()) ? baseDate
                                        : new Date(attrs.creationTime().toMillis());
                            case "ModifiedDate":
                                return (processCondition.isChangeFileModifiedDate()) ? baseDate
                                        : new Date(attrs.lastModifiedTime().toMillis());
                            case "AccessDate":
                                return (processCondition.isChangeFileAccessDate()) ? baseDate
                                        : new Date(attrs.lastAccessTime().toMillis());
                            case "PhotoTakenDate":
                                return (processCondition.isChangeExifDate()) ? baseDate
                                        : getPhotoTakenDate(file, imageMetadata);
                            case "Width":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH);
                            case "Height":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH);
                            case "FNumber":
                                return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FNUMBER);
                            case "Aperture":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
                            case "MaxAperture":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_MAX_APERTURE_VALUE);
                            case "ISO":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_ISO);
                            case "FocalLength":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_FOCAL_LENGTH); // ?
                            case "FocalLength35mm":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_FOCAL_LENGTH_IN_35MM_FORMAT);
                            case "ShutterSpeed":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE);
                            case "Exposure":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE); // 
                            case "ExposureTime":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXPOSURE_TIME); // 
                            case "ExposureMode":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_MODE);
                            case "ExposureProgram":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_EXPOSURE_PROGRAM);
                            case "Brightness":
                                return getEXIFDoubleValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE);
                            case "WhiteBalance":
                                return getEXIFIntValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_WHITE_BALANCE_1);
                            case "LightSource":
                                return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_LIGHT_SOURCE);
                            case "Lens":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS);
                            case "LensMake":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MAKE);
                            case "LensModel":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MODEL);
                            case "LensSerialNumber":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_LENS_SERIAL_NUMBER);
                            case "Make":
                                return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MAKE);
                            case "Model":
                                return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MODEL);
                            case "SerialNumber":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_SERIAL_NUMBER);
                            case "Software":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SOFTWARE);
                            case "ProcessingSoftware":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_PROCESSING_SOFTWARE);
                            case "OwnerName":
                                return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_OWNER_NAME);
                            case "CameraOwnerName":
                                return getEXIFStringValue(imageMetadata,
                                        ExifTagConstants.EXIF_TAG_CAMERA_OWNER_NAME);
                            case "GPSLat":
                                return getEXIFGpsLat(imageMetadata);
                            case "GPSLatDeg":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        0);
                            case "GPSLatMin":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        1);
                            case "GPSLatSec":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE,
                                        2);
                            case "GPSLatRef":
                                return getEXIFStringValue(imageMetadata,
                                        GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF);
                            case "GPSLon":
                                return getEXIFGpsLon(imageMetadata);
                            case "GPSLonDeg":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        0);
                            case "GPSLonMin":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        1);
                            case "GPSLonSec":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE,
                                        2);
                            case "GPSLonRef":
                                return getEXIFStringValue(imageMetadata,
                                        GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF);
                            case "GPSAlt":
                                return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE);
                            case "GPSAltRef":
                                return getEXIFIntValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
                            default:
                                throw new PictoInvalidDestinationPathException(Messages
                                        .getString("message.warn.invalid.destSubPath.varName", varName));
                            }
                        } catch (PictoException e) {
                            throw e;
                        } catch (Exception e) {
                            throw new PictoInvalidDestinationPathException(
                                    Messages.getString("message.warn.invalid.destSubPath.pattern"), e);
                        }
                    });

                    Path destSubPath = processCondition.getDestRootPath().resolve(destSubPathname).normalize();

                    if (!destSubPath.startsWith(processCondition.getDestRootPath())) {
                        throw new PictoInvalidDestinationPathException(
                                Messages.getString("message.warn.invalid.destination.path", destSubPath));
                    }

                    ProcessData processData = new ProcessData();
                    processData.setSrcPath(file);
                    processData.setSrcFileAttributes(attrs);
                    processData.setDestPath(destSubPath);
                    processData.setBaseDate(baseDate);

                    processDataSetter.accept(processData);

                    return FileVisitResult.CONTINUE;
                }
            });
}

From source file:org.beryx.vbundle.chart.html.HtmlChartContentPane.java

public String getContent() {
    if (optFile.isSelected()) {
        String filePath = txtFile.getText().replace('\\', '/');
        Path path = Paths.get(filePath);
        Path pathUserDir = Paths.get(System.getProperty("user.dir").replace('\\', '/'));
        if (path.startsWith(pathUserDir)) {
            path = pathUserDir.relativize(path);
        }//ww w  .j  av  a 2 s.  com
        return "file('" + path.toString().replace('\\', '/') + "')";
    } else if (optUrl.isSelected()) {
        return "url('" + txtUrl.getText() + "')";
    } else {
        return "\"" + StringEscapeUtils.escapeJava(txtInline.getText()) + "\"";
    }
}

From source file:org.dhus.store.datastore.hfs.HfsManager.java

/**
 * Check file existence within the current HFS.
 *
 * @param file file to check/*from   www .j  a v  a 2 s  . co  m*/
 * @return true if HFS contains the file and if exists
 */
public boolean isContaining(File file) {
    Path root = Paths.get(this.getPath()).toAbsolutePath();
    Path product_path = file.getAbsoluteFile().toPath();
    File product = product_path.toFile();

    return product_path.startsWith(root) && product.exists() && product.isFile();
}

From source file:org.orderofthebee.addons.support.tools.repo.AbstractLogFileWebScript.java

/**
 * Validates a log file paths and resolves them to file handles.
 *
 * @param filePaths/*from  ww w  .j  a  v  a2  s . co m*/
 *            the file paths to validate
 * @return the resolved file handles if the file paths are valid and allowed to be accessed
 *
 * @throws WebScriptException
 *             if access to any log file is prohibited
 */
protected List<File> validateFilePaths(final List<String> filePaths) {
    ParameterCheck.mandatoryCollection("filePaths", filePaths);

    final List<Path> paths = new ArrayList<>();
    for (final String filePath : filePaths) {
        paths.add(Paths.get(filePath));
    }

    boolean allPathsAllowed = true;
    final List<Logger> allLoggers = this.getAllLoggers();
    final List<File> files = new ArrayList<>();

    for (final Logger logger : allLoggers) {
        @SuppressWarnings("unchecked")
        final Enumeration<Appender> allAppenders = logger.getAllAppenders();
        while (allAppenders.hasMoreElements() && allPathsAllowed) {
            final Appender appender = allAppenders.nextElement();
            if (appender instanceof FileAppender) {
                final String appenderFile = ((FileAppender) appender).getFile();
                final File configuredFile = new File(appenderFile);
                final Path configuredFilePath = configuredFile.toPath().toAbsolutePath().getParent();

                for (final Path path : paths) {
                    allPathsAllowed = allPathsAllowed && path.startsWith(configuredFilePath)
                            && path.getFileName().toString().startsWith(configuredFile.getName());

                    if (!allPathsAllowed) {
                        throw new WebScriptException(Status.STATUS_FORBIDDEN, "The log file path " + path
                                + " could not be resolved to a valid log file - access to any other file system contents is forbidden via this web script");
                    }

                    final File file = path.toFile();
                    if (!file.exists()) {
                        throw new WebScriptException(Status.STATUS_NOT_FOUND,
                                "The log file path " + path + " could not be resolved to an existing log file");
                    }

                    files.add(file);
                }
            }
        }
    }

    return files;
}

From source file:net.sf.jasperreports.repo.FileRepositoryService.java

protected File locateFile(String location) {
    File file = new File(getRoot(), location);
    if (file.exists()) {
        //checking that syntactically the requested path is still inside the root
        //we are not dealing with symlinks/real paths for now
        Path rootPath = rootNormalizedPath();
        Path filePath = file.toPath().normalize();
        if (!filePath.startsWith(rootPath)) {
            log.warn("Requested path " + location + " normalized to " + filePath
                    + ", which falls outside repository root path " + rootPath);
            file = null;//from  w  ww  . ja  v  a2  s.c  o  m
        }
    } else {
        if (resolveAbsolutePath) {
            file = new File(location);
            if (!file.exists()) {
                file = null;
            }
        } else {
            file = null;
        }
    }
    return file;
}

From source file:net.sf.jasperreports.repo.FileRepositoryService.java

@Override
public ResourceInfo getResourceInfo(RepositoryContext context, String location) {
    File file = getFile(context, location);
    if (file != null) {
        try {//w ww  .ja  v  a  2s. c o  m
            Path filePath = file.toPath().toRealPath();
            if (rootRealPath != null && filePath.startsWith(rootRealPath)) {
                Path relativePath = rootRealPath.relativize(filePath);
                return StandardResourceInfo.from(relativePath);
            } else if (resolveAbsolutePath) {
                return StandardResourceInfo.from(filePath);
            }
        } catch (IOException e) {
            log.warn("Failed to resolve real path for file " + file, e);
        }
    }
    return null;
}

From source file:at.ac.tuwien.qse.sepm.dao.repo.impl.MemoryPhotoRepository.java

@Override
public boolean accepts(Path file) throws DAOException {
    if (file == null)
        throw new IllegalArgumentException();
    LOGGER.debug("accepting {}", file);
    boolean result = file.startsWith(getPrefix());
    LOGGER.info("accepts {} is {}", file, result);
    return result;
}

From source file:com.surevine.gateway.scm.model.LocalRepoBean.java

/**
 * Attempts to delete the local repository directory. Fails silently as there's nothing the system can do to
 * recover and not deleting the directory shouldn't affect the usual operation of the system.
 *///w w w. j  a va2s  .  c  om
public void deleteRepoDirectory() {
    final Path localDirectory = getRepoDirectory();
    if (localDirectory != null && Files.exists(localDirectory)
            && localDirectory.startsWith(Paths.get(PropertyUtil.getGitDir()))) {
        // check that it's a directory inside the system configured git directory before deleting
        try {
            FileUtils.deleteDirectory(localDirectory.toFile());
        } catch (final IOException e) {
            // drop the exception
        }
    }
}

From source file:org.openhab.tools.analysis.checkstyle.ServiceComponentManifestCheck.java

private void verifyBuildPropertiesFile() {
    if (buildPropertiesPath != null) {
        IBuildEntry binIncludes = buildPropertiesFile.getEntry(IBuildEntry.BIN_INCLUDES);
        if (binIncludes != null) {
            String[] includedTokens = binIncludes.getTokens();
            // Exclude the component files that are added to the bin.includes property
            for (String included : includedTokens) {
                for (Iterator<Path> iterator = componentXmlRelativePaths.iterator(); iterator.hasNext();) {
                    Path componentXmlFile = iterator.next();
                    if (componentXmlFile.startsWith(included)) {
                        iterator.remove();
                    }/*from www  . j a  v a2 s  .c o  m*/
                }
            }
        }

        for (Path path : componentXmlRelativePaths) {
            logMessage(buildPropertiesPath, 0, BUILD_PROPERTIES_FILE_NAME, MessageFormat.format(
                    "The service component {0} isn`t included in the build.properties file."
                            + " Good approach is to include all files by adding `OSGI-INF/` value to the bin.includes property.",
                    path));
        }
    }
}