/** * Make a temporary copy of a JAR file. */ static File makeTempJar(File moduleFile) throws IOException { String prefix = moduleFile.getName(); if (prefix.endsWith(".jar") || prefix.endsWith(".JAR")) { // NOI18N prefix = prefix.substring(0, prefix.length() - 4); } if (prefix.length() < 3) prefix += '.'; if (prefix.length() < 3) prefix += '.'; if (prefix.length() < 3) prefix += '.'; String suffix = "-test.jar"; // NOI18N File physicalModuleFile = File.createTempFile(prefix, suffix); physicalModuleFile.deleteOnExit(); try (InputStream is = Files.newInputStream(moduleFile.toPath()); OutputStream os = Files.newOutputStream(physicalModuleFile.toPath())) { byte[] buf = new byte[4096]; int i; while ((i = is.read(buf)) != -1) { os.write(buf, 0, i); } } catch (InvalidPathException ex) { throw new IOException(ex); } err.fine("Made " + physicalModuleFile); return physicalModuleFile; }
private static boolean clustersChanged() { if (clustersChanged != null) { return clustersChanged; } final String clustersCache = "all-clusters.dat"; // NOI18N File f = fileImpl(clustersCache, null, -1); // no timestamp check if (f != null) { try (DataInputStream dis = new DataInputStream(Files.newInputStream(f.toPath()))) { if (Clusters.compareDirs(dis)) { return false; } } catch (IOException | InvalidPathException ex) { return clustersChanged = true; } } else { // missing cluster file signals caches are OK, for // backward compatibility return clustersChanged = false; } return clustersChanged = true; }
protected byte[] readClass(String path) throws IOException { File clsFile = new File(dir, path.replace('/', File.separatorChar)); if (!clsFile.exists()) return null; int len = (int)clsFile.length(); byte[] data = new byte[len]; try (InputStream is = Files.newInputStream(clsFile.toPath())) { int count = 0; while (count < len) { count += is.read(data, count, len - count); } return data; } catch (InvalidPathException ex) { throw new IOException(ex); } }
private static File copyJAR(FileObject fo, URI archiveFileURI, boolean replace) throws IOException { synchronized (copiedJARs) { File copy = copiedJARs.get(archiveFileURI); if (copy == null || replace) { if (copy == null) { copy = File.createTempFile("copy", "-" + archiveFileURI.toString().replaceFirst(".+/", "")); // NOI18N copy = copy.getCanonicalFile(); copy.deleteOnExit(); } try (InputStream is = fo.getInputStream(); OutputStream os = Files.newOutputStream(copy.toPath())) { FileUtil.copy(is, os); } catch (InvalidPathException ex) { throw new IOException(ex); } copiedJARs.put(archiveFileURI, copy); } return copy; } }
protected OutputStream outputStream(final String name) throws java.io.IOException { File f = getFile(name); if (!f.exists()) { f.getParentFile().mkdirs(); } try { OutputStream retVal = new BufferedOutputStream(Files.newOutputStream(f.toPath())); // workaround for #42624 if (BaseUtilities.isMac()) { retVal = getOutputStreamForMac42624(retVal, name); } return retVal; } catch (InvalidPathException ex) { throw new IOException(ex); } }
private static boolean pathToURISupported() { Boolean res = pathURIConsistent; if (res == null) { boolean c; try { final File f = new File("küñ"); //NOI18N c = f.toPath().toUri().equals(f.toURI()); } catch (InvalidPathException e) { c = false; } if (!c) { LOG.fine("The java.nio.file.Path.toUri is inconsistent with java.io.File.toURI"); //NOI18N } res = pathURIConsistent = c; } return res; }
private String randomNonTranslogPatternString(int min, int max) { String string; boolean validPathString; do { validPathString = false; string = randomRealisticUnicodeOfCodepointLength(randomIntBetween(min, max)); try { final Path resolved = translogDir.resolve(string); // some strings (like '/' , '..') do not refer to a file, which we this method should return validPathString = resolved.getFileName() != null; } catch (InvalidPathException ex) { // some FS don't like our random file names -- let's just skip these random choices } } while (Translog.PARSE_STRICT_ID_PATTERN.matcher(string).matches() || validPathString == false); return string; }
private static Path createPathFromText(String text) { if (text == null || text.isEmpty()) return null; if (text.startsWith("\"") && text.endsWith("\"")) text = text.substring(1, text.length() - 1); if (!text.endsWith(DLL_NAME)) return null; try { Path path = Paths.get(text); if (!Files.isRegularFile(path)) { error("Read error", "The DLL file you selected cannot be found."); return null; } else if (!Files.isReadable(path) || !Files.isWritable(path)) { error("Read error", "The DLL file you selected cannot be read from or written to.\n\n" + "Make sure that the file is not marked read-only and\n" + "that you have the required permissions to write to it."); return null; } return path; } catch (InvalidPathException ipe) { return null; } }
public static Path parseRelativePath(Node node, Path def) throws InvalidXMLException { if(node == null) return def; final String text = node.getValueNormalize(); try { Path path = Paths.get(text); if(path.isAbsolute()) { throw new InvalidPathException(text, "Path is not relative"); } for(Path part : path) { if(part.toString().trim().startsWith("..")) { throw new InvalidPathException(text, "Path contains an invalid component"); } } return path; } catch(InvalidPathException e) { throw new InvalidXMLException("Invalid relative path '" + text + "'", node, e); } }
/** * @param name Absolute path */ public Local(final String name) throws LocalAccessDeniedException { String path = name; if(PreferencesFactory.get().getBoolean("local.normalize.unicode")) { path = new NFCNormalizer().normalize(path).toString(); } if(PreferencesFactory.get().getBoolean("local.normalize.tilde")) { path = new TildeExpander().expand(path); } if(PreferencesFactory.get().getBoolean("local.normalize.prefix")) { path = new WorkdirPrefixer().normalize(path); } try { this.path = Paths.get(path).toString(); } catch(InvalidPathException e) { throw new LocalAccessDeniedException(String.format("The name %s is not a valid path for the filesystem", path), e); } this.attributes = new LocalAttributes(path); }
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 } }
@Override public final List<Plugin> loadPlugins(String pluginFolder, boolean autoregister) { File folder = new File(pluginFolder); LOGGER.debug("Loading from supplied plugin folder"); if (!folder.isDirectory()) { throw new InvalidPathException(pluginFolder, "Set a valid plugin directory"); } else { List<Plugin> loaded; // if (isDebug()) { // loaded = loadDebug(folder); // } else { loaded = load(folder); // } if (autoregister) { for (Plugin p : loaded) { getContext().addPlugin(p); } return loaded; } else { return loaded; } } }
@Override public boolean isValid(final String value, final ConstraintValidatorContext context) { try { if (StringUtils.isEmpty(value)) { return true; // do not validate empty value there are other constraints for that e.g. @NotNull, @Size etc... } final Path path = Paths.get(value); if (checkIfExists && !path.toFile().exists()) { return false; } final String fileExt = FilenameUtils.getExtension(value); return allowableFileExtensions.isEmpty() || !allowableFileExtensions.stream().filter(fileExt::equalsIgnoreCase).findFirst().orElse(StringUtils.EMPTY).isEmpty(); } catch (final InvalidPathException e) { LOGGER.error(e.getMessage(), e); return false; } }
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<>() { @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 char[] normalize( char[] path ) { if( path.length == 0 ) { return path; } char prevC = 0; for( int i = 0; i < path.length; i++ ) { char c = path[i]; if( c == '\\' ) { return normalize( path, i ); } if( c == (char) '/' && prevC == '/' ) { return normalize( path, i - 1 ); } if( c == '\u0000' ) { throw new InvalidPathException( String.valueOf( path ), "Path: nul character not allowed" ); } prevC = c; } return path; }
/** * Create a subpath (subdirectory or file) below a given path. * * The provided element name is sanitized first if necessary. * * @param path * Path to create new element below * @param subElement * Name representing single path segment (slashes will be * replaced) * @return Resulting path with new subelement */ public static Path createSafeSubpath(final Path path, final String subElement) { // remove slashes, as subElement just represents a single segment String halfSafeElement = subElement.replaceAll("[\\\\/]", "_"); // - leading dots may hide items in some systems // - trailing dots are ignored in windows // => replace both to avoid side effects halfSafeElement = halfSafeElement.replaceAll("^\\.+|\\.+$", "_"); Path subPath; try { // try without sanitizing first, because the user's FS might // be less restrictive subPath = path.resolve(halfSafeElement); } catch (InvalidPathException e) { subPath = path.resolve(PathUtil.sanitizePathElement(halfSafeElement)); } return subPath; }
/** * Validates that the source download location is a valid path name. * * @param logger * used to log any messages */ protected void validateTargetFolder(PrintStream logger) { String targetFolder = getTargetFolder(); if (StringUtils.isNotEmpty(targetFolder)) { logger.println(Messages.targetFolder() + " = " + targetFolder); //$NON-NLS-1$ try { Paths.get(targetFolder); } catch (InvalidPathException exc) { throw new IllegalArgumentException(Messages.invalidSourceDownloadLocation(exc.getLocalizedMessage())); } } }
public static void main(String[] args) { FileSystem fs = FileSystems.getDefault(); String linuxPath = "/home/ard/Documents/tmp-pdf.txt"; // this is a linux filesytem path. String windowsPath = "C:\\Users\\aaron.decker\\Documents"; // in java you must escape backslashes Path testPath = fs.getPath(linuxPath); System.out.println(testPath); Path testPath2 = fs.getPath(windowsPath, "tmp.txt"); System.out.println(testPath2); try { // null char is not allowed on linux "\0" // on windows ? is not allowed. Path testPath3 = fs.getPath("\0"); // special NULL char. System.out.println(testPath3); } catch (InvalidPathException e ) { System.out.println(e); } }
@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; }
/** * Gets the configured custom program {@link Path} from the * {@link Configuration} using the specified key. If the specified key has * no value, {@code null} is returned. * * @param configurationKey the {@link Configuration} key to use. * @return The resulting {@link Path} or {@code null}. * @throws ConfigurationException If the configured value can't be parsed as * a valid {@link Path}. */ @Nullable public Path getCustomProgramPath(@Nullable String configurationKey) throws ConfigurationException { if (isBlank(configurationKey) || configuration == null) { return null; } try { String configuredPath = configuration.getString(configurationKey); if (isBlank(configuredPath)) { return null; } return Paths.get(configuredPath); } catch (ConversionException | InvalidPathException e) { throw new ConfigurationException( "Invalid configured custom program path in \"" + configurationKey + "\": " + e.getMessage(), e ); } }
static LuaFunction loadTextChunkFromFile(FileSystem fileSystem, ChunkLoader loader, String fileName, ByteString modeString, Object env) throws LoaderException { final LuaFunction fn; try { Path p = fileSystem.getPath(fileName); if (!modeString.contains((byte) 't')) { throw new LuaRuntimeException("attempt to load a text chunk (mode is '" + modeString + "')"); } // FIXME: this is extremely wasteful! byte[] bytes = Files.readAllBytes(p); ByteString chunkText = ByteString.copyOf(bytes); fn = loader.loadTextChunk(new Variable(env), fileName, chunkText.toString()); } catch (InvalidPathException | IOException ex) { throw new LoaderException(ex, fileName); } if (fn == null) { throw new LuaRuntimeException("loader returned nil"); } return fn; }
@Nullable private static Path searchPaths(List<String> possiblePaths) { for (String pathString : possiblePaths) { if (pathString != null) { try { Path path = Paths.get(pathString); if (Files.exists(path)) { return path; } } catch (InvalidPathException ex) { // ignore } } } return null; }
@VisibleForTesting Path getWindowsPythonPath() { String cloudSdkPython = System.getenv("CLOUDSDK_PYTHON"); if (cloudSdkPython != null) { Path cloudSdkPythonPath = Paths.get(cloudSdkPython); if (Files.exists(cloudSdkPythonPath)) { return cloudSdkPythonPath; } else { throw new InvalidPathException(cloudSdkPython, "python binary not in specified location"); } } Path pythonPath = getSdkPath().resolve(WINDOWS_BUNDLED_PYTHON); if (Files.exists(pythonPath)) { return pythonPath; } else { return Paths.get("python"); } }
public static BufferedImage loadImage(String path) { try { if (Files.exists(Paths.get(path))) { return ImageIO.read(new File(path)); } InputStream local = DataHandler.class.getResourceAsStream(path); if (local != null) { return ImageIO.read(local); } return ImageIO.read(new URL(path)); } catch (InvalidPathException | IOException exception) { return null; } }
private File generateReport(IScanIssue[] issues){ File report = null; try{ String OS = System.getProperty("os.name").toUpperCase(Locale.getDefault()); Path env; if (OS.contains("WIN")){ env = Paths.get(System.getenv("APPDATA"),"Code Dx","Burp Extension"); } else if (OS.contains("MAC")){ env = Paths.get(System.getProperty("user.home"),"Library","Application Support","Code Dx","Burp Extension"); } else if (OS.contains("NUX")){ env = Paths.get(System.getProperty("user.home"),".codedx","burp-extension"); } else{ env = Paths.get(System.getProperty("user.dir"),"codedx","burp-extension"); } env.toFile().mkdirs(); report = new File(env.toFile(),"Burp.xml"); } catch(SecurityException | InvalidPathException | UnsupportedOperationException e){} callbacks.generateScanReport("XML", issues, report); return report; }
static String getGradlePath(String resourcePath) { String gradlePath = ""; String resourceFilePath = resourcePath; int jarFileIndex = resourcePath.lastIndexOf(EXCLAMATION_MARK); if (jarFileIndex > -1) { resourceFilePath = resourcePath.substring(0, jarFileIndex); } if (resourceFilePath.startsWith(JAR_FILE_PREFIX)) { resourceFilePath = resourceFilePath.replaceAll(JAR_FILE_PREFIX, FILE_PREFIX); } if (!resourceFilePath.startsWith(FILE_PREFIX)) { resourceFilePath = FILE_PREFIX + resourceFilePath; } try { Path jarPath = Paths.get(new URI(resourceFilePath)); gradlePath = jarPath.resolveSibling(GRADLE_FOLDER).toString(); } catch (InvalidPathException | URISyntaxException ex) { LOG.log(Level.SEVERE, null, ex); } return gradlePath; }
/** * Expand * * @param pathWithPlaceholder * @return */ @Override public IPath expand(String pathWithPlaceholder) { String variableName = getPlaceholderName(pathWithPlaceholder); if (variableName == null) { try { return new Path(pathWithPlaceholder); } catch (InvalidPathException e) { return null; } } String other = pathWithPlaceholder.substring(variableName.length() + 4); PathPlaceholder pathPlaceholder = mappings.get(variableName); if (pathPlaceholder == null || pathPlaceholder.getPath() == null) { return null; } return pathPlaceholder.getPath().append(other); }
/** * Export a file to a destination * * @param file: File to export * @param dest: File object with path to destination directory * @param prefix: Prefix to be added to file name * @return true if successful export * @throws IOException * @throws InvalidPathException */ public static boolean exportFile(File file, File dest, String prefix) throws IOException, InvalidPathException { if (!copyFile(file, dest)) { //one of the files failed to be copied return false; } // Resolve file name File resultFile = new File(dest.getAbsolutePath() + File.separator + file.getName()); String resultName = resultFile.getName(); String regex = MATCH_DIGIT_TO_FIRST_ALPHA; resultName = resultName.replaceFirst(regex, ""); // Rename file String targetName = resultFile.getParent() + File.separator + prefix + "_" + resultName; File targetFile = new File(targetName); Path result = Files.move(resultFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); return result.toFile().equals(targetFile); }