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());
}
}
}
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);
}
}
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);
}
}
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);
}
}
}
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();
}
Aggregations