Java Code Examples for java.nio.file.InvalidPathException

The following examples show how to use java.nio.file.InvalidPathException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
 
Example 2
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 3
Source Project: yajsync   Source File: PathOps.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @throws InvalidPathException if trying to resolve a relative path
 *         prefixed with a .. directory
 */
private static Path normalizePathWin(Path path)
{
    LinkedList<Path> paths = new LinkedList<>();
    Path dotDotDir = path.getFileSystem().getPath(Text.DOT_DOT);
    for (Path p : path) {
        if (p.equals(dotDotDir)) {
            if (paths.isEmpty()) {
                throw new InvalidPathException(path.toString(),
                                               "cannot resolve ..");
            }
            paths.removeLast();
        } else {
            String normalized =
                Text.deleteTrailingDots(p.toString()).toLowerCase();
            if (!normalized.isEmpty()) {
                paths.add(path.getFileSystem().getPath(normalized));
            }
        }
    }
    return joinPaths(path, paths);
}
 
Example 4
Source Project: yajsync   Source File: PathOps.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Path normalizePathDefault(Path path)
{
    LinkedList<Path> paths = new LinkedList<>();
    Path dotDir = path.getFileSystem().getPath(Text.DOT);
    Path dotDotDir = path.getFileSystem().getPath(Text.DOT_DOT);
    for (Path p : path) {
        if (p.equals(dotDotDir)) {
            if (paths.isEmpty()) {
                throw new InvalidPathException(path.toString(),
                                               "cannot resolve ..");
            }
            paths.removeLast();
        } else if (!p.equals(dotDir)) {
            paths.add(p);
        }
    }
    return joinPaths(path, paths);
}
 
Example 5
protected static File locateContextDirectory(RepositoryResourceContext resourceContext, Function<String, File> rootLocator)
{
	String contextLocation = resourceContext.getContextLocation();
	if (contextLocation != null)
	{
		try
		{
			Paths.get(contextLocation);//valid patch check
			File contextDir = rootLocator.apply(contextLocation);
			if (contextDir != null && contextDir.isDirectory())
			{
				return contextDir;
			}
		}
		catch (InvalidPathException e)
		{
			if (log.isDebugEnabled())
			{
				log.debug("location \"" + contextLocation + "\" is not a file path: " + e);
			}
		}
	}
	return null;
}
 
Example 6
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 7
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 8
Source Project: jsr203-hadoop   Source File: HadoopPath.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] normalize(byte[] path) {
  if (path.length == 0)
    return path;
  byte prevC = 0;
  for (int i = 0; i < path.length; i++) {
    byte c = path[i];
    if (c == '\\')
      return normalize(path, i);
    if (c == (byte) '/' && prevC == '/')
      return normalize(path, i - 1);
    if (c == '\u0000')
      throw new InvalidPathException(this.hdfs.getString(path),
          "Path: nul character not allowed");
    prevC = c;
  }
  return path;
}
 
Example 9
Source Project: jdk8u_jdk   Source File: JarUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add or remove specified files to existing jar file. If a specified file
 * to be updated or added does not exist, the jar entry will be created
 * with the file name itself as the content.
 *
 * @param src the original jar file name
 * @param dest the new jar file name
 * @param files the files to update. The list is broken into 2 groups
 *              by a "-" string. The files before in the 1st group will
 *              be either updated or added. The files in the 2nd group
 *              will be removed. If no "-" exists, all files belong to
 *              the 1st group.
 */
public static void updateJar(String src, String dest, String... files)
        throws IOException {
    Map<String,Object> changes = new HashMap<>();
    boolean update = true;
    for (String file : files) {
        if (file.equals("-")) {
            update = false;
        } else if (update) {
            try {
                Path p = Paths.get(file);
                if (Files.exists(p)) {
                    changes.put(file, p);
                } else {
                    changes.put(file, file);
                }
            } catch (InvalidPathException e) {
                // Fallback if file not a valid Path.
                changes.put(file, file);
            }
        } else {
            changes.put(file, Boolean.FALSE);
        }
    }
    updateJar(src, dest, changes);
}
 
Example 10
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 11
Source Project: jdk8u60   Source File: ProxyClassesDumper.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 12
Node createNode() {
	String imageUrl;
	try {
		imageUrl = (basePath != null)
			? basePath.resolve(url).toUri().toString()
			: "file:" + url;
	} catch (InvalidPathException ex) {
		return createErrorNode();
	}

	// load image
	Image image = loadImage(imageUrl);
	if (image.isError())
		return createErrorNode(); // loading failed

	// create image view
	ImageView view = new ImageView(image);
	view.setPreserveRatio(true);
	view.setFitWidth(Math.min(image.getWidth(),MAX_SIZE));
	view.setFitHeight(Math.min(image.getHeight(),MAX_SIZE));
	return view;
}
 
Example 13
Source Project: jimfs   Source File: WindowsPathType.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse the root of a UNC-style path, throwing an exception if the path does not start with a
 * valid UNC root.
 */
private String parseUncRoot(String path, String original) {
  Matcher uncMatcher = UNC_ROOT.matcher(path);
  if (uncMatcher.find()) {
    String host = uncMatcher.group(2);
    if (host == null) {
      throw new InvalidPathException(original, "UNC path is missing hostname");
    }
    String share = uncMatcher.group(3);
    if (share == null) {
      throw new InvalidPathException(original, "UNC path is missing sharename");
    }

    return path.substring(uncMatcher.start(), uncMatcher.end());
  } else {
    // probably shouldn't ever reach this
    throw new InvalidPathException(original, "Invalid UNC path");
  }
}
 
Example 14
Source Project: Bytecoder   Source File: ProxyClassesDumper.java    License: Apache License 2.0 6 votes vote down vote up
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Path.of(path.isEmpty() ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
 
Example 15
Source Project: zap-extensions   Source File: ZestZapUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static String extractFileName(String filePath) {
    if (filePath == null || filePath.isEmpty()) {
        return "";
    }

    Path file;
    try {
        file = Paths.get(filePath);
    } catch (InvalidPathException e) {
        log.warn("Failed to parse the file path: " + filePath, e);
        return "";
    }

    Path fileName = file.getFileName();
    if (fileName == null) {
        return "";
    }
    return fileName.toString();
}
 
Example 16
Source Project: BashSupport   Source File: BashRunConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String suggestedName() {
    if (scriptName == null || scriptName.isEmpty()) {
        return null;
    }

    try {
        Path fileName = (Paths.get(scriptName)).getFileName();
        if (fileName == null) {
            return null;
        }

        String name = fileName.toString();

        int ind = name.lastIndexOf('.');
        if (ind != -1) {
            return name.substring(0, ind);
        }
        return name;
    } catch (InvalidPathException e) {
        return null;
    }
}
 
Example 17
Source Project: Bytecoder   Source File: ProxyClassesDumper.java    License: Apache License 2.0 6 votes vote down vote up
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 18
public void dumpClass(String className, final byte[] classBytes) {
    Path file;
    try {
        file = dumpDir.resolve(encodeForFilename(className) + ".class");
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Invalid path for class " + className);
        return;
    }

    try {
        Path dir = file.getParent();
        Files.createDirectories(dir);
        Files.write(file, classBytes);
    } catch (Exception ignore) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Exception writing to path at " + file.toString());
        // simply don't care if this operation failed
    }
}
 
Example 19
Source Project: jdk8u-jdk   Source File: ProxyClassesDumper.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
 
Example 20
Source Project: pdfsam   Source File: PdfsamApp.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void init() {
    STOPWATCH.start();
    rawParameters = getParameters().getRaw();
    verboseIfRequired();
    startLogAppender();
    System.setProperty(PDDocumentHandler.SAMBOX_USE_ASYNC_WRITER, Boolean.TRUE.toString());
    System.setProperty(Sejda.UNETHICAL_READ_PROPERTY_NAME, Boolean.TRUE.toString());
    LOG.info("Starting PDFsam");
    clean = rawParameters.contains("--clean") || rawParameters.contains("-clean") || rawParameters.contains("-c");
    cleanUserContextIfNeeded(userContext);
    String localeString = userContext.getLocale();
    if (isNotBlank(localeString)) {
        eventStudio().broadcast(new SetLocaleEvent(localeString));
    }
    String defaultworkingPath = userContext.getDefaultWorkingPath();
    if (isNotBlank(defaultworkingPath)) {
        try {
            if (Files.isDirectory(Paths.get(defaultworkingPath))) {
                eventStudio().broadcast(new SetLatestDirectoryEvent(new File(defaultworkingPath)));
            }
        } catch (InvalidPathException e) {
            LOG.warn("Unable to set initial directory, default path is invalid.", e);
        }
    }
}
 
Example 21
Source Project: openjdk-jdk8u   Source File: Command.java    License: GNU General Public License v2.0 6 votes vote down vote up
final protected Path getJFRInputFile(Deque<String> options) throws UserSyntaxException, UserDataException {
    if (options.isEmpty()) {
        throw new UserSyntaxException("missing file");
    }
    String file = options.removeLast();
    if (file.startsWith("--")) {
        throw new UserSyntaxException("missing file");
    }
    try {
        Path path = Paths.get(file).toAbsolutePath();
        ensureAccess(path);
        ensureJFRFile(path);
        return path;
    } catch (IOError ioe) {
        throw new UserDataException("i/o error reading file '" + file + "', " + ioe.getMessage());
    } catch (InvalidPathException ipe) {
        throw new UserDataException("invalid path '" + file + "'");
    }
}
 
Example 22
Source Project: openjdk-jdk8u   Source File: DCmdDump.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void dump(PlatformRecorder recorder, Recording recording, String name, String filename, Long maxSize, Boolean pathToGcRoots, Instant beginTime, Instant endTime) throws DCmdException {
    try (PlatformRecording r = newSnapShot(recorder, recording, pathToGcRoots)) {
        r.filter(beginTime, endTime, maxSize);
        if (r.getChunks().isEmpty()) {
            throw new DCmdException("Dump failed. No data found in the specified interval.");
        }
        SafePath dumpFile = resolvePath(recording, filename);

        // Needed for JVM
        Utils.touch(dumpFile.toPath());
        r.dumpStopped(new WriteableUserPath(dumpFile.toPath()));
        reportOperationComplete("Dumped", name, dumpFile);
    } catch (IOException | InvalidPathException e) {
        throw new DCmdException("Dump failed. Could not copy recording data. %s", e.getMessage());
    }
}
 
Example 23
Source Project: jolie   Source File: FileService.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@RequestResponse
public Value getParentPath( Value request ) throws FaultException {
	Value response = Value.create();
	String fileName = request.strValue();
	URI uri = null;
	Path parent = null;

	try {
		uri = new URL( fileName ).toURI();
		parent = Paths.get( uri ).getParent();
	} catch( InvalidPathException | URISyntaxException | MalformedURLException invalidPathException ) {
		throw new FaultException( invalidPathException );
	}

	if( parent == null ) {
		throw new FaultException( new InvalidPathException( fileName, "Path has no parent" ) );
	}

	response.setValue( parent.toString() );

	return response;
}
 
Example 24
private URL assertUrl(String urlString) throws IOException{
	if (StringUtils.isBlank(urlString)) {
		throw new IOException("urlString is null");
	}
	
	URL url = isValidURL(urlString);
	if (url != null) {
		return url;
	} else {
		File file = new File(urlString);
		try {
			file.toPath();
			return file.toURI().toURL();
		} catch (InvalidPathException e) {
		}
		
		if (StringUtils.startsWith(urlString, "\\\\")) {
			String replaced = urlString.replace("\\", "/");
			return isValidURL("smb:" + replaced);
		}
	}
	
	throw new IOException("Can not handle url string [" + urlString + "]");
}
 
Example 25
Source Project: RepoSense   Source File: RepoLocation.java    License: MIT License 6 votes vote down vote up
/**
 * Verifies {@code location} can be presented as a {@code URL} or {@code Path}.
 * @throws InvalidLocationException if otherwise.
 */
private void verifyLocation(String location) throws InvalidLocationException {
    boolean isValidPathLocation = false;
    boolean isValidGitUrl = false;

    try {
        Path pathLocation = Paths.get(location);
        isValidPathLocation = Files.exists(pathLocation);
    } catch (InvalidPathException ipe) {
        // Ignore exception
    }

    try {
        new URL(location);
        isValidGitUrl = location.endsWith(GIT_LINK_SUFFIX);
    } catch (MalformedURLException mue) {
        // Ignore exception
    }

    if (!isValidPathLocation && !isValidGitUrl) {
        throw new InvalidLocationException(location + " is an invalid location.");
    }
}
 
Example 26
Source Project: mycore   Source File: MCRDirectoryStream.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    if (path != null) {
        MCRPath file = checkRelativePath(path);
        if (file.getNameCount() != 1) {
            throw new InvalidPathException(path.toString(), "'path' must have one name component.");
        }
    }
    checkClosed();
    if (type == null) {
        throw new NullPointerException();
    }
    //must support BasicFileAttributeView
    if (type == BasicFileAttributeView.class) {
        return (V) new BasicFileAttributeViewImpl(this, path);
    }
    if (type == MCRMD5AttributeView.class) {
        return (V) new MD5FileAttributeViewImpl(this, path);
    }
    return null;
}
 
Example 27
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
 
Example 28
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
 
Example 29
Source Project: mycore   Source File: MCRFileSystemUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
static MCRPath checkPathAbsolute(Path path) {
    MCRPath mcrPath = MCRPath.toMCRPath(path);
    if (!(Objects.requireNonNull(mcrPath.getFileSystem(), "'path' requires a associated filesystem.")
        .provider() instanceof MCRFileSystemProvider)) {
        throw new ProviderMismatchException("Path does not match to this provider: " + path);
    }
    if (!mcrPath.isAbsolute()) {
        throw new InvalidPathException(mcrPath.toString(), "'path' must be absolute.");
    }
    return mcrPath;
}
 
Example 30
/**
 * Check if the path is valid directory.
 *
 * @param path
 * @return true, if path is valid directory, else return false
 */
public static boolean isValidPath(String path) {
  try {
    return Files.isDirectory(Paths.get(path));
  } catch (InvalidPathException | NullPointerException ex) {
    return Boolean.FALSE;
  }
}