use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project tomee by apache.
the class CxfRsHttpListener method deployApplication.
@Override
public void deployApplication(final Application application, final String prefix, final String webContext, final Collection<Object> additionalProviders, final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader, final Collection<Injection> injections, final Context context, final WebBeansContext owbCtx, final ServiceConfiguration serviceConfiguration) {
final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
try {
final ApplicationData applicationData = getApplicationData(application, prefix, additionalProviders);
logApplication(applicationData);
if (applicationData.getResources().size() == 0) {
throw new NoResourcesFoundException(applicationData);
}
final JAXRSServerFactoryBean factory = newFactory(prefix, createServiceJmxName(classLoader), createEndpointName(application));
configureFactory(additionalProviders, serviceConfiguration, factory, owbCtx, application);
factory.setApplication(application);
final List<Class<?>> classes = new ArrayList<>();
for (final Class<?> clazz : application.getClasses()) {
if (!additionalProviders.contains(clazz) && !clazz.isInterface()) {
classes.add(clazz);
final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
if (restServiceInfo != null) {
final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
} else {
if (owbCtx != null) {
final BeanManagerImpl bm = owbCtx.getBeanManagerImpl();
Bean<?> bean = null;
if (bm != null && bm.isInUse()) {
try {
final Set<Bean<?>> beans = bm.getBeans(clazz);
bean = bm.resolve(beans);
} catch (final InjectionException ie) {
final String msg = "Resource class " + clazz.getName() + " can not be instantiated";
LOGGER.warning(msg, ie);
throw new WebApplicationException(Response.serverError().entity(msg).build());
}
if (bean != null && isConsideredSingleton(bean.getScope())) {
final Object reference = bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean));
factory.setResourceProvider(clazz, new CdiSingletonResourceProvider(classLoader, clazz, reference, injections, context, owbCtx));
continue;
}
}
}
factory.setResourceProvider(clazz, new OpenEJBPerRequestPojoResourceProvider(classLoader, clazz, injections, context, owbCtx));
}
}
}
for (final Object o : application.getSingletons()) {
if (!additionalProviders.contains(o)) {
final Class<?> clazz = realClass(o.getClass());
classes.add(clazz);
final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
if (restServiceInfo != null) {
final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
} else {
if (owbCtx != null && owbCtx.getBeanManagerImpl().isInUse()) {
final CdiSingletonResourceProvider provider = new CdiSingletonResourceProvider(classLoader, clazz, o, injections, context, owbCtx);
singletons.add(provider);
factory.setResourceProvider(clazz, provider);
} else {
factory.setResourceProvider(clazz, new SingletonResourceProvider(o));
}
}
}
}
factory.setResourceClasses(classes);
factory.setInvoker(new AutoJAXRSInvoker(restEjbs));
injectApplication(application, factory);
/*
* During setApplication CXF will inspect the binding annotations
* on the Application subclass and apply them to every Resource class
* definition. This is how global bindings are supported. Thus, if
* setApplication is called before we've called setResourceClasses()
* binding annotations on the Application subclass will not work.
*
* Global binding annotations are tested in:
* com/sun/ts/tests/jaxrs/spec/filter/globalbinding/JAXRSClient#globalBoundResourceTest_from_standalone
*/
factory.setApplication(application);
this.context = webContext;
if (!webContext.startsWith("/")) {
this.context = "/" + webContext;
}
// /webcontext/servlet for event firing
final Level level = SERVER_IMPL_LOGGER.getLevel();
try {
SERVER_IMPL_LOGGER.setLevel(Level.OFF);
} catch (final UnsupportedOperationException e) {
// ignore
}
try {
factory.setProvider(new SseContextProvider());
factory.setProvider(new TomEESseEventSinkContextProvider());
server = factory.create();
fixProviders(serviceConfiguration);
fireServerCreated(oldLoader);
final ServerProviderFactory spf = ServerProviderFactory.class.cast(server.getEndpoint().get(ServerProviderFactory.class.getName()));
LOGGER.info("Using readers:");
for (final Object provider : List.class.cast(Reflections.get(spf, "messageReaders"))) {
LOGGER.info(" " + ProviderInfo.class.cast(provider).getProvider());
}
LOGGER.info("Using writers:");
for (final Object provider : List.class.cast(Reflections.get(spf, "messageWriters"))) {
LOGGER.info(" " + ProviderInfo.class.cast(provider).getProvider());
}
LOGGER.info("Using exception mappers:");
for (final Object provider : List.class.cast(Reflections.get(spf, "exceptionMappers"))) {
LOGGER.info(" " + ProviderInfo.class.cast(provider).getProvider());
}
} finally {
try {
SERVER_IMPL_LOGGER.setLevel(level);
} catch (final UnsupportedOperationException e) {
// ignore
}
}
final int servletIdx = 1 + this.context.substring(1).indexOf('/');
if (servletIdx > 0) {
this.servlet = this.context.substring(servletIdx);
this.context = this.context.substring(0, servletIdx);
}
destination = (HttpDestination) server.getDestination();
final String base;
if (prefix.endsWith("/")) {
base = prefix.substring(0, prefix.length() - 1);
} else if (prefix.endsWith(wildcard)) {
base = prefix.substring(0, prefix.length() - wildcard.length());
} else {
base = prefix;
}
// stack info to log to get nice logs
logEndpoints(application, prefix, restEjbs, factory, base);
} finally {
if (oldLoader != null) {
CxfUtil.clearBusLoader(oldLoader);
}
}
}
use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project tomee by apache.
the class JAXRSServerFactoryBean method setupFactory.
protected ServerProviderFactory setupFactory(Endpoint ep) {
ServerProviderFactory factory = ServerProviderFactory.createInstance(getBus());
setBeanInfo(factory);
factory.setApplicationProvider(appProvider);
super.setupFactory(factory, ep);
return factory;
}
use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project tomee by apache.
the class JAXRSInInterceptor method processRequest.
private void processRequest(Message message, Exchange exchange) throws IOException {
ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(message);
RequestPreprocessor rp = providerFactory.getRequestPreprocessor();
if (rp != null) {
rp.preprocess(message, new UriInfoImpl(message, null));
}
// Global pre-match request filters
if (JAXRSUtils.runContainerRequestFilters(providerFactory, message, true, null)) {
return;
}
// HTTP method
String httpMethod = HttpUtils.getProtocolHeader(message, Message.HTTP_REQUEST_METHOD, HttpMethod.POST, true);
// Path to match
String rawPath = HttpUtils.getPathToMatch(message, true);
Map<String, List<String>> protocolHeaders = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
// Content-Type
String requestContentType = null;
List<String> ctHeaderValues = protocolHeaders.get(Message.CONTENT_TYPE);
if (ctHeaderValues != null && !ctHeaderValues.isEmpty()) {
requestContentType = ctHeaderValues.get(0);
message.put(Message.CONTENT_TYPE, requestContentType);
}
if (requestContentType == null) {
requestContentType = (String) message.get(Message.CONTENT_TYPE);
if (requestContentType == null) {
requestContentType = MediaType.WILDCARD;
}
}
// Accept
String acceptTypes = null;
List<String> acceptHeaderValues = protocolHeaders.get(Message.ACCEPT_CONTENT_TYPE);
if (acceptHeaderValues != null && !acceptHeaderValues.isEmpty()) {
acceptTypes = acceptHeaderValues.get(0);
message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes);
}
if (acceptTypes == null) {
acceptTypes = HttpUtils.getProtocolHeader(message, Message.ACCEPT_CONTENT_TYPE, null);
if (acceptTypes == null) {
acceptTypes = "*/*";
message.put(Message.ACCEPT_CONTENT_TYPE, acceptTypes);
}
}
final List<MediaType> acceptContentTypes;
try {
acceptContentTypes = JAXRSUtils.sortMediaTypes(acceptTypes, JAXRSUtils.MEDIA_TYPE_Q_PARAM);
} catch (IllegalArgumentException ex) {
throw ExceptionUtils.toNotAcceptableException(null, null);
}
exchange.put(Message.ACCEPT_CONTENT_TYPE, acceptContentTypes);
// 1. Matching target resource class
List<ClassResourceInfo> resources = JAXRSUtils.getRootResources(message);
Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources = JAXRSUtils.selectResourceClass(resources, rawPath, message);
if (matchedResources == 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);
Level logLevel = JAXRSUtils.getExceptionLogLevel(message, NotFoundException.class);
LOG.log(logLevel == null ? Level.FINE : logLevel, errorMsg.toString());
Response resp = JAXRSUtils.createResponse(resources, message, errorMsg.toString(), Response.Status.NOT_FOUND.getStatusCode(), false);
throw ExceptionUtils.toNotFoundException(null, resp);
}
MultivaluedMap<String, String> matchedValues = new MetadataMap<>();
final OperationResourceInfo ori;
try {
ori = JAXRSUtils.findTargetMethod(matchedResources, message, httpMethod, matchedValues, requestContentType, acceptContentTypes, true, true);
setExchangeProperties(message, exchange, ori, matchedValues, resources.size());
} catch (WebApplicationException ex) {
if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), httpMethod)) {
Response response = JAXRSUtils.createResponse(resources, null, null, 200, true);
exchange.put(Response.class, response);
return;
}
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());
}
// Global and name-bound post-match request filters
if (!ori.isSubResourceLocator() && JAXRSUtils.runContainerRequestFilters(providerFactory, message, false, ori.getNameBindings())) {
return;
}
// Process parameters
List<Object> params = JAXRSUtils.processParameters(ori, matchedValues, message);
message.setContent(List.class, params);
}
use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project cxf by apache.
the class JAXRSServerFactoryBean method setupFactory.
protected ServerProviderFactory setupFactory(Endpoint ep) {
ServerProviderFactory factory = ServerProviderFactory.createInstance(getBus());
setBeanInfo(factory);
factory.setApplicationProvider(appProvider);
super.setupFactory(factory, ep);
return factory;
}
use of org.apache.cxf.jaxrs.provider.ServerProviderFactory in project cxf by apache.
the class JAXRSInvoker method invoke.
@SuppressWarnings("unchecked")
public Object invoke(Exchange exchange, Object request, Object resourceObject) {
final OperationResourceInfo ori = exchange.get(OperationResourceInfo.class);
final ClassResourceInfo cri = ori.getClassResourceInfo();
final Message inMessage = exchange.getInMessage();
final ServerProviderFactory providerFactory = ServerProviderFactory.getInstance(inMessage);
cri.injectContexts(resourceObject, ori, inMessage);
if (cri.isRoot()) {
ProviderInfo<Application> appProvider = providerFactory.getApplicationProvider();
if (appProvider != null) {
InjectionUtils.injectContexts(appProvider.getProvider(), appProvider, inMessage);
}
}
Method methodToInvoke = getMethodToInvoke(cri, ori, resourceObject);
List<Object> params = null;
if (request instanceof List) {
params = CastUtils.cast((List<?>) request);
} else if (request != null) {
params = new MessageContentsList(request);
}
Object result = null;
ClassLoaderHolder contextLoader = null;
AsyncResponseImpl asyncResponse = null;
try {
if (setServiceLoaderAsContextLoader(inMessage)) {
contextLoader = ClassLoaderUtils.setThreadContextClassloader(resourceObject.getClass().getClassLoader());
}
if (!ori.isSubResourceLocator()) {
asyncResponse = (AsyncResponseImpl) inMessage.get(AsyncResponse.class);
}
result = invoke(exchange, resourceObject, methodToInvoke, params);
if (asyncResponse == null && !ori.isSubResourceLocator()) {
asyncResponse = checkFutureResponse(inMessage, checkResultObject(result));
}
if (asyncResponse != null) {
if (!asyncResponse.suspendContinuationIfNeeded()) {
result = handleAsyncResponse(exchange, asyncResponse);
} else {
providerFactory.clearThreadLocalProxies();
}
}
} catch (Fault ex) {
Object faultResponse;
if (asyncResponse != null) {
faultResponse = handleAsyncFault(exchange, asyncResponse, ex.getCause() == null ? ex : ex.getCause());
} else {
faultResponse = handleFault(ex, inMessage, cri, methodToInvoke);
}
return faultResponse;
} finally {
exchange.put(LAST_SERVICE_OBJECT, resourceObject);
if (contextLoader != null) {
contextLoader.reset();
}
}
ClassResourceInfo subCri = null;
if (ori.isSubResourceLocator()) {
try {
MultivaluedMap<String, String> values = getTemplateValues(inMessage);
String subResourcePath = values.getFirst(URITemplate.FINAL_MATCH_GROUP);
String httpMethod = (String) inMessage.get(Message.HTTP_REQUEST_METHOD);
String contentType = (String) inMessage.get(Message.CONTENT_TYPE);
if (contentType == null) {
contentType = "*/*";
}
List<MediaType> acceptContentType = (List<MediaType>) exchange.get(Message.ACCEPT_CONTENT_TYPE);
result = checkSubResultObject(result, subResourcePath);
final Class<?> subResponseType;
if (result.getClass() == Class.class) {
ResourceContext rc = new ResourceContextImpl(inMessage, ori);
result = rc.getResource((Class<?>) result);
subResponseType = InjectionUtils.getActualType(methodToInvoke.getGenericReturnType());
} else {
subResponseType = methodToInvoke.getReturnType();
}
subCri = cri.getSubResource(subResponseType, ClassHelper.getRealClass(exchange.getBus(), result), result);
if (subCri == null) {
org.apache.cxf.common.i18n.Message errorM = new org.apache.cxf.common.i18n.Message("NO_SUBRESOURCE_FOUND", BUNDLE, subResourcePath);
LOG.severe(errorM.toString());
throw ExceptionUtils.toNotFoundException(null, null);
}
OperationResourceInfo subOri = JAXRSUtils.findTargetMethod(Collections.singletonMap(subCri, values), inMessage, httpMethod, values, contentType, acceptContentType);
exchange.put(OperationResourceInfo.class, subOri);
inMessage.put(URITemplate.TEMPLATE_PARAMETERS, values);
inMessage.put(URITemplate.URI_TEMPLATE, JAXRSUtils.getUriTemplate(inMessage, subCri, ori, subOri));
if (!subOri.isSubResourceLocator() && JAXRSUtils.runContainerRequestFilters(providerFactory, inMessage, false, subOri.getNameBindings())) {
return new MessageContentsList(exchange.get(Response.class));
}
// work out request parameters for the sub-resource class. Here we
// presume InputStream has not been consumed yet by the root resource class.
List<Object> newParams = JAXRSUtils.processParameters(subOri, values, inMessage);
inMessage.setContent(List.class, newParams);
return this.invoke(exchange, newParams, result);
} catch (IOException ex) {
Response resp = JAXRSUtils.convertFaultToResponse(ex, inMessage);
if (resp == null) {
resp = JAXRSUtils.convertFaultToResponse(ex, inMessage);
}
return new MessageContentsList(resp);
} catch (WebApplicationException ex) {
Response excResponse;
if (JAXRSUtils.noResourceMethodForOptions(ex.getResponse(), (String) inMessage.get(Message.HTTP_REQUEST_METHOD))) {
excResponse = JAXRSUtils.createResponse(Collections.singletonList(subCri), null, null, 200, true);
} else {
excResponse = JAXRSUtils.convertFaultToResponse(ex, inMessage);
}
return new MessageContentsList(excResponse);
}
}
setResponseContentTypeIfNeeded(inMessage, result);
return result;
}
Aggregations