package org.apache.cxf.jaxrs.interceptor; import java.io.IOException; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.apache.cxf.common.i18n.BundleUtils; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.jaxrs.JAXRSServiceImpl; import org.apache.cxf.jaxrs.ext.RequestHandler; import org.apache.cxf.jaxrs.impl.MetadataMap; import org.apache.cxf.jaxrs.impl.RequestPreprocessor; import org.apache.cxf.jaxrs.impl.UriInfoImpl; import org.apache.cxf.jaxrs.lifecycle.ResourceProvider; import org.apache.cxf.jaxrs.model.ClassResourceInfo; import org.apache.cxf.jaxrs.model.OperationResourceInfo; import org.apache.cxf.jaxrs.model.ProviderInfo; import org.apache.cxf.jaxrs.model.URITemplate; import org.apache.cxf.jaxrs.provider.ProviderFactory; import org.apache.cxf.jaxrs.utils.HttpUtils; import org.apache.cxf.jaxrs.utils.InjectionUtils; import org.apache.cxf.jaxrs.utils.JAXRSUtils; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageUtils; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.cxf.service.Service; public class JAXRSInInterceptor extends AbstractPhaseInterceptor<Message> { private static final Logger LOG = LogUtils.getL7dLogger(JAXRSInInterceptor.class); private static final ResourceBundle BUNDLE = BundleUtils.getBundle(JAXRSInInterceptor.class); public JAXRSInInterceptor() { super(Phase.UNMARSHAL); } @Override public void handleFault(Message message) { super.handleFault(message); LOG.fine("Cleanup thread local variables"); Object rootInstance = message.getExchange().remove(JAXRSUtils.ROOT_INSTANCE); Object rootProvider = message.getExchange().remove(JAXRSUtils.ROOT_PROVIDER); if (rootInstance != null && rootProvider != null) { try { ((ResourceProvider)rootProvider).releaseInstance(message, rootInstance); } catch (Throwable tex) { LOG.warning("Exception occurred during releasing the service instance, " + tex.getMessage()); } } ProviderFactory.getInstance(message).clearThreadLocalProxies(); ClassResourceInfo cri = (ClassResourceInfo)message.getExchange().get(JAXRSUtils.ROOT_RESOURCE_CLASS); if (cri != null) { cri.clearThreadLocalProxies(); } } public void handleMessage(Message message) { try { processRequest(message); } catch (RuntimeException ex) { Response excResponse = JAXRSUtils.convertFaultToResponse(ex, message); if (excResponse == null) { ProviderFactory.getInstance(message).clearThreadLocalProxies(); message.getExchange().put(Message.PROPOGATE_EXCEPTION, JAXRSUtils.propogateException(message)); throw ex; } message.getExchange().put(Response.class, excResponse); } } private void processRequest(Message message) { if (message.getExchange().get(OperationResourceInfo.class) != null) { // it's a suspended invocation; return; } RequestPreprocessor rp = ProviderFactory.getInstance(message).getRequestPreprocessor(); if (rp != null) { rp.preprocess(message, new UriInfoImpl(message, null)); if (message.getExchange().get(Response.class) != null) { return; } } String requestContentType = (String)message.get(Message.CONTENT_TYPE); if (requestContentType == null) { requestContentType = "*/*"; } String rawPath = HttpUtils.getPathToMatch(message, true); //1. Matching target resource class Service service = message.getExchange().get(Service.class); List<ClassResourceInfo> resources = ((JAXRSServiceImpl)service).getClassResourceInfos(); String acceptTypes = HttpUtils.getProtocolHeader(message, Message.ACCEPT_CONTENT_TYPE, null); if (acceptTypes == null) { acceptTypes = "*/*"; message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes); } List<MediaType> acceptContentTypes = null; try { acceptContentTypes = JAXRSUtils.sortMediaTypes(acceptTypes); } catch (IllegalArgumentException ex) { throw new WebApplicationException(406); } message.getExchange().put(Message.ACCEPT_CONTENT_TYPE, acceptContentTypes); MultivaluedMap<String, String> values = new MetadataMap<String, String>(); ClassResourceInfo resource = JAXRSUtils.selectResourceClass(resources, rawPath, values, message); if (resource == null) { org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("NO_ROOT_EXC", BUNDLE, message.get(Message.REQUEST_URI), rawPath); LOG.warning(errorMsg.toString()); Response resp = JAXRSUtils.createResponse(resource, message, errorMsg.toString(), Response.Status.NOT_FOUND.getStatusCode(), false); throw new WebApplicationException(resp); } message.getExchange().put(JAXRSUtils.ROOT_RESOURCE_CLASS, resource); String httpMethod = HttpUtils.getProtocolHeader(message, Message.HTTP_REQUEST_METHOD, "POST"); OperationResourceInfo ori = null; boolean operChecked = false; List<ProviderInfo<RequestHandler>> shs = ProviderFactory.getInstance(message).getRequestHandlers(); for (ProviderInfo<RequestHandler> sh : shs) { String newAcceptTypes = HttpUtils.getProtocolHeader(message, Message.ACCEPT_CONTENT_TYPE, "*/*"); if (!acceptTypes.equals(newAcceptTypes) || (ori == null && !operChecked)) { acceptTypes = newAcceptTypes; acceptContentTypes = JAXRSUtils.sortMediaTypes(newAcceptTypes); message.getExchange().put(Message.ACCEPT_CONTENT_TYPE, acceptContentTypes); if (ori != null) { values = new MetadataMap<String, String>(); resource = JAXRSUtils.selectResourceClass(resources, rawPath, values, message); } try { ori = JAXRSUtils.findTargetMethod(resource, message, httpMethod, values, requestContentType, acceptContentTypes, false); setExchangeProperties(message, ori, values, resources.size()); } catch (WebApplicationException ex) { operChecked = true; } } InjectionUtils.injectContextFields(sh.getProvider(), sh, message); InjectionUtils.injectContextMethods(sh.getProvider(), sh, message); Response response = sh.getProvider().handleRequest(message, resource); if (response != null) { message.getExchange().put(Response.class, response); return; } } String newAcceptTypes = (String)message.get(Message.ACCEPT_CONTENT_TYPE); if (!acceptTypes.equals(newAcceptTypes) || ori == null) { acceptTypes = newAcceptTypes; acceptContentTypes = JAXRSUtils.sortMediaTypes(acceptTypes); message.getExchange().put(Message.ACCEPT_CONTENT_TYPE, acceptContentTypes); if (ori != null) { values = new MetadataMap<String, String>(); resource = JAXRSUtils.selectResourceClass(resources, rawPath, values, message); } try { ori = JAXRSUtils.findTargetMethod(resource, message, httpMethod, values, requestContentType, acceptContentTypes, true); setExchangeProperties(message, ori, values, resources.size()); } catch (WebApplicationException ex) { if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), httpMethod)) { Response response = JAXRSUtils.createResponse(resource, null, null, 200, true); message.getExchange().put(Response.class, response); return; } else { throw ex; } } } if (LOG.isLoggable(Level.FINE)) { LOG.fine("Request path is: " + rawPath); LOG.fine("Request HTTP method is: " + httpMethod); LOG.fine("Request contentType is: " + requestContentType); LOG.fine("Accept contentType is: " + acceptTypes); LOG.fine("Found operation: " + ori.getMethodToInvoke().getName()); } setExchangeProperties(message, ori, values, resources.size()); //Process parameters 处理请求参数,一般解析参数从这里开始 try { List<Object> params = JAXRSUtils.processParameters(ori, values, message); message.setContent(List.class, params); } catch (IOException ex) { Response excResponse = JAXRSUtils.convertFaultToResponse(ex, message); if (excResponse == null) { throw new WebApplicationException(ex); } else { message.getExchange().put(Response.class, excResponse); } } } private void setExchangeProperties(Message message, OperationResourceInfo ori, MultivaluedMap<String, String> values, int numberOfResources) { message.getExchange().put(OperationResourceInfo.class, ori); message.put("org.apache.cxf.resource.method", ori.getMethodToInvoke()); message.put(URITemplate.TEMPLATE_PARAMETERS, values); String plainOperationName = ori.getMethodToInvoke().getName(); if (numberOfResources > 1) { plainOperationName = ori.getClassResourceInfo().getServiceClass().getSimpleName() + "#" + plainOperationName; } message.getExchange().put("org.apache.cxf.resource.operation.name", plainOperationName); boolean oneway = ori.isOneway() || MessageUtils.isTrue(HttpUtils.getProtocolHeader(message, Message.ONE_WAY_REQUEST, null)); message.getExchange().setOneWay(oneway); } }
public class JAXRSUtils{ //Message contains following information: PATH, HTTP_REQUEST_METHOD, CONTENT_TYPE, InputStream. public static List<Object> processParameters(OperationResourceInfo ori, MultivaluedMap<String, String> values, Message message) throws IOException, WebApplicationException { Method method = ori.getMethodToInvoke(); Class<?>[] parameterTypes = method.getParameterTypes(); Parameter[] paramsInfo = ori.getParameters().toArray(new Parameter[]{}); Method annotatedMethod = ori.getAnnotatedMethod(); Type[] genericParameterTypes = annotatedMethod == null ? method.getGenericParameterTypes() : annotatedMethod.getGenericParameterTypes(); Annotation[][] anns = annotatedMethod == null ? null : annotatedMethod.getParameterAnnotations(); List<Object> params = new ArrayList<Object>(parameterTypes.length); for (int i = 0; i < parameterTypes.length; i++) { Class<?> param = parameterTypes[i]; Type genericParam = genericParameterTypes[i]; if (genericParam instanceof TypeVariable) { genericParam = InjectionUtils.getSuperType(ori.getClassResourceInfo().getServiceClass(), (TypeVariable<?>)genericParam); } if (param == Object.class) { param = (Class<?>)genericParam; } else if (genericParam == Object.class) { genericParam = param; } Object paramValue = processParameter(param, genericParam, anns == null ? new Annotation[0] : anns[i], paramsInfo[i], values, message, ori); params.add(paramValue); } return params; } private static Object processParameter(Class<?> parameterClass, Type parameterType, Annotation[] parameterAnns, Parameter parameter, MultivaluedMap<String, String> values, Message message, OperationResourceInfo ori) throws IOException, WebApplicationException { InputStream is = message.getContent(InputStream.class); if (parameter.getType() == ParameterType.REQUEST_BODY) { String contentType = (String)message.get(Message.CONTENT_TYPE); if (contentType == null) { org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("NO_CONTENT_TYPE_SPECIFIED", BUNDLE, ori.getHttpMethod()); LOG.fine(errorMsg.toString()); contentType = MediaType.WILDCARD; } return readFromMessageBody(parameterClass, parameterType, parameterAnns, is, MediaType.valueOf(contentType), ori.getConsumeTypes(), message); } else if (parameter.getType() == ParameterType.CONTEXT) { return createContextValue(message, parameterType, parameterClass); } else { return createHttpParameterValue(parameter, parameterClass, parameterType, parameterAnns, message, values, ori); } } private static <T> T readFromMessageBody(Class<T> targetTypeClass, Type parameterType, Annotation[] parameterAnnotations, InputStream is, MediaType contentType, List<MediaType> consumeTypes, Message m) throws IOException, WebApplicationException { List<MediaType> types = JAXRSUtils.intersectMimeTypes(consumeTypes, contentType); MessageBodyReader<T> provider = null; for (MediaType type : types) { //获取用户提供的provider进行参数解析 provider = ProviderFactory.getInstance(m) .createMessageBodyReader(targetTypeClass, parameterType, parameterAnnotations, type, m); if (provider != null) { try { HttpHeaders headers = new HttpHeadersImpl(m); return provider.readFrom(targetTypeClass, parameterType, parameterAnnotations, contentType, headers.getRequestHeaders(), is); } catch (IOException e) { throw e; } catch (WebApplicationException ex) { throw ex; } catch (Exception ex) { throw new WebApplicationException(ex); } } else { String errorMessage = new org.apache.cxf.common.i18n.Message("NO_MSG_READER", BUNDLE, targetTypeClass.getSimpleName(), contentType).toString(); LOG.warning(errorMessage); throw new WebApplicationException(Response.Status.UNSUPPORTED_MEDIA_TYPE); } } return null; } }
相关推荐
在本文中,我们将深入探讨如何使用Apache CXF框架来处理JavaBean式的复合类型以及List集合类型的参数和返回值。CXF是一个开源的、强大的Web服务框架,它支持多种Web服务标准,包括SOAP、RESTful等,并且允许开发者以...
【Spring+CXF请求WebService详解】 在Java开发领域,Spring框架以其强大的依赖注入和面向切面编程能力被广泛应用,而CXF则是一个优秀的开源服务开发框架,支持SOAP和RESTful服务。当Spring与CXF结合使用时,可以...
这可能包括修改CXF的默认编码设置、调整XML解析器配置、检查数据库连接参数以及确保文件读写操作的编码设置正确。 总之,处理CXF中的编码问题需要对字符编码有深入的理解,并且熟悉CXF框架的配置和API。通过正确...
对于CXF客户端,可以使用`javax.ws.rs.client.ClientBuilder`创建一个客户端实例,然后通过`target()`方法指定服务地址,`register()`方法注册JSON处理类,最后调用`invoke()`方法发起请求并获取JSON响应。...
以上是关于"Apache CXF + Spring3 + REST + JSON配置"的基本介绍,实际应用中可能涉及更多的细节和高级特性,如错误处理、分页、过滤器、拦截器等。在具体实践中,应结合项目需求灵活运用这些技术,以构建高效、可靠...
通过实例化服务代理类,调用对应的方法,传入参数,即可发起Web服务请求。CXF会处理底层的HTTP通信和XML序列化/反序列化。 7. **异常处理**:CXF提供了丰富的异常处理机制,如`WebServiceException`,可以帮助...
- CXF支持SOAP 1.1和1.2版本,提供了完整的SOAP处理能力,包括消息编码、处理WS-Security等。 - 使用CXF,开发者可以通过JAX-WS(Java API for XML Web Services)来创建SOAP服务。JAX-WS是Java中定义Web服务的...
这涉及到了服务地址的配置、服务接口的定义、以及请求参数的处理等步骤。通过使用CXF提供的工具或编程方式,我们可以快速地创建并执行这些测试,验证客户端是否能正确地与服务器进行通信,以及接收和处理返回的数据...
在CXF客户端代码中,你可以通过调用代理类的方法并传入XML字符串作为参数来发送SOAP请求。 同时,描述中还提到“生成了json对象”,这可能意味着服务还支持RESTful API。REST(Representational State Transfer)是...
3. 生成请求:根据业务需求,设置请求参数,利用工具生成实际的SOAP请求XML字符串。 4. 发送请求:将生成的XML字符串通过HTTP客户端发送到目标SOAP服务,获取响应。 5. 处理响应:解析返回的SOAP响应,进行进一步...
在处理WSDL文档时,还可以使用其他工具和库,比如Apache CXF或Metro,它们提供了更强大的功能,如代码生成、调试和错误处理。此外,对于大型复杂的服务,可能还需要关注WSDL文档中的类型定义(XSD schema),这些...
客户端通过解析WSDL文件,可以了解服务的URL、可用的方法和参数等信息,进而生成符合SOAP规范的请求消息。服务器接收到请求后,根据SOAP消息的内容进行处理,并返回同样格式的响应。这一过程高度依赖于XML的标准化...
这样,Jetty将负责处理HTTP请求,并将它们转发给CXF处理Web服务。 6. **发布服务** 启动Jetty服务器,Web服务即发布成功。此时,任何能够访问该服务器的客户端都可以通过指定的URL调用我们的Web服务。 四、客户端...
2. **实现服务接口**:接着,你需要提供这个接口的实现类,如`WebServiceImpl`,在这里处理业务逻辑,例如解析XML请求并将其存储到MySQL数据库。 ```java @Service("myWebService") public class WebServiceImpl ...
CXF提供了`org.apache.cxf.jaxrs.ext.multipart.MultipartProvider`类,它可以解析Multipart请求并将文件内容转化为可操作的对象。 3. **处理文件上传**: 在服务端的实现类中,我们可以读取`InputStream`或`Part`...
- Cxf拦截器特征机制:通过拦截器可以在WebService的请求和响应过程中插入自定义逻辑,用于实现安全验证、日志记录等功能。 - 安全机制:包括用户认证、数字签名和混合验证等,确保WebService通信的安全性。 综上...
MyBatis会根据Mapper接口和XML配置动态生成SQL语句,而CXF则负责解析WSDL(Web Service Definition Language)并处理SOAP请求。 总的来说,这个DEMO为学习和实践Spring、MyBatis和CXF的集成提供了一个很好的起点,...
首先,我们需要在Spring配置文件中配置CXF,声明一个CXFServlet,这样CXF就能处理HTTP请求。这通常通过在`web.xml`中添加如下配置来完成: ```xml <servlet-name>CXFServlet <servlet-class>org.apache.cxf....
JAXB将Java对象转换为XML,反之亦然,这样Map就可以被作为请求参数或响应结果。 3. **服务端实现**:在服务端,开发者需要创建一个接口,其中包含一个或多个方法,这些方法接受或返回Map类型。然后,实现这个接口,...
- **SOAP**: 在HTTP的基础上,将XML格式的请求参数放置于HTTP Body中发送给Web Service服务器进行处理。处理完成后,服务器将结果也封装成XML格式返回给客户端。 #### SOAP的工作流程 1. **请求**: 客户端通过HTTP...