use of java.nio.file.Files in project sirix by sirixdb.
the class FMSETest method test.
/**
* Test a folder of XML files.
*
* @param FOLDER path string
* @throws Exception if any exception occurs
*/
private void test(final String FOLDER) throws Exception {
Database database = TestHelper.getDatabase(PATHS.PATH1.getFile());
ResourceManager resource = database.getResourceManager(new ResourceManagerConfiguration.Builder(TestHelper.RESOURCE).build());
final Path folder = Paths.get(FOLDER);
final List<Path> list = Files.list(folder).filter(path -> path.getFileName().endsWith(".xml")).collect(toList());
// Sort files list according to file names.
list.sort((first, second) -> {
final String firstName = first.getFileName().toString().substring(0, first.getFileName().toString().indexOf('.'));
final String secondName = second.getFileName().toString().substring(0, second.getFileName().toString().indexOf('.'));
if (Integer.parseInt(firstName) < Integer.parseInt(secondName)) {
return -1;
} else if (Integer.parseInt(firstName) > Integer.parseInt(secondName)) {
return +1;
} else {
return 0;
}
});
boolean first = true;
// Shredder files.
for (final Path file : list) {
if (file.getFileName().endsWith(".xml")) {
if (first) {
first = false;
try (final XdmNodeWriteTrx wtx = resource.beginNodeWriteTrx()) {
final XMLShredder shredder = new XMLShredder.Builder(wtx, XMLShredder.createFileReader(file), Insert.ASFIRSTCHILD).commitAfterwards().build();
shredder.call();
}
} else {
FMSEImport.main(new String[] { PATHS.PATH1.getFile().toAbsolutePath().toString(), file.toAbsolutePath().toString() });
}
resource.close();
resource = database.getResourceManager(new ResourceManagerConfiguration.Builder(TestHelper.RESOURCE).build());
final OutputStream out = new ByteArrayOutputStream();
final XMLSerializer serializer = new XMLSerializerBuilder(resource, out).build();
serializer.call();
final StringBuilder sBuilder = TestHelper.readFile(file, false);
final Diff diff = new Diff(sBuilder.toString(), out.toString());
final DetailedDiff detDiff = new DetailedDiff(diff);
@SuppressWarnings("unchecked") final List<Difference> differences = detDiff.getAllDifferences();
for (final Difference difference : differences) {
System.err.println("***********************");
System.err.println(difference);
System.err.println("***********************");
}
assertTrue("pieces of XML are similar " + diff, diff.similar());
assertTrue("but are they identical? " + diff, diff.identical());
}
}
database.close();
}
use of java.nio.file.Files in project rom-manager by Jakz.
the class Scanner method scanForRoms.
public void scanForRoms(boolean total) throws IOException {
ignoredPaths.clear();
foundFiles.clear();
clones.clear();
if (total) {
logger.i(LogTarget.romset(set), "Scanning for roms");
set.resetStatus();
} else {
logger.i(LogTarget.romset(set), "Scanning for new roms");
set.romStream().filter(r -> r.isPresent()).map(r -> r.handle().path()).forEach(ignoredPaths::add);
}
ignoredPaths.addAll(settings.getIgnoredPaths());
Path folder = settings.romsPath;
if (!canProceedWithScan())
return;
FolderScanner folderScanner = new FolderScanner(ignoredPaths, true);
final Set<Path> pathsToScan = folderScanner.scan(folder);
List<VerifierEntry> foundEntries = Collections.synchronizedList(new ArrayList<>());
/* scanning task */
{
Operation<Path, List<VerifierEntry>> operation = path -> {
logger.d(LogTarget.file(path), "> Scanning %s", path.getFileName().toString());
try {
return scanner.scanFile(path);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (RuntimeException e) {
logger.e(LogTarget.file(path), "Exception while scanning %s", path.toString());
e.printStackTrace();
if (!SevenZip.isInitializedSuccessfully()) {
Throwable ee = SevenZip.getLastInitializationException();
ee.printStackTrace();
}
return null;
}
};
BiConsumer<Long, Float> guiProgress = (i, f) -> {
Main.progress.update(f, "Scanning " + i + " of " + pathsToScan.size() + "...");
};
Consumer<List<VerifierEntry>> callback = results -> {
foundEntries.addAll(results);
};
Runnable onComplete = () -> {
SwingUtilities.invokeLater(() -> {
Main.progress.finished();
List<VerifierEntry> transformedEntries = foundEntries.stream().collect(Collectors.toList());
HandleSet handleSet = new HandleSet(transformedEntries);
HandleSet.Stats stats = handleSet.stats();
logger.i(LogTarget.romset(set), "Found %d potential matches (%d binary, %d inside archives, %d nested inside %d archives).", stats.totalHandles, stats.binaryCount, stats.archivedCount, stats.nestedArchiveInnerCount, stats.nestedArchiveCount);
transformedEntries.forEach(h -> logger.d(LogTarget.romset(set), "> %s", h.toString()));
Runnable verifyTask = verifyTask(transformedEntries, total);
verifyTask.run();
});
};
AsyncGuiPoolWorker<Path, List<VerifierEntry>> worker = new AsyncGuiPoolWorker<>(operation, guiProgress, 1);
SwingUtilities.invokeLater(() -> {
Main.progress.show(Main.mainFrame, "Scanning " + pathsToScan.size() + " files", () -> worker.cancel());
});
worker.compute(pathsToScan, callback, onComplete);
}
}
use of java.nio.file.Files in project rom-manager by Jakz.
the class MoveUnknownFilesPlugin method execute.
@Override
public void execute(GameSet set) {
try {
counter = 0;
if (!Files.exists(path) || !Files.isDirectory(path))
Files.createDirectory(path);
Set<Path> existing = set.romStream().filter(r -> r.isPresent()).map(r -> r.handle().path()).collect(Collectors.toSet());
Settings settings = getGameSetSettings();
Set<Path> total = new FolderScanner(FileSystems.getDefault().getPathMatcher("glob:*.*"), settings.getIgnoredPaths(), true).scan(settings.romsPath);
total.removeAll(existing);
total.stream().filter(f -> !f.getParent().equals(path)).forEach(f -> {
Path dest = path.resolve(f.getFileName());
int i = 1;
while (Files.exists(dest)) dest = path.resolve(f.getFileName().toString() + (i++));
try {
Files.move(f, dest);
++counter;
} catch (IOException e) {
e.printStackTrace();
/* TODO: log */
}
});
message("Moved " + counter + " unknown files");
} catch (IOException e) {
e.printStackTrace();
// TODO: log
}
}
use of java.nio.file.Files in project ant by apache.
the class FileUtils method hasErrorInCase.
/**
* test whether a file or directory exists, with an error in the
* upper/lower case spelling of the name.
* Using this method is only interesting on case insensitive file systems
* (Windows).
* <p>
* It will return true only if 3 conditions are met:
* </p>
* <ul>
* <li>operating system is case insensitive</li>
* <li>file exists</li>
* <li>actual name from directory reading is different from the
* supplied argument</li>
* </ul>
* <p>
* The purpose is to identify files or directories on case-insensitive
* filesystems whose case is not what is expected.
* </p>
* Possibly to rename them afterwards to the desired upper/lowercase
* combination.
*
* @param localFile file to test
* @return true if the file exists and the case of the actual file
* is not the case of the parameter
* @since Ant 1.7.1
*/
public boolean hasErrorInCase(File localFile) {
localFile = normalize(localFile.getAbsolutePath());
if (!localFile.exists()) {
return false;
}
final String localFileName = localFile.getName();
FilenameFilter ff = (dir, name) -> name.equalsIgnoreCase(localFileName) && (!name.equals(localFileName));
String[] names = localFile.getParentFile().list(ff);
return names != null && names.length == 1;
}
use of java.nio.file.Files in project irida by phac-nml.
the class AnalysisController method getAjaxDownloadAnalysisSubmissionIndividualFile.
/**
* Download single output files from an {@link AnalysisSubmission}
*
* @param analysisSubmissionId Id for a {@link AnalysisSubmission}
* @param fileId the id of the file to download
* @param response {@link HttpServletResponse}
*/
@RequestMapping(value = "/ajax/download/{analysisSubmissionId}/file/{fileId}")
public void getAjaxDownloadAnalysisSubmissionIndividualFile(@PathVariable Long analysisSubmissionId, @PathVariable Long fileId, HttpServletResponse response) {
AnalysisSubmission analysisSubmission = analysisSubmissionService.read(analysisSubmissionId);
Analysis analysis = analysisSubmission.getAnalysis();
Set<AnalysisOutputFile> files = analysis.getAnalysisOutputFiles();
Optional<AnalysisOutputFile> optFile = files.stream().filter(f -> f.getId().equals(fileId)).findAny();
if (!optFile.isPresent()) {
throw new EntityNotFoundException("Could not find file with id " + fileId);
}
FileUtilities.createSingleFileResponse(response, optFile.get());
}
Aggregations