Search in sources :

Example 16 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project Universal-G-Code-Sender by winder.

the class FirmwareUtils method initialize.

public static synchronized void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);
    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();
    }
    FileSystem fileSystem = null;
    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";
        URI location = FirmwareUtils.class.getResource(dir).toURI();
        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }
            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }
        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));
                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }
                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }
                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }
    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            // ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}
Also used : Path(java.nio.file.Path) FileNotFoundException(java.io.FileNotFoundException) Gson(com.google.gson.Gson) IOException(java.io.IOException) JsonIOException(com.google.gson.JsonIOException) URI(java.net.URI) FileInputStream(java.io.FileInputStream) JsonSyntaxException(com.google.gson.JsonSyntaxException) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JsonIOException(com.google.gson.JsonIOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonIOException(com.google.gson.JsonIOException) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) FileSystem(java.nio.file.FileSystem) FileReader(java.io.FileReader) File(java.io.File)

Example 17 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project hub-fortify-ssc-integration-service by blackducksoftware.

the class CSVUtils method writeToCSV.

/**
 * It will be used to render the list of vulnerabilities in CSV
 *
 * @param vulnerabilities
 * @param fileName
 * @param delimiter
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
@SuppressWarnings("resource")
public static void writeToCSV(List<Vulnerability> vulnerabilities, String fileName, char delimiter) throws JsonGenerationException, JsonMappingException, FileNotFoundException, UnsupportedEncodingException, IOException {
    // create mapper and schema
    CsvMapper mapper = new CsvMapper();
    // Create the schema with the header
    CsvSchema schema = mapper.schemaFor(Vulnerability.class).withHeader();
    schema = schema.withColumnSeparator(delimiter);
    // output writer
    ObjectWriter objectWriter = mapper.writer(schema);
    File file = new File(fileName);
    FileOutputStream fileOutputStream;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        throw new FileSystemNotFoundException(fileName + " CSV file is not created successfully");
    }
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024);
    OutputStreamWriter writerOutputStream;
    try {
        writerOutputStream = new OutputStreamWriter(bufferedOutputStream, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedEncodingException(e.getMessage());
    }
    // write to CSV file
    try {
        objectWriter.writeValue(writerOutputStream, vulnerabilities);
    } catch (IOException e) {
        throw new IOException("Error while rendering the vulnerabilities in CSV file::" + fileName, e);
    }
}
Also used : CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) CsvMapper(com.fasterxml.jackson.dataformat.csv.CsvMapper) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Vulnerability(com.blackducksoftware.integration.fortify.batch.model.Vulnerability) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 18 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project cucumber-jvm by cucumber.

the class PathScanner method findResourcesForUri.

void findResourcesForUri(URI baseUri, Predicate<Path> filter, Function<Path, Consumer<Path>> consumer) {
    try (CloseablePath closeablePath = open(baseUri)) {
        Path baseDir = closeablePath.getPath();
        findResourcesForPath(baseDir, filter, consumer);
    } catch (FileSystemNotFoundException e) {
        log.warn(e, () -> "Failed to find resources for '" + baseUri + "'");
    } catch (IOException | URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
Also used : Path(java.nio.file.Path) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException)

Example 19 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project spring-framework by spring-projects.

the class PathEditor method setAsText.

@Override
public void setAsText(String text) throws IllegalArgumentException {
    boolean nioPathCandidate = !text.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX);
    if (nioPathCandidate && !text.startsWith("/")) {
        try {
            URI uri = new URI(text);
            if (uri.getScheme() != null) {
                nioPathCandidate = false;
                // Let's try NIO file system providers via Paths.get(URI)
                setValue(Paths.get(uri).normalize());
                return;
            }
        } catch (URISyntaxException ex) {
            // Not a valid URI; potentially a Windows-style path after
            // a file prefix (let's try as Spring resource location)
            nioPathCandidate = !text.startsWith(ResourceUtils.FILE_URL_PREFIX);
        } catch (FileSystemNotFoundException ex) {
        // URI scheme not registered for NIO (let's try URL
        // protocol handlers via Spring's resource mechanism).
        }
    }
    this.resourceEditor.setAsText(text);
    Resource resource = (Resource) this.resourceEditor.getValue();
    if (resource == null) {
        setValue(null);
    } else if (nioPathCandidate && !resource.exists()) {
        setValue(Paths.get(text).normalize());
    } else {
        try {
            setValue(resource.getFile().toPath());
        } catch (IOException ex) {
            throw new IllegalArgumentException("Failed to retrieve file for " + resource, ex);
        }
    }
}
Also used : FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) Resource(org.springframework.core.io.Resource) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI)

Example 20 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project flow by vaadin.

the class StaticFileServerTest method concurrentRequestsToJarResources_checksAreCorrect.

@Test
public void concurrentRequestsToJarResources_checksAreCorrect() throws IOException, InterruptedException, ExecutionException, URISyntaxException {
    fileServer.writeResponse = false;
    Assert.assertTrue("Can not run concurrently with other test", StaticFileServer.openFileSystems.isEmpty());
    final TemporaryFolder folder = TemporaryFolder.builder().build();
    folder.create();
    Path tempArchive = generateZipArchive(folder);
    setupRequestURI("", "", "/frontend/.");
    final URL folderResourceURL = new URL("jar:file:///" + tempArchive.toString().replaceAll("\\\\", "/") + "!/frontend");
    Mockito.when(servletService.getStaticResource("/frontend/.")).thenReturn(folderResourceURL);
    int THREADS = 5;
    List<Callable<Result>> folderNotResource = IntStream.range(0, THREADS).mapToObj(i -> {
        Callable<Result> callable = () -> {
            try {
                if (fileServer.serveStaticResource(request, response)) {
                    throw new IllegalArgumentException("Folder 'frontend' in jar should not be a static resource.");
                }
            } catch (Exception e) {
                return new Result(e);
            }
            return new Result(null);
        };
        return callable;
    }).collect(Collectors.toList());
    ExecutorService executor = Executors.newFixedThreadPool(THREADS);
    List<Future<Result>> futures = executor.invokeAll(folderNotResource);
    List<String> exceptions = new ArrayList<>();
    executor.shutdown();
    for (Future<Result> resultFuture : futures) {
        Result result = resultFuture.get();
        if (result.exception != null) {
            exceptions.add(result.exception.getMessage());
        }
    }
    Assert.assertTrue("There were exceptions in concurrent requests {" + exceptions + "}", exceptions.isEmpty());
    Assert.assertFalse("Folder URI should have been cleared", StaticFileServer.openFileSystems.containsKey(folderResourceURL.toURI()));
    try {
        FileSystems.getFileSystem(folderResourceURL.toURI());
        Assert.fail("FileSystem for folder resource should be closed");
    } catch (FileSystemNotFoundException fsnfe) {
    // This should happen as we should not have an open FileSystem here.
    }
    setupRequestURI("", "", "/file.txt");
    final URL fileResourceURL = new URL("jar:file:///" + tempArchive.toString().replaceAll("\\\\", "/") + "!/file.txt");
    Mockito.when(servletService.getStaticResource("/file.txt")).thenReturn(fileResourceURL);
    List<Callable<Result>> fileIsResource = IntStream.range(0, THREADS).mapToObj(i -> {
        Callable<Result> callable = () -> {
            try {
                if (!fileServer.serveStaticResource(request, response)) {
                    throw new IllegalArgumentException("File 'file.txt' inside jar should be a static resource.");
                }
            } catch (Exception e) {
                return new Result(e);
            }
            return new Result(null);
        };
        return callable;
    }).collect(Collectors.toList());
    executor = Executors.newFixedThreadPool(THREADS);
    futures = executor.invokeAll(fileIsResource);
    exceptions = new ArrayList<>();
    executor.shutdown();
    for (Future<Result> resultFuture : futures) {
        Result result = resultFuture.get();
        if (result.exception != null) {
            exceptions.add(result.exception.getMessage());
        }
    }
    Assert.assertTrue("There were exceptions in concurrent requests {" + exceptions + "}", exceptions.isEmpty());
    Assert.assertFalse("URI should have been cleared", fileServer.openFileSystems.containsKey(fileResourceURL.toURI()));
    try {
        FileSystems.getFileSystem(fileResourceURL.toURI());
        Assert.fail("FileSystem for file resource should be closed");
    } catch (FileSystemNotFoundException fsnfe) {
    // This should happen as we should not have an open FileSystem here.
    }
    folder.delete();
}
Also used : Path(java.nio.file.Path) STATISTICS_JSON_DEFAULT(com.vaadin.flow.server.Constants.STATISTICS_JSON_DEFAULT) Arrays(java.util.Arrays) ArgumentMatchers(org.mockito.ArgumentMatchers) URL(java.net.URL) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) URISyntaxException(java.net.URISyntaxException) POLYFILLS_DEFAULT_VALUE(com.vaadin.flow.server.Constants.POLYFILLS_DEFAULT_VALUE) Future(java.util.concurrent.Future) WarURLStreamHandlerFactory(com.vaadin.flow.WarURLStreamHandlerFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) VAADIN_SERVLET_RESOURCES(com.vaadin.flow.server.Constants.VAADIN_SERVLET_RESOURCES) ZoneOffset(java.time.ZoneOffset) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) FileSystem(java.nio.file.FileSystem) ResponseWriter(com.vaadin.flow.internal.ResponseWriter) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) Serializable(java.io.Serializable) NotThreadSafe(net.jcip.annotations.NotThreadSafe) URLStreamHandler(java.net.URLStreamHandler) List(java.util.List) IntStream(java.util.stream.IntStream) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BeforeClass(org.junit.BeforeClass) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) WriteListener(javax.servlet.WriteListener) URLConnection(java.net.URLConnection) SERVLET_PARAMETER_STATISTICS_JSON(com.vaadin.flow.server.InitParameters.SERVLET_PARAMETER_STATISTICS_JSON) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) MalformedURLException(java.net.MalformedURLException) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) Field(java.lang.reflect.Field) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Mockito(org.mockito.Mockito) ServletContext(javax.servlet.ServletContext) Assert(org.junit.Assert) Collections(java.util.Collections) FileSystems(java.nio.file.FileSystems) TemporaryFolder(org.junit.rules.TemporaryFolder) ArrayList(java.util.ArrayList) URL(java.net.URL) Callable(java.util.concurrent.Callable) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) TemporaryFolder(org.junit.rules.TemporaryFolder) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Test(org.junit.Test)

Aggregations

FileSystemNotFoundException (java.nio.file.FileSystemNotFoundException)20 IOException (java.io.IOException)11 Path (java.nio.file.Path)11 URI (java.net.URI)9 URISyntaxException (java.net.URISyntaxException)9 FileSystem (java.nio.file.FileSystem)5 File (java.io.File)4 URL (java.net.URL)4 HashMap (java.util.HashMap)3 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 FileOutputStream (java.io.FileOutputStream)2 MalformedURLException (java.net.MalformedURLException)2 Test (org.junit.Test)2 Vulnerability (com.blackducksoftware.integration.fortify.batch.model.Vulnerability)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 CsvMapper (com.fasterxml.jackson.dataformat.csv.CsvMapper)1 CsvSchema (com.fasterxml.jackson.dataformat.csv.CsvSchema)1 CharSource (com.google.common.io.CharSource)1 Var (com.google.errorprone.annotations.Var)1