Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ node_modules/
derby.log
.pmdruleset.xml
.sts4-cache/
**/.factorypath
.vscode/
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.cxf.microprofile.client.cdi;

import java.util.Optional;
import java.util.concurrent.Callable;

import org.apache.cxf.Bus;


public final class CDIFacade {

private static final boolean CDI_AVAILABLE;

private CDIFacade() {
}

static {
boolean b;
try {
Class.forName("javax.enterprise.inject.spi.BeanManager");
b = true;
} catch (Throwable t) {
b = false;
}
CDI_AVAILABLE = b;
}

public static Optional<Object> getBeanManager(Bus b) {
return nullableOptional(() -> CDIUtils.getCurrentBeanManager(b));
}

public static Optional<Object> getBeanManager() {
try {
return nullableOptional(() -> CDIUtils.getCurrentBeanManager());
} catch (Throwable t) {
t.printStackTrace();
return Optional.ofNullable(null);
}
}

public static <T> Optional<Instance<T>> getInstanceFromCDI(Class<T> clazz, Bus b) {
return nullableOptional(() -> CDIUtils.getInstanceFromCDI(clazz, b));
}

public static <T> Optional<Instance<T>> getInstanceFromCDI(Class<T> clazz) {
return nullableOptional(() -> CDIUtils.getInstanceFromCDI(clazz));
}

private static <T> Optional<T> nullableOptional(Callable<T> callable) {
if (!CDI_AVAILABLE) {
return Optional.empty();
}

T t;
try {
t = callable.call();
} catch (Throwable ex) {
// expected if no CDI implementation is available
t = null;
}
return Optional.ofNullable(t);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,8 @@ public Object invoke(Object restClient, Method m, Object[] params, Callable<Obje
static CDIInterceptorWrapper createWrapper(Class<?> restClient) {
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<CDIInterceptorWrapper>) () -> {
Class<?> cdiClass = Class.forName("javax.enterprise.inject.spi.CDI", false,
restClient.getClassLoader());
Method currentMethod = cdiClass.getMethod("current");
Object cdiCurrent = currentMethod.invoke(null);

Method getBeanMgrMethod = cdiClass.getMethod("getBeanManager");

return new CDIInterceptorWrapperImpl(restClient, getBeanMgrMethod.invoke(cdiCurrent));
Object beanManager = CDIFacade.getBeanManager().orElseThrow(() -> new Exception("CDI not available"));
return new CDIInterceptorWrapperImpl(restClient, beanManager);
});
} catch (PrivilegedActionException pae) {
// expected for environments where CDI is not supported
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.cxf.microprofile.client.cdi;

import java.util.NoSuchElementException;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.CDI;

import org.apache.cxf.Bus;


public final class CDIUtils {

private CDIUtils() {
}

static BeanManager getCurrentBeanManager(Bus bus) {
BeanManager bm = bus.getExtension(BeanManager.class);
if (bm == null) {
bm = getCurrentBeanManager();
bus.setExtension(bm, BeanManager.class);
}
return bm;
}

static BeanManager getCurrentBeanManager() {
return CDI.current().getBeanManager();
}


static <T> Instance<T> getInstanceFromCDI(Class<T> clazz) {
return getInstanceFromCDI(clazz, null);
}

static <T> Instance<T> getInstanceFromCDI(Class<T> clazz, Bus bus) {
Instance<T> instance;
try {
instance = findBean(clazz, bus);
} catch (ExceptionInInitializerError | NoClassDefFoundError | IllegalStateException ex) {
// expected if no CDI implementation is available
instance = null;
} catch (NoSuchElementException ex) {
// expected if ClientHeadersFactory is not managed by CDI
instance = null;
}
return instance;
}

@SuppressWarnings("unchecked")
private static <T> Instance<T> findBean(Class<T> clazz, Bus bus) {
BeanManager beanManager = bus == null ? getCurrentBeanManager() : getCurrentBeanManager(bus);
Bean<?> bean = beanManager.getBeans(clazz).iterator().next();
CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
Instance<T> instance = new Instance<>((T) beanManager.getReference(bean, clazz, ctx),
beanManager.isNormalScope(bean.getScope()) ? () -> { } : ctx::release);
return instance;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.cxf.microprofile.client.cdi;

public class Instance<T> {

private final T value;
private final Runnable releaseMethod;

Instance(T value, Runnable releaseMethod) {
this.value = value;
this.releaseMethod = releaseMethod;
}

public T getValue() {
return value;
}

public void release() {
releaseMethod.run();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
Expand All @@ -52,13 +54,16 @@
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.jaxrs.model.Parameter;
import org.apache.cxf.jaxrs.model.ParameterType;
import org.apache.cxf.jaxrs.model.ProviderInfo;
import org.apache.cxf.jaxrs.utils.HttpUtils;
import org.apache.cxf.jaxrs.utils.InjectionUtils;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.microprofile.client.MPRestClientCallback;
import org.apache.cxf.microprofile.client.MicroProfileClientProviderFactory;
import org.apache.cxf.microprofile.client.cdi.CDIFacade;
import org.apache.cxf.microprofile.client.cdi.CDIInterceptorWrapper;
import org.apache.cxf.microprofile.client.cdi.Instance;
import org.eclipse.microprofile.rest.client.annotation.ClientHeaderParam;
import org.eclipse.microprofile.rest.client.annotation.RegisterClientHeaders;
import org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory;
Expand Down Expand Up @@ -97,6 +102,9 @@ public void completed(Object o) { }

private final CDIInterceptorWrapper interceptorWrapper;
private Object objectInstance;
private Map<Class<ClientHeadersFactory>, ProviderInfo<ClientHeadersFactory>> clientHeaderFactories =
new WeakHashMap<>();
private List<Instance<?>> cdiInstances = new LinkedList<>();

//CHECKSTYLE:OFF
public MicroProfileClientProxyImpl(URI baseURI, ClassLoader loader, ClassResourceInfo cri,
Expand Down Expand Up @@ -372,6 +380,7 @@ private Parameter createClientHeaderParameter(ClientHeaderParam anno, Class<?> c
}

@Override
@SuppressWarnings("unchecked")
protected void handleHeaders(Method m,
Object[] params,
MultivaluedMap<String, String> headers,
Expand Down Expand Up @@ -409,25 +418,53 @@ protected void handleHeaders(Method m,
}
}

ClientHeadersFactory headersFactory = null;

if (headersFactoryAnno != null) {
Class<?> headersFactoryClass = headersFactoryAnno.value();
headersFactory = (ClientHeadersFactory) headersFactoryClass.newInstance();
mergeHeaders(headersFactory, headers);
Class<ClientHeadersFactory> headersFactoryClass = (Class<ClientHeadersFactory>)
headersFactoryAnno.value();
mergeHeaders(headersFactoryClass, headers);
}
} catch (Throwable t) {
throwException(t);
}
}

private void mergeHeaders(ClientHeadersFactory factory,
MultivaluedMap<String, String> existingHeaders) {
private ClientHeadersFactory mapClientHeadersInstance(Instance<ClientHeadersFactory> instance) {
cdiInstances.add(instance);
return instance.getValue();
}

private void mergeHeaders(Class<ClientHeadersFactory> factoryCls, MultivaluedMap<String, String> existingHeaders) {

try {
ClientHeadersFactory factory;

Message m = JAXRS_UTILS_GET_CURRENT_MESSAGE_METHOD == null ? null
: (Message) JAXRS_UTILS_GET_CURRENT_MESSAGE_METHOD.invoke(null);

if (m != null) {
factory = CDIFacade.getInstanceFromCDI(factoryCls, m.getExchange().getBus())
.map(this::mapClientHeadersInstance)
.orElse(factoryCls.newInstance());
ProviderInfo<ClientHeadersFactory> pi = clientHeaderFactories.computeIfAbsent(factoryCls, k -> {
return new ProviderInfo<ClientHeadersFactory>(factory, m.getExchange().getBus(), true);
});
InjectionUtils.injectContexts(factory, pi, m);
} else {
factory = CDIFacade.getInstanceFromCDI(factoryCls)
.map(this::mapClientHeadersInstance)
.orElse(factoryCls.newInstance());
}

MultivaluedMap<String, String> jaxrsHeaders = getJaxrsHeaders();
MultivaluedMap<String, String> updatedHeaders = factory.update(jaxrsHeaders, existingHeaders);
existingHeaders.putAll(updatedHeaders);
MultivaluedMap<String, String> updatedHeaders = factory.update(getJaxrsHeaders(m), existingHeaders);
existingHeaders.putAll(updatedHeaders);
} catch (Throwable t) {
// expected if not running in a JAX-RS server environment.
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "Caught exception getting JAX-RS incoming headers", t);
}
}
}

@Override
public Object invoke(Object o, Method m, Object[] params) throws Throwable {
checkClosed();
Expand Down Expand Up @@ -474,19 +511,22 @@ private void throwException(Throwable t) {
throw new RuntimeException(t);
}

private static MultivaluedMap<String, String> getJaxrsHeaders() {
/**
* Returns the incoming request headers from the current JAX-RS request, assuming
* that this is invoked inside a JAX-RS request. If not, it will return an empty
* map.
*/
private static MultivaluedMap<String, String> getJaxrsHeaders(Message m) {
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
try {
if (JAXRS_UTILS_GET_CURRENT_MESSAGE_METHOD != null) {
Message m = (Message) JAXRS_UTILS_GET_CURRENT_MESSAGE_METHOD.invoke(null);
headers.putAll(CastUtils.cast((Map<?, ?>)m.get(Message.PROTOCOL_HEADERS)));
}
} catch (Throwable t) {
// expected if not running in a JAX-RS server environment.
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "Caught exception getting JAX-RS incoming headers", t);
}
if (m != null) {
headers.putAll(CastUtils.cast((Map<?, ?>) m.get(Message.PROTOCOL_HEADERS)));
}
return headers;
}

@Override
public void close() {
cdiInstances.forEach(Instance::release);
super.close();
}
}
Loading