Search in sources :

Example 66 with InvalidPathException

use of java.nio.file.InvalidPathException in project knime-core by knime.

the class ListFilesSettings method getRootsFromLocationString.

/**
 * Split location string by ";" and return individual directories.
 *
 * @return A list of files representing directories.
 * @throws InvalidSettingsException If the argument is invalid or does not represent a list of existing directories.
 */
public Collection<URL> getRootsFromLocationString() throws InvalidSettingsException {
    if (m_locationString == null || m_locationString.equals("")) {
        throw new InvalidSettingsException("Please select a folder!");
    }
    String[] subs = m_locationString.split(";");
    List<URL> result = new ArrayList<URL>();
    for (String s : subs) {
        try {
            URL u = FileUtil.toURL(s);
            if ("file".equalsIgnoreCase(u.getProtocol())) {
                Path p = Paths.get(u.toURI());
                if (!Files.isDirectory(p)) {
                    throw new InvalidSettingsException("\"" + s + "\" does not exist or is not a directory");
                }
            } else if (!"knime".equalsIgnoreCase(u.getProtocol())) {
                throw new InvalidSettingsException("Listing of " + u.getProtocol() + " URLs is not supported.");
            } else {
                Path resolved = FileUtil.resolveToPath(u);
                if ((resolved != null) && !Files.isDirectory(resolved)) {
                    throw new InvalidSettingsException("\"" + s + "\" does not exist or is not a directory");
                }
            }
            result.add(u);
        } catch (InvalidPathException e) {
            throw new InvalidSettingsException("Can not resolve \"" + s + "\" to a local path.", e);
        } catch (IOException e) {
            throw new InvalidSettingsException("Can not resolve \"" + s + "\" to a local path.", e);
        } catch (URISyntaxException e) {
            throw new InvalidSettingsException("Can not resolve \"" + s + "\" to a local path.", e);
        }
    }
    return result;
}
Also used : Path(java.nio.file.Path) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) InvalidPathException(java.nio.file.InvalidPathException)

Example 67 with InvalidPathException

use of java.nio.file.InvalidPathException in project knime-core by knime.

the class FilesHistoryPanel method getOutputFileName.

private String getOutputFileName() {
    // file chooser triggered by choose button
    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setAcceptAllFileFilterUsed(true);
    List<SimpleFileFilter> filters = createFiltersFromSuffixes(m_suffixes);
    for (SimpleFileFilter filter : filters) {
        fileChooser.addChoosableFileFilter(filter);
    }
    if (filters.size() > 0) {
        fileChooser.setFileFilter(filters.get(0));
    }
    fileChooser.setFileSelectionMode(m_selectMode);
    fileChooser.setDialogType(m_dialogType);
    // AP-2562
    // It seems only resized event is happening when showing the dialog
    // Grabbing the focus then makes two clicks to single click selection.
    fileChooser.addComponentListener(new ComponentAdapter() {

        @Override
        public void componentResized(final ComponentEvent e) {
            fileChooser.grabFocus();
        }
    });
    try {
        URL url = FileUtil.toURL(getSelectedFileWithPropertiesReplaced());
        Path localPath = FileUtil.resolveToPath(url);
        if (localPath != null) {
            if (Files.isDirectory(localPath)) {
                fileChooser.setCurrentDirectory(localPath.toFile());
            } else {
                fileChooser.setSelectedFile(localPath.toFile());
            }
        }
    } catch (IOException | URISyntaxException | InvalidPathException ex) {
    // ignore
    }
    int r;
    /* This if construct is result of a fix for bug 5841.
        * showDialog does not resolve localized folder names correctly under Mac OS,
        * so we use the methods showSaveDialog and showOpenDialog if possible.
        */
    if (this.m_dialogType == JFileChooser.SAVE_DIALOG) {
        r = fileChooser.showSaveDialog(FilesHistoryPanel.this);
    } else if (this.m_dialogType == JFileChooser.OPEN_DIALOG) {
        r = fileChooser.showOpenDialog(FilesHistoryPanel.this);
    } else {
        r = fileChooser.showDialog(FilesHistoryPanel.this, "OK");
    }
    if (r == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        if (m_dialogType == JFileChooser.SAVE_DIALOG) {
            String forceFileExtension = StringUtils.defaultString(m_forcedFileExtensionOnSave);
            final String fileName = file.getName();
            if (!(StringUtils.endsWithAny(fileName, m_suffixes) || StringUtils.endsWithIgnoreCase(fileName, m_forcedFileExtensionOnSave))) {
                file = new File(file.getParentFile(), fileName.concat(forceFileExtension));
            }
        }
        if (file.exists() && (m_selectMode == JFileChooser.FILES_ONLY) && file.isDirectory()) {
            JOptionPane.showMessageDialog(this, "Error: Please select a file, not a directory.");
            return null;
        }
        return file.getAbsolutePath();
    }
    return null;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) InvalidPathException(java.nio.file.InvalidPathException) JFileChooser(javax.swing.JFileChooser) SimpleFileFilter(org.knime.core.util.SimpleFileFilter) ComponentEvent(java.awt.event.ComponentEvent) File(java.io.File) ComponentAdapter(java.awt.event.ComponentAdapter)

Example 68 with InvalidPathException

use of java.nio.file.InvalidPathException in project graal by oracle.

the class PathUtilities method sanitizeFileName.

/**
 * Gets a value based on {@code name} that can be passed to {@link Paths#get(String, String...)}
 * without causing an {@link InvalidPathException}.
 *
 * @return {@code name} with all characters invalid for the current file system replaced by
 *         {@code '_'}
 */
public static String sanitizeFileName(String name) {
    try {
        Path path = Paths.get(name);
        if (path.getNameCount() == 0) {
            return name;
        }
    } catch (InvalidPathException e) {
    // fall through
    }
    StringBuilder buf = new StringBuilder(name.length());
    for (int i = 0; i < name.length(); i++) {
        char c = name.charAt(i);
        if (c != File.separatorChar && c != ' ' && !Character.isISOControl(c)) {
            try {
                Paths.get(String.valueOf(c));
                buf.append(c);
                continue;
            } catch (InvalidPathException e) {
            }
        }
        buf.append('_');
    }
    return buf.toString();
}
Also used : Path(java.nio.file.Path) InvalidPathException(java.nio.file.InvalidPathException)

Example 69 with InvalidPathException

use of java.nio.file.InvalidPathException in project Universal-Pointer-Searcher by BullyWiiPlaza.

the class MemoryDumpDialog method runComponentAvailabilitySetter.

private void runComponentAvailabilitySetter() {
    val thread = new Thread(() -> {
        // Wait till the dialog is visible
        while (!isShowing()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
        // Keep setting the availability and background colors
        while (isShowing()) {
            // Verify the file path
            val filePath = filePathField.getText();
            var isFilePathValid = false;
            try {
                isFilePathValid = isRegularFile(Paths.get(filePath));
            } catch (InvalidPathException ignored) {
            }
            val finalIsFilePathValid = isFilePathValid;
            invokeLater(() -> filePathField.setBackground(finalIsFilePathValid ? VALID_INPUT_COLOR : INVALID_INPUT_COLOR));
            // Verify the starting address
            var startingAddress = -1L;
            try {
                startingAddress = parseUnsignedLong(startingAddressField.getText(), 16);
            } catch (NumberFormatException ignored) {
            }
            val maximumInteger = getMaximumInteger();
            val isStartingAddressFieldValid = startingAddress >= 0 && startingAddress <= maximumInteger;
            invokeLater(() -> startingAddressField.setBackground(isStartingAddressFieldValid ? VALID_INPUT_COLOR : INVALID_INPUT_COLOR));
            // Verify the target address
            val isTargetAddressFieldValid = isTargetAddressFieldValid(filePath, startingAddress, isStartingAddressFieldValid);
            val isAddingMemoryDumpAllowed = isFilePathValid && isStartingAddressFieldValid && isTargetAddressFieldValid;
            invokeLater(() -> confirmMemoryDumpButton.setEnabled(isAddingMemoryDumpAllowed));
            try {
                Thread.sleep(50);
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
    });
    thread.start();
}
Also used : lombok.val(lombok.val) lombok.experimental.var(lombok.experimental.var) InvalidPathException(java.nio.file.InvalidPathException)

Example 70 with InvalidPathException

use of java.nio.file.InvalidPathException in project sis by apache.

the class ChannelFactory method prepare.

/**
 * Returns a byte channel factory from the given input or output,
 * or {@code null} if the given input/output is of unknown type.
 * More specifically:
 *
 * <ul>
 *   <li>If the given storage is {@code null}, then this method returns {@code null}.</li>
 *   <li>If the given storage is a {@link ReadableByteChannel} or an {@link InputStream},
 *       then the factory will return that input directly or indirectly as a wrapper.</li>
 *   <li>If the given storage is a {@link WritableByteChannel} or an {@link OutputStream}
 *       and the {@code allowWriteOnly} argument is {@code true},
 *       then the factory will return that output directly or indirectly as a wrapper.</li>
 *   <li>If the given storage if a {@link Path}, {@link File}, {@link URL}, {@link URI}
 *       or {@link CharSequence}, then the factory will open new channels on demand.</li>
 * </ul>
 *
 * The given options are used for opening the channel on a <em>best effort basis</em>.
 * In particular, even if the caller provided the {@code WRITE} option, he still needs
 * to verify if the returned channel implements {@link java.nio.channels.WritableByteChannel}.
 * This is because the channel may be opened by {@link URL#openStream()}, in which case the
 * options are ignored.
 *
 * <p>The following options are illegal for read operations and will cause an exception to be
 * thrown if provided while {@code allowWriteOnly} is {@code false}:
 * {@code APPEND}, {@code TRUNCATE_EXISTING}, {@code DELETE_ON_CLOSE}. We reject those options
 * because this method is primarily designed for readable channels, with optional data edition.
 * Since the write option is not guaranteed to be honored, we have to reject the options that
 * would alter significatively the channel behavior depending on whether we have been able to
 * honor the options or not.</p>
 *
 * @param  storage         the stream or the file to open, or {@code null}.
 * @param  encoding        if the input is an encoded URL, the character encoding (normally {@code "UTF-8"}).
 *                         If the URL is not encoded, then {@code null}. This argument is ignored if the given
 *                         input does not need to be converted from URL to {@code File}.
 * @param  allowWriteOnly  whether to allow wrapping {@link WritableByteChannel} and {@link OutputStream}.
 * @param  options         the options to use for creating a new byte channel. Can be null or empty for read-only.
 * @return the channel factory for the given input, or {@code null} if the given input is of unknown type.
 * @throws IOException if an error occurred while processing the given input.
 */
public static ChannelFactory prepare(Object storage, final String encoding, final boolean allowWriteOnly, OpenOption... options) throws IOException {
    /*
         * Unconditionally verify the options (unless 'allowWriteOnly' is true),
         * even if we may not use them.
         */
    final Set<OpenOption> optionSet;
    if (options == null || options.length == 0) {
        optionSet = Collections.singleton(StandardOpenOption.READ);
    } else {
        optionSet = new HashSet<>(Arrays.asList(options));
        optionSet.add(StandardOpenOption.READ);
        if (!allowWriteOnly && optionSet.removeAll(ILLEGAL_OPTIONS)) {
            throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalArgumentValue_2, "options", Arrays.toString(options)));
        }
    }
    /*
         * Check for inputs that are already readable channels or input streams.
         * Note that Channels.newChannel(InputStream) checks for instances of FileInputStream in order to delegate
         * to its getChannel() method, but only if the input stream type is exactly FileInputStream, not a subtype.
         * If Apache SIS defines its own FileInputStream subclass someday, we may need to add a special case here.
         */
    if (storage instanceof ReadableByteChannel || (allowWriteOnly && storage instanceof WritableByteChannel)) {
        return new Stream((Channel) storage);
    } else if (storage instanceof InputStream) {
        return new Stream(Channels.newChannel((InputStream) storage));
    } else if (allowWriteOnly && storage instanceof OutputStream) {
        return new Stream(Channels.newChannel((OutputStream) storage));
    }
    /*
         * In the following cases, we will try hard to convert to Path objects before to fallback
         * on File, URL or URI, because only Path instances allow us to use the given OpenOptions.
         */
    if (storage instanceof URL) {
        try {
            storage = IOUtilities.toPath((URL) storage, encoding);
        } catch (IOException e) {
            /*
                 * This is normal if the URL uses HTTP or FTP protocol for instance. Log the exception at FINE
                 * level without stack trace. We will open the channel later using the URL instead than the Path.
                 */
            recoverableException(e);
        }
    } else if (storage instanceof URI) {
        /*
             * If the user gave us a URI, try to convert to a Path before to fallback to URL, in order to be
             * able to use the given OpenOptions.  Note that the conversion to Path is likely to fail if the
             * URL uses HTTP or FTP protocols, because JDK7 does not provide file systems for them by default.
             */
        final URI uri = (URI) storage;
        if (!uri.isAbsolute()) {
            /*
                 * All methods invoked in this block throws IllegalArgumentException if the URI has no scheme,
                 * so we are better to check now and provide a more appropriate exception for this method.
                 */
            throw new IOException(Resources.format(Resources.Keys.MissingSchemeInURI_1, uri));
        } else
            try {
                storage = Paths.get(uri);
            } catch (IllegalArgumentException | FileSystemNotFoundException e) {
                try {
                    storage = uri.toURL();
                } catch (MalformedURLException ioe) {
                    ioe.addSuppressed(e);
                    throw ioe;
                }
                /*
                 * We have been able to convert to URL, but the given OpenOptions may not be used.
                 * Log the exception at FINE level without stack trace, because the exception is
                 * probably a normal behavior in this context.
                 */
                recoverableException(e);
            }
    } else {
        if (storage instanceof CharSequence) {
            // Needs to be before the check for File or URL.
            storage = IOUtilities.toFileOrURL(storage.toString(), encoding);
        }
        /*
             * If the input is a File or a CharSequence that we have been able to convert to a File,
             * try to convert to a Path in order to be able to use the OpenOptions. Only if we fail
             * to convert to a Path (which is unlikely), we will use directly the File.
             */
        if (storage instanceof File) {
            final File file = (File) storage;
            try {
                storage = file.toPath();
            } catch (final InvalidPathException e) {
                /*
                     * Unlikely to happen. But if it happens anyway, try to open the channel in a
                     * way less surprising for the user (closer to the object he has specified).
                     */
                if (file.isFile()) {
                    return new Fallback(file, e);
                }
            }
        }
    }
    /*
         * One last check for URL. The URL may be either the given input if we have not been able
         * to convert it to a Path, or a URI, File or CharSequence input converted to URL. Do not
         * try to convert the URL to a Path, because this has already been tried before this point.
         */
    if (storage instanceof URL) {
        final URL file = (URL) storage;
        return new ChannelFactory() {

            @Override
            public ReadableByteChannel readable(String filename, WarningListeners<DataStore> listeners) throws IOException {
                return Channels.newChannel(file.openStream());
            }

            @Override
            public WritableByteChannel writable(String filename, WarningListeners<DataStore> listeners) throws IOException {
                return Channels.newChannel(file.openConnection().getOutputStream());
            }
        };
    }
    if (storage instanceof Path) {
        final Path path = (Path) storage;
        if (Files.isRegularFile(path)) {
            return new ChannelFactory() {

                @Override
                public ReadableByteChannel readable(String filename, WarningListeners<DataStore> listeners) throws IOException {
                    return Files.newByteChannel(path, optionSet);
                }

                @Override
                public WritableByteChannel writable(String filename, WarningListeners<DataStore> listeners) throws IOException {
                    return Files.newByteChannel(path, optionSet);
                }
            };
        }
    }
    return null;
}
Also used : Path(java.nio.file.Path) ReadableByteChannel(java.nio.channels.ReadableByteChannel) WarningListeners(org.apache.sis.util.logging.WarningListeners) MalformedURLException(java.net.MalformedURLException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) WritableByteChannel(java.nio.channels.WritableByteChannel) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) InvalidPathException(java.nio.file.InvalidPathException) OpenOption(java.nio.file.OpenOption) StandardOpenOption(java.nio.file.StandardOpenOption) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File)

Aggregations

InvalidPathException (java.nio.file.InvalidPathException)111 Path (java.nio.file.Path)58 IOException (java.io.IOException)30 File (java.io.File)17 URL (java.net.URL)15 MalformedURLException (java.net.MalformedURLException)12 Test (org.junit.Test)11 AlluxioURI (alluxio.AlluxioURI)7 ArrayList (java.util.ArrayList)7 Resource (org.springframework.core.io.Resource)7 Nullable (org.springframework.lang.Nullable)7 URI (java.net.URI)6 URISyntaxException (java.net.URISyntaxException)6 FileDoesNotExistException (alluxio.exception.FileDoesNotExistException)5 BufferedReader (java.io.BufferedReader)5 URIStatus (alluxio.client.file.URIStatus)4 ViewResolve (com.nvlad.yii2support.views.entities.ViewResolve)4 RepositoryChanged (com.searchcode.app.dto.RepositoryChanged)4 InputStream (java.io.InputStream)4 InputStreamReader (java.io.InputStreamReader)4