use of java.nio.file.Files in project ddf by codice.
the class FileSystemStorageProvider method getContentFilePath.
private Path getContentFilePath(URI uri) throws StorageException {
Path contentIdDir = getContentItemDir(uri);
List<Path> contentFiles;
if (contentIdDir != null && contentIdDir.toFile().exists()) {
try {
contentFiles = listPaths(contentIdDir);
} catch (IOException e) {
throw new StorageException(e);
}
contentFiles.removeIf(Files::isDirectory);
if (contentFiles.size() != 1) {
throw new StorageException("Content ID: " + uri.getSchemeSpecificPart() + " storage folder is corrupted.");
}
// there should only be one file
return contentFiles.get(0);
}
return null;
}
use of java.nio.file.Files in project CzechIdMng by bcvsolutions.
the class DefaultImportManager method removeRedundant.
/**
* Ensures delete redundant entities in target IdM. Deletes DTOs are within
* golden DTO type (super parent = typically system, role, ...).
*
* @param descriptor
* @param context
*/
private void removeRedundant(ExportDescriptorDto descriptor, ImportContext context) {
Class<? extends BaseDto> dtoClass = descriptor.getDtoClass();
// Does this DTO support the authoritative mode?
boolean supportsAuthoritativeMode = descriptor.isSupportsAuthoritativeMode();
if (!supportsAuthoritativeMode) {
return;
}
String superParentFilterProperty = descriptor.getSuperParentFilterProperty();
Assert.notNull(superParentFilterProperty, "For authoritative mode must be superParentFilterProperty defined!");
// Find super parent (gold) DTO (typically it is DTO for system, role ...)
Class<? extends AbstractDto> superParentDtoClass = getSuperParentDtoClass(descriptor, context);
Assert.notNull(superParentDtoClass, "Supper parent cannot be null here!");
Path superParentDtoTypePath = Paths.get(context.getTempDirectory().toString(), superParentDtoClass.getSimpleName());
try {
// Find all super parent IDs for this DTO type in batch.
Set<UUID> superParentIdsInBatch;
try (Stream<Path> paths = Files.walk(superParentDtoTypePath)) {
superParentIdsInBatch = //
paths.filter(//
Files::isRegularFile).map(path -> {
BaseDto dto = convertFileToDto(path.toFile(), superParentDtoClass, context);
return (UUID) dto.getId();
}).collect(Collectors.toSet());
}
Set<Class<? extends BaseDto>> inheritedClasses = getInheritedClasses(dtoClass, context.getManifest());
// Find all IDs for all children classes
Set<Serializable> childrenIdsInBatch = Sets.newHashSet();
for (Class<? extends BaseDto> inheritedClass : inheritedClasses) {
// Find all IDs for this DTO type in batch.
Path dtoTypePath = Paths.get(context.getTempDirectory().toString(), inheritedClass.getSimpleName());
try (Stream<Path> paths = Files.walk(dtoTypePath)) {
Set<Serializable> childrenIds = //
paths.filter(//
Files::isRegularFile).map(//
path -> convertFileToDto(path.toFile(), inheritedClass, context)).map(dto -> {
// If ID has been replaced, then we need to also replace it.
if (context.getReplacedIDs().containsKey((UUID) dto.getId())) {
return context.getReplacedIDs().get((UUID) dto.getId());
}
return dto.getId();
}).collect(Collectors.toSet());
childrenIdsInBatch.addAll(childrenIds);
}
}
superParentIdsInBatch.forEach(superParentId -> {
try {
Class<? extends BaseDto> serviceDtoClass = dtoClass;
if (dtoClass.isAnnotationPresent(Inheritable.class)) {
serviceDtoClass = dtoClass.getAnnotation(Inheritable.class).dtoService();
}
ReadWriteDtoService<BaseDto, BaseFilter> dtoService = getDtoService(serviceDtoClass);
BaseFilter filterBase = dtoService.getFilterClass().getDeclaredConstructor().newInstance();
// Fill super-parent-property by superParentId (call setter = check if filter is
// implemented).
new PropertyDescriptor(superParentFilterProperty, dtoService.getFilterClass()).getWriteMethod().invoke(filterBase, superParentId);
// Load all IDs in IdM for this parent ID.
List<UUID> childrenIdsInIdM = //
dtoService.find(filterBase, null).getContent().stream().map(//
childDto -> ((AbstractDto) childDto).getId()).collect(Collectors.toList());
// IDs to delete = entities missing in the batch.
Set<UUID> idsToDelete = //
childrenIdsInIdM.stream().filter(//
idmId -> !childrenIdsInBatch.contains(idmId)).collect(Collectors.toSet());
idsToDelete.forEach(id -> {
BaseDto baseDto = dtoService.get(id);
IdmImportLogDto dtoLog = new IdmImportLogDto(context.getBatch(), baseDto, RequestOperationType.REMOVE, superParentId);
if (!context.isDryRun()) {
dtoService.delete(baseDto);
dtoLog.setResult(new OperationResultDto(OperationState.EXECUTED));
} else {
dtoLog.setResult(new OperationResultDto.Builder(OperationState.NOT_EXECUTED).setModel(//
new DefaultResultModel(CoreResultCode.IMPORT_EXECUTED_AS_DRYRUN)).build());
}
importLogService.saveDistinct(dtoLog);
});
} catch (ReflectiveOperationException | IllegalArgumentException | IntrospectionException e) {
throw new ResultCodeException(CoreResultCode.EXPORT_IMPORT_REFLECTION_FAILED, e);
}
});
} catch (IOException e) {
throw new ResultCodeException(CoreResultCode.EXPORT_IMPORT_IO_FAILED, e);
}
}
use of java.nio.file.Files in project vertx-docgen by vert-x3.
the class BaseProcessor method process.
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
for (StackTraceElement elt : trace) {
if (elt.getClassName().startsWith("org.jetbrains")) {
return true;
}
}
if (failures.isEmpty()) {
try {
if (!roundEnv.processingOver()) {
roundEnv.getElementsAnnotatedWith(Document.class).forEach(elt -> {
try {
PackageDoc doc = new PackageDoc((PackageElement) elt);
state.put(doc, handleGen(doc));
} catch (DocGenException e) {
if (e.element == null) {
e.element = elt;
}
throw e;
}
});
if (sources != null && sources.size() > 0) {
for (String source : sources) {
// Handle wildcards
List<File> files = new ArrayList<>();
File f = new File(source);
if (!f.exists()) {
if (f.getName().contains("*")) {
StringBuilder sb = new StringBuilder();
for (char c : f.getName().toCharArray()) {
if (c == '*') {
sb.append(".*");
} else {
sb.append(Matcher.quoteReplacement(Character.toString(c)));
}
}
Pattern p = Pattern.compile(sb.toString());
File parentFile = f.getParentFile();
File[] children = parentFile.listFiles();
if (children != null) {
for (File child : children) {
if (p.matcher(child.getName()).matches()) {
files.add(child);
}
}
}
} else {
throw new FileNotFoundException("Cannot process document " + source);
}
} else {
files.add(f);
}
for (File file : files) {
if (file.isFile()) {
FileDoc fileDoc = new FileDoc(file, file.getName());
Map<DocGenerator, DocWriter> m = handleGen(fileDoc);
state.put(fileDoc, m);
} else if (file.isDirectory()) {
Files.walk(file.toPath()).map(Path::toFile).filter(File::isFile).forEach(docFile -> {
String relativePath = file.toPath().relativize(docFile.toPath()).toString();
FileDoc fileDoc = new FileDoc(docFile, relativePath);
Map<DocGenerator, DocWriter> m = handleGen(fileDoc);
state.put(fileDoc, m);
});
} else {
throw new IOException("Document " + file.getAbsolutePath() + " is not a file nor a dir");
}
}
}
sources.clear();
}
Set<String> processed = new HashSet<>();
while (true) {
Optional<ElementResolution> opt = resolutions.values().stream().filter(res -> res.elt == null && !processed.contains(res.signature)).findFirst();
if (opt.isPresent()) {
ElementResolution res = opt.get();
processed.add(res.signature);
res.tryResolve();
} else {
break;
}
}
} else {
state.forEach((doc, m) -> {
m.forEach((gen, w) -> {
String content = postProcess(gen.getName(), w.render());
write(gen, doc, content);
});
});
}
} catch (Exception e) {
Element reportedElt = (e instanceof DocGenException) ? ((DocGenException) e).element : null;
String msg = e.getMessage();
if (msg == null) {
msg = e.toString();
}
e.printStackTrace();
if (reportedElt != null) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg, reportedElt);
if (reportedElt instanceof PackageElement) {
failures.put(((PackageElement) reportedElt).getQualifiedName().toString(), msg);
} else {
throw new UnsupportedOperationException("not implemented");
}
} else {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, msg);
}
}
}
return false;
}
use of java.nio.file.Files in project gradle by gradle.
the class SimpleGeneratedJavaClassCompiler method compile.
/**
* Compiles generated Java source files.
*
* @param srcDir where the compiler will output the sources
* @param dstDir where the compiler will output the class files
* @param classes the classes to compile
* @param classPath the classpath to use for compilation
*/
public static void compile(File srcDir, File dstDir, List<ClassSource> classes, ClassPath classPath) throws GeneratedClassCompilationException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new GeneratedClassCompilationException("No Java compiler found, please ensure you are running Gradle with a JDK");
}
DiagnosticCollector<JavaFileObject> ds = new DiagnosticCollector<>();
try (StandardJavaFileManager mgr = compiler.getStandardFileManager(ds, null, null)) {
List<String> options = buildOptions(dstDir, classPath);
List<File> filesToCompile = outputSourceFilesToSourceDir(srcDir, classes);
if (dstDir.exists() || dstDir.mkdirs()) {
Iterable<? extends JavaFileObject> sources = mgr.getJavaFileObjectsFromFiles(filesToCompile);
JavaCompiler.CompilationTask task = compiler.getTask(null, mgr, ds, options, null, sources);
task.call();
} else {
throw new GeneratedClassCompilationException("Unable to create output classes directory");
}
} catch (IOException e) {
throw new GeneratedClassCompilationException("Unable to compile generated classes", e);
}
List<Diagnostic<? extends JavaFileObject>> diagnostics = ds.getDiagnostics().stream().filter(d -> d.getKind() == Diagnostic.Kind.ERROR).collect(Collectors.toList());
if (!diagnostics.isEmpty()) {
throwCompilationError(diagnostics);
}
}
use of java.nio.file.Files in project winery by eclipse.
the class CsarExporter method addManifest.
private String addManifest(DefinitionsChildId id, Map<CsarContentProperties, CsarEntry> refMap, ZipOutputStream out, Map<String, Object> exportConfiguration) throws IOException {
String entryDefinitionsReference = CsarExporter.getDefinitionsPathInsideCSAR(repository, id);
out.putNextEntry(new ZipEntry("TOSCA-Metadata/TOSCA.meta"));
StringBuilder stringBuilder = new StringBuilder();
// Setting Versions
stringBuilder.append(TOSCA_META_VERSION).append(": 1.0").append("\n");
stringBuilder.append(CSAR_VERSION).append(": 1.0").append("\n");
stringBuilder.append(CREATED_BY).append(": Winery ").append(Environments.getInstance().getVersion()).append("\n");
// Winery currently is unaware of tDefinitions, therefore, we use the
// name of the service template
stringBuilder.append(ENTRY_DEFINITIONS).append(": ").append(entryDefinitionsReference).append("\n");
stringBuilder.append("\n");
assert (refMap.keySet().stream().anyMatch(fileProperties -> fileProperties.getPathInsideCsar().equals(entryDefinitionsReference)));
// Setting other files, mainly files belonging to artifacts
for (Map.Entry<CsarContentProperties, CsarEntry> item : refMap.entrySet()) {
final CsarEntry csarEntry = item.getValue();
final CsarContentProperties fileProperties = item.getKey();
stringBuilder.append(NAME).append(": ").append(fileProperties.getPathInsideCsar()).append("\n");
String mimeType;
if (csarEntry instanceof DocumentBasedCsarEntry) {
mimeType = MimeTypes.MIMETYPE_XSD;
} else if (csarEntry instanceof XMLDefinitionsBasedCsarEntry || csarEntry instanceof DefinitionsBasedCsarEntry) {
mimeType = MimeTypes.MIMETYPE_TOSCA_DEFINITIONS;
} else {
mimeType = repository.getMimeType(((RepositoryRefBasedCsarEntry) csarEntry).getReference());
}
stringBuilder.append(CONTENT_TYPE).append(": ").append(mimeType).append("\n");
if (exportConfiguration.containsKey(CsarExportConfiguration.INCLUDE_HASHES.name()) && Objects.nonNull(fileProperties.getFileHash())) {
stringBuilder.append(HASH).append(": ").append(fileProperties.getFileHash()).append("\n");
}
if (exportConfiguration.containsKey(CsarExportConfiguration.STORE_IMMUTABLY.name()) && Objects.nonNull(fileProperties.getImmutableAddress())) {
stringBuilder.append(IMMUTABLE_ADDRESS).append(": ").append(fileProperties.getImmutableAddress()).append("\n");
}
stringBuilder.append("\n");
}
String manifestString = stringBuilder.toString();
out.write(manifestString.getBytes());
out.closeEntry();
return manifestString;
}
Aggregations