use of java.nio.file.Files in project cas by apereo.
the class ExportPropertiesCommand method exportProperties.
/**
* Export properties.
*
* @param dir the directory for the configuration export
* @throws Exception the exception
*/
@ShellMethod(key = "export-props", value = "Export CAS properties and settings from configuration metadata.")
public void exportProperties(@ShellOption(value = { "dir", "--dir" }, help = "Path to a directory where reference configuration files would be exported.", defaultValue = "./etc/cas/config") final String dir) throws Exception {
val allProps = CasConfigurationMetadataCatalog.query(ConfigurationMetadataCatalogQuery.builder().queryType(ConfigurationMetadataCatalogQuery.QueryTypes.ALL).build());
try (val writer = Files.newBufferedWriter(new File(dir, "all-properties.ref").toPath(), Charset.defaultCharset())) {
allProps.properties().forEach(Unchecked.consumer(prop -> writeProperty(writer, prop)));
writer.flush();
}
val casProps = CasConfigurationMetadataCatalog.query(ConfigurationMetadataCatalogQuery.builder().queryType(ConfigurationMetadataCatalogQuery.QueryTypes.CAS).build());
try (val writer = Files.newBufferedWriter(new File(dir, "cas-properties.ref").toPath(), Charset.defaultCharset())) {
casProps.properties().forEach(Unchecked.consumer(prop -> writeProperty(writer, prop)));
writer.flush();
}
val thirdPartyProperties = CasConfigurationMetadataCatalog.query(ConfigurationMetadataCatalogQuery.builder().queryType(ConfigurationMetadataCatalogQuery.QueryTypes.THIRD_PARTY).build());
try (val writer = Files.newBufferedWriter(new File(dir, "thirdparty-properties.ref").toPath(), Charset.defaultCharset())) {
thirdPartyProperties.properties().forEach(Unchecked.consumer(prop -> writeProperty(writer, prop)));
writer.flush();
}
LOGGER.info("Exported configuration properties to [{}]", new File(dir).getAbsolutePath());
}
use of java.nio.file.Files in project batfish by batfish.
the class Batfish method readFiles.
private SortedMap<Path, String> readFiles(Path directory, String description) {
_logger.infof("\n*** READING FILES: %s ***\n", description);
_logger.resetTimer();
SortedMap<Path, String> fileData = new TreeMap<>();
List<Path> filePaths;
try (Stream<Path> paths = CommonUtil.list(directory)) {
filePaths = paths.filter(path -> !path.getFileName().toString().startsWith(".")).sorted().collect(Collectors.toList());
}
AtomicInteger completed = newBatch("Reading files: " + description, filePaths.size());
for (Path file : filePaths) {
_logger.debugf("Reading: \"%s\"\n", file);
String fileTextRaw = CommonUtil.readFile(file.toAbsolutePath());
String fileText = fileTextRaw + ((fileTextRaw.length() != 0) ? "\n" : "");
fileData.put(file, fileText);
completed.incrementAndGet();
}
_logger.printElapsedTime();
return fileData;
}
use of java.nio.file.Files in project batfish by batfish.
the class Batfish method serializeHostConfigs.
private SortedMap<String, VendorConfiguration> serializeHostConfigs(Path testRigPath, Path outputPath, ParseVendorConfigurationAnswerElement answerElement) {
SortedMap<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_HOST_CONFIGS_DIR);
// read the host files
SortedMap<String, VendorConfiguration> allHostConfigurations;
try (ActiveSpan parseHostConfigsSpan = GlobalTracer.get().buildSpan("Parse host configs").startActive()) {
// avoid unused warning
assert parseHostConfigsSpan != null;
allHostConfigurations = parseVendorConfigurations(configurationData, answerElement, ConfigurationFormat.HOST);
}
if (allHostConfigurations == null) {
throw new BatfishException("Exiting due to parser errors");
}
_logger.infof("Testrig:%s in container:%s has total number of host configs:%d", getTestrigName(), getContainerName(), allHostConfigurations.size());
// split into hostConfigurations and overlayConfigurations
SortedMap<String, VendorConfiguration> overlayConfigurations = allHostConfigurations.entrySet().stream().filter(e -> ((HostConfiguration) e.getValue()).getOverlay()).collect(toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new));
SortedMap<String, VendorConfiguration> nonOverlayHostConfigurations = allHostConfigurations.entrySet().stream().filter(e -> !((HostConfiguration) e.getValue()).getOverlay()).collect(toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new));
// read and associate iptables files for specified hosts
SortedMap<Path, String> iptablesData = new TreeMap<>();
readIptableFiles(testRigPath, allHostConfigurations, iptablesData, answerElement);
SortedMap<String, VendorConfiguration> iptablesConfigurations = parseVendorConfigurations(iptablesData, answerElement, ConfigurationFormat.IPTABLES);
for (VendorConfiguration vc : allHostConfigurations.values()) {
HostConfiguration hostConfig = (HostConfiguration) vc;
if (hostConfig.getIptablesFile() != null) {
Path path = Paths.get(testRigPath.toString(), hostConfig.getIptablesFile());
String relativePathStr = _testrigSettings.getBasePath().relativize(path).toString();
if (iptablesConfigurations.containsKey(relativePathStr)) {
hostConfig.setIptablesVendorConfig((IptablesVendorConfiguration) iptablesConfigurations.get(relativePathStr));
}
}
}
// now, serialize
_logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
_logger.resetTimer();
CommonUtil.createDirectories(outputPath);
Map<Path, VendorConfiguration> output = new TreeMap<>();
nonOverlayHostConfigurations.forEach((name, vc) -> {
Path currentOutputPath = outputPath.resolve(name);
output.put(currentOutputPath, vc);
});
serializeObjects(output);
// serialize warnings
serializeObject(answerElement, _testrigSettings.getParseAnswerPath());
_logger.printElapsedTime();
return overlayConfigurations;
}
use of java.nio.file.Files in project sts4 by spring-projects.
the class SpringIndexer method scanFiles.
private void scanFiles(WorkspaceFolder directory) {
try {
Map<Optional<IJavaProject>, List<String>> projects = Files.walk(Paths.get(new URI(directory.getUri()))).filter(path -> path.getFileName().toString().endsWith(".java")).filter(Files::isRegularFile).map(path -> path.toAbsolutePath().toString()).collect(Collectors.groupingBy((javaFile) -> projectFinder.find(new TextDocumentIdentifier(new File(javaFile).toURI().toString()))));
projects.forEach((maybeProject, files) -> maybeProject.ifPresent(project -> scanProject(project, files.toArray(new String[0]))));
} catch (Exception e) {
e.printStackTrace();
}
}
use of java.nio.file.Files in project mycore by MyCoRe-Org.
the class MCRPathXML method getDirectoryXML.
/**
* Sends the contents of an MCRDirectory as XML data to the client
*/
public static Document getDirectoryXML(MCRPath path, BasicFileAttributes attr) throws IOException {
LOGGER.debug("MCRDirectoryXML: start listing of directory {}", path);
Element root = new Element("mcr_directory");
Document doc = new org.jdom2.Document(root);
addString(root, "uri", path.toUri().toString(), false);
addString(root, "ownerID", path.getOwner(), false);
MCRPath relativePath = path.getRoot().relativize(path);
boolean isRoot = relativePath.toString().isEmpty();
addString(root, "name", (isRoot ? "" : relativePath.getFileName().toString()), true);
addString(root, "path", toStringValue(relativePath), true);
if (!isRoot) {
addString(root, "parentPath", toStringValue(relativePath.getParent()), true);
}
addBasicAttributes(root, attr, path);
Element numChildren = new Element("numChildren");
Element here = new Element("here");
root.addContent(numChildren);
numChildren.addContent(here);
Element nodes = new Element("children");
root.addContent(nodes);
SortedMap<MCRPath, MCRFileAttributes<?>> directories = new TreeMap<>();
SortedMap<MCRPath, MCRFileAttributes<?>> files = new TreeMap<>();
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
LOGGER.debug(() -> "Opened DirectoryStream for " + path);
Function<Path, MCRFileAttributes<?>> attrResolver = p -> {
try {
return Files.readAttributes(p, MCRFileAttributes.class);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
if (dirStream instanceof SecureDirectoryStream) {
// fast path
LOGGER.debug(() -> "Using SecureDirectoryStream code path for " + path);
attrResolver = p -> {
try {
BasicFileAttributeView attributeView = ((SecureDirectoryStream<Path>) dirStream).getFileAttributeView(p.getFileName(), BasicFileAttributeView.class);
return (MCRFileAttributes<?>) attributeView.readAttributes();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
for (Path child : dirStream) {
MCRFileAttributes<?> childAttrs;
try {
childAttrs = attrResolver.apply(child);
} catch (UncheckedIOException e) {
throw e.getCause();
}
if (childAttrs.isDirectory()) {
directories.put(MCRPath.toMCRPath(child), childAttrs);
} else {
files.put(MCRPath.toMCRPath(child), childAttrs);
}
}
}
// store current directory statistics
addString(here, "directories", Integer.toString(directories.size()), false);
addString(here, "files", Integer.toString(files.size()), false);
for (Map.Entry<MCRPath, MCRFileAttributes<?>> dirEntry : directories.entrySet()) {
Element child = new Element("child");
child.setAttribute("type", "directory");
addString(child, "name", dirEntry.getKey().getFileName().toString(), true);
addString(child, "uri", dirEntry.getKey().toUri().toString(), false);
nodes.addContent(child);
addBasicAttributes(child, dirEntry.getValue(), dirEntry.getKey());
}
for (Map.Entry<MCRPath, MCRFileAttributes<?>> fileEntry : files.entrySet()) {
Element child = new Element("child");
child.setAttribute("type", "file");
addString(child, "name", fileEntry.getKey().getFileName().toString(), true);
addString(child, "uri", fileEntry.getKey().toUri().toString(), false);
nodes.addContent(child);
addAttributes(child, fileEntry.getValue(), fileEntry.getKey());
}
LOGGER.debug("MCRDirectoryXML: end listing of directory {}", path);
return doc;
}
Aggregations