Example usage for javax.xml.namespace QName valueOf

List of usage examples for javax.xml.namespace QName valueOf

Introduction

In this page you can find the example usage for javax.xml.namespace QName valueOf.

Prototype

public static QName valueOf(String qNameAsString) 

Source Link

Document

<p><code>QName</code> derived from parsing the formatted <code>String</code>.</p> <p>If the <code>String</code> is <code>null</code> or does not conform to #toString() QName.toString() formatting, an <code>IllegalArgumentException</code> is thrown.</p> <p><em>The <code>String</code> <strong>MUST</strong> be in the form returned by #toString() QName.toString() .</em></p> <p>The commonly accepted way of representing a <code>QName</code> as a <code>String</code> was <a href="http://jclark.com/xml/xmlns.htm">defined</a> by James Clark.

Usage

From source file:org.eclipse.winery.repository.backend.BackendUtils.java

public static <T extends TOSCAComponentId> T getTOSCAcomponentId(Class<T> idClass, String qnameStr) {
    QName qname = QName.valueOf(qnameStr);
    return BackendUtils.getTOSCAcomponentId(idClass, qname.getNamespaceURI(), qname.getLocalPart(), false);
}

From source file:org.eclipse.winery.repository.export.TOSCAExportUtil.java

/**
 * There is now equivalent id class for//from w w  w .  j a v a  2  s .c o  m
 * AbstractComponentInstanceResourceWithNameDerivedFromAbstractFinal, therefore we take the super
 * type and hope that the caller knows what he does.
 */
private Collection<TOSCAComponentId> getReferencedTOSCAComponentIdOfParentForAnAbstractComponentsWithTypeReferenceResource(
        TOSCAComponentId id) {
    AbstractComponentInstanceResourceWithNameDerivedFromAbstractFinal res = (AbstractComponentInstanceResourceWithNameDerivedFromAbstractFinal) AbstractComponentsResource
            .getComponentInstaceResource(id);
    String derivedFrom = res.getInheritanceManagement().getDerivedFrom();
    if (StringUtils.isEmpty(derivedFrom)) {
        return Collections.emptySet();
    } else {
        // Instantiate an id with the same class as the current id
        TOSCAComponentId parentId;
        QName qname = QName.valueOf(derivedFrom);

        Constructor<? extends TOSCAComponentId> constructor;
        try {
            constructor = id.getClass().getConstructor(QName.class);
        } catch (NoSuchMethodException | SecurityException e1) {
            throw new IllegalStateException("Could get constructor to instantiate parent id", e1);
        }
        try {
            parentId = constructor.newInstance(qname);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new IllegalStateException("Could not instantiate id for parent", e);
        }

        Collection<TOSCAComponentId> result = new ArrayList<>(1);
        result.add(parentId);
        return result;
    }
}

From source file:org.eclipse.winery.repository.resources.API.APIResource.java

@GET
@Path("getallartifacttemplatesofcontaineddeploymentartifacts")
@Produces(MediaType.APPLICATION_JSON)/*ww w.ja v a2  s  . com*/
public Response getAllArtifactTemplatesOfContainedDeploymentArtifacts(
        @QueryParam("servicetemplate") String serviceTemplateQNameString,
        @QueryParam("nodetemplateid") String nodeTemplateId) {
    if (StringUtils.isEmpty(serviceTemplateQNameString)) {
        return Response.status(Status.BAD_REQUEST).entity("servicetemplate has be given as query parameter")
                .build();
    }

    QName serviceTemplateQName = QName.valueOf(serviceTemplateQNameString);

    ServiceTemplateId serviceTemplateId = new ServiceTemplateId(serviceTemplateQName);
    if (!Repository.INSTANCE.exists(serviceTemplateId)) {
        return Response.status(Status.BAD_REQUEST).entity("service template does not exist").build();
    }
    ServiceTemplateResource serviceTemplateResource = new ServiceTemplateResource(serviceTemplateId);

    Collection<QName> artifactTemplates = new ArrayList<>();
    List<TNodeTemplate> allNestedNodeTemplates = BackendUtils
            .getAllNestedNodeTemplates(serviceTemplateResource.getServiceTemplate());
    for (TNodeTemplate nodeTemplate : allNestedNodeTemplates) {
        if (StringUtils.isEmpty(nodeTemplateId) || nodeTemplate.getId().equals(nodeTemplateId)) {
            Collection<QName> ats = BackendUtils
                    .getArtifactTemplatesOfReferencedDeploymentArtifacts(nodeTemplate);
            artifactTemplates.addAll(ats);
        }
    }

    // convert QName list to select2 data
    Select2DataWithOptGroups res = new Select2DataWithOptGroups();
    for (QName qName : artifactTemplates) {
        res.add(qName.getNamespaceURI(), qName.toString(), qName.getLocalPart());
    }
    return Response.ok().entity(res.asSortedSet()).build();
}

From source file:org.eclipse.winery.repository.resources.API.APIResource.java

/**
 * Implementation similar to getAllArtifactTemplatesOfContainedDeploymentArtifacts. Only
 * difference is "getArtifactTemplatesOfReferencedImplementationArtifacts" instead of
 * "getArtifactTemplatesOfReferencedDeploymentArtifacts".
 *///from   w w w. ja  va2 s.co  m
@GET
@Path("getallartifacttemplatesofcontainedimplementationartifacts")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllArtifactTemplatesOfContainedImplementationArtifacts(
        @QueryParam("servicetemplate") String serviceTemplateQNameString,
        @QueryParam("nodetemplateid") String nodeTemplateId) {
    if (StringUtils.isEmpty(serviceTemplateQNameString)) {
        return Response.status(Status.BAD_REQUEST).entity("servicetemplate has be given as query parameter")
                .build();
    }
    QName serviceTemplateQName = QName.valueOf(serviceTemplateQNameString);

    ServiceTemplateId serviceTemplateId = new ServiceTemplateId(serviceTemplateQName);
    if (!Repository.INSTANCE.exists(serviceTemplateId)) {
        return Response.status(Status.BAD_REQUEST).entity("service template does not exist").build();
    }
    ServiceTemplateResource serviceTemplateResource = new ServiceTemplateResource(serviceTemplateId);

    Collection<QName> artifactTemplates = new ArrayList<>();
    List<TNodeTemplate> allNestedNodeTemplates = BackendUtils
            .getAllNestedNodeTemplates(serviceTemplateResource.getServiceTemplate());
    for (TNodeTemplate nodeTemplate : allNestedNodeTemplates) {
        if (StringUtils.isEmpty(nodeTemplateId) || nodeTemplate.getId().equals(nodeTemplateId)) {
            Collection<QName> ats = BackendUtils
                    .getArtifactTemplatesOfReferencedImplementationArtifacts(nodeTemplate);
            artifactTemplates.addAll(ats);
        }
    }

    // convert QName list to select2 data
    Select2DataWithOptGroups res = new Select2DataWithOptGroups();
    for (QName qName : artifactTemplates) {
        res.add(qName.getNamespaceURI(), qName.toString(), qName.getLocalPart());
    }
    return Response.ok().entity(res.asSortedSet()).build();
}

From source file:org.eclipse.winery.repository.resources.artifacts.GenericArtifactsResource.java

/**
 * @return TImplementationArtifact | TDeploymentArtifact (XML) | URL of generated IA zip (in case of autoGenerateIA)
 *//* w  w  w .j a  va  2s . co m*/
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_XML)
@RestDoc(methodDescription = "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 onPost(
        @FormParam("artifactName") @RestDocParam(description = "This is the name of the implementation/deployment artifact. "
                + "Is <em>also</em>used as prefix of the name of the corresponding artifact template if no specific template is provided. "
                + "In contrast to CS01, we require a artifactName also for the implementationArtifact to be able to properly referencing it.") String artifactNameStr,

        @FormParam("artifactTemplate") @RestDocParam(description = "QName of the artifact Template - used by Winery Backend instead of artifactTemplateName + artifactTemplateNS") String artifactTemplate,

        @FormParam("artifactTemplateName") @RestDocParam(description = "if provided and autoCreateArtifactTemplate, a template of this id localname and artifactTemplateNS generated. "
                + "Winery always sends this string if auto creation is desired.") String artifactTemplateName,

        @FormParam("artifactTemplateNS") String artifactTemplateNS,

        @FormParam("autoCreateArtifactTemplate") @RestDocParam(description = "if empty, no, or false, no artifact template is created. "
                + "An artifact type has to be given in that case. "
                + "Furthermore, an artifact template name + artifact template namespace has to be provided. "
                + "Otherwise, the artifactNameStr is used as name for the artifact and a <em>new</em> artifact template is created having {@code <artifactNameString>Template} as name") String autoCreateArtifactTemplate,

        @FormParam("artifactType") @RestDocParam(description = "QName of the type, format: {namespace}localname. "
                + "Optional if artifactTemplateName + artifactTempalteNS is provided") String artifactTypeStr,

        @FormParam("artifactSpecificContent") @RestDocParam(description = "<em>XML</em> snippet that should be put inside the artifact XML in the TOSCA serialization. "
                + "This feature will be removed soon. "
                + "TODO: This only works if there is a single child element expected and not several elements. "
                + "Future versions of the Winery will support arbitrary content there.") String artifactSpecificContent,

        @FormParam("interfaceName") String interfaceNameStr,

        @FormParam("operationName") String operationNameStr,

        @FormParam("autoGenerateIA") @RestDocParam(description = "If not empty, the IA generator will be called") String autoGenerateIA,

        @FormParam("javapackage") @RestDocParam(description = "The Java package to use for IA generation") String javapackage,

        @Context UriInfo uriInfo) {
    // we assume that the parent ComponentInstance container exists

    // @formatter:on

    if (StringUtils.isEmpty(artifactNameStr)) {
        return Response.status(Status.BAD_REQUEST).entity("Empty artifactName").build();
    }
    if (StringUtils.isEmpty(artifactTypeStr)) {
        if (StringUtils.isEmpty(artifactTemplateName) || StringUtils.isEmpty(artifactTemplateNS)) {
            if (StringUtils.isEmpty(artifactTemplate)) {
                return Response.status(Status.BAD_REQUEST)
                        .entity("No artifact type given and no template given. Cannot guess artifact type")
                        .build();
            }
        }
    }

    if (!StringUtils.isEmpty(autoGenerateIA)) {
        if (StringUtils.isEmpty(javapackage)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("no java package name supplied for IA auto generation.").build();
        }
        if (StringUtils.isEmpty(interfaceNameStr)) {
            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(artifactTemplate)) {
        QName qname = QName.valueOf(artifactTemplate);
        artifactTemplateName = qname.getLocalPart();
        artifactTemplateNS = qname.getNamespaceURI();
    }

    Document doc = null;

    // check artifact specific content for validity
    // if invalid, abort and do not create anything
    if (!StringUtils.isEmpty(artifactSpecificContent)) {
        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            StringReader sr = new StringReader(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(autoCreateArtifactTemplate)
            || autoCreateArtifactTemplate.equalsIgnoreCase("no")
            || autoCreateArtifactTemplate.equalsIgnoreCase("false"));
    if (!doAutoCreateArtifactTemplate) {
        // no auto creation
        if (!StringUtils.isEmpty(artifactTemplateName) && !StringUtils.isEmpty(artifactTemplateNS)) {
            QName artifactTemplateQName = new QName(artifactTemplateNS, artifactTemplateName);
            artifactTemplateId = BackendUtils.getTOSCAcomponentId(ArtifactTemplateId.class,
                    artifactTemplateQName);
        }
        if (StringUtils.isEmpty(artifactTypeStr)) {
            // 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();
            }
            artifactTemplateResource = new ArtifactTemplateResource(artifactTemplateId);
            artifactTypeId = BackendUtils.getTOSCAcomponentId(ArtifactTypeId.class,
                    artifactTemplateResource.getType());
        } else {
            // artifactTypeStr is directly given, use that
            artifactTypeId = BackendUtils.getTOSCAcomponentId(ArtifactTypeId.class, artifactTypeStr);
        }
    } else {
        // do the artifact template auto creation magic

        if (StringUtils.isEmpty(artifactTypeStr)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity("Artifact template auto creation requested, but no artifact type supplied.")
                    .build();
        }

        // we assume that the type points to a valid artifact type
        artifactTypeId = BackendUtils.getTOSCAcomponentId(ArtifactTypeId.class, artifactTypeStr);

        if (StringUtils.isEmpty(artifactTemplateName) || StringUtils.isEmpty(artifactTemplateNS)) {
            // 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(artifactNameStr + "artifactTemplate", false));
        } else {
            QName artifactTemplateQName = new QName(artifactTemplateNS, artifactTemplateName);
            artifactTemplateId = new ArtifactTemplateId(artifactTemplateQName);
        }
        ResourceCreationResult creationResult = BackendUtils.create(artifactTemplateId);
        if (!creationResult.isSuccess()) {
            // something went wrong. skip
            return creationResult.getResponse();
        }

        // associate the type to the created artifact template
        artifactTemplateResource = new ArtifactTemplateResource(artifactTemplateId);
        // set the type. The resource is automatically persisted inside
        artifactTemplateResource.setType(artifactTypeStr);
    }

    // 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(artifactNameStr);
        a.setInterfaceName(interfaceNameStr);
        a.setOperationName(operationNameStr);
        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(artifactNameStr);
        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 = BackendUtils.persist(super.res);
    // TODO: check for error and in case one found return that

    if (StringUtils.isEmpty(autoGenerateIA)) {
        // no IA generation
        // we include an XML for the data table

        String implOrDeplArtifactXML = Utils.getXMLAsString(resultingArtifact);

        return Response.created(Utils.createURI(Util.URLencode(artifactNameStr))).entity(implOrDeplArtifactXML)
                .build();
    } else {
        // after everything was created, we fire up the artifact generation
        return this.generateImplementationArtifact(interfaceNameStr, javapackage, uriInfo, artifactTemplateId,
                artifactTemplateResource);
    }
}

From source file:org.eclipse.winery.repository.resources.entitytypes.nodetypes.reqandcapdefs.CapabilityDefinitionsResource.java

private TCapabilityDefinition buildDefinition(ReqCapDefinitionInfo info) {
    if (StringUtils.isEmpty(info.getName()) || StringUtils.isEmpty(info.getType())) {
        logger.debug("Name or Type has to be provided");
        return null;
    }/*from   ww  w . j a v a 2 s. c o  m*/

    int lbound = 1;
    if (!StringUtils.isEmpty(info.getLowerBound())) {
        try {
            lbound = Integer.parseInt(info.getLowerBound());
        } catch (NumberFormatException e) {
            logger.debug("Bad format of lowerbound: " + e.getMessage());
            return null;
        }
    }

    String ubound = "1";
    if (!StringUtils.isEmpty(info.getUpperBound())) {
        ubound = info.getUpperBound();
    }

    TCapabilityDefinition def = new TCapabilityDefinition();
    def.setLowerBound(lbound);
    def.setUpperBound(ubound);
    def.setName(info.getName());
    def.setCapabilityType(QName.valueOf(info.getType()));
    return def;
}

From source file:org.eclipse.winery.repository.resources.entitytypes.nodetypes.reqandcapdefs.RequirementDefinitionsResource.java

private TRequirementDefinition buildDefinition(ReqCapDefinitionInfo info) {
    if (StringUtils.isEmpty(info.getName()) || StringUtils.isEmpty(info.getType())) {
        logger.debug("Name or Type has to be provided");
        return null;
    }//from   w ww .  j  a  va2 s  .  c om

    int lbound = 1;
    if (!StringUtils.isEmpty(info.getLowerBound())) {
        try {
            lbound = Integer.parseInt(info.getLowerBound());
        } catch (NumberFormatException e) {
            logger.debug("Bad format of lowerbound: " + e.getMessage());
            return null;
        }
    }

    String ubound = "1";
    if (!StringUtils.isEmpty(info.getUpperBound())) {
        ubound = info.getUpperBound();
    }

    TRequirementDefinition def = new TRequirementDefinition();
    def.setLowerBound(lbound);
    def.setUpperBound(ubound);
    def.setName(info.getName());
    def.setRequirementType(QName.valueOf(info.getType()));
    return def;
}

From source file:org.eclipse.winery.repository.resources.entitytypes.nodetypes.reqandcapdefs.RequirementOrCapabilityDefinitionsResource.java

@POST
// As there is no supertype of TCapabilityType and TRequirementType containing the common attributes, we have to rely on unchecked casts
@SuppressWarnings("unchecked")
public Response onPost(@FormParam("name") String name, @FormParam("type") String type,
        @FormParam("lowerbound") String lowerBound, @FormParam("upperbound") String upperbound) {
    if (StringUtils.isEmpty(name)) {
        return Response.status(Status.BAD_REQUEST).entity("Name has to be provided").build();
    }/* w w  w. j a va  2 s.c o  m*/
    if (StringUtils.isEmpty(type)) {
        return Response.status(Status.BAD_REQUEST).entity("Type has to be provided").build();
    }

    int lbound = 1;
    if (!StringUtils.isEmpty(lowerBound)) {
        try {
            lbound = Integer.parseInt(lowerBound);
        } catch (NumberFormatException e) {
            return Response.status(Status.BAD_REQUEST).entity("Bad format of lowerbound: " + e.getMessage())
                    .build();
        }
    }

    String ubound = "1";
    if (!StringUtils.isEmpty(upperbound)) {
        ubound = upperbound;
    }

    // we also support replacement of existing requirements
    // therefore, we loop through the existing requirements
    int idx = -1;
    boolean found = false;
    for (ReqDefOrCapDef d : this.list) {
        idx++;
        if (this.getId(d).equals(name)) {
            found = true;
            break;
        }
    }

    QName typeQName = QName.valueOf(type);
    // Create object and put type in it
    ReqDefOrCapDef def;
    if (this instanceof CapabilityDefinitionsResource) {
        def = (ReqDefOrCapDef) new TCapabilityDefinition();
        ((TCapabilityDefinition) def).setCapabilityType(typeQName);
    } else {
        assert (this instanceof RequirementDefinitionsResource);
        def = (ReqDefOrCapDef) new TRequirementDefinition();
        ((TRequirementDefinition) def).setRequirementType(typeQName);
    }

    // copy all other data into object
    AbstractReqOrCapDefResource.invokeSetter(def, "setName", name);
    AbstractReqOrCapDefResource.invokeSetter(def, "setLowerBound", lbound);
    AbstractReqOrCapDefResource.invokeSetter(def, "setUpperBound", ubound);

    if (found) {
        // replace element
        this.list.set(idx, def);
    } else {
        // add new element
        this.list.add(def);
    }

    Response r = BackendUtils.persist(this.res);
    return r;
}

From source file:org.eclipse.winery.repository.resources.entitytypes.properties.PropertiesDefinitionResource.java

@POST
@RestDoc(methodDescription = "Updates/creates a property based on XSD element or XML schema.")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)//w  w  w. j a  v a 2 s .  com
public Response onPost(
        @FormParam("name") @RestDocParam(description = "Either xsdelement or xsdtype. 'name' comes from x-editable, which uses that as field name") String name,
        @FormParam("value") @RestDocParam(description = "The qname") String value) {
    // @formatter:on
    if (StringUtils.isEmpty(name)) {
        return Response.status(Status.BAD_REQUEST).entity("You have to provide a key/type or a name/value pair")
                .build();
    }
    if (StringUtils.isEmpty(value)) {
        return Response.status(Status.BAD_REQUEST)
                .entity("If a name is provided, a value has also to be provided").build();
    }

    // first of all, remove Winery's Properties definition (if it exists)
    ModelUtilities.removeWinerysPropertiesDefinition(this.getEntityType());

    QName qname = QName.valueOf(value);

    // replace old properties definition by new one
    PropertiesDefinition def = new PropertiesDefinition();
    if (name.equals("xsdtype")) {
        def.setType(qname);
    } else if (name.equals("xsdelement")) {
        def.setElement(qname);
    } else {
        return Response.status(Status.BAD_REQUEST).entity("Invalid name. Choose xsdelement or xsdtype").build();
    }
    this.getEntityType().setPropertiesDefinition(def);
    List<String> errors = new ArrayList<>();
    BackendUtils.deriveWPD(this.getEntityType(), errors);
    // currently the errors are just logged
    for (String error : errors) {
        PropertiesDefinitionResource.logger.debug(error);
    }
    return BackendUtils.persist(this.parentRes);

}

From source file:org.eclipse.winery.repository.resources.entitytypes.requirementtypes.RequiredCapabilityTypeResource.java

@PUT
@Consumes(MediaType.TEXT_PLAIN)/*from  w  w w .jav  a2s .c o m*/
public Response putRequiredCapabilityType(String type) {
    if (StringUtils.isEmpty(type)) {
        return Response.status(Status.BAD_REQUEST).entity("type must not be empty").build();
    }
    QName qname = QName.valueOf(type);
    CapabilityTypeId id = new CapabilityTypeId(qname);
    if (Repository.INSTANCE.exists(id)) {
        // everything allright. Store new reference
        this.getRequirementType().setRequiredCapabilityType(qname);
        return BackendUtils.persist(this.requirementTypeResource);
    } else {
        throw new NotFoundException("Given QName could not be resolved to an existing capability type");
    }
}