Search in sources :

Example 11 with Namespace

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

the class AbstractComponentsResource method getListOfAllIds.

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>.
 * <p>
 * If grouped is set, the list will be grouped by namespace.
 * <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped, @QueryParam("full") @ApiParam("If set, the full information of the definition's child is returned. E.g., in the case of node types, the same result as a GET on {ns}/{id] is returned. Works only in the case of grouped.") String full) {
    Class<? extends DefinitionsChildId> idClass = RestUtils.getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    final IRepository repository = RepositoryFactory.getRepository();
    SortedSet<? extends DefinitionsChildId> allDefinitionsChildIds = repository.getAllDefinitionsChildIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.setCodec(BackendUtils.mapper);
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (DefinitionsChildId id : allDefinitionsChildIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource.getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                if (full != null) {
                    try {
                        jg.writeFieldName("full");
                        jg.writeObject(BackendUtils.getDefinitionsHavingCorrectImports(repository, id));
                    } catch (Exception e) {
                        throw new WebApplicationException(e);
                    }
                }
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends DefinitionsChildId>> groupedIds = allDefinitionsChildIds.stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource.getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            if (full != null) {
                                try {
                                    jg.writeFieldName("full");
                                    jg.writeObject(BackendUtils.getDefinitionsHavingCorrectImports(repository, id));
                                } catch (Exception e) {
                                    throw new WebApplicationException(e);
                                }
                            }
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}
Also used : java.util(java.util) ServiceTemplateId(org.eclipse.winery.common.ids.definitions.ServiceTemplateId) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) LoggerFactory(org.slf4j.LoggerFactory) ApiParam(io.swagger.annotations.ApiParam) StringUtils(org.apache.commons.lang3.StringUtils) Constructor(java.lang.reflect.Constructor) NotFoundException(com.sun.jersey.api.NotFoundException) MediaType(javax.ws.rs.core.MediaType) ArtifactTemplateId(org.eclipse.winery.common.ids.definitions.ArtifactTemplateId) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) Status(javax.ws.rs.core.Response.Status) PolicyTemplateId(org.eclipse.winery.common.ids.definitions.PolicyTemplateId) Logger(org.slf4j.Logger) StringWriter(java.io.StringWriter) IOException(java.io.IOException) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) Util(org.eclipse.winery.common.Util) Collectors(java.util.stream.Collectors) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) InvocationTargetException(java.lang.reflect.InvocationTargetException) JsonFactory(com.fasterxml.jackson.core.JsonFactory) javax.ws.rs(javax.ws.rs) IRepository(org.eclipse.winery.repository.backend.IRepository) RestUtils(org.eclipse.winery.repository.rest.RestUtils) Namespace(org.eclipse.winery.common.ids.Namespace) QName(javax.xml.namespace.QName) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) JsonFactory(com.fasterxml.jackson.core.JsonFactory) IOException(java.io.IOException) NotFoundException(com.sun.jersey.api.NotFoundException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Namespace(org.eclipse.winery.common.ids.Namespace) StringWriter(java.io.StringWriter) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) IRepository(org.eclipse.winery.repository.backend.IRepository)

Example 12 with Namespace

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

the class NamespacesResource method getNamespacesAsJSONlist.

/**
 * Returns the list of all namespaces registered with his manager and used at component instances.
 *
 * @return a JSON list containing the non-encoded URIs of each known namespace
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<NamespaceWithPrefix> getNamespacesAsJSONlist(@ApiParam(value = "if set all namespaces are returned otherwise the list will be filtered by disallowed namespaces", required = false) @QueryParam("all") String allNamespaces) {
    Collection<Namespace> namespaces = this.getNamespaces();
    // We now have all namespaces
    // We need to check if the "all" parameter has been set and filter accordingly
    // We need to convert from Namespace to String
    List<NamespaceWithPrefix> namespacesList = new ArrayList<>();
    for (Namespace ns : namespaces) {
        if (allNamespaces == null) {
            if (!Namespaces.getDisallowedNamespaces().contains(ns.getDecoded())) {
                namespacesList.add(new NamespaceWithPrefix(ns, this.namespaceManager.getPrefix(ns.getDecoded())));
            }
        } else {
            namespacesList.add(new NamespaceWithPrefix(ns, this.namespaceManager.getPrefix(ns.getDecoded())));
        }
    }
    Collections.sort(namespacesList);
    return namespacesList;
}
Also used : Namespace(org.eclipse.winery.common.ids.Namespace) NamespaceWithPrefix(org.eclipse.winery.repository.rest.resources.apiData.NamespaceWithPrefix)

Example 13 with Namespace

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

the class GenericArtifactsResource method generateArtifact.

// @formatter:off
/**
 * @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
            GenericArtifactsResource.LOGGER.debug("Invalid content", e);
            return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
        }
    }
    // determine artifactTemplate and artifactType
    ArtifactTypeId artifactTypeId;
    ArtifactTemplateId artifactTemplateId = null;
    ArtifactTemplateResource artifactTemplateResource = 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) {
        ImplementationArtifact a = new ImplementationArtifact();
        // Winery internal id is the name of the artifact:
        // store the name
        a.setName(apiData.artifactName);
        a.setInterfaceName(apiData.interfaceName);
        a.setOperationName(apiData.operationName);
        assert (artifactTypeId != null);
        a.setArtifactType(artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            a.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...
            a.getAny().add(doc.getDocumentElement());
        }
        this.list.add((ArtifactT) a);
        resultingArtifact = (ArtifactT) a;
    } else {
        // for comments see other branch
        TDeploymentArtifact a = new TDeploymentArtifact();
        a.setName(apiData.artifactName);
        assert (artifactTypeId != null);
        a.setArtifactType(artifactTypeId.getQName());
        if (artifactTemplateId != null) {
            a.setArtifactRef(artifactTemplateId.getQName());
        }
        if (doc != null) {
            a.getAny().add(doc.getDocumentElement());
        }
        this.list.add((ArtifactT) a);
        resultingArtifact = (ArtifactT) a;
    }
    Response persistResponse = RestUtils.persist(super.res);
    if (StringUtils.isEmpty(apiData.autoGenerateIA)) {
        return Response.created(RestUtils.createURI(Util.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) WebApplicationException(javax.ws.rs.WebApplicationException) ArtifactTypeId(org.eclipse.winery.common.ids.definitions.ArtifactTypeId) QName(javax.xml.namespace.QName) 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.common.ids.definitions.ArtifactTemplateId) ArtifactTemplateResource(org.eclipse.winery.repository.rest.resources.entitytemplates.artifacttemplates.ArtifactTemplateResource) Namespace(org.eclipse.winery.common.ids.Namespace) ImplementationArtifact(org.eclipse.winery.model.tosca.TImplementationArtifacts.ImplementationArtifact) Response(javax.ws.rs.core.Response) DocumentBuilder(javax.xml.parsers.DocumentBuilder) NonNull(org.eclipse.jdt.annotation.NonNull) StringReader(java.io.StringReader) XmlId(org.eclipse.winery.common.ids.XmlId) IRepository(org.eclipse.winery.repository.backend.IRepository) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

Namespace (org.eclipse.winery.common.ids.Namespace)13 QName (javax.xml.namespace.QName)5 XmlId (org.eclipse.winery.common.ids.XmlId)5 RepositoryFactory (org.eclipse.winery.repository.backend.RepositoryFactory)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 Collectors (java.util.stream.Collectors)3 RepositoryFileReference (org.eclipse.winery.common.RepositoryFileReference)3 ServiceTemplateId (org.eclipse.winery.common.ids.definitions.ServiceTemplateId)3 TServiceTemplate (org.eclipse.winery.model.tosca.TServiceTemplate)3 PropertyDefinitionKV (org.eclipse.winery.model.tosca.kvproperties.PropertyDefinitionKV)3 WinerysPropertiesDefinition (org.eclipse.winery.model.tosca.kvproperties.WinerysPropertiesDefinition)3 IRepository (org.eclipse.winery.repository.backend.IRepository)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 FileInputStream (java.io.FileInputStream)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 java.util (java.util)2 Stream (java.util.stream.Stream)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2