Example usage for javax.xml.namespace QName QName

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

Introduction

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

Prototype

public QName(String namespaceURI, String localPart, String prefix) 

Source Link

Document

QName constructor specifying the Namespace URI, local part and prefix.

If the Namespace URI is null, it is set to javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI .

Usage

From source file:com.autentia.xml.namespace.QNameBuilder.java

private QName discoverQNameAndCachesIt(Class<?> classType, String classTypeNameSuffix, String prefixSuffix,
        QNamesCache cache) {//  w w w .  jav  a  2s .c  o  m
    QName qName = cache.getQNameFor(classType);
    if (qName == null) {
        qName = discoverQNameFromJaxb(classType);

        final String localPart = (isNotBlank(qName.getLocalPart()) ? qName.getLocalPart()
                : discoverLocalPartFor(classType)) + classTypeNameSuffix;
        final String namespaceUri = isNotBlank(qName.getNamespaceURI()) ? qName.getNamespaceURI()
                : discoverNamespaceUriFor(classType, localPart);
        final String prefix = isNotBlank(qName.getPrefix()) ? qName.getPrefix()
                : discoverPrefixFor(classType, prefixSuffix);
        qName = new QName(namespaceUri, localPart, prefix);

        cache.putQNameFor(classType, qName);
    }
    return qName;
}

From source file:com.nesscomputing.jersey.wadl.NessWadlAnnotator.java

@Override
public Method createMethod(AbstractResource r, AbstractResourceMethod m) {
    Method method = delegate.createMethod(r, m);

    Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<>();

    for (Annotation a : r.getResourceClass().getAnnotations()) {
        Class<? extends Annotation> type = a.annotationType();
        if (type.getAnnotation(WadlAnnotation.class) != null) {
            annotations.put(type, a);/* www.  j ava  2s. com*/
        }
    }
    for (Annotation a : m.getMethod().getAnnotations()) {
        Class<? extends Annotation> type = a.annotationType();
        if (type.getAnnotation(WadlAnnotation.class) != null) {
            annotations.put(type, a);
        }
    }

    for (Annotation a : annotations.values()) {
        WadlAnnotation wadlAnnotation = checkNotNull(a.annotationType().getAnnotation(WadlAnnotation.class));
        Map<QName, String> attr = method.getOtherAttributes();
        String value = annotationStringValue(a);

        for (String xmlElement : wadlAnnotation.value()) {
            attr.put(new QName(NESSAPI_XML_NS, xmlElement, NESSAPI_XML_PREFIX), value);
        }
    }

    return method;
}

From source file:org.jasig.portlet.blackboardvcportlet.service.util.SASWebServiceTemplate.java

@Override
public Object marshalSendAndReceiveToSAS(final String soapAction, final Object requestPayload) {
    return marshalSendAndReceive(requestPayload, new WebServiceMessageCallback() {

        @Override//from  w w w.j a  v a  2 s. c  o m
        public void doWithMessage(WebServiceMessage webServiceMessage)
                throws IOException, TransformerException {
            if (webServiceMessage instanceof SaajSoapMessage) {
                final SaajSoapMessage casted = (SaajSoapMessage) webServiceMessage;
                casted.setSoapAction(soapAction);

                QName qName = new QName(elluminateMarshller.getContextPath(), "BasicAuth", "sas");
                try {
                    SOAPElement baHeader = casted.getSaajMessage().getSOAPHeader().addChildElement(qName);
                    baHeader.addChildElement(new QName("sas", "Name")).addTextNode(username);
                    baHeader.addChildElement(new QName("sas", "Password")).addTextNode(password);
                } catch (Exception e) {
                    logger.error("Error creating SOAPHeader: ", e);
                }
            }
        }
    });
}

From source file:org.wso2.carbon.connector.EWSIntegrationTest.java

@Test(enabled = true, groups = { "wso2.esb" }, description = "EWS test case")
public void testCreateItem() throws Exception {
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    // Sending Create Message Request
    String createItemProxyUrl = getProxyServiceURL("createItemOperation");
    RestResponse<OMElement> esbSoapResponse = sendXmlRestRequest(createItemProxyUrl, "POST",
            esbRequestHeadersMap, "CreateItem.xml");
    OMElement omElement = esbSoapResponse.getBody();
    OMElement createItemResponseMessageOmelement = omElement.getFirstElement().getFirstChildWithName(new QName(
            "http://schemas.microsoft.com/exchange/services/2006/messages", "CreateItemResponseMessage", "m"));
    String success = createItemResponseMessageOmelement.getAttributeValue(new QName("ResponseClass"));
    // Assert if Create Message got successes
    Assert.assertEquals(success, "Success");
    //Extract Message Id and change Key
    itemId = (String) xPathEvaluate(omElement, "string(//t:ItemId/@Id)", namespaceMap);
    changeKey = (String) xPathEvaluate(omElement, "string(//t:ItemId/@ChangeKey)", namespaceMap);
    Assert.assertNotNull(itemId);// w  w  w .  j a v  a  2 s .c  o m
    Assert.assertNotNull(changeKey);
    //Sending CreateAttachment Request
    String createAttachmentOperation = getProxyServiceURL("createAttachmentOperation");
    FileInputStream fileInputStream = new FileInputStream(
            getESBResourceLocation() + File.separator + "config" + File.separator + "restRequests"
                    + File.separator + "sampleRequest" + File.separator + "CreateAttachment.xml");
    OMElement createAttachmentSoapRequest = AXIOMUtil.stringToOM(IOUtils.toString(fileInputStream));
    OMElement parentItemID = createAttachmentSoapRequest.getFirstChildWithName(new QName("ParentItemId"));
    parentItemID.getFirstChildWithName(new QName("Id")).setText(itemId);
    parentItemID.getFirstChildWithName(new QName("ChangeKey")).setText(changeKey);
    HttpPost httpPost = new HttpPost(createAttachmentOperation);
    httpPost.setEntity(new StringEntity(createAttachmentSoapRequest.toString(),
            ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    HttpResponse response = defaultHttpClient.execute(httpPost);
    OMElement createAttachmentResponse = AXIOMUtil
            .stringToOM(IOUtils.toString(response.getEntity().getContent()));
    String createAttachmentStatus = createAttachmentResponse.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    String attachmentId = (String) xPathEvaluate(createAttachmentResponse, "string(//t:AttachmentId/@Id)",
            namespaceMap);
    //Checked for the attachment creation got Success
    Assert.assertEquals(createAttachmentStatus, "Success");
    //Sending Get AttachmentRequest
    String getAttachmentProxyUrl = getProxyServiceURL("getAttachment");
    String payload = "<GetAttachment><AttachmentId>" + attachmentId + "</AttachmentId></GetAttachment>";
    HttpPost getAttachmentPost = new HttpPost(getAttachmentProxyUrl);
    getAttachmentPost
            .setEntity(new StringEntity(payload, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    HttpResponse getAttachmentPostHttpResponse = defaultHttpClient.execute(getAttachmentPost);
    OMElement getAttachmentOm = AXIOMUtil
            .stringToOM(IOUtils.toString(getAttachmentPostHttpResponse.getEntity().getContent()));
    String GetAttachmentStatus = getAttachmentOm.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    //Check for Getting attachment Response
    Assert.assertEquals(GetAttachmentStatus, "Success");
}

From source file:org.javelin.sws.ext.bind.internal.model.AttributePattern.java

@Override
protected void replayNonNullString(String value, XMLEventWriter eventWriter, MarshallingContext context)
        throws XMLStreamException {
    if (!XMLConstants.NULL_NS_URI.equals(this.attributeName.getNamespaceURI())) {
        // we MUST create second namespace declaration if the current one has default ("") prefix, otherwise the attribute will have absent
        // namespace!
        // see: http://www.w3.org/TR/xml-names11/#defaulting - "The namespace name for an unprefixed attribute name always has no value."
        String prefix = this.safeRegisterNamespace(context, eventWriter, this.attributeName);
        if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
            Namespace namespace = this.safePrepareNamespace(
                    context, eventWriter, new QName(this.attributeName.getNamespaceURI(),
                            this.attributeName.getLocalPart(), context.newPrefix()),
                    NamespaceRegistration.IF_DEFAULT_PREFIX);
            prefix = namespace.getPrefix();
        }/*  w w w. ja  v  a  2s.  c o m*/
        eventWriter.add(XML_EVENTS_FACTORY.createAttribute(prefix, this.attributeName.getNamespaceURI(),
                this.attributeName.getLocalPart(), value));
    } else {
        // attribute is unqalified and has no namespace
        eventWriter.add(XML_EVENTS_FACTORY.createAttribute(this.attributeName.getLocalPart(), value));
    }
}

From source file:io.twipple.springframework.data.clusterpoint.mapping.BasicClusterpointPersistentEntity.java

@Override
@NotNull// w  w w .ja  va  2 s .co  m
public Object getTypeAlias() {
    if (qualifiedName == null) {
        String namespaceUri = buildXmlNamespace();
        String localName = Objects.toString(super.getTypeAlias(), null);
        if (localName == null) {
            localName = buildXmlLocalName();
        }
        String prefix = buildXmlPrefix();

        qualifiedName = new QName(namespaceUri, localName, prefix);
    }
    return qualifiedName;
}

From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeWebServiceCallBack.java

@Override
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
    actionCallback.doWithMessage(message);
    SoapMessage soap = (SoapMessage) message;
    QName rsv = new QName("http://schemas.microsoft.com/exchange/services/2006/types", "RequestServerVersion",
            "ns3");

    SoapHeaderElement version = soap.getEnvelope().getHeader().addHeaderElement(rsv);
    version.addAttribute(new QName("Version"), requestServerVersion);

    if (StringUtils.isNotBlank(impersonatedAccountId)) {
        // TODO create header using message construction not derived from String XML value
        StringSource headerSource = new StringSource(
                impersonationFirstPart + impersonatedAccountId + impersonationSecondPart);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(headerSource, soap.getEnvelope().getHeader().getResult());
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        message.writeTo(bout);/*from w  w w  . j  av  a 2  s  .  c o  m*/
        log.debug("Including impersonation header in SOAP message for account {}", impersonatedAccountId);
    }
}

From source file:gov.ornl.stucco.stix_extractors.MetasploitExtractor.java

private STIXPackage extract(String metasploitInfo) {
    List<CSVRecord> records;
    try {/*from  w  ww  .  j  av a  2  s .  c o  m*/
        records = getCSVRecordsList(HEADERS, metasploitInfo);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    if (records.isEmpty()) {
        return null;
    }

    CSVRecord record = records.get(0);
    int start;
    if (record.get(0).equals(ID)) {
        if (records.size() == 1) {
            return null;
        } else {
            start = 1;
        }
    } else {
        start = 0;
    }

    ExploitTargetsType ets = new ExploitTargetsType();
    TTPsType ttps = new TTPsType();

    for (int i = start; i < records.size(); i++) {
        try {
            record = records.get(i);

            /* exploit */
            ExploitType exploit = new ExploitType();
            BehaviorType behavior = new BehaviorType();
            boolean withExploit = false;

            if (!record.get(FULLNAME).isEmpty()) {
                exploit.withTitle(record.get(FULLNAME));
                withExploit = true;
            }

            if (!record.get(MTYPE).isEmpty()) {
                exploit.withId(new QName("gov.ornl.stucco",
                        record.get(MTYPE) + "-" + UUID.randomUUID().toString(), "stucco"));
                withExploit = true;

            }

            if (!record.get(NAME).isEmpty()) {
                exploit.withShortDescriptions(new StructuredTextType() //list
                        .withValue(record.get(NAME)));
                withExploit = true;
            }

            if (!record.get(DESCRIPTION).isEmpty()) {
                exploit.withDescriptions(new StructuredTextType() //list
                        .withValue(record.get(DESCRIPTION)));
                withExploit = true;
            }

            if (withExploit) {
                behavior.withExploits(new ExploitsType().withExploits(exploit));
            }

            /* vulnerability */
            List<RelatedExploitTargetType> relatedEt = new ArrayList<RelatedExploitTargetType>();
            Pattern pattern = Pattern.compile("CVE-\\d{4}-\\d{4,7}");
            Matcher matcher = pattern.matcher(record.get(REF_NAMES));

            while (matcher.find()) {
                ExploitTarget et = new ExploitTarget().withId(
                        new QName("gov.ornl.stucco", "vulnerability-" + UUID.randomUUID().toString(), "stucco"))
                        .withTitle("Vulnerability").withVulnerabilities(new VulnerabilityType() //list
                                .withCVEID(matcher.group()).withTitle(matcher.group())
                                .withDescriptions(new StructuredTextType() //list
                                        .withValue(matcher.group()))
                                .withSource("Metasploit"));
                ets.withExploitTargets(et);

                relatedEt.add(new RelatedExploitTargetType()
                        .withExploitTarget(new ExploitTarget().withIdref(et.getId()))
                        .withRelationship(new ControlledVocabularyStringType().withValue("exploit")));
            }

            //if malware exists, then packing it and adding references to vulnerabilities
            if (withExploit) {
                TTP ttp = initTTP("Exploit", "Metasploit").withBehavior(behavior);
                if (!relatedEt.isEmpty()) {
                    ttp.withExploitTargets(
                            new org.mitre.stix.ttp_1.ExploitTargetsType().withExploitTargets(relatedEt));
                }

                ttps.withTTPS(ttp);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    if (!ets.getExploitTargets().isEmpty()) {
        try {
            stixPackage = initStixPackage("Vulnerability and Malware Description", "Metasploit")
                    .withExploitTargets(ets);
        } catch (DatatypeConfigurationException e) {
            e.printStackTrace();
        }
    }
    if (!ttps.getTTPS().isEmpty()) {
        if (stixPackage == null) {
            try {
                stixPackage = initStixPackage("Vulnerability and Malware Description", "Metasploit")
                        .withTTPs(ttps);
            } catch (DatatypeConfigurationException e) {
                e.printStackTrace();
            }
        } else {
            stixPackage.withTTPs(ttps);
        }
    }

    return stixPackage;
}

From source file:whitelabel.cloud.wsclient.WebServiceAuthenticator.java

public void authenticateInClear(final SOAPMessage request, final String username, final String password)
        throws WsAuthenticationException {

    if (request == null) {
        LOG.error(" SoapMessage request not defined");
        throw new WsAuthenticationException("SOAP_REQUEST_NOT_DEFINED");
    }//from www . j ava  2 s. com
    if (username == null || password == null || username.trim().length() == 0
            || password.trim().length() == 0) {
        LOG.error("Username: " + username + " password: " + password + " - invalid parameters");
        throw new WsAuthenticationException("INVALID_PARAMETERS");
    }

    String nonceValue = generateNonceBase64(16);
    String createdValue = dfe.print(new Date());
    String userValue = username;
    String pwdValue = password;
    String pwdType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";

    QName securityQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security",
            "wsse");
    QName usernameTokenQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
            "UsernameToken", "wsse");
    QName usernameQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Username",
            "wsse");
    QName PasswordQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Password",
            "wsse");
    QName PasswordTypeQName = new QName("Type");
    QName nonceQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Nonce",
            "wsse");
    QName createdQName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Created",
            "wsu");

    try {
        SOAPElement securitySoap = request.getSOAPHeader().addChildElement(securityQName);
        SOAPElement usernameTokenSoap = securitySoap.addChildElement(usernameTokenQName);
        SOAPElement usernameSoap = usernameTokenSoap.addChildElement(usernameQName);
        usernameSoap.addTextNode(userValue);
        SOAPElement passwordSoap = usernameTokenSoap.addChildElement(PasswordQName);
        passwordSoap.addTextNode(pwdValue);
        passwordSoap.addAttribute(PasswordTypeQName, pwdType);
        SOAPElement nonceSoap = usernameTokenSoap.addChildElement(nonceQName);
        nonceSoap.addTextNode(nonceValue);
        SOAPElement creadedSoap = usernameTokenSoap.addChildElement(createdQName);
        creadedSoap.addTextNode(createdValue);
    } catch (SOAPException se) {
        LOG.error(se);
        throw new WsAuthenticationException("SOAPHEADER_CREATION", se);
    }
}

From source file:com.alfaariss.oa.util.saml2.binding.soap11.SOAP11Utils.java

/**
 * Construct and send a SOAP Fault.//from  ww  w . ja  v  a  2  s  .  com
 *
 * Constructs a SOAP Fault message and send it using the out transport of
 * the message context.
 * 
 * The followinf SOAP codes are send:
 * <dl>
 *  <dt>soap11:Client</dt>
 *      <dd>In case of a {@link RequestorEvent#REQUEST_INVALID}</dd>
 *  <dt>soap11:Server</dt>
 *      <dd>In case of other {@link RequestorEvent}s</dd>   
 * </dl>
 * 
 * @param messageContext The message context.
 * @param event The requestor event.
 * @throws OAException If sending fails due to internal error.
 */
public static void sendSOAPFault(
        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> messageContext,
        RequestorEvent event) throws OAException {
    //DD SOAP HTTP server MUST return a "500 Internal Server Error" response and include a SOAP fault [saml-bindings-2.0-os r372]
    try {
        /** XMLObjectBuilderFactory */
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        //Build SOAP Envelope and Body
        EnvelopeBuilder envBuilder = (EnvelopeBuilder) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
        Envelope envelope = envBuilder.buildObject();

        BodyBuilder bodyBuilder = (BodyBuilder) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
        Body body = bodyBuilder.buildObject();

        //Build fault
        FaultCodeBuilder faultCodeBuilder = (FaultCodeBuilder) builderFactory
                .getBuilder(FaultCode.DEFAULT_ELEMENT_NAME);
        FaultCode code = faultCodeBuilder.buildObject(FaultCode.DEFAULT_ELEMENT_NAME);
        FaultStringBuilder faultStringBuilder = (FaultStringBuilder) builderFactory
                .getBuilder(FaultString.DEFAULT_ELEMENT_NAME);
        FaultString faultString = faultStringBuilder.buildObject(FaultString.DEFAULT_ELEMENT_NAME);
        switch (event) {
        case REQUEST_INVALID: {
            code.setValue(new QName(SOAPConstants.SOAP11_NS, "Client", SOAPConstants.SOAP11_PREFIX));
            faultString.setValue(event.name());
            break;
        }
        default: {
            code.setValue(new QName(SOAPConstants.SOAP11_NS, "Server", SOAPConstants.SOAP11_PREFIX));
            faultString.setValue(RequestorEvent.INTERNAL_ERROR.name());
            break;
        }
        }
        FaultBuilder faultBuilder = (FaultBuilder) builderFactory.getBuilder(Fault.DEFAULT_ELEMENT_NAME);
        Fault fault = faultBuilder.buildObject();

        fault.setCode(code);

        fault.setMessage(faultString);

        body.getUnknownXMLObjects().add(fault);
        envelope.setBody(body);

        //Marshall message
        messageContext.setOutboundMessage(envelope);
        Marshaller m = Configuration.getMarshallerFactory().getMarshaller(Envelope.DEFAULT_ELEMENT_NAME);
        m.marshall(envelope);

        //Send SOAP Fault
        HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport();
        HTTPTransportUtils.addNoCacheHeaders(outTransport);
        HTTPTransportUtils.setUTF8Encoding(outTransport);
        HTTPTransportUtils.setContentType(outTransport, "text/xml");
        outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security");

        outTransport.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), SAML2Constants.CHARSET);
        XMLHelper.writeNode(envelope.getDOM(), out);
        out.flush();
    } catch (UnsupportedEncodingException e) {
        _logger.error(SAML2Constants.CHARSET + " encoding error", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (IOException e) {
        _logger.error("I/O error while sending SOAP Fault", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (MarshallingException e) {
        _logger.error("Marshalling error while sending SOAP Fault", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}