use of org.apache.cxf.jaxrs.model.OperationResourceInfo in project opencast by opencast.
the class RestPublisherTest method testResourceComparatorSameNonMatch.
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testResourceComparatorSameNonMatch() {
ServiceReference serviceReference = EasyMock.createNiceMock(ServiceReference.class);
EasyMock.expect(serviceReference.getProperty(SERVICE_PATH_PROPERTY)).andReturn("/events").once();
EasyMock.expect(serviceReference.getProperty(SERVICE_PATH_PROPERTY)).andReturn("/org").once();
EasyMock.replay(serviceReference);
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bc.getServiceReference(EasyMock.anyString())).andReturn(serviceReference).anyTimes();
EasyMock.replay(bc);
ComponentContext cc = EasyMock.createNiceMock(ComponentContext.class);
EasyMock.expect(cc.getBundleContext()).andReturn(bc).anyTimes();
EasyMock.replay(cc);
componentContext = cc;
Message message = new MessageImpl();
ExchangeImpl exchange = new ExchangeImpl();
message.setExchange(exchange);
message.put(Message.ENDPOINT_ADDRESS, "http://localhost:8080/series");
ClassResourceInfo cri1 = new ClassResourceInfo(this.getClass());
ClassResourceInfo cri2 = new ClassResourceInfo(RestPublisher.class.getClass());
OperationResourceInfo oper1 = new OperationResourceInfo(this.getClass().getMethods()[0], cri1);
OperationResourceInfo oper2 = new OperationResourceInfo(RestPublisher.class.getClass().getMethods()[0], cri2);
Assert.assertTrue(rc.compare(cri1, cri2, message) < 0);
Assert.assertTrue(rc.compare(oper1, oper2, message) < 0);
}
use of org.apache.cxf.jaxrs.model.OperationResourceInfo in project tomee by apache.
the class JAXRSUtils method findTargetMethod.
// CHECKSTYLE:OFF
public static OperationResourceInfo findTargetMethod(Map<ClassResourceInfo, MultivaluedMap<String, String>> matchedResources, Message message, String httpMethod, MultivaluedMap<String, String> matchedValues, String requestContentType, List<MediaType> acceptContentTypes, boolean throwException, boolean recordMatchedUri) {
// CHECKSTYLE:ON
final boolean getMethod = HttpMethod.GET.equals(httpMethod);
MediaType requestType;
try {
requestType = toMediaType(requestContentType);
} catch (IllegalArgumentException ex) {
throw ExceptionUtils.toNotSupportedException(ex, null);
}
SortedMap<OperationResourceInfo, MultivaluedMap<String, String>> candidateList = new TreeMap<OperationResourceInfo, MultivaluedMap<String, String>>(new OperationResourceInfoComparator(message, httpMethod, getMethod, requestType, acceptContentTypes));
int pathMatched = 0;
int methodMatched = 0;
int consumeMatched = 0;
boolean resourceMethodsAdded = false;
boolean generateOptionsResponse = false;
List<OperationResourceInfo> finalPathSubresources = null;
for (Map.Entry<ClassResourceInfo, MultivaluedMap<String, String>> rEntry : matchedResources.entrySet()) {
ClassResourceInfo resource = rEntry.getKey();
MultivaluedMap<String, String> values = rEntry.getValue();
String path = getCurrentPath(values);
LOG.fine(() -> new org.apache.cxf.common.i18n.Message("START_OPER_MATCH", BUNDLE, resource.getServiceClass().getName()).toString());
for (OperationResourceInfo ori : resource.getMethodDispatcher().getOperationResourceInfos()) {
boolean added = false;
URITemplate uriTemplate = ori.getURITemplate();
MultivaluedMap<String, String> map = new MetadataMap<>(values);
if (uriTemplate != null && uriTemplate.match(path, map)) {
String finalGroup = map.getFirst(URITemplate.FINAL_MATCH_GROUP);
boolean finalPath = StringUtils.isEmpty(finalGroup) || PATH_SEGMENT_SEP.equals(finalGroup);
if (ori.isSubResourceLocator()) {
candidateList.put(ori, map);
if (finalPath) {
if (finalPathSubresources == null) {
finalPathSubresources = new LinkedList<>();
}
finalPathSubresources.add(ori);
}
added = true;
} else if (finalPath) {
pathMatched++;
if (matchHttpMethod(ori.getHttpMethod(), httpMethod)) {
methodMatched++;
// CHECKSTYLE:OFF
if (getMethod || matchConsumeTypes(requestType, ori)) {
consumeMatched++;
for (MediaType acceptType : acceptContentTypes) {
if (matchProduceTypes(acceptType, ori)) {
candidateList.put(ori, map);
added = true;
resourceMethodsAdded = true;
break;
}
}
}
// CHECKSTYLE:ON
} else if ("OPTIONS".equalsIgnoreCase(httpMethod)) {
generateOptionsResponse = true;
}
}
}
LOG.fine(matchMessageLogSupplier(ori, path, httpMethod, requestType, acceptContentTypes, added));
}
}
if (finalPathSubresources != null && (resourceMethodsAdded || generateOptionsResponse) && !MessageUtils.getContextualBoolean(message, KEEP_SUBRESOURCE_CANDIDATES, false)) {
for (OperationResourceInfo key : finalPathSubresources) {
candidateList.remove(key);
}
}
if (!candidateList.isEmpty()) {
Map.Entry<OperationResourceInfo, MultivaluedMap<String, String>> firstEntry = candidateList.entrySet().iterator().next();
matchedValues.clear();
matchedValues.putAll(firstEntry.getValue());
OperationResourceInfo ori = firstEntry.getKey();
if (headMethodPossible(ori.getHttpMethod(), httpMethod)) {
LOG.info(new org.apache.cxf.common.i18n.Message("GET_INSTEAD_OF_HEAD", BUNDLE, ori.getClassResourceInfo().getServiceClass().getName(), ori.getMethodToInvoke().getName()).toString());
}
LOG.fine(() -> new org.apache.cxf.common.i18n.Message("OPER_SELECTED", BUNDLE, ori.getMethodToInvoke().getName(), ori.getClassResourceInfo().getServiceClass().getName()).toString());
if (!ori.isSubResourceLocator()) {
MediaType responseMediaType = intersectSortMediaTypes(acceptContentTypes, ori.getProduceTypes(), false).get(0);
message.getExchange().put(Message.CONTENT_TYPE, mediaTypeToString(responseMediaType, MEDIA_TYPE_Q_PARAM, MEDIA_TYPE_QS_PARAM));
}
if (recordMatchedUri) {
pushOntoStack(ori, matchedValues, message);
}
return ori;
}
if (!throwException) {
return null;
}
int status;
// priority : path, method, consumes, produces;
if (pathMatched == 0) {
status = 404;
} else if (methodMatched == 0) {
status = 405;
} else if (consumeMatched == 0) {
status = 415;
} else {
// Not a single Produces match
status = 406;
}
Map.Entry<ClassResourceInfo, MultivaluedMap<String, String>> firstCri = matchedResources.entrySet().iterator().next();
String name = firstCri.getKey().isRoot() ? "NO_OP_EXC" : "NO_SUBRESOURCE_METHOD_FOUND";
org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message(name, BUNDLE, message.get(Message.REQUEST_URI), getCurrentPath(firstCri.getValue()), httpMethod, mediaTypeToString(requestType), convertTypesToString(acceptContentTypes));
if (!"OPTIONS".equalsIgnoreCase(httpMethod)) {
Level logLevel = getExceptionLogLevel(message, ClientErrorException.class);
LOG.log(logLevel == null ? Level.FINE : logLevel, () -> errorMsg.toString());
}
Response response = createResponse(getRootResources(message), message, errorMsg.toString(), status, methodMatched == 0);
throw ExceptionUtils.toHttpException(null, response);
}
use of org.apache.cxf.jaxrs.model.OperationResourceInfo in project tomee by apache.
the class ClientProxyImpl method invoke.
/**
* Updates the current state if Client method is invoked, otherwise
* does the remote invocation or returns a new proxy if subresource
* method is invoked. Can throw an expected exception if ResponseExceptionMapper
* is registered
*/
@Override
public Object invoke(Object o, Method m, Object[] params) throws Throwable {
checkClosed();
Class<?> declaringClass = m.getDeclaringClass();
if (Client.class == declaringClass || InvocationHandlerAware.class == declaringClass || Object.class == declaringClass || Closeable.class == declaringClass || AutoCloseable.class == declaringClass) {
return m.invoke(this, params);
}
resetResponse();
OperationResourceInfo ori = cri.getMethodDispatcher().getOperationResourceInfo(m);
if (ori == null) {
if (m.isDefault()) {
return invokeDefaultMethod(declaringClass, o, m, params);
}
reportInvalidResourceMethod(m, "INVALID_RESOURCE_METHOD");
}
MultivaluedMap<ParameterType, Parameter> types = getParametersInfo(m, params, ori);
List<Parameter> beanParamsList = getParameters(types, ParameterType.BEAN);
int bodyIndex = getBodyIndex(types, ori);
List<Object> pathParams = getPathParamValues(m, params, types, beanParamsList, ori, bodyIndex);
UriBuilder builder = getCurrentBuilder().clone();
if (isRoot) {
addNonEmptyPath(builder, ori.getClassResourceInfo().getURITemplate().getValue());
}
addNonEmptyPath(builder, ori.getURITemplate().getValue());
handleMatrixes(m, params, types, beanParamsList, builder);
handleQueries(m, params, types, beanParamsList, builder);
URI uri = builder.buildFromEncoded(pathParams.toArray()).normalize();
MultivaluedMap<String, String> headers = getHeaders();
MultivaluedMap<String, String> paramHeaders = new MetadataMap<>();
handleHeaders(m, params, paramHeaders, beanParamsList, types);
handleCookies(m, params, paramHeaders, beanParamsList, types);
if (ori.isSubResourceLocator()) {
ClassResourceInfo subCri = cri.getSubResource(m.getReturnType(), m.getReturnType());
if (subCri == null) {
reportInvalidResourceMethod(m, "INVALID_SUBRESOURCE");
}
MultivaluedMap<String, String> subHeaders = paramHeaders;
if (inheritHeaders) {
subHeaders.putAll(headers);
}
ClientState newState = getState().newState(uri, subHeaders, getTemplateParametersMap(ori.getURITemplate(), pathParams));
ClientProxyImpl proxyImpl = new ClientProxyImpl(newState, proxyLoader, subCri, false, inheritHeaders);
proxyImpl.setConfiguration(getConfiguration());
return JAXRSClientFactory.createProxy(m.getReturnType(), proxyLoader, proxyImpl);
}
headers.putAll(paramHeaders);
getState().setTemplates(getTemplateParametersMap(ori.getURITemplate(), pathParams));
Object body = null;
if (bodyIndex != -1) {
body = params[bodyIndex];
if (body == null) {
bodyIndex = -1;
}
} else if (types.containsKey(ParameterType.FORM)) {
body = handleForm(m, params, types, beanParamsList);
} else if (types.containsKey(ParameterType.REQUEST_BODY)) {
body = handleMultipart(types, ori, params);
} else if (hasFormParams(params, beanParamsList)) {
body = handleForm(m, params, types, beanParamsList);
}
setRequestHeaders(headers, ori, types.containsKey(ParameterType.FORM), body == null ? null : body.getClass(), m.getReturnType());
try {
return doChainedInvocation(uri, headers, ori, params, body, bodyIndex, null, null);
} finally {
resetResponseStateImmediatelyIfNeeded();
}
}
use of org.apache.cxf.jaxrs.model.OperationResourceInfo in project tomee by apache.
the class ClientProxyImpl method doChainedInvocation.
// CHECKSTYLE:OFF
protected Object doChainedInvocation(URI uri, MultivaluedMap<String, String> headers, OperationResourceInfo ori, Object[] methodParams, Object body, int bodyIndex, Exchange exchange, Map<String, Object> invocationContext) throws Throwable {
// CHECKSTYLE:ON
Bus configuredBus = getConfiguration().getBus();
Bus origBus = BusFactory.getAndSetThreadDefaultBus(configuredBus);
ClassLoaderHolder origLoader = null;
try {
ClassLoader loader = configuredBus.getExtension(ClassLoader.class);
if (loader != null) {
origLoader = ClassLoaderUtils.setThreadContextClassloader(loader);
}
Message outMessage = createMessage(body, ori, headers, uri, exchange, invocationContext, true);
if (bodyIndex != -1) {
outMessage.put(Type.class, ori.getMethodToInvoke().getGenericParameterTypes()[bodyIndex]);
}
outMessage.getExchange().setOneWay(ori.isOneway());
setSupportOnewayResponseProperty(outMessage);
outMessage.setContent(OperationResourceInfo.class, ori);
setPlainOperationNameProperty(outMessage, ori.getMethodToInvoke().getName());
outMessage.getExchange().put(Method.class, ori.getMethodToInvoke());
outMessage.put(Annotation.class.getName(), getMethodAnnotations(ori.getAnnotatedMethod(), bodyIndex));
outMessage.getExchange().put(Message.SERVICE_OBJECT, proxy);
if (methodParams != null) {
outMessage.put(List.class, Arrays.asList(methodParams));
}
if (body != null) {
outMessage.put(PROXY_METHOD_PARAM_BODY_INDEX, bodyIndex);
}
outMessage.getInterceptorChain().add(bodyWriter);
Map<String, Object> reqContext = getRequestContext(outMessage);
reqContext.put(OperationResourceInfo.class.getName(), ori);
reqContext.put(PROXY_METHOD_PARAM_BODY_INDEX, bodyIndex);
// execute chain
InvocationCallback<Object> asyncCallback = checkAsyncCallback(ori, reqContext, outMessage);
if (asyncCallback != null) {
return doInvokeAsync(ori, outMessage, asyncCallback);
}
doRunInterceptorChain(outMessage);
Object[] results = preProcessResult(outMessage);
if (results != null && results.length == 1) {
return results[0];
}
try {
return handleResponse(outMessage, ori.getClassResourceInfo().getServiceClass());
} finally {
completeExchange(outMessage.getExchange(), true);
}
} finally {
if (origLoader != null) {
origLoader.reset();
}
if (origBus != configuredBus) {
BusFactory.setThreadDefaultBus(origBus);
}
}
}
use of org.apache.cxf.jaxrs.model.OperationResourceInfo in project tomee by apache.
the class CxfRsHttpListener method getServiceObject.
private Object getServiceObject(final Message message) {
final OperationResourceInfo ori = message.getExchange().get(OperationResourceInfo.class);
if (ori == null) {
return null;
}
if (!ori.getClassResourceInfo().isRoot()) {
return message.getExchange().get("org.apache.cxf.service.object.last");
}
final ResourceProvider resourceProvider = ori.getClassResourceInfo().getResourceProvider();
if (resourceProvider.isSingleton()) {
return resourceProvider.getInstance(message);
}
final Object o = message.getExchange().get(CdiResourceProvider.INSTANCE_KEY);
return o != null || !OpenEJBPerRequestPojoResourceProvider.class.isInstance(resourceProvider) ? o : resourceProvider.getInstance(message);
}
Aggregations