getting cause:null in property dlqDeliveryFailureCause - spring

I am trying to set up Dead Letter Queue monitoring for a system. So far, I can get it to be thrown in the DLQ queue without problems when the message consumption fails on the consumer. Now I'm having some trouble with getting the reason why it failed;
currently I get the following
java.lang.Throwable: Delivery[2] exceeds redelivery policy imit:RedeliveryPolicy
{destination = queue://*,
collisionAvoidanceFactor = 0.15,
maximumRedeliveries = 1,
maximumRedeliveryDelay = -1,
initialRedeliveryDelay = 10000,
useCollisionAvoidance = false,
useExponentialBackOff = true,
backOffMultiplier = 5.0,
redeliveryDelay = 10000,
preDispatchCheck = true},
cause:null
I do not know why cause is coming back as null. I'm using Spring with ActiveMQ. I'm using the DefaultJmsListenerContainerFactory, which creates a DefaultMessageListenerContainer. I would like cause to be filled with the exception that happened on my consumer but I can't get it to work. Apparently there's something on Spring that's not bubbling up the exception correctly, but I'm not sure what it is. I'm using spring-jms:4.3.10. I would really appreciate the help.

I am using spring-boot-starter-activemq:2.2.2.RELEASE (spring-jms:5.2.2, activemq-client-5.15.11) and I have the same behavior.
(links point to the versions I use)
The rollback cause is added here for the POSION_ACK_TYPE (sic!).
Its assignment to the MessageDispatch is only happening in one place: when dealing with a RuntimeException in the case there is a javax.jms.MessageListener registered.
Unfortunately (for this particular case), Spring doesn't register one, because it prefers to deal with its own hierarchy. So, long story short, there is no chance to make it happen with Spring out-of-the-box.
However, I managed to write an hack-ish way of getting an access to the MessageDispatch instance dealt with, inject the exception as the rollback cause, and it works!
package com.example;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import javax.jms.*;
public class MyJmsMessageListenerContainer extends DefaultMessageListenerContainer {
private final MessageDeliveryFailureCauseEnricher messageDeliveryFailureCauseEnricher = new MessageDeliveryFailureCauseEnricher();
private MessageConsumer messageConsumer; // Keep for later introspection
#Override
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
this.messageConsumer = super.createConsumer(session, destination);
return this.messageConsumer;
}
#Override
protected void invokeListener(Session session, Message message) throws JMSException {
try {
super.invokeListener(session, message);
} catch (Throwable throwable) {
messageDeliveryFailureCauseEnricher.enrich(throwable, this.messageConsumer);
throw throwable;
}
}
}
Note: don't deal with the Throwable by overriding the protected void handleListenerException(Throwable ex) method, because at that moment some cleanup already happened in the ActiveMQMessageConsumer instance.
package com.example;
import org.apache.activemq.ActiveMQMessageConsumer;
import org.apache.activemq.command.MessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import javax.jms.MessageConsumer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
class MessageDeliveryFailureCauseEnricher {
private static final Logger logger = LoggerFactory.getLogger(MessageDeliveryFailureCauseEnricher.class);
private final Map<Class<?>, Field> accessorFields = new HashMap<>();
private final Field targetField;
public MessageDeliveryFailureCauseEnricher() {
this.targetField = register(ActiveMQMessageConsumer.class, "deliveredMessages");
// Your mileage may vary; here is mine:
register("brave.jms.TracingMessageConsumer", "delegate");
register("org.springframework.jms.connection.CachedMessageConsumer", "target");
}
private Field register(String className, String fieldName) {
Field result = null;
if (className == null) {
logger.warn("Can't register a field from a missing class name");
} else {
try {
Class<?> clazz = Class.forName(className);
result = register(clazz, fieldName);
} catch (ClassNotFoundException e) {
logger.warn("Class not found on classpath: {}", className);
}
}
return result;
}
private Field register(Class<?> clazz, String fieldName) {
Field result = null;
if (fieldName == null) {
logger.warn("Can't register a missing class field name");
} else {
Field field = ReflectionUtils.findField(clazz, fieldName);
if (field != null) {
ReflectionUtils.makeAccessible(field);
accessorFields.put(clazz, field);
}
result = field;
}
return result;
}
void enrich(Throwable throwable, MessageConsumer messageConsumer) {
if (throwable != null) {
if (messageConsumer == null) {
logger.error("Can't enrich the MessageDispatch with rollback cause '{}' if no MessageConsumer is provided", throwable.getMessage());
} else {
LinkedList<MessageDispatch> deliveredMessages = lookupFrom(messageConsumer);
if (deliveredMessages != null && !deliveredMessages.isEmpty()) {
deliveredMessages.getLast().setRollbackCause(throwable); // Might cause problems if we prefetch more than 1 message
}
}
}
}
private LinkedList<MessageDispatch> lookupFrom(Object object) {
LinkedList<MessageDispatch> result = null;
if (object != null) {
Field field = accessorFields.get(object.getClass());
if (field != null) {
Object fieldValue = ReflectionUtils.getField(field, object);
if (fieldValue != null) {
if (targetField == field) {
result = (LinkedList<MessageDispatch>) fieldValue;
} else {
result = lookupFrom(fieldValue);
}
}
}
}
return result;
}
}
The magic happen in the second class:
At construction time we make some private fields accessible.
When a Throwable is caught, we traverse these fields to end up with the appropriate MessageDispatch instance (beware if you prefetch more than 1 message), and inject it the throwable we want to be part of the dlqDeliveryFailureCause JMS property.
I crafted this solution this afternoon, after hours of debugging (thanks OSS!) and many trials and errors. It works, but I have the feeling it's more of an hack than a real, solid solution.
With that in mind, I made my best to avoid side effects, so the worst that can happen is no trace of the original Throwable in the message ending in the Dead Letter Queue.
If I missed the point somewhere, I'b be glad to learn more about this.

Related

Micrometer - WebMvcTagsContributor not adding custom tags

I'm trying to add custom tags - the path variables and their values from each request - to each metric micrometer generates. I'm using spring-boot with java 16.
From my research i've found that creating a bean of type WebMvcTagsContributor alows me to do just that.
This is the code
public class CustomWebMvcTagsContributor implements WebMvcTagsContributor {
private static int PRINT_ERROR_COUNTER = 0;
#Override
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response,
Object handler,
Throwable exception) {
return Tags.of(getAllTags(request));
}
private static List<Tag> getAllTags(HttpServletRequest request) {
Object attributesMapObject = request.getAttribute(View.PATH_VARIABLES);
if (isNull(attributesMapObject)) {
attributesMapObject = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (isNull(attributesMapObject)) {
attributesMapObject = extractPathVariablesFromURI(request);
}
}
if (nonNull(attributesMapObject)) {
return getPathVariablesTags(attributesMapObject);
}
return List.of();
}
private static Object extractPathVariablesFromURI(HttpServletRequest request) {
Long currentUserId = SecurityUtils.getCurrentUserId().orElse(null);
try {
URI uri = new URI(request.getRequestURI());
String path = uri.getPath(); //get the path
UriTemplate uriTemplate = new UriTemplate((String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)); //create template
return uriTemplate.match(path); //extract values form template
} catch (Exception e) {
log.warn("[Error on 3rd attempt]", e);
}
return null;
}
private static List<Tag> getPathVariablesTags(Object attributesMapObject) {
try {
Long currentUserId = SecurityUtils.getCurrentUserId().orElse(null);
if (nonNull(attributesMapObject)) {
var attributesMap = (Map<String, Object>) attributesMapObject;
List<Tag> tags = attributesMap.entrySet().stream()
.map(stringObjectEntry -> Tag.of(stringObjectEntry.getKey(),
String.valueOf(stringObjectEntry.getValue())))
.toList();
log.warn("[CustomTags] [{}]", CommonUtils.toJson(tags));
return tags;
}
} catch (Exception e) {
if (PRINT_ERROR_COUNTER < 5) {
log.error("[Error while getting attributes map object]", e);
PRINT_ERROR_COUNTER++;
}
}
return List.of();
}
#Override
public Iterable<Tag> getLongRequestTags(HttpServletRequest request, Object handler) {
return null;
}
}
#Bean
public WebMvcTagsContributor webMvcTagsContributor() {
return new CustomWebMvcTagsContributor();
}
In order to test this, i've created a small spring boot app, added an endpoint to it. It works just fine.
The problem is when I add this code to the production app.
The metrics generates are the default ones and i can't figure out why.
What can I check to see why the tags are not added?
local test project
http_server_requests_seconds_count {exception="None", method="GET",id="123",outcome="Success",status="200",test="test",uri="/test/{id}/compute/{test}",)1.0
in prod - different (& bigger) app
http_server_requests_seconds_count {exception="None", method="GET",outcome="Success",status="200",uri="/api/{something}/test",)1.0
What i've tried and didn't work
Created a bean that implemented WebMvcTagsProvider - this one had an odd behaviour - it wasn't creating metrics for endpoints that had path variables in the path - though in my local test project it worked as expected
I added that log there in order to see what the extra tags are but doesn't seem to reach there as i don't see anything in the logs - i know, you might say that the current user id stops it, but it's not that.

Moshi with Graal has all reflection registered but cannot map fields

I'm trying to use Moshi with GraalVM's native-image, and trying to get the reflection to work.
I have my class:
public class SimpleJson {
private String message;
public SimpleJson(String message) { this.message = message; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
}
and code
var simpleJsonJsonAdapter = moshi.adapter(SimpleJson.class);
var simpleJsonString = "{\"message\": \"hello there\"}";
var simpleJsonObj = simpleJsonJsonAdapter.fromJson(simpleJsonString);
var simpleJsonStringBack = simpleJsonJsonAdapter.toJson(simpleJsonObj);
System.out.println("Converting: " + simpleJsonString);
System.out.println("Simple json has message: " + simpleJsonObj.getMessage());
System.out.println("Simple message full json coming back is: " + simpleJsonStringBack);
which prints:
Converting: {"message": "hello there"}
Simple json has message: null
Simple message full json coming back is: {}
and this only works (by avoiding an exception with SimpleJson is instantiated reflectively but was never registered) with the following chunk of code, to get everything registered ready for reflection:
#AutomaticFeature
public class RuntimeReflectionRegistrationFeature implements Feature {
#Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
try {
// Enable the moshi adapters
var moshiPkgs = "com.squareup.moshi";
// Standard shared models
var pkgs = "my.models";
// Register moshi
new ClassGraph()
.enableClassInfo()
.acceptPackages(moshiPkgs)
.scan()
.getSubclasses(JsonAdapter.class.getName())
.forEach(
classInfo -> {
System.out.println("Building moshi adapter class info for " + classInfo);
registerMoshiAdapter(classInfo.loadClass());
});
// Register everything we've got
new ClassGraph()
.enableClassInfo() // Scan classes, methods, fields, annotations
.acceptPackages(pkgs) // Scan package(s) and subpackages
.scan()
.getAllClasses()
.forEach(
classInfo -> {
System.out.println("Building class info for " + classInfo);
registerGeneralClass(classInfo.loadClass());
});
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
private void registerMoshiAdapter(Class<?> classInfo) {
try {
RuntimeReflection.register(classInfo);
Arrays.stream(classInfo.getMethods()).forEach(RuntimeReflection::register);
ParameterizedType superclass = (ParameterizedType) classInfo.getGenericSuperclass();
// extends JsonAdapter<X>()
var valueType = Arrays.stream(superclass.getActualTypeArguments()).findFirst();
if (valueType.isPresent() && valueType.get() instanceof Class) {
Arrays.stream(((Class<?>) valueType.get()).getConstructors())
.forEach(RuntimeReflection::register);
}
RuntimeReflection.register(classInfo.getConstructor(Moshi.class));
} catch (RuntimeException | NoSuchMethodException name) {
// expected
}
}
private void registerGeneralClass(Class<?> classInfo) {
try {
RuntimeReflection.register(classInfo);
Arrays.stream(classInfo.getDeclaredMethods()).forEach(RuntimeReflection::register);
Arrays.stream(classInfo.getDeclaredConstructors()).forEach(RuntimeReflection::register);
} catch (RuntimeException name) {
// expected
}
}
}
(inspired by this issue, although I believe that's trying to address MoshiAdapters generated which is a Kotlin only thing).
So, Java doesn't complain about reflection (which it was previously trying to do, hence the error message mentioned), but Moshi isn't actually doing anything.
Does anyone have any suggestions on how to work around this?
Note, I did try the manual reflect-config.json approach with
[
{
"allDeclaredClasses": true,
"queryAllDeclaredConstructors": true,
"queryAllPublicConstructors": true,
"name": "my.models.SimpleJson",
"queryAllDeclaredMethods": true,
"queryAllPublicMethods": true,
"allPublicClasses": true
}
}
but this resulted in error around Runtime reflection is not supported for... - also not good!
The solution was simple in the end... the registration just needed
Arrays.stream(classInfo.getDeclaredFields()).forEach(RuntimeReflection::register);
adding.

How to accept http requests after shutdown signal in Quarkus?

I tried this:
void onShutdown(#Observes final ShutdownEvent event) throws InterruptedException {
log.infof("ShutdownEvent received, waiting for %s seconds before shutting down", shutdownWaitSeconds);
TimeUnit.SECONDS.sleep(shutdownWaitSeconds);
log.info("Continue shutting down");
}
But after receiving ShutdownEvent Quarkus already responds with 503 to http requests. Looks like this could be done with ShutdownListener in preShutdown method. I have implemented this listener but it does not get called yet. How do I register ShutdownListener?
Use case here is OpenShift sending requests to terminating pod.
Option 1: Create Quarkus extension
Instructions are here. ShutdownController is my own class implementing ShutdownListener where I have a sleep in preShutdown method.
class ShutdownControllerProcessor {
#BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem("shutdown-controller");
}
#BuildStep
ShutdownListenerBuildItem shutdownListener() {
// Called at build time. Default constructor will be called at runtime.
// Getting MethodNotFoundException when calling default constructor here.
return new ShutdownListenerBuildItem(new ShutdownController(10));
}
}
Option 2: Modify ShutdownRecorder private static final field
New shutdown listener can be added using reflection. This is a bit ugly solution.
registerIfNeeded() need to be called after Quarkus startup, for example with timer 1 second after #PostConstruct.
#ApplicationScoped
public class ListenerRegisterer {
public void registerIfNeeded() {
try {
tryToRegister();
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private void tryToRegister() throws NoSuchFieldException, IllegalAccessException {
final var field = ShutdownRecorder.class.getDeclaredField("shutdownListeners");
field.setAccessible(true);
final var listeners = (List<ShutdownListener>) field.get(null);
if (listeners != null && !listeners.toString().contains("ShutdownController")) {
listeners.add(new ShutdownController(10));
setFinalStatic(field, listeners);
}
}
private static void setFinalStatic(final Field field, final Object newValue) throws NoSuchFieldException, IllegalAccessException {
field.setAccessible(true);
final var modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
}

How to get a session by session id in JBoss 5

I want to verify that session in JBoss 5 is still active and in logged in state. to implement a JWT (json web token).
for this, I need to get session by id.
to debug it: JBoss uses a special version of tomcat called JBoss web.
then I searched "jboss web 2* jar" and added it as source for sources to eclipse then I could debug it. also in eclipse, I have installed from eclipse marketplace FernFlower decompiler (* I took the actual version from https://developer.jboss.org/wiki/VersionOfTomcatInJBossAS)
I referenced those sources
how to refresh JSESSIONID cookie after login
https://github.com/auth0/java-jwt
my solution may help other pseudo tomcat serverlet servers
package com.mysoftware.controller.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mysoftware.util.SqlInjectionAndXSSRequestWrapper;
import com.mysoftware.model.User;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.jboss.seam.security.Identity;
import org.jboss.seam.web.ServletContexts;
import org.jboss.util.Base64;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
public class JWTAuthorization {
public static String isSessionIdLoggedIn(String requestedSessionId) {
try {
// get the request
HttpServletRequest request =ServletContexts.instance().getRequest();
ServletRequest serverletRequest = ((ServletRequestWrapper)request).getRequest();
// first need to unwrap the request until the core - org.apache.catalina.connector.Request.
// i had additional wrapper around the request SqlInjectionAndXSSRequestWrapper. (you probably wont have it)
// for simplicity i added SqlInjectionAndXSSRequestWrapper.request to my class, just saved the constructor argument.
SqlInjectionAndXSSRequestWrapper injectionRequest = (SqlInjectionAndXSSRequestWrapper) serverletRequest;
// code may start here, I run it and cast it and debug it and when I see it crash: "can't convert class x to y'. I understand which class it is and unwrap it accordingly.
RequestFacade requestFacade = (RequestFacade) injectionRequest.request;
Field catalinaRequestField;
//Getting actual catalina request using reflection
catalinaRequestField = requestFacade.getClass().getDeclaredField( "request" );
catalinaRequestField.setAccessible( true ); // grant access to (protected) field
Request realRequest = (Request)catalinaRequestField.get( requestFacade );
Manager manager = realRequest.getContext().getManager();
HttpSession session = null;
try {
session=(HttpSession) manager.findSession(requestedSessionId);
} catch (IOException var7) {}
if (session != null && !((Session) session).isValid()) {session = null;}
if (session != null) {((Session) session).access();} // mark usage
if (session != null && session.isNew()) return "new";
if (session != null )
{
Identity identity = (Identity)session.getAttribute("org.jboss.seam.security.identity");
if (identity != null && identity.isLoggedIn()) return "login";
}
return "not login";
} catch (Exception e1) {
e1.printStackTrace();
return "exception";
}
}
protected final static String sessionidencryptionkey="1234567890ghdg";
protected final static String jwtsecret="1234567890sdghsg";
public static String getTokenForCRM(User user)
{
try {
Algorithm algorithm = Algorithm.HMAC256(jwtsecret);
String token = JWT.create()
.withSubject(user.getId().toString())
.withArrayClaim("CRM", new String[]{ user.getAccount().getCrm() } )
.withClaim("SessionID", encrypt( ServletContexts.instance().getRequest().getSession().getId() , sessionidencryptionkey) )
.sign(algorithm);
return token;
} catch (Exception exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
return "ERROR_CREATEING_TOKEN";
}
public static String getSessionId(DecodedJWT token)
{
try {
return decrypt( token.getClaim("SessionID").asString() , sessionidencryptionkey) ;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
public static DecodedJWT verifyToken(String token)
{
try {
Algorithm algorithm = Algorithm.HMAC256(jwtsecret);
JWTVerifier verifier = JWT.require(algorithm)
//.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
return jwt;
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
return null;
}
public static String encrypt(String strClearText,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
byte[] encrypted=cipher.doFinal(strClearText.getBytes());
strData=new String(encrypted);
//strData=Base64.encodeBytes(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
public static String decrypt(String strEncrypted,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeyspec);
final byte[] strEncryptedBytes=strEncrypted.getBytes();
// final byte[] strEncryptedBytes==Base64.encode(strEncrypted)
byte[] decrypted=cipher.doFinal(strEncryptedBytes);
strData=new String(decrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
}
my testing code was.
inside a controller i had:
call it without wuery on different browsers,
then add parameter of the other session id in one of the browsers
#GET
#Path("testJWTSessionCheck")
#Produces("application/json")
public String testJWTSessionCheck( #QueryParam("s") String requestedSessionId) {
if(requestedSessionId!=null && requestedSessionId.length()>5) {
JWTAuthorization.isSessionIdLoggedIn(requestedSessionId);
}
HttpSession session1 = ServletContexts.instance().getRequest().getSession(false);
return session1.getId();
}

Mockito Unit Test with HTTPUrlConnection

I wrote code in our Spring Boot 2 application to make a third-party API call with HTTPUrlConnection.
public String loginApi(LoginDTO loginDto)
{
String responseData = null;
HttpURLConnection conn = null;
try {
link = authBaseUrl + loginUrl;
url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty(CONTENT_TYPE, MEDIA_TYPE);
String body = getAuth0LoginDto(loginDto);
// =====================
// For POST only - START
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
os.close();
// For POST only - END
// ====================
try (BufferedReader br = (conn.getResponseCode() >= 400
? new BufferedReader(new InputStreamReader(conn.getErrorStream()))
: new BufferedReader(new InputStreamReader(conn.getInputStream())))) {
StringBuilder everything = new StringBuilder();
String output = null;
while ((output = br.readLine()) != null) {
everything.append(output);
}
responseData = everything.toString();
}
} catch (JsonProcessingException e) {
throw new Auth0Exception("Could not create Auth0 Login Body", e);
} catch (IOException e) {
throw new Auth0Exception("Error with Login API", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return responseData;
}
Now, I am very much used to doing real integration testing, where I make a real call to the web-service and check the results.
I am now being asked to use strictly Mockito, not PowerMockito, not EasyMock, to create mocking tests, and I have never done that before. My knowledge of Mockito is weak also since I haven't used it in a very long time.
So, I know it has been asked before, and I have really searched on the internet, and I really haven't found a full piece of code as an example. I see code snippets which leaves me with pieces missing, and I am not knowledgeable enough to add those parts myself.
I know this code actual implementation works fine, and the integration test works fine also. But, what I have seen before is that some users are being told they need to change their client code in order to make the mockito tests work.
If I don't get the mocking tests working for HTTPUrlConnection, then I'll be forced to switch over to RestTemplate and Mocking since my co-worker insists we use RestTemplate anyway.
Thanks!
Since you have asked for a small example which does not make sense but should show the idea:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class App {
public int status(URL url) {
HttpURLConnection urlConnection = null;
try {
urlConnection = create(url);
return urlConnection.getResponseCode();
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
I would implement this with a spy and as I recommended a mocked HttpURLConnection:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
#ExtendWith(MockitoExtension.class)
class AppTest {
#Spy
App app;
#Mock
HttpURLConnection connection;
#Test
void status() throws IOException {
int expected = 200;
doReturn(connection).when(app).create(any());
doReturn(expected).when(connection).getResponseCode();
URL url = new URL("http://www.google.ats");
int status = app.status(url);
Assertions.assertEquals(expected, status);
}
}

Resources