protected Object unmarshalFromInputStream( Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt) throws JAXBException { // Try to create the read before unmarshalling the stream XMLStreamReader xmlReader = null; try { if (is == null) { Reader reader = getStreamHandlerFromCurrentMessage(Reader.class); if (reader == null) { LOG.severe("No InputStream, Reader, or XMLStreamReader is available"); throw ExceptionUtils.toInternalServerErrorException(null, null); } xmlReader = StaxUtils.createXMLStreamReader(reader); } else { xmlReader = StaxUtils.createXMLStreamReader(is); } configureReaderRestrictions(xmlReader); return unmarshaller.unmarshal(xmlReader); } finally { try { StaxUtils.close(xmlReader); } catch (XMLStreamException e) { // Ignore } } }
private SoapMessage makeInvocation( Map<String, String> outProperties, List<String> xpaths, Map<String, String> inProperties) throws Exception { Document doc = readDocument("wsse-request-clean.xml"); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(); PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor(); SoapMessage msg = new SoapMessage(new MessageImpl()); Exchange ex = new ExchangeImpl(); ex.setInMessage(msg); SOAPMessage saajMsg = MessageFactory.newInstance().createMessage(); SOAPPart part = saajMsg.getSOAPPart(); part.setContent(new DOMSource(doc)); saajMsg.saveChanges(); msg.setContent(SOAPMessage.class, saajMsg); for (String key : outProperties.keySet()) { msg.put(key, outProperties.get(key)); } handler.handleMessage(msg); doc = part; for (String xpath : xpaths) { assertValid(xpath, doc); } byte[] docbytes = getMessageBytes(doc); XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); doc = StaxUtils.read(db, reader, false); WSS4JInInterceptor inHandler = new WSS4JInInterceptor(); SoapMessage inmsg = new SoapMessage(new MessageImpl()); ex.setInMessage(inmsg); inmsg.setContent(SOAPMessage.class, saajMsg); for (String key : inProperties.keySet()) { inHandler.setProperty(key, inProperties.get(key)); } inHandler.handleMessage(inmsg); return inmsg; }
public EndpointReference readEndpointReference(Source eprInfoset) { try { Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller(); return (EndpointReference) unmarshaller.unmarshal(StaxUtils.createXMLStreamReader(eprInfoset)); } catch (JAXBException e) { throw new WebServiceException( new Message("ERROR_UNMARSHAL_ENDPOINTREFERENCE", LOG).toString(), e); } }
@Override protected Object unmarshalFromInputStream( Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt) throws JAXBException { try { Templates t = createTemplates(getInTemplates(anns, mt), inParamsMap, inProperties); if (t == null && supportJaxbOnly) { return super.unmarshalFromInputStream(unmarshaller, is, anns, mt); } if (unmarshaller.getClass().getName().contains("eclipse")) { // eclipse MOXy doesn't work properly with the XMLFilter/Reader thing // so we need to bounce through a DOM Source reader = new StaxSource(StaxUtils.createXMLStreamReader(is)); DOMResult dom = new DOMResult(); t.newTransformer().transform(reader, dom); return unmarshaller.unmarshal(dom.getNode()); } XMLFilter filter = null; try { filter = factory.newXMLFilter(t); } catch (TransformerConfigurationException ex) { TemplatesImpl ti = (TemplatesImpl) t; filter = factory.newXMLFilter(ti.getTemplates()); trySettingProperties(filter, ti); } XMLReader reader = new StaxSource(StaxUtils.createXMLStreamReader(is)); filter.setParent(reader); SAXSource source = new SAXSource(); source.setXMLReader(filter); if (systemId != null) { source.setSystemId(systemId); } return unmarshaller.unmarshal(source); } catch (TransformerException ex) { LOG.warning("Transformation exception : " + ex.getMessage()); throw ExceptionUtils.toInternalServerErrorException(ex, null); } }
private XMLStreamReader createXMLStreamReaderFromSOAPMessage(SOAPMessage soapMessage) { // responseMsg.setContent(SOAPMessage.class, soapMessage); XMLStreamReader xmlReader = null; try { DOMSource bodySource = new DOMSource(soapMessage.getSOAPPart().getEnvelope().getBody()); xmlReader = StaxUtils.createXMLStreamReader(bodySource); xmlReader.nextTag(); xmlReader.nextTag(); // move past body tag } catch (SOAPException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } return xmlReader; }
/** * Parses the SecurityToken by wrapping within an AssertionWrapper. * * @param securityToken SecurityToken */ private void parseToken(SecurityToken securityToken) { XMLStreamReader xmlStreamReader = StaxUtils.createXMLStreamReader(securityToken.getToken()); try { AttrStatement attributeStatement = null; AuthenticationStatement authenticationStatement = null; Attr attribute = null; int attrs = 0; while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: { String localName = xmlStreamReader.getLocalName(); switch (localName) { case NameID.DEFAULT_ELEMENT_LOCAL_NAME: name = xmlStreamReader.getElementText(); for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) { if (xmlStreamReader .getAttributeLocalName(i) .equals(NameID.FORMAT_ATTRIB_NAME)) { nameIDFormat = xmlStreamReader.getAttributeValue(i); break; } } break; case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME: attributeStatement = new AttrStatement(); attributeStatements.add(attributeStatement); break; case AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME: authenticationStatement = new AuthenticationStatement(); authenticationStatements.add(authenticationStatement); attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME.equals(name)) { authenticationStatement.setAuthnInstant(DateTime.parse(value)); } } break; case AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME: if (authenticationStatement != null) { String classValue = xmlStreamReader.getText(); classValue = classValue.trim(); AuthenticationContextClassRef authenticationContextClassRef = new AuthenticationContextClassRef(); authenticationContextClassRef.setAuthnContextClassRef(classValue); AuthenticationContext authenticationContext = new AuthenticationContext(); authenticationContext.setAuthnContextClassRef(authenticationContextClassRef); authenticationStatement.setAuthnContext(authenticationContext); } break; case Attribute.DEFAULT_ELEMENT_LOCAL_NAME: attribute = new Attr(); if (attributeStatement != null) { attributeStatement.addAttribute(attribute); } attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (Attribute.NAME_ATTTRIB_NAME.equals(name)) { attribute.setName(value); } else if (Attribute.NAME_FORMAT_ATTRIB_NAME.equals(name)) { attribute.setNameFormat(value); } } break; case AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME: XSString xsString = new XMLString(); xsString.setValue(xmlStreamReader.getElementText()); if (attribute != null) { attribute.addAttributeValue(xsString); } break; case Issuer.DEFAULT_ELEMENT_LOCAL_NAME: issuer = xmlStreamReader.getElementText(); break; case Conditions.DEFAULT_ELEMENT_LOCAL_NAME: attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (Conditions.NOT_BEFORE_ATTRIB_NAME.equals(name)) { notBefore = DatatypeConverter.parseDateTime(value).getTime(); } else if (Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME.equals(name)) { notOnOrAfter = DatatypeConverter.parseDateTime(value).getTime(); } } break; } break; } case XMLStreamConstants.END_ELEMENT: { String localName = xmlStreamReader.getLocalName(); switch (localName) { case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME: attributeStatement = null; break; case Attribute.DEFAULT_ELEMENT_LOCAL_NAME: attribute = null; break; } break; } } } } catch (XMLStreamException e) { LOGGER.error("Unable to parse security token.", e); } finally { try { xmlStreamReader.close(); } catch (XMLStreamException ignore) { // ignore } } }
private void doResend(SoapMessage message) { try { // initialize copied interceptor chain for message PhaseInterceptorChain retransmitChain = manager.getRetransmitChain(message); ProtocolVariation protocol = RMContextUtils.getProtocolVariation(message); Endpoint endpoint = manager.getReliableEndpoint(message).getEndpoint(protocol); PhaseChainCache cache = new PhaseChainCache(); boolean after = true; if (retransmitChain == null) { // no saved retransmit chain, so construct one from scratch (won't work for WS-Security on // server, so // need to fix) retransmitChain = buildRetransmitChain(endpoint, cache); after = false; } message.setInterceptorChain(retransmitChain); // clear flag for SOAP out interceptor so envelope will be written message.remove(SoapOutInterceptor.WROTE_ENVELOPE_START); // discard all saved content Set<Class<?>> formats = message.getContentFormats(); List<CachedOutputStreamCallback> callbacks = null; for (Class<?> clas : formats) { Object content = message.getContent(clas); if (content != null) { LOG.info( "Removing " + clas.getName() + " content of actual type " + content.getClass().getName()); message.removeContent(clas); if (clas == OutputStream.class && content instanceof WriteOnCloseOutputStream) { callbacks = ((WriteOnCloseOutputStream) content).getCallbacks(); } } } // read SOAP headers from saved input stream RewindableInputStream is = (RewindableInputStream) message.get(RMMessageConstants.SAVED_CONTENT); is.rewind(); XMLStreamReader reader = StaxUtils.createXMLStreamReader(is, "UTF-8"); message.getHeaders().clear(); if (reader.getEventType() != XMLStreamConstants.START_ELEMENT && reader.nextTag() != XMLStreamConstants.START_ELEMENT) { throw new IllegalStateException("No document found"); } readHeaders(reader, message); int event; while ((event = reader.nextTag()) != XMLStreamConstants.START_ELEMENT) { if (event == XMLStreamConstants.END_ELEMENT) { throw new IllegalStateException("No body content present"); } } // set message addressing properties AddressingProperties maps = new MAPCodec().unmarshalMAPs(message); RMContextUtils.storeMAPs(maps, message, true, MessageUtils.isRequestor(message)); AttributedURIType to = null; if (null != maps) { to = maps.getTo(); } if (null == to) { LOG.log(Level.SEVERE, "NO_ADDRESS_FOR_RESEND_MSG"); return; } if (RMUtils.getAddressingConstants().getAnonymousURI().equals(to.getValue())) { LOG.log(Level.FINE, "Cannot resend to anonymous target"); return; } // initialize conduit for new message Conduit c = message.getExchange().getConduit(message); if (c == null) { c = buildConduit(message, endpoint, to); } c.prepare(message); // replace standard message marshaling with copy from saved stream ListIterator<Interceptor<? extends Message>> iterator = retransmitChain.getIterator(); while (iterator.hasNext()) { Interceptor<? extends Message> incept = iterator.next(); // remove JAX-WS interceptors which handle message modes and such if (incept.getClass().getName().startsWith("org.apache.cxf.jaxws.interceptors")) { retransmitChain.remove(incept); } else if (incept instanceof PhaseInterceptor && (((PhaseInterceptor<?>) incept).getPhase() == Phase.MARSHAL)) { // remove any interceptors from the marshal phase retransmitChain.remove(incept); } } retransmitChain.add(new CopyOutInterceptor(reader)); // restore callbacks on output stream if (callbacks != null) { OutputStream os = message.getContent(OutputStream.class); if (os != null) { WriteOnCloseOutputStream woc; if (os instanceof WriteOnCloseOutputStream) { woc = (WriteOnCloseOutputStream) os; } else { woc = new WriteOnCloseOutputStream(os); message.setContent(OutputStream.class, woc); } for (CachedOutputStreamCallback cb : callbacks) { woc.registerCallback(cb); } } } // send the message message.put(RMMessageConstants.RM_RETRANSMISSION, Boolean.TRUE); if (after) { retransmitChain.doInterceptStartingAfter(message, RMCaptureOutInterceptor.class.getName()); } else { retransmitChain.doIntercept(message); } if (LOG.isLoggable(Level.INFO)) { RMProperties rmps = RMContextUtils.retrieveRMProperties(message, true); SequenceType seq = rmps.getSequence(); LOG.log( Level.INFO, "Retransmitted message " + seq.getMessageNumber() + " in sequence " + seq.getIdentifier().getValue()); rmps = new RMProperties(); } } catch (Exception ex) { LOG.log(Level.SEVERE, "RESEND_FAILED_MSG", ex); } }
@Test public void testCustomProcessorObject() throws Exception { Document doc = readDocument("wsse-request-clean.xml"); WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(); PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor(); SoapMessage msg = new SoapMessage(new MessageImpl()); Exchange ex = new ExchangeImpl(); ex.setInMessage(msg); SOAPMessage saajMsg = MessageFactory.newInstance().createMessage(); SOAPPart part = saajMsg.getSOAPPart(); part.setContent(new DOMSource(doc)); saajMsg.saveChanges(); msg.setContent(SOAPMessage.class, saajMsg); msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE); msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties"); msg.put(WSHandlerConstants.USER, "myalias"); msg.put("password", "myAliasPassword"); handler.handleMessage(msg); doc = part; assertValid("//wsse:Security", doc); assertValid("//wsse:Security/ds:Signature", doc); byte[] docbytes = getMessageBytes(doc); XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); doc = StaxUtils.read(db, reader, false); final Map<String, Object> properties = new HashMap<String, Object>(); final Map<QName, Object> customMap = new HashMap<QName, Object>(); customMap.put(new QName(WSConstants.SIG_NS, WSConstants.SIG_LN), CustomProcessor.class); properties.put(WSS4JInInterceptor.PROCESSOR_MAP, customMap); WSS4JInInterceptor inHandler = new WSS4JInInterceptor(properties); SoapMessage inmsg = new SoapMessage(new MessageImpl()); ex.setInMessage(inmsg); inmsg.setContent(SOAPMessage.class, saajMsg); inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE); inHandler.handleMessage(inmsg); List<WSHandlerResult> results = getResults(inmsg); assertTrue(results != null && results.size() == 1); List<WSSecurityEngineResult> signatureResults = results.get(0).getActionResults().get(WSConstants.SIGN); assertTrue(signatureResults.size() == 1); Object obj = signatureResults.get(0).get("foo"); assertNotNull(obj); assertEquals(obj.getClass().getName(), CustomProcessor.class.getName()); }