Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.x] - Simplify named socket WebTarget injection in Tests #5269

Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright (c) 2022 Oracle and/or its affiliates.
*
* Licensed 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 io.helidon.microprofile.tests.junit5;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.client.WebTarget;
import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@HelidonTest
@AddBean(TestNamedWebTarget.ResourceClass.class)
@AddConfig(key = "server.sockets.0.port", value = "0")
@AddConfig(key = "server.sockets.0.name", value = "named")
class TestNamedWebTarget {

@Inject
private WebTarget target;

@Inject
@Socket("named")
private WebTarget namedTarget;

@Test
void testTargetsAreDifferent(){
//Should be different
assertNotEquals(target.getUri(), namedTarget.getUri());
}

@Test
void testRegularTarget() {
assertThat(target, notNullValue());
String response = target.path("/test")
.request()
.get(String.class);
assertThat(response, is("Hello from ResourceClass"));
}

@Test
void testNamedSocketTarget() {
assertThat(namedTarget, notNullValue());
String response = namedTarget.path("/test/named")
.request()
.get(String.class);
assertThat(response, is("Hello from Named Resource"));
}

@Path("/test")
public static class ResourceClass {
@GET
public String getIt() {
return "Hello from ResourceClass";
}

@GET
@Path("named")
public String getNamed() {
return "Hello from Named Resource";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.helidon.microprofile.tests.junit5;


import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
Expand Down Expand Up @@ -44,6 +45,8 @@
import jakarta.enterprise.inject.spi.BeforeBeanDiscovery;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.inject.spi.ProcessInjectionPoint;
import jakarta.enterprise.inject.spi.configurator.AnnotatedTypeConfigurator;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
Expand All @@ -67,6 +70,7 @@
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;


/**
* Junit5 extension to support Helidon CDI container in tests.
*/
Expand Down Expand Up @@ -100,6 +104,7 @@ class HelidonJunitExtension implements BeforeAllCallback,
private Config config;
private SeContainer container;


@SuppressWarnings("unchecked")
@Override
public void beforeAll(ExtensionContext context) {
Expand Down Expand Up @@ -451,31 +456,61 @@ private static class AddBeansExtension implements Extension {
private final Class<?> testClass;
private final List<AddBean> addBeans;

private final HashMap<String, Annotation> socketAnnotations = new HashMap<>();

private AddBeansExtension(Class<?> testClass, List<AddBean> addBeans) {
this.testClass = testClass;
this.addBeans = addBeans;
}

@SuppressWarnings("unchecked")

dalexandrov marked this conversation as resolved.
Show resolved Hide resolved
void processSocketInjectionPoints(@Observes ProcessInjectionPoint<?, WebTarget> event) throws Exception{
InjectionPoint injectionPoint = event.getInjectionPoint();
Set<Annotation> qualifiers = injectionPoint.getQualifiers();
for (Annotation qualifier : qualifiers) {
if (qualifier.annotationType().equals(Socket.class)) {
String value = ((Socket) qualifier).value();
socketAnnotations.put(value, qualifier);
break;
}
}

}

void registerOtherBeans(@Observes AfterBeanDiscovery event) {

Client client = ClientBuilder.newClient();

//register for all named Ports
socketAnnotations.forEach((namedPort, qualifier) -> {

event.addBean()
.addType(WebTarget.class)
.scope(ApplicationScoped.class)
.qualifiers(qualifier)
.createWith(context -> getWebTarget(client, namedPort));
});

event.addBean()
.addType(jakarta.ws.rs.client.WebTarget.class)
.scope(ApplicationScoped.class)
.createWith(context -> {
try {
Class<? extends Extension> extClass = (Class<? extends Extension>) Class
.forName("io.helidon.microprofile.server.ServerCdiExtension");
Extension extension = CDI.current().getBeanManager().getExtension(extClass);
Method m = extension.getClass().getMethod("port");
int port = (int) m.invoke(extension);
String uri = "http://localhost:" + port;
return client.target(uri);
} catch (ReflectiveOperationException e) {
return client.target("http://localhost:7001");
}
});
.createWith(context -> getWebTarget(client, "@default"));

}

@SuppressWarnings("unchecked")
private static WebTarget getWebTarget(Client client, String namedPort) {
try {
Class<? extends Extension> extClass = (Class<? extends Extension>) Class
.forName("io.helidon.microprofile.server.ServerCdiExtension");
Extension extension = CDI.current().getBeanManager().getExtension(extClass);
Method m = extension.getClass().getMethod("port", String.class);
int port = (int) m.invoke(extension, new Object[]{namedPort});
String uri = "http://localhost:" + port;
return client.target(uri);
} catch (ReflectiveOperationException e) {
return client.target("http://localhost:7001");
}
}

void registerAddedBeans(@Observes BeforeBeanDiscovery event) {
Expand Down Expand Up @@ -512,6 +547,7 @@ private boolean hasBda(Class<?> value) {

return false;
}

}

private static final class ConfigMeta {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2022 Oracle and/or its affiliates.
*
* Licensed 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 io.helidon.microprofile.tests.junit5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import jakarta.inject.Qualifier;

/**
* Named socket Qualifier for {@code WebTarget}.
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface Socket {
dalexandrov marked this conversation as resolved.
Show resolved Hide resolved

/**
* Name of the socket.
*
* @return String with the name of the Socket
*/
String value();

}