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:be.agiv.security.handler.WSAddressingHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException {
    LOG.debug("adding WS-Addressing headers");
    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
    SOAPHeader header = envelope.getHeader();
    if (null == header) {
        header = envelope.addHeader();//from   w  w  w  .j a  v a2 s . co  m
    }

    String wsuPrefix = null;
    String wsAddrPrefix = null;
    Iterator namespacePrefixesIter = envelope.getNamespacePrefixes();
    while (namespacePrefixesIter.hasNext()) {
        String namespacePrefix = (String) namespacePrefixesIter.next();
        String namespace = envelope.getNamespaceURI(namespacePrefix);
        if (WSConstants.WS_ADDR_NAMESPACE.equals(namespace)) {
            wsAddrPrefix = namespacePrefix;
        } else if (WSConstants.WS_SECURITY_UTILITY_NAMESPACE.equals(namespace)) {
            wsuPrefix = namespacePrefix;
        }
    }
    if (null == wsAddrPrefix) {
        wsAddrPrefix = getUniquePrefix("a", envelope);
        envelope.addNamespaceDeclaration(wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE);
    }
    if (null == wsuPrefix) {
        /*
         * Using "wsu" is very important for the IP-STS X509 credential.
         * Apparently the STS refuses when the namespace prefix of the
         * wsu:Id on the WS-Addressing To element is different from the
         * wsu:Id prefix on the WS-Security timestamp.
         */
        wsuPrefix = "wsu";
        envelope.addNamespaceDeclaration(wsuPrefix, WSConstants.WS_SECURITY_UTILITY_NAMESPACE);
    }

    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPHeaderElement actionHeaderElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "Action", wsAddrPrefix));
    actionHeaderElement.setMustUnderstand(true);
    actionHeaderElement.addTextNode(this.action);

    SOAPHeaderElement messageIdElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "MessageID", wsAddrPrefix));
    String messageId = "urn:uuid:" + UUID.randomUUID().toString();
    context.put(MESSAGE_ID_CONTEXT_ATTRIBUTE, messageId);
    messageIdElement.addTextNode(messageId);

    SOAPHeaderElement replyToElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "ReplyTo", wsAddrPrefix));
    SOAPElement addressElement = factory.createElement("Address", wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE);
    addressElement.addTextNode("http://www.w3.org/2005/08/addressing/anonymous");
    replyToElement.addChildElement(addressElement);

    SOAPHeaderElement toElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "To", wsAddrPrefix));
    toElement.setMustUnderstand(true);

    toElement.addTextNode(this.to);

    String toIdentifier = "to-id-" + UUID.randomUUID().toString();
    toElement.addAttribute(new QName(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", wsuPrefix), toIdentifier);
    try {
        toElement.setIdAttributeNS(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", true);
    } catch (UnsupportedOperationException e) {
        // Axis2 has missing implementation of setIdAttributeNS
        LOG.error("error setting Id attribute: " + e.getMessage());
    }
    context.put(TO_ID_CONTEXT_ATTRIBUTE, toIdentifier);
}

From source file:org.gofleet.openLS.monav.MoNaVConnector.java

/**
 * Route plan using monav daemon. Only geometry.
 * //from  w  ww .j a v a 2 s .c  om
 * @param param
 * @return
 * @throws IOException
 * @throws ParseException
 * @throws JAXBException
 * @throws InterruptedException
 */
@Override
public DetermineRouteResponseType routePlan(DetermineRouteRequestType param, int maxResponses) {
    DetermineRouteResponseType res = new DetermineRouteResponseType();
    Double cost = null;
    String cmd = "/opt/monav/bin/daemon-test /var/www/monav/routing_yes/";

    RouteGeometryType routeGeometry = new RouteGeometryType();

    WayPointListType wayPointList = param.getRoutePlan().getWayPointList();

    Point point = GeoUtil.getPoint(wayPointList.getStartPoint(), null);
    cmd += " " + point.getY() + " " + point.getX();

    for (WayPointType wayPoint : wayPointList.getViaPoint()) {
        point = GeoUtil.getPoint(wayPoint, null);
        cmd += " " + point.getY() + " " + point.getX();
    }

    point = GeoUtil.getPoint(wayPointList.getEndPoint(), null);
    cmd += " " + point.getY() + " " + point.getX();

    LOG.debug(cmd);

    Process p;
    try {
        p = Runtime.getRuntime().exec(cmd);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    LineStringType lst = new LineStringType();

    List<JAXBElement<?>> list = new LinkedList<JAXBElement<?>>();

    String l;
    try {
        l = br.readLine();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    while (l != null) {
        LOG.info(l);
        try {
            if (cost == null && l.indexOf("distance:") >= 0)
                cost = -1d;// TODO

            Double x = Double.parseDouble(l.substring(0, l.indexOf(" ")));
            Double y = Double.parseDouble(l.substring(1 + l.indexOf(" ")));

            DirectPositionListType e = new DirectPositionListType();
            e.getValue().add(y);
            e.getValue().add(x);

            JAXBElement<DirectPositionListType> elem = new JAXBElement<DirectPositionListType>(
                    new QName("http://www.opengis.net/gml", "pos", "gml"), DirectPositionListType.class, e);

            list.add(elem);

        } catch (Throwable t) {
            // LOG.error(t);
        }

        try {
            l = br.readLine();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    try {

        lst.setPosOrPointPropertyOrPointRep(list);
        routeGeometry.setLineString(lst);
        res.setRouteGeometry(routeGeometry);
        res.setRouteHandle(new RouteHandleType());
        res.setRouteInstructionsList(new RouteInstructionsListType());
        res.setRouteMap(new LinkedList<RouteMapType>());
        res.setRouteSummary(new RouteSummaryType());
    } catch (Throwable t) {
        LOG.error("Error generating route response: " + t, t);
    }
    return res;
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {/*from   w w  w  .  j ava  2  s. c  om*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:com.liferay.wsrp.proxy.TypeConvertorUtil.java

private static void _convert(int sourceVersion, String sourcePackage, Object sourceClass, Object sourceChild,
        String sourceChildName, Object destination) throws Exception {

    Class<?> sourceChildClass = sourceChild.getClass();

    if (sourceChildClass == NavigationalContext.class) {
        sourceChildName = "navigationalState";

        NavigationalContext navigationalContext = (NavigationalContext) sourceChild;

        sourceChild = navigationalContext.getOpaqueValue();
    } else if (sourceChildClass == SessionParams.class) {
        sourceChildName = "sessionID";

        SessionParams sessionParams = (SessionParams) sourceChild;

        sourceChild = sessionParams.getSessionID();
    }/*ww  w .j  ava 2s.  c  o m*/

    if (sourceChild == null) {
        return;
    }

    sourceChildClass = sourceChild.getClass();

    Object destinationChild = null;

    if (sourceChildClass.isArray()) {
        destinationChild = convert(sourceChild, sourceVersion);
    } else {
        destinationChild = sourceChild;

        sourceChildClass = sourceChild.getClass();

        if (sourceChildClass.getName().contains(sourcePackage)) {
            destinationChild = convert(sourceChild, sourceVersion);
        }
    }

    String destinationChildName = sourceChildName;

    if (sourceChildName.equals("itemBinary")) {
        destinationChildName = "markupBinary";
    } else if (sourceChildName.equals("itemString")) {
        destinationChildName = "markupString";
    } else if (sourceChildName.equals("markupBinary")) {
        destinationChildName = "itemBinary";
    } else if (sourceChildName.equals("markupString")) {
        destinationChildName = "itemString";
    } else if (sourceChildName.equals("name") && (sourceClass == Property.class)) {

        QName qName = (QName) destinationChild;

        destinationChild = qName.getLocalPart();
    } else if (sourceChildName.equals("name") && (sourceClass == PropertyDescription.class)) {

        String name = (String) destinationChild;

        destinationChild = new QName("namespace", name, "prefix");
    } else if (sourceChildName.equals("navigationalState") && (sourceClass == MarkupParams.class)) {

        String navigationalState = (String) sourceChild;

        NavigationalContext navigationalContext = new NavigationalContext();

        navigationalContext.setOpaqueValue(navigationalState);

        destinationChild = navigationalContext;

        destinationChildName = "navigationalContext";
    } else if (sourceChildName.equals("requiresRewriting")) {
        destinationChildName = "requiresUrlRewriting";
    } else if (sourceChildName.equals("requiresUrlRewriting")) {
        destinationChildName = "requiresRewriting";
    } else if (sourceChildName.equals("sessionID") && (sourceClass == RuntimeContext.class)) {

        String sessionID = (String) sourceChild;

        SessionParams sessionParams = new SessionParams();

        sessionParams.setSessionID(sessionID);

        destinationChild = sessionParams;

        destinationChildName = "sessionParams";
    }

    try {
        PropertyUtils.setProperty(destination, destinationChildName, destinationChild);
    } catch (NoSuchMethodException nsme) {
        if (_log.isWarnEnabled()) {
            _log.warn(nsme, nsme);
        }
    }
}

From source file:org.drools.server.CxfSoapClientServerGridTest.java

private SOAPMessage createMessageForKsession(String ksessionName) throws SOAPException {

    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
    QName payloadName = new QName("http://soap.jax.drools.org", "execute", "ns1");

    body.addBodyElement(payloadName);//from w ww . ja va 2 s .  co  m
    String add = "";
    String packages = "org.test";
    if (ksessionName.equals("ksession2")) {
        add = "2";
        packages = "org.grid.test";
    }
    String cmd = "";
    cmd += "<batch-execution lookup=\"" + ksessionName + "\">\n";
    cmd += "  <insert out-identifier=\"message\">\n";
    cmd += "      <" + packages + ".Message" + add + ">\n";
    cmd += "         <text>Helllo World" + ksessionName + "</text>\n";
    cmd += "      </" + packages + ".Message" + add + ">\n";
    cmd += "   </insert>\n";
    cmd += "   <fire-all-rules/>\n";
    cmd += "</batch-execution>\n";

    body.addTextNode(cmd);
    OutputStream os = new ByteArrayOutputStream();
    try {
        soapMessage.writeTo(os);
    } catch (IOException ex) {
        Logger.getLogger(CxfSoapClientServerGridTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    //System.out.println("SOAP = "+os.toString());
    return soapMessage;

}

From source file:com.github.sardine.FunctionalSardineTest.java

@Test
@Ignore//  w  w  w.  j  a  v  a  2s . co  m
public void testSetAcl() throws IOException {
    final String url = String.format("http://demo.sabredav.org/public/folder-%s/",
            UUID.randomUUID().toString());
    Sardine sardine = SardineFactory.begin("testuser", "test");
    sardine.createDirectory(url);
    List<DavAce> aces = new ArrayList<DavAce>();
    sardine.setAcl(url, aces);
    DavAcl acls = sardine.getAcl(url);
    for (DavAce davace : acls.getAces()) {
        if (davace.getInherited() == null)
            fail("We have cleared all ACEs, should not have anymore non inherited ACEs");
    }
    aces.clear();
    DavAce ace = new DavAce(new DavPrincipal(PrincipalType.HREF, "/users/someone", null));
    ace.getGranted().add("read");
    aces.add(ace);
    ace = new DavAce(new DavPrincipal(PrincipalType.PROPERTY, new QName("DAV:", "owner", "somespace"), null));
    ace.getGranted().add("read");
    aces.add(ace);
    sardine.setAcl(url, aces);
    int count = 0;
    for (DavAce davace : sardine.getAcl(url).getAces()) {
        if (davace.getInherited() == null) {
            count++;
        }
    }
    sardine.delete(url);
    assertEquals("After setting two ACL, should find them back", 2, count);
}

From source file:com.netflix.ice.login.saml.Saml.java

public LoginResponse processLogin(HttpServletRequest request) throws LoginMethodException {
    IceSession iceSession = new IceSession(request.getSession());
    iceSession.voidSession(); //a second login request voids anything previous
    logger.info("Saml::processLogin");
    LoginResponse lr = new LoginResponse();
    String assertion = (String) request.getParameter("SAMLResponse");
    if (assertion == null) {
        lr.redirectTo = config.singleSignOnUrl;
        return lr;
    }//  w w w .j ava  2s.  c  o  m
    logger.trace("Received SAML Assertion: " + assertion);
    try {
        // 1.1 2.0 schemas
        Schema schema = SAMLSchemaBuilder.getSAML11Schema();

        //get parser pool manager
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        parserPoolManager.setSchema(schema);

        String data = new String(Base64.decode(assertion));
        logger.info("Decoded SAML Assertion: " + data);

        StringReader reader = new StringReader(data);
        Document document = parserPoolManager.parse(reader);
        Element documentRoot = document.getDocumentElement();

        QName qName = new QName(documentRoot.getNamespaceURI(), documentRoot.getLocalName(),
                documentRoot.getPrefix());

        //get an unmarshaller
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(documentRoot);

        //unmarshall using the document root element
        XMLObject xmlObj = unmarshaller.unmarshall(documentRoot);
        Response response = (Response) xmlObj;
        for (Assertion myAssertion : response.getAssertions()) {
            if (!myAssertion.isSigned()) {
                logger.error("SAML Assertion not signed");
                throw new LoginMethodException("SAML Assertions must be signed by a trusted provider");
            }

            Signature assertionSignature = myAssertion.getSignature();
            SAMLSignatureProfileValidator profVal = new SAMLSignatureProfileValidator();

            logger.info("Validating SAML Assertion");
            // will throw a ValidationException 
            profVal.validate(assertionSignature);

            //Credential signCred = assertionSignature.getSigningCredential();
            boolean goodSignature = false;
            for (Certificate trustedCert : trustedSigningCerts) {
                BasicCredential cred = new BasicCredential();
                cred.setPublicKey(trustedCert.getPublicKey());
                SignatureValidator validator = new SignatureValidator(cred);
                try {
                    validator.validate(assertionSignature);
                } catch (ValidationException ve) {
                    /* Not a good key! */
                    logger.debug("Not signed by " + trustedCert.toString());
                    continue;
                }
                logger.info("Assertion trusted from " + trustedCert.toString());
                processAssertion(iceSession, myAssertion, lr);
                goodSignature = true;
                break;
            }

            if (goodSignature) {
                lr.loginSuccess = true;
            }

        }
    } catch (org.xml.sax.SAXException saxe) {
        logger.error(saxe.toString());
    } catch (org.opensaml.xml.parse.XMLParserException xmlpe) {
        logger.error(xmlpe.toString());
    } catch (org.opensaml.xml.io.UnmarshallingException uee) {
        logger.error(uee.toString());
    } catch (org.opensaml.xml.validation.ValidationException ve) {
        throw new LoginMethodException("SAML Assertion Signature was not usable: " + ve.toString());
    }
    return lr;
}

From source file:com.onespatial.jrc.tns.oml_to_rif.fixture.DomBasedUnitTest.java

/**
 * @param rifDocument/* ww w.  jav a2 s . co m*/
 *            {@link org.w3._2007.rif.Document}
 * @return {@link Document}
 * @throws JAXBException
 *             if any errors occurred trying to marshall the RIF content to
 *             an DOM document
 * @throws ParserConfigurationException
 */
protected org.w3c.dom.Document getDomFromRif(org.w3._2007.rif.Document rifDocument) throws JAXBException {
    org.w3c.dom.Document domDocument = builder.newDocument();
    JAXBContext jc = JAXBContext.newInstance("org.w3._2007.rif", getClass().getClassLoader()); //$NON-NLS-1$
    jc.createMarshaller()
            .marshal(new JAXBElement<org.w3._2007.rif.Document>(new QName("http://www.w3.org/2007/rif#", //$NON-NLS-1$
                    "Document", "rif"), org.w3._2007.rif.Document.class, rifDocument), //$NON-NLS-1$ //$NON-NLS-2$
                    domDocument);
    return domDocument;
}

From source file:com.nortal.jroad.wsdl.XTeeSoapProvider.java

@Override
protected void populatePort(Definition definition, Port port) throws WSDLException {
    super.populatePort(definition, port);
    ExtensionRegistry extensionRegistry = definition.getExtensionRegistry();
    extensionRegistry.mapExtensionTypes(Port.class,
            new QName(XTeeWsdlDefinition.XROAD_NAMESPACE, "address", XTeeWsdlDefinition.XROAD_PREFIX),
            UnknownExtensibilityElement.class);
    UnknownExtensibilityElement element = (UnknownExtensibilityElement) extensionRegistry.createExtension(
            Port.class,
            new QName(XTeeWsdlDefinition.XROAD_NAMESPACE, "address", XTeeWsdlDefinition.XROAD_NAMESPACE));
    Document doc;/*from  ww  w. ja v  a  2s.  co  m*/
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Element xRoadAddr = doc.createElementNS(XTeeWsdlDefinition.XROAD_NAMESPACE, "address");
    xRoadAddr.setPrefix(XTeeWsdlDefinition.XROAD_PREFIX);
    xRoadAddr.setAttribute("producer", xRoadDatabase);
    element.setElement(xRoadAddr);
    port.addExtensibilityElement(element);
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static JAXBElement<Object> createElement(String key, String value) {
    return new JAXBElement(new QName("http://www.yale.edu/tp/cas", key, "cas"), String.class,
            value == null ? "" : value);
}