Search in sources :

Example 11 with Definitions

use of org.eclipse.winery.model.tosca.Definitions in project winery by eclipse.

the class IWineryRepositoryCommon method getTypeForTemplate.

/**
 * Returns the stored type for the given template
 *
 * @param template the template to determine the type for
 * @throws NullPointerException if template.getType() returns null
 */
// we suppress "unchecked" as we use Class.forName
@SuppressWarnings("unchecked")
default TEntityType getTypeForTemplate(TEntityTemplate template) {
    QName type = template.getType();
    Objects.requireNonNull(type);
    // Possibilities:
    // a) try all possibly types whether an appropriate QName exists
    // b) derive type class from template class. Determine appropriate template element afterwards.
    // We go for b)
    String instanceResourceClassName = template.getClass().toString();
    int idx = instanceResourceClassName.lastIndexOf('.');
    // get everything from ".T", where "." is the last dot
    instanceResourceClassName = instanceResourceClassName.substring(idx + 2);
    // strip off "Template"
    instanceResourceClassName = instanceResourceClassName.substring(0, instanceResourceClassName.length() - "Template".length());
    // add "Type"
    instanceResourceClassName += "Type";
    // an id is required to instantiate the resource
    String idClassName = "org.eclipse.winery.common.ids.definitions." + instanceResourceClassName + "Id";
    org.slf4j.Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    LOGGER.debug("idClassName: {}", idClassName);
    // Get instance of id class having "type" as id
    Class<? extends DefinitionsChildId> idClass;
    try {
        idClass = (Class<? extends DefinitionsChildId>) Class.forName(idClassName);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Could not determine id class", e);
    }
    Constructor<? extends DefinitionsChildId> idConstructor;
    try {
        idConstructor = idClass.getConstructor(QName.class);
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Could not get QName id constructor", e);
    }
    DefinitionsChildId typeId;
    try {
        typeId = idConstructor.newInstance(type);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new IllegalStateException("Could not instantiate type", e);
    }
    final Definitions definitions = this.getDefinitions(typeId);
    return (TEntityType) definitions.getElement();
}
Also used : DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) QName(javax.xml.namespace.QName) TEntityType(org.eclipse.winery.model.tosca.TEntityType) Definitions(org.eclipse.winery.model.tosca.Definitions) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 12 with Definitions

use of org.eclipse.winery.model.tosca.Definitions in project winery by eclipse.

the class BackendUtilsTestWithGitBackedRepository method initializePropertiesDoesNothingInTheCaseOfXmlElemenetPropperties.

@Test
public void initializePropertiesDoesNothingInTheCaseOfXmlElemenetPropperties() throws Exception {
    this.setRevisionTo("origin/plain");
    PolicyTemplateId policyTemplateId = new PolicyTemplateId("http://www.example.org", "policytemplate", false);
    // create prepared policy template
    final IRepository repository = RepositoryFactory.getRepository();
    final Definitions definitions = BackendUtils.createWrapperDefinitionsAndInitialEmptyElement(repository, policyTemplateId);
    final TPolicyTemplate policyTemplate = (TPolicyTemplate) definitions.getElement();
    QName policyTypeQName = new QName("http://plain.winery.opentosca.org/policytypes", "PolicyTypeWithXmlElementProperty");
    policyTemplate.setType(policyTypeQName);
    BackendUtils.initializeProperties(repository, policyTemplate);
    Assert.assertNull(policyTemplate.getProperties());
}
Also used : TPolicyTemplate(org.eclipse.winery.model.tosca.TPolicyTemplate) QName(javax.xml.namespace.QName) Definitions(org.eclipse.winery.model.tosca.Definitions) PolicyTemplateId(org.eclipse.winery.common.ids.definitions.PolicyTemplateId) Test(org.junit.Test)

Example 13 with Definitions

use of org.eclipse.winery.model.tosca.Definitions in project winery by eclipse.

the class BackendUtilsTestWithGitBackedRepository method initializePropertiesGeneratesCorrectKvProperties.

@Test
public void initializePropertiesGeneratesCorrectKvProperties() throws Exception {
    this.setRevisionTo("origin/plain");
    PolicyTemplateId policyTemplateId = new PolicyTemplateId("http://www.example.org", "policytemplate", false);
    // create prepared policy template
    final IRepository repository = RepositoryFactory.getRepository();
    final Definitions definitions = BackendUtils.createWrapperDefinitionsAndInitialEmptyElement(repository, policyTemplateId);
    final TPolicyTemplate policyTemplate = (TPolicyTemplate) definitions.getElement();
    QName policyTypeQName = new QName("http://plain.winery.opentosca.org/policytypes", "PolicyTypeWithTwoKvProperties");
    policyTemplate.setType(policyTypeQName);
    BackendUtils.initializeProperties(repository, policyTemplate);
    Assert.assertNotNull(policyTemplate.getProperties());
    LinkedHashMap<String, String> kvProperties = policyTemplate.getProperties().getKVProperties();
    LinkedHashMap<String, String> expectedPropertyKVS = new LinkedHashMap<>();
    expectedPropertyKVS.put("key1", "");
    expectedPropertyKVS.put("key2", "");
    Assert.assertEquals(expectedPropertyKVS, kvProperties);
}
Also used : TPolicyTemplate(org.eclipse.winery.model.tosca.TPolicyTemplate) QName(javax.xml.namespace.QName) Definitions(org.eclipse.winery.model.tosca.Definitions) PolicyTemplateId(org.eclipse.winery.common.ids.definitions.PolicyTemplateId) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 14 with Definitions

use of org.eclipse.winery.model.tosca.Definitions in project winery by eclipse.

the class WriterUtils method storeDefinitions.

public static void storeDefinitions(Definitions definitions, boolean overwrite, Path dir) {
    Path path = null;
    try {
        path = Files.createTempDirectory("winery");
    } catch (IOException e) {
        e.printStackTrace();
    }
    LOGGER.debug("Store definition: {}", definitions.getId());
    saveDefinitions(definitions, path, definitions.getTargetNamespace(), definitions.getId());
    Definitions cleanDefinitions = loadDefinitions(path, definitions.getTargetNamespace(), definitions.getId());
    CsarImporter csarImporter = new CsarImporter();
    List<Exception> exceptions = new ArrayList<>();
    cleanDefinitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().forEach(entry -> {
        String namespace = csarImporter.getNamespace(entry, definitions.getTargetNamespace());
        csarImporter.setNamespace(entry, namespace);
        String id = ModelUtilities.getId(entry);
        Class<? extends DefinitionsChildId> widClazz = Util.getComponentIdClassForTExtensibleElements(entry.getClass());
        final DefinitionsChildId wid = BackendUtils.getDefinitionsChildId(widClazz, namespace, id, false);
        if (RepositoryFactory.getRepository().exists(wid)) {
            if (overwrite) {
                try {
                    RepositoryFactory.getRepository().forceDelete(wid);
                } catch (IOException e) {
                    exceptions.add(e);
                }
            } else {
                return;
            }
        }
        if (entry instanceof TArtifactTemplate) {
            TArtifactTemplate.ArtifactReferences artifactReferences = ((TArtifactTemplate) entry).getArtifactReferences();
            Stream.of(artifactReferences).filter(Objects::nonNull).flatMap(ref -> ref.getArtifactReference().stream()).filter(Objects::nonNull).forEach(ref -> {
                String reference = ref.getReference();
                URI refURI;
                try {
                    refURI = new URI(reference);
                } catch (URISyntaxException e) {
                    LOGGER.error("Invalid URI {}", reference);
                    return;
                }
                if (refURI.isAbsolute()) {
                    return;
                }
                Path artifactPath = dir.resolve(reference);
                if (!Files.exists(artifactPath)) {
                    LOGGER.error("File not found {}", artifactPath);
                    return;
                }
                ArtifactTemplateFilesDirectoryId aDir = new ArtifactTemplateFilesDirectoryId((ArtifactTemplateId) wid);
                RepositoryFileReference aFile = new RepositoryFileReference(aDir, artifactPath.getFileName().toString());
                MediaType mediaType = null;
                try (InputStream is = Files.newInputStream(artifactPath);
                    BufferedInputStream bis = new BufferedInputStream(is)) {
                    mediaType = BackendUtils.getMimeType(bis, artifactPath.getFileName().toString());
                    RepositoryFactory.getRepository().putContentToFile(aFile, bis, mediaType);
                } catch (IOException e) {
                    LOGGER.error("Could not read artifact template file: {}", artifactPath);
                    return;
                }
            });
        }
        final Definitions part = BackendUtils.createWrapperDefinitions(wid);
        part.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(entry);
        RepositoryFileReference ref = BackendUtils.getRefOfDefinitions(wid);
        String content = BackendUtils.getXMLAsString(part, true);
        try {
            RepositoryFactory.getRepository().putContentToFile(ref, content, MediaTypes.MEDIATYPE_TOSCA_DEFINITIONS);
        } catch (Exception e) {
            exceptions.add(e);
        }
    });
}
Also used : Path(java.nio.file.Path) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) CsarImporter(org.eclipse.winery.repository.importing.CsarImporter) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) Definitions(org.eclipse.winery.model.tosca.Definitions) TDefinitions(org.eclipse.winery.model.tosca.TDefinitions) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) TransformerException(javax.xml.transform.TransformerException) URISyntaxException(java.net.URISyntaxException) JAXBException(javax.xml.bind.JAXBException) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) RepositoryFileReference(org.eclipse.winery.common.RepositoryFileReference) MediaType(org.apache.tika.mime.MediaType)

Example 15 with Definitions

use of org.eclipse.winery.model.tosca.Definitions in project winery by eclipse.

the class Converter method convertX2Y.

public InputStream convertX2Y(InputStream csar) {
    Path filePath = Utils.unzipFile(csar);
    Path fileOutPath = filePath.resolve("tmp");
    try {
        TOSCAMetaFileParser parser = new TOSCAMetaFileParser();
        TOSCAMetaFile metaFile = parser.parse(filePath.resolve("TOSCA-Metadata").resolve("TOSCA.meta"));
        org.eclipse.winery.yaml.common.reader.xml.Reader reader = new org.eclipse.winery.yaml.common.reader.xml.Reader();
        try {
            String fileName = metaFile.getEntryDefinitions();
            Definitions definitions = reader.parse(filePath, Paths.get(fileName));
            this.convertX2Y(definitions, fileOutPath);
        } catch (MultiException e) {
            LOGGER.error("Convert TOSCA XML to TOSCA YAML error", e);
        }
        return Utils.zipPath(fileOutPath);
    } catch (Exception e) {
        LOGGER.error("Error", e);
        throw new AssertionError();
    }
}
Also used : Definitions(org.eclipse.winery.model.tosca.Definitions) Reader(org.eclipse.winery.yaml.common.reader.yaml.Reader) TOSCAMetaFileParser(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFileParser) IOException(java.io.IOException) WineryRepositoryException(org.eclipse.winery.repository.exceptions.WineryRepositoryException) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) MultiException(org.eclipse.winery.yaml.common.exception.MultiException) TOSCAMetaFile(org.eclipse.winery.model.csar.toscametafile.TOSCAMetaFile)

Aggregations

Definitions (org.eclipse.winery.model.tosca.Definitions)21 RepositoryFileReference (org.eclipse.winery.common.RepositoryFileReference)7 TDefinitions (org.eclipse.winery.model.tosca.TDefinitions)7 IOException (java.io.IOException)6 JAXBException (javax.xml.bind.JAXBException)5 QName (javax.xml.namespace.QName)5 Test (org.junit.Test)5 Unmarshaller (javax.xml.bind.Unmarshaller)4 TServiceTemplate (org.eclipse.winery.model.tosca.yaml.TServiceTemplate)4 BufferedInputStream (java.io.BufferedInputStream)3 InputStream (java.io.InputStream)3 DefinitionsChildId (org.eclipse.winery.common.ids.definitions.DefinitionsChildId)3 PolicyTemplateId (org.eclipse.winery.common.ids.definitions.PolicyTemplateId)3 TArtifactTemplate (org.eclipse.winery.model.tosca.TArtifactTemplate)3 TEntityType (org.eclipse.winery.model.tosca.TEntityType)3 TExtensibleElements (org.eclipse.winery.model.tosca.TExtensibleElements)3 TImport (org.eclipse.winery.model.tosca.TImport)3 TPolicyTemplate (org.eclipse.winery.model.tosca.TPolicyTemplate)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 URI (java.net.URI)2