Search in sources :

Example 6 with Namespace

use of org.eclipse.winery.model.ids.Namespace in project winery by eclipse.

the class RepositoryBasedXsdImportManager method getAllXsdDefinitions.

/**
 * @param getType true: XSConstants.TYPE_DEFINITION; false: XSConstants.ELEMENT_DECLARATION
 */
private List<NamespaceAndDefinedLocalNames> getAllXsdDefinitions(boolean getType) {
    MutableMultimap<Namespace, String> data = Multimaps.mutable.list.empty();
    SortedSet<XSDImportId> allImports = owner.getAllDefinitionsChildIds(XSDImportId.class);
    for (XSDImportId id : allImports) {
        final List<String> allDefinedLocalNames = getAllDefinedLocalNames(id, getType);
        data.putAll(id.getNamespace(), allDefinedLocalNames);
    }
    List<NamespaceAndDefinedLocalNames> result = Lists.mutable.empty();
    data.forEachKeyMultiValues((namespace, strings) -> {
        final NamespaceAndDefinedLocalNames namespaceAndDefinedLocalNames = new NamespaceAndDefinedLocalNames(namespace);
        strings.forEach(localName -> namespaceAndDefinedLocalNames.addLocalName(localName));
        result.add(namespaceAndDefinedLocalNames);
    });
    return result;
}
Also used : XSDImportId(org.eclipse.winery.model.ids.definitions.imports.XSDImportId) Namespace(org.eclipse.winery.model.ids.Namespace)

Example 7 with Namespace

use of org.eclipse.winery.model.ids.Namespace in project winery by eclipse.

the class GenericArtifactsResource method generateArtifact.

/**
 * @return TImplementationArtifact | TDeploymentArtifact (XML) | URL of generated IA zip (in case of autoGenerateIA)
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Creates a new implementation/deployment artifact. If an implementation artifact with the same name already exists, it is <em>overridden</em>.")
@SuppressWarnings("unchecked")
public Response generateArtifact(GenerateArtifactApiData apiData, @Context UriInfo uriInfo) {
    // we assume that the parent ComponentInstance container exists
    final IRepository repository = RepositoryFactory.getRepository();
    if (StringUtils.isEmpty(apiData.artifactName)) {
        return Response.status(Status.BAD_REQUEST).entity("Empty artifactName").build();
    }
    if (StringUtils.isEmpty(apiData.artifactType)) {
        if (StringUtils.isEmpty(apiData.artifactTemplateName) || StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
            if (StringUtils.isEmpty(apiData.artifactTemplate)) {
                return Response.status(Status.BAD_REQUEST).entity("No artifact type given and no template given. Cannot guess artifact type").build();
            }
        }
    }
    if (!StringUtils.isEmpty(apiData.autoGenerateIA)) {
        if (StringUtils.isEmpty(apiData.javaPackage)) {
            return Response.status(Status.BAD_REQUEST).entity("no java package name supplied for IA auto generation.").build();
        }
        if (StringUtils.isEmpty(apiData.interfaceName)) {
            return Response.status(Status.BAD_REQUEST).entity("no interface name supplied for IA auto generation.").build();
        }
    }
    // convert second calling form to first calling form
    if (!StringUtils.isEmpty(apiData.artifactTemplate)) {
        QName qname = QName.valueOf(apiData.artifactTemplate);
        apiData.artifactTemplateName = qname.getLocalPart();
        apiData.artifactTemplateNamespace = qname.getNamespaceURI();
    }
    Document doc = null;
    // if invalid, abort and do not create anything
    if (!StringUtils.isEmpty(apiData.artifactSpecificContent)) {
        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            StringReader sr = new StringReader(apiData.artifactSpecificContent);
            is.setCharacterStream(sr);
            doc = db.parse(is);
        } catch (Exception e) {
            // FIXME: currently we allow a single element only. However, the content should be internally wrapped by an (arbitrary) XML element as the content will be nested in the artifact element, too
            LOGGER.debug("Invalid content", e);
            return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
        }
    }
    // determine artifactTemplate and artifactType
    ArtifactTypeId artifactTypeId;
    ArtifactTemplateId artifactTemplateId = null;
    boolean doAutoCreateArtifactTemplate = !(StringUtils.isEmpty(apiData.autoCreateArtifactTemplate) || apiData.autoCreateArtifactTemplate.equalsIgnoreCase("no") || apiData.autoCreateArtifactTemplate.equalsIgnoreCase("false"));
    if (!doAutoCreateArtifactTemplate) {
        // no auto creation
        if (!StringUtils.isEmpty(apiData.artifactTemplateName) && !StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
            QName artifactTemplateQName = new QName(apiData.artifactTemplateNamespace, apiData.artifactTemplateName);
            artifactTemplateId = BackendUtils.getDefinitionsChildId(ArtifactTemplateId.class, artifactTemplateQName);
        }
        if (StringUtils.isEmpty(apiData.artifactType)) {
            // derive the type from the artifact template
            if (artifactTemplateId == null) {
                return Response.status(Status.NOT_ACCEPTABLE).entity("No artifactTemplate and no artifactType provided. Deriving the artifactType is not possible.").build();
            }
            @NonNull final QName type = repository.getElement(artifactTemplateId).getType();
            artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, type);
        } else {
            // artifactTypeStr is directly given, use that
            artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, apiData.artifactType);
        }
    } else {
        if (StringUtils.isEmpty(apiData.artifactType)) {
            return Response.status(Status.BAD_REQUEST).entity("Artifact template auto creation requested, but no artifact type supplied.").build();
        }
        artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, apiData.artifactType);
        // ensure that given type exists
        if (!repository.exists(artifactTypeId)) {
            LOGGER.debug("Artifact type {} is created", apiData.artifactType);
            final TArtifactType element = repository.getElement(artifactTypeId);
            try {
                repository.setElement(artifactTypeId, element);
            } catch (IOException e) {
                throw new WebApplicationException(e);
            }
        }
        if (StringUtils.isEmpty(apiData.artifactTemplateName) || StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
            // no explicit name provided
            // we use the artifactNameStr as prefix for the
            // artifact template name
            // we create a new artifact template in the namespace of the parent
            // element
            Namespace namespace = this.resWithNamespace.getNamespace();
            artifactTemplateId = new ArtifactTemplateId(namespace, new XmlId(apiData.artifactName + "artifactTemplate", false));
        } else {
            QName artifactTemplateQName = new QName(apiData.artifactTemplateNamespace, apiData.artifactTemplateName);
            artifactTemplateId = new ArtifactTemplateId(artifactTemplateQName);
        }
        // even if artifactTemplate does not exist, it is loaded
        final TArtifactTemplate artifactTemplate = repository.getElement(artifactTemplateId);
        artifactTemplate.setType(artifactTypeId.getQName());
        try {
            repository.setElement(artifactTemplateId, artifactTemplate);
        } catch (IOException e) {
            throw new WebApplicationException(e);
        }
    }
    // variable artifactTypeId is set
    // variable artifactTemplateId is not null if artifactTemplate has been generated
    // we have to generate the DA/IA resource now
    // Doing it here instead of doing it at the subclasses is dirty on the
    // one hand, but quicker to implement on the other hand
    // Create the artifact itself
    ArtifactT resultingArtifact;
    if (this instanceof ImplementationArtifactsResource) {
        TImplementationArtifact.Builder builder = new TImplementationArtifact.Builder(artifactTypeId.getQName()).setName(apiData.artifactName).setInterfaceName(apiData.interfaceName).setOperationName(apiData.operationName);
        if (artifactTemplateId != null) {
            builder.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            // the content has been checked for validity at the beginning of the method.
            // If this point in the code is reached, the XML has been parsed into doc
            // just copy over the dom node. Hopefully, that works...
            builder.setAny(Collections.singletonList(doc.getDocumentElement()));
        }
        resultingArtifact = (ArtifactT) builder.build();
    } else {
        // for comments see other branch
        TDeploymentArtifact.Builder builder = new TDeploymentArtifact.Builder(apiData.artifactName, artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            builder.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            builder.setAny(Collections.singletonList(doc.getDocumentElement()));
        }
        resultingArtifact = (ArtifactT) builder.build();
    }
    this.list.add(resultingArtifact);
    // TODO: Check for error, and in case one found return it
    RestUtils.persist(super.res);
    if (StringUtils.isEmpty(apiData.autoGenerateIA)) {
        // No IA generation
        return Response.created(URI.create(EncodingUtil.URLencode(apiData.artifactName))).entity(resultingArtifact).build();
    } else {
        // after everything was created, we fire up the artifact generation
        return this.generateImplementationArtifact(apiData.interfaceName, apiData.javaPackage, uriInfo, artifactTemplateId);
    }
}
Also used : InputSource(org.xml.sax.InputSource) TImplementationArtifact(org.eclipse.winery.model.tosca.TImplementationArtifact) WebApplicationException(javax.ws.rs.WebApplicationException) ArtifactTypeId(org.eclipse.winery.model.ids.definitions.ArtifactTypeId) QName(javax.xml.namespace.QName) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) DocumentBuilder(javax.xml.parsers.DocumentBuilder) IOException(java.io.IOException) Document(org.w3c.dom.Document) WebApplicationException(javax.ws.rs.WebApplicationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) Namespace(org.eclipse.winery.model.ids.Namespace) DocumentBuilder(javax.xml.parsers.DocumentBuilder) NonNull(org.eclipse.jdt.annotation.NonNull) StringReader(java.io.StringReader) TArtifactType(org.eclipse.winery.model.tosca.TArtifactType) XmlId(org.eclipse.winery.model.ids.XmlId) TDeploymentArtifact(org.eclipse.winery.model.tosca.TDeploymentArtifact) IRepository(org.eclipse.winery.repository.backend.IRepository) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation)

Example 8 with Namespace

use of org.eclipse.winery.model.ids.Namespace in project winery by eclipse.

the class AbstractFileBasedRepository method getNamespaces.

private Collection<Namespace> getNamespaces(Collection<Class<? extends DefinitionsChildId>> definitionsChildIds) {
    // we use a HashSet to avoid reporting duplicate namespaces
    Collection<Namespace> res = new HashSet<>();
    for (Class<? extends DefinitionsChildId> id : definitionsChildIds) {
        String rootPathFragment = IdUtil.getRootPathFragment(id);
        Path dir = this.getRepositoryRoot().resolve(rootPathFragment);
        if (!Files.exists(dir)) {
            continue;
        }
        assert (Files.isDirectory(dir));
        final OnlyNonHiddenDirectories onhdf = new OnlyNonHiddenDirectories();
        // list all directories contained in this directory
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, onhdf)) {
            for (Path nsP : ds) {
                // the current path is the namespace
                Namespace ns = new Namespace(nsP.getFileName().toString(), true);
                res.add(ns);
            }
        } catch (IOException e) {
            LOGGER.debug("Cannot close ds", e);
        }
    }
    return res;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) Namespace(org.eclipse.winery.model.ids.Namespace) HashSet(java.util.HashSet)

Example 9 with Namespace

use of org.eclipse.winery.model.ids.Namespace in project winery by eclipse.

the class BackendUtils method deriveWPD.

/**
 * Derives Winery's Properties Definition from an existing properties definition
 *
 * @param ci     the entity type to try to modify the WPDs
 * @param errors the list to add errors to
 */
// FIXME this is specifically for xml backends and therefore broken under the new canonical model
public static void deriveWPD(TEntityType ci, List<String> errors, IRepository repository) {
    BackendUtils.LOGGER.trace("deriveWPD");
    TEntityType.PropertiesDefinition propertiesDefinition = ci.getProperties();
    if (propertiesDefinition == null) {
        // if there's no properties definition, there's nothing to derive because we're in YAML mode
        return;
    }
    if (!(propertiesDefinition instanceof TEntityType.XmlElementDefinition)) {
        BackendUtils.LOGGER.debug("only works for an element definition, not for types");
        return;
    }
    final QName element = ((TEntityType.XmlElementDefinition) propertiesDefinition).getElement();
    BackendUtils.LOGGER.debug("Looking for the definition of {" + element.getNamespaceURI() + "}" + element.getLocalPart());
    // fetch the XSD defining the element
    final XsdImportManager xsdImportManager = repository.getXsdImportManager();
    Map<String, RepositoryFileReference> mapFromLocalNameToXSD = xsdImportManager.getMapFromLocalNameToXSD(new Namespace(element.getNamespaceURI(), false), false);
    RepositoryFileReference ref = mapFromLocalNameToXSD.get(element.getLocalPart());
    if (ref == null) {
        String msg = "XSD not found for " + element.getNamespaceURI() + " / " + element.getLocalPart();
        BackendUtils.LOGGER.debug(msg);
        errors.add(msg);
        return;
    }
    final Optional<XSModel> xsModelOptional = BackendUtils.getXSModel(ref, repository);
    if (!xsModelOptional.isPresent()) {
        LOGGER.error("no XSModel found");
    }
    XSModel xsModel = xsModelOptional.get();
    XSElementDeclaration elementDeclaration = xsModel.getElementDeclaration(element.getLocalPart(), element.getNamespaceURI());
    if (elementDeclaration == null) {
        String msg = "XSD model claimed to contain declaration for {" + element.getNamespaceURI() + "}" + element.getLocalPart() + ", but it did not.";
        BackendUtils.LOGGER.debug(msg);
        errors.add(msg);
        return;
    }
    // go through the XSD definition and
    XSTypeDefinition typeDefinition = elementDeclaration.getTypeDefinition();
    if (!(typeDefinition instanceof XSComplexTypeDefinition)) {
        BackendUtils.LOGGER.debug("XSD does not follow the requirements put by winery: No Complex Type Definition");
        return;
    }
    XSComplexTypeDefinition cTypeDefinition = (XSComplexTypeDefinition) typeDefinition;
    XSParticle particle = cTypeDefinition.getParticle();
    if (particle == null) {
        BackendUtils.LOGGER.debug("XSD does not follow the requirements put by winery: Complex type does not contain particles");
        return;
    }
    XSTerm term = particle.getTerm();
    if (!(term instanceof XSModelGroup)) {
        BackendUtils.LOGGER.debug("XSD does not follow the requirements put by winery: Not a model group");
        return;
    }
    XSModelGroup modelGroup = (XSModelGroup) term;
    if (modelGroup.getCompositor() != XSModelGroup.COMPOSITOR_SEQUENCE) {
        BackendUtils.LOGGER.debug("XSD does not follow the requirements put by winery: Model group is not a sequence");
        return;
    }
    XSObjectList particles = modelGroup.getParticles();
    int len = particles.getLength();
    boolean everyThingIsASimpleType = true;
    List<PropertyDefinitionKV> list = new ArrayList<>();
    if (len != 0) {
        for (int i = 0; i < len; i++) {
            XSParticle innerParticle = (XSParticle) particles.item(i);
            XSTerm innerTerm = innerParticle.getTerm();
            if (innerTerm instanceof XSElementDeclaration) {
                XSElementDeclaration innerElementDeclaration = (XSElementDeclaration) innerTerm;
                String name = innerElementDeclaration.getName();
                XSTypeDefinition innerTypeDefinition = innerElementDeclaration.getTypeDefinition();
                if (innerTypeDefinition instanceof XSSimpleType) {
                    XSSimpleType xsSimpleType = (XSSimpleType) innerTypeDefinition;
                    String typeNS = xsSimpleType.getNamespace();
                    String typeName = xsSimpleType.getName();
                    if (typeNS.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                        PropertyDefinitionKV def = new PropertyDefinitionKV();
                        def.setKey(name);
                        // convention at WPD: use "xsd" as prefix for XML Schema Definition
                        def.setType("xsd:" + typeName);
                        list.add(def);
                    } else {
                        everyThingIsASimpleType = false;
                        break;
                    }
                } else {
                    everyThingIsASimpleType = false;
                    break;
                }
            } else {
                everyThingIsASimpleType = false;
                break;
            }
        }
    }
    if (!everyThingIsASimpleType) {
        BackendUtils.LOGGER.debug("XSD does not follow the requirements put by winery: Not all types in the sequence are simple types");
        return;
    }
    // everything went alright, we can add a WPD
    WinerysPropertiesDefinition wpd = new WinerysPropertiesDefinition();
    wpd.setIsDerivedFromXSD(Boolean.TRUE);
    wpd.setElementName(element.getLocalPart());
    wpd.setNamespace(element.getNamespaceURI());
    wpd.setPropertyDefinitions(list);
    ModelUtilities.replaceWinerysPropertiesDefinition(ci, wpd);
    BackendUtils.LOGGER.debug("Successfully generated WPD");
}
Also used : XSTypeDefinition(org.apache.xerces.xs.XSTypeDefinition) XSObjectList(org.apache.xerces.xs.XSObjectList) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) XSParticle(org.apache.xerces.xs.XSParticle) TEntityType(org.eclipse.winery.model.tosca.TEntityType) ArrayList(java.util.ArrayList) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition) XSComplexTypeDefinition(org.apache.xerces.xs.XSComplexTypeDefinition) XSSimpleType(org.apache.xerces.impl.dv.XSSimpleType) XSElementDeclaration(org.apache.xerces.xs.XSElementDeclaration) XSModel(org.apache.xerces.xs.XSModel) XsdImportManager(org.eclipse.winery.repository.backend.xsd.XsdImportManager) XSModelGroup(org.apache.xerces.xs.XSModelGroup) XSTerm(org.apache.xerces.xs.XSTerm) QName(javax.xml.namespace.QName) HasTargetNamespace(org.eclipse.winery.model.tosca.HasTargetNamespace) Namespace(org.eclipse.winery.model.ids.Namespace) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference)

Example 10 with Namespace

use of org.eclipse.winery.model.ids.Namespace in project winery by eclipse.

the class XmlRepository method getDefinitionsChildIds.

public <T extends DefinitionsChildId> SortedSet<T> getDefinitionsChildIds(Class<T> idClass, boolean omitDevelopmentVersions) {
    SortedSet<T> res = new TreeSet<>();
    String rootPathFragment = IdUtil.getRootPathFragment(idClass);
    Path dir = makeAbsolute(Paths.get(rootPathFragment));
    if (!Files.exists(dir)) {
        // return empty list if no ids are available
        return res;
    }
    assert (Files.isDirectory(dir));
    final OnlyNonHiddenDirectories hiddenDirectories = new OnlyNonHiddenDirectories();
    // list all directories contained in this directory
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, hiddenDirectories)) {
        for (Path nsP : ds) {
            // the current path is the namespace
            Namespace ns = new Namespace(nsP.getFileName().toString(), true);
            try (DirectoryStream<Path> idDS = Files.newDirectoryStream(nsP, hiddenDirectories)) {
                for (Path idP : idDS) {
                    XmlId xmlId = new XmlId(idP.getFileName().toString(), true);
                    if (omitDevelopmentVersions) {
                        WineryVersion version = VersionUtils.getVersion(xmlId.getDecoded());
                        if (version.toString().length() > 0 && version.getWorkInProgressVersion() > 0) {
                            continue;
                        }
                    }
                    Constructor<T> constructor;
                    try {
                        constructor = idClass.getConstructor(Namespace.class, XmlId.class);
                    } catch (Exception e) {
                        LOGGER.debug("Internal error at determining id constructor", e);
                        // abort everything, return invalid result
                        return res;
                    }
                    T id;
                    try {
                        id = constructor.newInstance(ns, xmlId);
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        LOGGER.debug("Internal error at invocation of id constructor", e);
                        // abort everything, return invalid result
                        return res;
                    }
                    res.add(id);
                }
            }
        }
    } catch (IOException e) {
        LOGGER.debug("Cannot close ds", e);
    }
    return res;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) Namespace(org.eclipse.winery.model.ids.Namespace) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) OnlyNonHiddenDirectories(org.eclipse.winery.repository.backend.filebased.OnlyNonHiddenDirectories) TreeSet(java.util.TreeSet) XmlId(org.eclipse.winery.model.ids.XmlId) WineryVersion(org.eclipse.winery.common.version.WineryVersion)

Aggregations

Namespace (org.eclipse.winery.model.ids.Namespace)13 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 IRepository (org.eclipse.winery.repository.backend.IRepository)5 Path (java.nio.file.Path)4 QName (javax.xml.namespace.QName)4 XmlId (org.eclipse.winery.model.ids.XmlId)4 Map (java.util.Map)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 TreeSet (java.util.TreeSet)2 Collectors (java.util.stream.Collectors)2 JAXBException (javax.xml.bind.JAXBException)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2 NonNull (org.eclipse.jdt.annotation.NonNull)2 Nullable (org.eclipse.jdt.annotation.Nullable)2 DefinitionsChildId (org.eclipse.winery.model.ids.definitions.DefinitionsChildId)2 EntityTemplateId (org.eclipse.winery.model.ids.definitions.EntityTemplateId)2