Search in sources :

Example 1 with MultiException

use of org.eclipse.winery.yaml.common.exception.MultiException in project winery by eclipse.

the class Reader method readMetadataObject.

/**
 * Uses snakeyaml to convert the part of an file containing metadata into an Object
 *
 * @return Object (Lists, Maps, Strings, Integers, Dates)
 * @throws UndefinedFile if the file could not be found.
 */
private Object readMetadataObject(Path path) throws MultiException {
    try (InputStream inputStream = new FileInputStream(path.toFile())) {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
        String metadata = buffer.lines().collect(Collectors.joining("\n"));
        Matcher matcher = Pattern.compile("\\nmetadata:").matcher(metadata);
        // No metadata return null
        if (!matcher.find())
            return null;
        // Prevent index out of bound
        int index = matcher.start() + 1;
        if (index >= metadata.length())
            return null;
        // Get file string starting with "metadata:"
        metadata = metadata.substring(matcher.start() + 1);
        matcher = Pattern.compile(("\\n[^ ]")).matcher(metadata);
        if (matcher.find()) {
            // Cut of the part of the file after metadata (indicated by newline and a key)
            metadata = metadata.substring(0, matcher.start());
        }
        return this.yaml.load(metadata);
    } catch (FileNotFoundException e) {
        throw new MultiException().add(new UndefinedFile("The file '{}' is missing", path).setFileContext(path));
    } catch (IOException e) {
        logger.error("Could not read from inputstream", e);
        return null;
    }
}
Also used : UndefinedFile(org.eclipse.winery.yaml.common.exception.UndefinedFile) Matcher(java.util.regex.Matcher) MultiException(org.eclipse.winery.yaml.common.exception.MultiException)

Example 2 with MultiException

use of org.eclipse.winery.yaml.common.exception.MultiException in project winery by eclipse.

the class Reader method readServiceTemplate.

/**
 * Reads a file and converts it to a ServiceTemplate
 *
 * @return ServiceTemplate
 * @throws MultiException the ServiceTemplate or the file is invalid.
 */
private TServiceTemplate readServiceTemplate(Path path, Path file, String namespace) throws MultiException {
    Path filePath;
    if (Objects.isNull(path)) {
        filePath = file;
    } else {
        filePath = path.resolve(file);
    }
    // 
    if (!fileChanged(filePath)) {
        if (exceptionBuffer.containsKey(filePath)) {
            throw exceptionBuffer.get(filePath);
        }
        if (serviceTemplateBuffer.containsKey(filePath)) {
            return serviceTemplateBuffer.get(filePath);
        }
    }
    logger.debug("Read Service Template: {}", filePath);
    try {
        // pre parse checking
        try {
            ObjectValidator objectValidator = new ObjectValidator();
            objectValidator.validateObject(readObject(filePath));
        } catch (ConstructorException e) {
            ExceptionInterpreter interpreter = new ExceptionInterpreter();
            throw new MultiException().add(interpreter.interpret(e));
        } catch (ScannerException e) {
            ExceptionInterpreter interpreter = new ExceptionInterpreter();
            throw new MultiException().add(interpreter.interpret(e));
        } catch (YAMLParserException e) {
            throw new MultiException().add(e);
        }
        // parse checking
        TServiceTemplate result = buildServiceTemplate(readObject(filePath), namespace);
        // post parse checking
        Validator validator = new Validator(path);
        validator.validate(result, namespace);
        serviceTemplateBuffer.put(filePath, result);
        return result;
    } catch (MultiException e) {
        exceptionBuffer.put(filePath, e);
        throw e.add(file.toString());
    }
}
Also used : Path(java.nio.file.Path) ScannerException(org.yaml.snakeyaml.scanner.ScannerException) ExceptionInterpreter(org.eclipse.winery.yaml.common.validator.support.ExceptionInterpreter) YAMLParserException(org.eclipse.winery.yaml.common.exception.YAMLParserException) ObjectValidator(org.eclipse.winery.yaml.common.validator.ObjectValidator) ConstructorException(org.yaml.snakeyaml.constructor.ConstructorException) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) ObjectValidator(org.eclipse.winery.yaml.common.validator.ObjectValidator) Validator(org.eclipse.winery.yaml.common.validator.Validator) TServiceTemplate(org.eclipse.winery.model.tosca.yaml.TServiceTemplate)

Example 3 with MultiException

use of org.eclipse.winery.yaml.common.exception.MultiException in project winery by eclipse.

the class ImportVisitor method visit.

@Override
public Result visit(TServiceTemplate node, Parameter parameter) {
    Reader reader = Reader.getReader();
    if (!this.namespace.equals(Namespaces.TOSCA_NS)) {
        Set<String> typeDefinitions = new HashSet<>(Arrays.asList(Defaults.TOSCA_NORMATIVE_TYPES, Defaults.TOSCA_NONNORMATIVE_TYPES));
        String tmpNamespace = this.namespace;
        this.namespace = Namespaces.TOSCA_NS;
        Path tmpDir = Utils.getTmpDir(Paths.get("types"));
        for (String typeDefinition : typeDefinitions) {
            try {
                Path outFilePath = tmpDir.resolve(typeDefinition);
                InputStream inputStream = this.getClass().getResourceAsStream(// Do not use File.separator here (https://stackoverflow.com/a/41677152/8235252)
                "/".concat(typeDefinition));
                Files.copy(inputStream, outFilePath, StandardCopyOption.REPLACE_EXISTING);
                TServiceTemplate serviceTemplate = reader.parseSkipTest(outFilePath, Namespaces.TOSCA_NS);
                if (Objects.nonNull(serviceTemplate)) {
                    serviceTemplate.accept(this, new Parameter());
                }
            } catch (MultiException e) {
                setException(e);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.namespace = tmpNamespace;
    }
    super.visit(node, parameter);
    return null;
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) Reader(org.eclipse.winery.yaml.common.reader.yaml.Reader) Parameter(org.eclipse.winery.yaml.common.validator.support.Parameter) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) HashSet(java.util.HashSet) TServiceTemplate(org.eclipse.winery.model.tosca.yaml.TServiceTemplate)

Example 4 with MultiException

use of org.eclipse.winery.yaml.common.exception.MultiException in project winery by eclipse.

the class Converter method convertY2X.

public void convertY2X(InputStream zip) throws MultiException {
    Path path = Utils.unzipFile(zip);
    LOGGER.debug("Unzip path: {}", path);
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{yml,yaml}");
    MultiException exception = Arrays.stream(Optional.ofNullable(path.toFile().listFiles()).orElse(new File[] {})).map(File::toPath).filter(file -> matcher.matches(file.getFileName())).map(file -> {
        Reader reader = Reader.getReader();
        try {
            String id = file.getFileName().toString().substring(0, file.getFileName().toString().lastIndexOf("."));
            Path fileName = file.subpath(path.getNameCount(), file.getNameCount());
            Path fileOutPath = path.resolve("tmp");
            String namespace = reader.getNamespace(path, fileName);
            TServiceTemplate serviceTemplate = reader.parse(path, fileName);
            LOGGER.debug("Convert filePath = {}, fileName = {}, id = {}, namespace = {}, fileOutPath = {}", path, fileName, id, namespace, fileOutPath);
            this.convertY2X(serviceTemplate, id, namespace, path, fileOutPath);
        } catch (MultiException e) {
            return e;
        }
        return null;
    }).filter(Objects::nonNull).reduce(MultiException::add).orElse(new MultiException());
    if (exception.hasException())
        throw exception;
}
Also used : Definitions(org.eclipse.winery.model.tosca.Definitions) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Utils(org.eclipse.winery.yaml.common.Utils) Y2XConverter(org.eclipse.winery.yaml.converter.yaml.Y2XConverter) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) TServiceTemplate(org.eclipse.winery.model.tosca.yaml.TServiceTemplate) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) WineryRepositoryException(org.eclipse.winery.repository.exceptions.WineryRepositoryException) Reader(org.eclipse.winery.yaml.common.reader.yaml.Reader) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) java.nio.file(java.nio.file) TOSCAMetaFileParser(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFileParser) X2YConverter(org.eclipse.winery.yaml.converter.xml.X2YConverter) Objects(java.util.Objects) IRepository(org.eclipse.winery.repository.backend.IRepository) Map(java.util.Map) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) Optional(java.util.Optional) TOSCAMetaFile(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFile) InputStream(java.io.InputStream) Objects(java.util.Objects) Reader(org.eclipse.winery.yaml.common.reader.yaml.Reader) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) File(java.io.File) TOSCAMetaFile(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFile) TServiceTemplate(org.eclipse.winery.model.tosca.yaml.TServiceTemplate)

Example 5 with MultiException

use of org.eclipse.winery.yaml.common.exception.MultiException in project winery by eclipse.

the class Converter method convertDefinitionsChildToYaml.

public String convertDefinitionsChildToYaml(DefinitionsChildId id) throws MultiException {
    Path path = Utils.getTmpDir(Paths.get(id.getQName().getLocalPart()));
    convertX2Y(repository.getDefinitions(id), path);
    // convention: single file in root contains the YAML support
    // TODO: Links in the YAML should be changed to real links into Winery
    Optional<Path> rootYamlFile;
    try {
        return Files.find(path, 1, (filePath, basicFileAttributes) -> filePath.getFileName().toString().endsWith(".yml")).findAny().map(p -> {
            try {
                return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
            } catch (IOException e) {
                LOGGER.debug("Could not read root file", e);
                return "Could not read root file";
            }
        }).orElseThrow(() -> {
            MultiException multiException = new MultiException();
            multiException.add(new WineryRepositoryException("Root YAML file not found."));
            return multiException;
        });
    } catch (IOException e) {
        MultiException multiException = new MultiException();
        multiException.add(new WineryRepositoryException("Root YAML file not found.", e));
        throw multiException;
    }
}
Also used : Definitions(org.eclipse.winery.model.tosca.Definitions) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Utils(org.eclipse.winery.yaml.common.Utils) Y2XConverter(org.eclipse.winery.yaml.converter.yaml.Y2XConverter) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) TServiceTemplate(org.eclipse.winery.model.tosca.yaml.TServiceTemplate) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) WineryRepositoryException(org.eclipse.winery.repository.exceptions.WineryRepositoryException) Reader(org.eclipse.winery.yaml.common.reader.yaml.Reader) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) java.nio.file(java.nio.file) TOSCAMetaFileParser(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFileParser) X2YConverter(org.eclipse.winery.yaml.converter.xml.X2YConverter) Objects(java.util.Objects) IRepository(org.eclipse.winery.repository.backend.IRepository) Map(java.util.Map) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) Optional(java.util.Optional) TOSCAMetaFile(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFile) InputStream(java.io.InputStream) IOException(java.io.IOException) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) WineryRepositoryException(org.eclipse.winery.repository.exceptions.WineryRepositoryException)

Aggregations

MultiException (org.eclipse.winery.yaml.common.exception.MultiException)13 Reader (org.eclipse.winery.yaml.common.reader.yaml.Reader)8 TServiceTemplate (org.eclipse.winery.model.tosca.yaml.TServiceTemplate)6 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 File (java.io.File)3 Path (java.nio.file.Path)3 Objects (java.util.Objects)3 TOSCAMetaFile (org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFile)3 TOSCAMetaFileParser (org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFileParser)3 Definitions (org.eclipse.winery.model.tosca.Definitions)3 RepositoryFactory (org.eclipse.winery.repository.backend.RepositoryFactory)3 WineryRepositoryException (org.eclipse.winery.repository.exceptions.WineryRepositoryException)3 StandardCharsets (java.nio.charset.StandardCharsets)2 java.nio.file (java.nio.file)2 Arrays (java.util.Arrays)2 Map (java.util.Map)2 Optional (java.util.Optional)2 QName (javax.xml.namespace.QName)2 DefinitionsChildId (org.eclipse.winery.common.ids.definitions.DefinitionsChildId)2