下面列出了怎么用java.nio.file.InvalidPathException的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
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
}
}
/**
* @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);
}
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);
}
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;
}
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
}
}
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
}
}
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;
}
/**
* 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);
}
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
}
}
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
}
}
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;
}
/**
* 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");
}
}
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;
}
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();
}
@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;
}
}
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
}
}
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
}
}
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;
}
@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);
}
}
}
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 + "'");
}
}
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());
}
}
@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;
}
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 + "]");
}
/**
* 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.");
}
}
@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;
}
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;
}
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;
}
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;
}
/**
* 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;
}
}