Search in sources :

Example 41 with RepositoryFileReference

use of org.eclipse.winery.repository.common.RepositoryFileReference in project winery by eclipse.

the class GenericImportResource method getFile.

@GET
@Path("{filename}")
public Response getFile(@PathParam("filename") @NonNull final String encodedFileName) {
    Objects.requireNonNull(encodedFileName);
    final Optional<TImport> theImport = ImportUtils.getTheImport(RepositoryFactory.getRepository(), (GenericImportId) id);
    if (!theImport.isPresent()) {
        return Response.status(Status.NOT_FOUND).build();
    }
    @Nullable final String location = theImport.get().getLocation();
    @NonNull String fileName = EncodingUtil.URLdecode(encodedFileName);
    if (!fileName.equals(location)) {
        LOGGER.debug("Filename mismatch %s vs %s", fileName, location);
        return Response.status(Status.NOT_FOUND).build();
    }
    RepositoryFileReference ref = new RepositoryFileReference(this.id, location);
    return RestUtils.returnRepoPath(ref, null);
}
Also used : RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) NonNull(org.eclipse.jdt.annotation.NonNull) TImport(org.eclipse.winery.model.tosca.TImport) Nullable(org.eclipse.jdt.annotation.Nullable) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 42 with RepositoryFileReference

use of org.eclipse.winery.repository.common.RepositoryFileReference in project winery by eclipse.

the class XSDImportResource method getXSD.

@GET
@ApiOperation(value = "May be used by the modeler to generate an XML editor based on the XML schema")
// we cannot use "MimeTypes.MIMETYPE_XSD" here as the latter is "text/xml" and org.eclipse.winery.repository.resources.AbstractComponentInstanceResource.getDefinitionsAsResponse() also produces text/xml
@Produces("text/xsd")
public Response getXSD() {
    final Optional<String> location = ImportUtils.getLocation(RepositoryFactory.getRepository(), (GenericImportId) id);
    if (!location.isPresent()) {
        return Response.status(Status.NOT_FOUND).build();
    }
    RepositoryFileReference ref = new RepositoryFileReference(this.id, location.get());
    return RestUtils.returnRepoPath(ref, null);
}
Also used : RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 43 with RepositoryFileReference

use of org.eclipse.winery.repository.common.RepositoryFileReference 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 44 with RepositoryFileReference

use of org.eclipse.winery.repository.common.RepositoryFileReference in project winery by eclipse.

the class BackendUtils method synchronizeReferences.

/**
 * Synchronizes the list of files of the given artifact template with the list of files contained in the given
 * repository. The repository is updated after synchronization.
 * <p>
 * This was intended if a user manually added files in the "files" directory and expected winery to correctly export
 * a CSAR
 *
 * @param repository The repository to search for the files
 * @param id         the id of the artifact template
 * @return The synchronized artifact template. Used for testing only, because mockito cannot mock static methods
 * (https://github.com/mockito/mockito/issues/1013).
 */
public static TArtifactTemplate synchronizeReferences(IRepository repository, ArtifactTemplateId id) throws IOException {
    TArtifactTemplate template = repository.getElement(id);
    List<TArtifactReference> toRemove = new ArrayList<>();
    List<RepositoryFileReference> toAdd = new ArrayList<>();
    List<TArtifactReference> artifactReferences = template.getArtifactReferences();
    DirectoryId fileDir = new ArtifactTemplateFilesDirectoryId(id);
    SortedSet<RepositoryFileReference> files = repository.getContainedFiles(fileDir);
    if (artifactReferences == null) {
        artifactReferences = new ArrayList<>();
        template.setArtifactReferences(artifactReferences);
    }
    determineChanges(artifactReferences, files, toRemove, toAdd);
    if (toAdd.size() > 0 || toRemove.size() > 0) {
        // apply removal list
        toRemove.forEach(artifactReferences::remove);
        // apply addition list
        artifactReferences.addAll(toAdd.stream().map(fileRef -> {
            String path = Util.getUrlPath(fileRef);
            return new TArtifactReference.Builder(path).build();
        }).collect(Collectors.toList()));
        // finally, persist only if something changed
        BackendUtils.persist(repository, id, template);
    }
    return template;
}
Also used : TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) TArtifactReference(org.eclipse.winery.model.tosca.TArtifactReference) ArrayList(java.util.ArrayList) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) GenericDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.GenericDirectoryId) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference)

Example 45 with RepositoryFileReference

use of org.eclipse.winery.repository.common.RepositoryFileReference in project winery by eclipse.

the class BackendUtils method synchronizeReferences.

/**
 * Synchronizes the known plans with the data in the XML. When there is a stored file, but no known entry in the
 * XML, we guess "BPEL" as language and "buildProvenanceSmartContract plan" as type.
 */
public static void synchronizeReferences(ServiceTemplateId id, IRepository repository) throws IOException {
    final TServiceTemplate serviceTemplate = repository.getElement(id);
    // locally stored plans
    List<TPlan> plans = serviceTemplate.getPlans();
    // plans stored in the repository
    PlansId plansContainerId = new PlansId(id);
    SortedSet<PlanId> nestedPlans = repository.getNestedIds(plansContainerId, PlanId.class);
    Set<PlanId> plansToAdd = new HashSet<>(nestedPlans);
    if (nestedPlans.isEmpty() && plans == null) {
        // data on the file system equals the data -> no plans
        return;
    }
    if (plans == null) {
        plans = new ArrayList<>();
        serviceTemplate.setPlans(plans);
    }
    for (Iterator<TPlan> iterator = plans.iterator(); iterator.hasNext(); ) {
        TPlan plan = iterator.next();
        if (plan.getPlanModel() != null) {
            // in case, a plan is directly contained in a Model element, we do not need to do anything
            continue;
        }
        TPlan.PlanModelReference planModelReference;
        if ((planModelReference = plan.getPlanModelReference()) != null) {
            String ref = planModelReference.getReference();
            if ((ref == null) || ref.startsWith("../")) {
                // special case (due to errors in the importer): empty PlanModelReference field
                if (plan.getId() == null || plan.getId().isEmpty()) {
                    // invalid plan entry: no id.
                    // we remove the entry
                    iterator.remove();
                    continue;
                }
                PlanId planId = new PlanId(plansContainerId, new XmlId(plan.getId(), false));
                if (nestedPlans.contains(planId)) {
                    // everything alright
                    // we do NOT need to add the plan on the HDD to the XML
                    plansToAdd.remove(planId);
                } else {
                    // no local storage for the plan, we remove it from the XML
                    iterator.remove();
                }
            }
        }
    }
    // add all plans locally stored, but not contained in the XML, as plan element to the plans of the service template.
    for (PlanId planId : plansToAdd) {
        SortedSet<RepositoryFileReference> files = repository.getContainedFiles(planId);
        if (files.size() != 1) {
            throw new IllegalStateException("Currently, only one file per plan is supported.");
        }
        RepositoryFileReference ref = files.iterator().next();
        TPlan plan = new TPlan.Builder(planId.getXmlId().getDecoded(), Constants.TOSCA_PLANTYPE_BUILD_PLAN, Namespaces.URI_BPEL20_EXECUTABLE).setName(planId.getXmlId().getDecoded()).build();
        // create a PlanModelReferenceElement pointing to that file
        String path = Util.getUrlPath(ref);
        // path is relative from the definitions element
        path = "../" + path;
        TPlan.PlanModelReference pref = new TPlan.PlanModelReference();
        pref.setReference(path);
        plan.setPlanModelReference(pref);
        plans.add(plan);
    }
    if (serviceTemplate.getPlans() != null && serviceTemplate.getPlans().isEmpty()) {
        serviceTemplate.setPlans(null);
    }
    repository.setElement(id, serviceTemplate);
}
Also used : PlanId(org.eclipse.winery.model.ids.elements.PlanId) PlansId(org.eclipse.winery.model.ids.elements.PlansId) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) TPlan(org.eclipse.winery.model.tosca.TPlan) XmlId(org.eclipse.winery.model.ids.XmlId) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) HashSet(java.util.HashSet)

Aggregations

RepositoryFileReference (org.eclipse.winery.repository.common.RepositoryFileReference)81 IOException (java.io.IOException)33 Path (java.nio.file.Path)26 TDefinitions (org.eclipse.winery.model.tosca.TDefinitions)17 QName (javax.xml.namespace.QName)14 ArtifactTemplateFilesDirectoryId (org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId)14 InputStream (java.io.InputStream)13 ArrayList (java.util.ArrayList)12 ArtifactTemplateId (org.eclipse.winery.model.ids.definitions.ArtifactTemplateId)12 IRepository (org.eclipse.winery.repository.backend.IRepository)12 ServiceTemplateId (org.eclipse.winery.model.ids.definitions.ServiceTemplateId)11 PlanId (org.eclipse.winery.model.ids.elements.PlanId)10 PlansId (org.eclipse.winery.model.ids.elements.PlansId)10 XmlId (org.eclipse.winery.model.ids.XmlId)9 Test (org.junit.jupiter.api.Test)9 DefinitionsChildId (org.eclipse.winery.model.ids.definitions.DefinitionsChildId)8 MediaType (org.apache.tika.mime.MediaType)7 TArtifactTemplate (org.eclipse.winery.model.tosca.TArtifactTemplate)7 BufferedInputStream (java.io.BufferedInputStream)6 HashMap (java.util.HashMap)6