protected void setContexts( Message message, Exchange exchange, Map<String, Object> context, boolean proxy) { Map<String, Object> reqContext = null; Map<String, Object> resContext = null; if (context == null) { context = new HashMap<String, Object>(); } reqContext = CastUtils.cast((Map<?, ?>) context.get(REQUEST_CONTEXT)); resContext = CastUtils.cast((Map<?, ?>) context.get(RESPONSE_CONTEXT)); if (reqContext == null) { reqContext = new HashMap<String, Object>(cfg.getRequestContext()); context.put(REQUEST_CONTEXT, reqContext); } reqContext.put(Message.PROTOCOL_HEADERS, message.get(Message.PROTOCOL_HEADERS)); reqContext.put(Message.REQUEST_URI, message.get(Message.REQUEST_URI)); reqContext.put(Message.ENDPOINT_ADDRESS, message.get(Message.ENDPOINT_ADDRESS)); reqContext.put(PROXY_PROPERTY, proxy); if (resContext == null) { resContext = new HashMap<String, Object>(); context.put(RESPONSE_CONTEXT, resContext); } message.put(Message.INVOCATION_CONTEXT, context); message.putAll(reqContext); exchange.putAll(reqContext); }
protected void updateDefinition( Definition def, Map<String, Definition> done, Map<String, SchemaReference> doneSchemas, String base, EndpointInfo ei) { OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus); Collection<List<?>> imports = CastUtils.cast((Collection<?>) def.getImports().values()); for (List<?> lst : imports) { List<Import> impLst = CastUtils.cast(lst); for (Import imp : impLst) { String start = imp.getLocationURI(); String decodedStart = null; // Always use the URL decoded version to ensure that we have a // canonical representation of the import URL for lookup. try { decodedStart = URLDecoder.decode(start, "utf-8"); } catch (UnsupportedEncodingException e) { throw new WSDLQueryException( new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, start), e); } String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base); if (resolvedSchemaLocation == null) { try { // check to see if it's already in a URL format. If so, leave it. new URL(start); } catch (MalformedURLException e) { if (done.put(decodedStart, imp.getDefinition()) == null) { updateDefinition(imp.getDefinition(), done, doneSchemas, base, ei); } } } else { if (done.put(decodedStart, imp.getDefinition()) == null) { done.put(resolvedSchemaLocation, imp.getDefinition()); updateDefinition(imp.getDefinition(), done, doneSchemas, base, ei); } } } } /* This doesn't actually work. Setting setSchemaLocationURI on the import * for some reason doesn't actually result in the new URI being written * */ Types types = def.getTypes(); if (types != null) { for (ExtensibilityElement el : CastUtils.cast(types.getExtensibilityElements(), ExtensibilityElement.class)) { if (el instanceof Schema) { Schema see = (Schema) el; updateSchemaImports(see, doneSchemas, base); } } } }
/** * This test verifies the precedence of Authorization Information. Setting authorization * information on the Message takes precedence over a Basic Auth Supplier with preemptive * UserPass, and that followed by setting it directly on the Conduit. */ @Test public void testAuthPolicyPrecedence() throws Exception { Bus bus = new ExtensionManagerBus(); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://nowhere.com/bar/foo"); HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null); conduit.finalizeConfig(); conduit.getAuthorization().setUserName("Satan"); conduit.getAuthorization().setPassword("hell"); Message message = getNewMessage(); // Test call conduit.prepare(message); Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); assertNotNull("Authorization Header should exist", headers.get("Authorization")); assertEquals( "Unexpected Authorization Token", "Basic " + Base64Utility.encode("Satan:hell".getBytes()), headers.get("Authorization").get(0)); // Setting a Basic Auth User Pass should override conduit.setAuthSupplier(new TestAuthSupplier()); message = getNewMessage(); // Test Call conduit.prepare(message); headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); List<String> authorization = headers.get("Authorization"); assertNotNull("Authorization Token must be set", authorization); assertEquals("Wrong Authorization Token", "myauth", authorization.get(0)); conduit.setAuthSupplier(null); // Setting authorization policy on the message should override // conduit setting AuthorizationPolicy authPolicy = new AuthorizationPolicy(); authPolicy.setUserName("Hello"); authPolicy.setPassword("world"); authPolicy.setAuthorizationType("Basic"); message = getNewMessage(); message.put(AuthorizationPolicy.class, authPolicy); conduit.prepare(message); headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); assertEquals( "Unexpected Authorization Token", "Basic " + Base64Utility.encode("Hello:world".getBytes()), headers.get("Authorization").get(0)); }
public static String getEndpointName(Binding binding, Definition wsdlDef) { LOG.log(Level.FINE, "Getting endpoint name for an object reference"); Collection<Service> services = CastUtils.cast(wsdlDef.getServices().values()); for (Service serv : services) { Collection<Port> ports = CastUtils.cast(serv.getPorts().values()); for (Port pt : ports) { if (pt.getBinding().equals(binding)) { return pt.getName(); } } } return null; }
private boolean checkSignatureIsSignedPlacement(List<WSSecurityEngineResult> signedResults) { for (int i = 0; i < signedResults.size(); i++) { WSSecurityEngineResult signedResult = signedResults.get(i); List<WSDataRef> sl = CastUtils.cast((List<?>) signedResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS)); if (sl != null && sl.size() >= 1) { for (WSDataRef dataRef : sl) { QName signedQName = dataRef.getName(); if (WSSecurityEngine.SIGNATURE.equals(signedQName)) { Element protectedElement = dataRef.getProtectedElement(); boolean endorsingSigFound = false; // Results are stored in reverse order for (WSSecurityEngineResult result : signedResults) { if (result == signedResult) { endorsingSigFound = true; } Element resultElement = (Element) result.get(WSSecurityEngineResult.TAG_TOKEN_ELEMENT); if (resultElement == protectedElement) { if (endorsingSigFound) { break; } else { return false; } } } } } } } return true; }
private void addServices(final Definition wsdlDef) { Iterator<QName> sNames = CastUtils.cast(wsdlDef.getServices().keySet().iterator()); while (sNames.hasNext()) { QName sName = sNames.next(); services.put(sName, definition.getService(sName)); } }
private String getEncryptedKey() { List<WSHandlerResult> results = CastUtils.cast( (List<?>) message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); for (WSHandlerResult rResult : results) { List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults(); for (WSSecurityEngineResult wser : wsSecEngineResults) { Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION); String encryptedKeyID = (String) wser.get(WSSecurityEngineResult.TAG_ID); if (actInt.intValue() == WSConstants.ENCR && encryptedKeyID != null && encryptedKeyID.length() != 0) { Date created = new Date(); Date expires = new Date(); expires.setTime(created.getTime() + 300000); SecurityToken tempTok = new SecurityToken(encryptedKeyID, created, expires); tempTok.setSecret((byte[]) wser.get(WSSecurityEngineResult.TAG_SECRET)); tempTok.setSHA1( getSHA1((byte[]) wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY))); tokenStore.add(tempTok); return encryptedKeyID; } } } return null; }
private String invokeEndpoint(String operation, String operationPara) throws Exception { ObjectName endpointName = null; ObjectName queryEndpointName; String ret = ""; Object[] jmxPara = null; String[] jmxSig = null; if (operationPara != null) { jmxPara = new Object[] {operationPara}; jmxSig = new String[] {String.class.getName()}; } else { jmxPara = new Object[0]; jmxSig = new String[0]; } queryEndpointName = getEndpointObjectName(); Set<ObjectName> endpointNames = CastUtils.cast(mbsc.queryNames(queryEndpointName, null)); // now get the ObjectName with the busId Iterator<ObjectName> it = endpointNames.iterator(); if (it.hasNext()) { // only deal with the first endpoint object which return from the list. endpointName = it.next(); ret = (String) mbsc.invoke(endpointName, operation, jmxPara, jmxSig); LOG.info("invoke endpoint " + endpointName + " operation " + operation + " succeed!"); } return ret; }
private String getUTDerivedKey() throws WSSecurityException { List<WSHandlerResult> results = CastUtils.cast( (List<?>) message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS)); for (WSHandlerResult rResult : results) { List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults(); for (WSSecurityEngineResult wser : wsSecEngineResults) { Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION); String utID = (String) wser.get(WSSecurityEngineResult.TAG_ID); if (actInt.intValue() == WSConstants.UT_NOPASSWORD) { if (utID == null || utID.length() == 0) { utID = wssConfig.getIdAllocator().createId("UsernameToken-", null); } Date created = new Date(); Date expires = new Date(); expires.setTime(created.getTime() + 300000); SecurityToken tempTok = new SecurityToken(utID, created, expires); byte[] secret = (byte[]) wser.get(WSSecurityEngineResult.TAG_SECRET); tempTok.setSecret(secret); tokenStore.add(tempTok); return utID; } } } return null; }
@Test public void testAuthPolicyFromEndpointInfo() throws Exception { Bus bus = new ExtensionManagerBus(); EndpointInfo ei = new EndpointInfo(); AuthorizationPolicy ap = new AuthorizationPolicy(); ap.setPassword("password"); ap.setUserName("testUser"); ei.addExtensor(ap); ei.setAddress("http://nowhere.com/bar/foo"); HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null); conduit.finalizeConfig(); Message message = getNewMessage(); // Test call conduit.prepare(message); Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); assertNotNull("Authorization Header should exist", headers.get("Authorization")); assertEquals( "Unexpected Authorization Token", "Basic " + Base64Utility.encode("testUser:password".getBytes()), headers.get("Authorization").get(0)); }
@SuppressWarnings("unchecked") protected Object[] retryInvoke( BindingOperationInfo oi, Object[] params, Map<String, Object> context, Exchange exchange) throws Exception { try { Object body = params.length == 0 ? null : params[0]; Map<String, Object> reqContext = CastUtils.cast((Map<?, ?>) context.get(REQUEST_CONTEXT)); MultivaluedMap<String, String> headers = (MultivaluedMap<String, String>) reqContext.get(Message.PROTOCOL_HEADERS); URI newRequestURI = calculateNewRequestURI(reqContext); // TODO: if failover conduit selector fails to find a failover target // then it will revert to the previous endpoint; that is not very likely // but possible - thus ideally we need to resert base and current URI only // if we get the same ConduitInitiatior endpoint instance before and after // retryInvoke. Object response = retryInvoke(newRequestURI, headers, body, exchange, context); exchange.put(List.class, getContentsList(response)); return new Object[] {response}; } catch (Throwable t) { Exception ex = t instanceof Exception ? (Exception) t : new Exception(t); exchange.put(Exception.class, ex); return null; } }
private javax.wsdl.Message findMessage(QName qn, Definition def, List<Definition> done) { javax.wsdl.Message msg = def.getMessage(qn); if (msg == null) { if (done.contains(def)) { return null; } done.add(def); Collection<List<Import>> ilist = CastUtils.cast(def.getImports().values()); for (List<Import> list : ilist) { for (Import i : list) { if (qn.getNamespaceURI().equals(i.getDefinition().getTargetNamespace())) { return i.getDefinition().getMessage(qn); } } } for (List<Import> list : ilist) { for (Import i : list) { msg = findMessage(qn, i.getDefinition(), done); if (msg != null) { return msg; } } } } return msg; }
@Override public Object invoke(Exchange exchange, Object o) { // get annotations declared on parameters Annotation[][] parameterAnnotations = this.getTargetMethod(exchange).getParameterAnnotations(); /* Get actual parameter list start (code copied from org.apache.cxf.service.invoker.AbstractInvoker.invoke) */ List<Object> params = null; if (o instanceof List) { params = CastUtils.cast((List<?>) o); } else if (o != null) { params = new MessageContentsList(o); } /* Get actual parameter list end */ // validate each parameter in the list if (params != null) { int i = 0; try { for (Object parameter : params) { validate(parameterAnnotations[i++], parameter); } } catch (ValidationException ve) { // Prevent CXF PhaseInterceptorChain to log complete stack trace (happens because // ValidationException // extends RuntimeException). Only error message with INFO level will be logged. exchange.getInMessage().put(FaultMode.class, FaultMode.CHECKED_APPLICATION_FAULT); throw ve; } } return underlying.invoke(exchange, o); }
@Override public void handleMessage(Message message) throws Fault { Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); TraceScope scope = super.startTraceSpan(headers, (String) message.get(Message.REQUEST_URI)); message.getExchange().put(TRACE_SPAN, scope); }
@Override public void handleMessage(SoapMessage message) throws Fault { if (message.getVersion() instanceof Soap11) { Map<String, List<String>> headers = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS)); headers.remove("SOAPAction"); } }
private Map<QName, Operation> getOperations(PortType portType) { Map<QName, Operation> operations = new HashMap<QName, Operation>(); Collection<Operation> pops = CastUtils.cast(portType.getOperations()); for (Operation op : pops) { operations.put(new QName(portType.getQName().getNamespaceURI(), op.getName()), op); } return operations; }
private Map<String, List<String>> getHeaders(Message message) { Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); if (headers == null) { headers = new HashMap<>(); message.put(Message.PROTOCOL_HEADERS, headers); } return headers; }
protected void updateResponseHeaders(Message message) { Map<String, List<String>> responseHeaders = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS)); if (responseHeaders == null) { responseHeaders = new HashMap<String, List<String>>(); message.put(Message.PROTOCOL_HEADERS, responseHeaders); } setPolicies(responseHeaders); }
private Collection<Attachment> getAttachments(boolean write) { MessageContext mc = getContext(); if (mc != null) { // TODO: there has to be a better fix String propertyName = write ? "WRITE-" + Message.ATTACHMENTS : Message.ATTACHMENTS; return CastUtils.cast((Collection<?>) mc.get(propertyName)); } else { return null; } }
private Collection<Import> getImports(final Definition wsdlDef) { Collection<Import> importList = new ArrayList<Import>(); Map<?, ?> imports = wsdlDef.getImports(); for (Map.Entry<?, ?> entry : imports.entrySet()) { List<Import> lst = CastUtils.cast((List<?>) entry.getValue()); importList.addAll(lst); } return importList; }
public boolean checkR2705() { Collection<Binding> bindings = CastUtils.cast(def.getBindings().values()); for (Binding binding : bindings) { if (SOAPBindingUtil.isMixedStyle(binding)) { addErrorMessage("Mixed style, invalid WSDL"); return false; } } return true; }
protected void updatePublishedEndpointUrl(String publishingUrl, Definition def, QName name) { Collection<Service> services = CastUtils.cast(def.getAllServices().values()); for (Service service : services) { Collection<Port> ports = CastUtils.cast(service.getPorts().values()); if (ports.isEmpty()) { continue; } if (name == null) { setSoapAddressLocationOn(ports.iterator().next(), publishingUrl); break; // only update the first port since we don't target any specific port } else { for (Port port : ports) { if (name.getLocalPart().equals(port.getName())) { setSoapAddressLocationOn(port, publishingUrl); } } } } }
// TODO: Should also check SoapHeader/SoapHeaderFault public boolean checkR2205() { Collection<Binding> bindings = CastUtils.cast(def.getBindings().values()); for (Binding binding : bindings) { if (!SOAPBindingUtil.isSOAPBinding(binding)) { System.err.println( "WSIBP Validator found <" + binding.getQName() + "> is NOT a SOAP binding"); continue; } if (binding.getPortType() == null) { // will error later continue; } for (Iterator<?> ite2 = binding.getPortType().getOperations().iterator(); ite2.hasNext(); ) { Operation operation = (Operation) ite2.next(); Collection<Fault> faults = CastUtils.cast(operation.getFaults().values()); if (CollectionUtils.isEmpty(faults)) { continue; } for (Fault fault : faults) { Message message = fault.getMessage(); Collection<Part> parts = CastUtils.cast(message.getParts().values()); for (Part part : parts) { if (part.getElementName() == null) { addErrorMessage( getErrorPrefix("WSI-BP-1.0 R2205") + "In Message " + message.getQName() + ", part " + part.getName() + " must specify a 'element' attribute"); return false; } } } } } return true; }
public Set<QName> getUnderstoodHeaders() { Set<QName> understood = new HashSet<QName>(); for (Handler h : getBinding().getHandlerChain()) { if (h instanceof SOAPHandler) { Set<QName> headers = CastUtils.cast(((SOAPHandler) h).getHeaders()); if (headers != null) { understood.addAll(headers); } } } return understood; }
protected OutputStream flushHeaders(Message outMessage) throws IOException { updateResponseHeaders(outMessage); Object responseObj = outMessage.get(HTTP_RESPONSE); OutputStream responseStream = null; boolean oneWay = isOneWay(outMessage); if (responseObj instanceof HttpServletResponse) { HttpServletResponse response = (HttpServletResponse) responseObj; Integer i = (Integer) outMessage.get(Message.RESPONSE_CODE); if (i != null) { int status = i.intValue(); if (HttpURLConnection.HTTP_INTERNAL_ERROR == i) { Map<Object, Object> pHeaders = CastUtils.cast((Map) outMessage.get(Message.PROTOCOL_HEADERS)); if (null != pHeaders && pHeaders.containsKey(PROTOCOL_HEADERS_CONTENT_TYPE)) { pHeaders.remove(PROTOCOL_HEADERS_CONTENT_TYPE); } } response.setStatus(status); } else if (oneWay) { response.setStatus(HttpURLConnection.HTTP_ACCEPTED); } else { response.setStatus(HttpURLConnection.HTTP_OK); } copyResponseHeaders(outMessage, response); if (oneWay && !isPartialResponse(outMessage)) { response.setContentLength(0); response.flushBuffer(); response.getOutputStream().close(); } else { responseStream = response.getOutputStream(); } } else if (null != responseObj) { String m = (new org.apache.cxf.common.i18n.Message( "UNEXPECTED_RESPONSE_TYPE_MSG", LOG, responseObj.getClass())) .toString(); LOG.log(Level.WARNING, m); throw new IOException(m); } else { String m = (new org.apache.cxf.common.i18n.Message("NULL_RESPONSE_MSG", LOG)).toString(); LOG.log(Level.WARNING, m); throw new IOException(m); } if (oneWay) { outMessage.remove(HTTP_RESPONSE); } return responseStream; }
public static List<Parameter> getParameters(Method resourceMethod) { Annotation[][] paramAnns = resourceMethod.getParameterAnnotations(); if (paramAnns.length == 0) { return CastUtils.cast(Collections.emptyList(), Parameter.class); } Class<?>[] types = resourceMethod.getParameterTypes(); List<Parameter> params = new ArrayList<Parameter>(paramAnns.length); for (int i = 0; i < paramAnns.length; i++) { Parameter p = getParameter(i, paramAnns[i], types[i]); params.add(p); } return params; }
@Test public void testRequestorOutboundSoapAction() throws Exception { SoapMessage message = setUpMessage(); interceptor.handleMessage(message); control.verify(); Map<String, List<String>> reqHeaders = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS)); assertNotNull(reqHeaders); List<String> soapaction = reqHeaders.get("soapaction"); assertTrue(null != soapaction && soapaction.size() == 1); assertEquals("\"http://foo/bar/SEI/opReq\"", soapaction.get(0)); }
@Override public Builder property(String name, Object value) { Map<String, Object> contextProps = WebClient.getConfig(webClient).getRequestContext(); Map<String, Object> filterProps = CastUtils.cast((Map<?, ?>) contextProps.get(PROPERTY_KEY)); if (filterProps == null) { filterProps = new HashMap<String, Object>(); contextProps.put(PROPERTY_KEY, filterProps); } if (value == null) { filterProps.remove(name); } else { filterProps.put(name, value); } return this; }
public int doubleIt(int numberToDouble) { // // Get the transformed SAML Assertion from the STS and check it // MessageContext context = wsc.getMessageContext(); final List<WSHandlerResult> handlerResults = CastUtils.cast((List<?>) context.get(WSHandlerConstants.RECV_RESULTS)); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(handlerResults.get(0).getResults(), WSConstants.UT); SamlAssertionWrapper assertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_TRANSFORMED_TOKEN); Assert.assertTrue(assertion != null && "DoubleItSTSIssuer".equals(assertion.getIssuerString())); return numberToDouble * 2; }
public static void populateEprInfo(EprMetaData info) { if (!info.isValid()) { return; } Binding match = info.getBinding(); Definition wsdlDef = info.getCandidateWsdlDef(); Collection<Service> services = CastUtils.cast(wsdlDef.getServices().values()); for (Service serv : services) { Collection<Port> ports = CastUtils.cast(serv.getPorts().values()); for (Port pt : ports) { if (pt.getBinding().equals(match)) { info.setPortName(pt.getName()); info.setServiceQName(serv.getQName()); break; } } } if (info.getServiceQName() == null) { Iterator<?> importLists = wsdlDef.getImports().values().iterator(); while (info.getServiceQName() == null && importLists.hasNext()) { List<?> imports = (List<?>) importLists.next(); for (java.lang.Object imp : imports) { if (imp instanceof Import) { Definition importDef = ((Import) imp).getDefinition(); LOG.log(Level.FINE, "following wsdl import " + importDef.getDocumentBaseURI()); info.setCandidateWsdlDef(importDef); populateEprInfo(info); if (info.getServiceQName() != null) { break; } } } } } }