https://linen.dev logo
#wiremock-java
Title
# wiremock-java
s

Shruti Mishra

05/14/2023, 10:14 AM
Hi Team, In the below code, while I am trying to make custom error response in request filter class, when I am returning badRequest, it is giving 422 error code. But the expectation is 400. Can someone suggest a solution on this.
Copy code
package com.example.wiremock.stub;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import com.example.wiremock.errorhandler.BadRequestError;
import com.example.wiremock.errorhandler.MockError;
import com.example.wiremock.errorhandler.MockErrorResponse;
import com.example.wiremock.luukuresponse.LuukkuBasicInfoResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.common.Errors;
import com.github.tomakehurst.wiremock.common.Errors.Error;
import com.github.tomakehurst.wiremock.common.Errors.Error.Source;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilterAction;
import com.github.tomakehurst.wiremock.extension.requestfilter.StubRequestFilter;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;

import java.util.ArrayList;
import java.util.List;


@Component
public class BasicAuthRequestFilter extends StubRequestFilter { 


	
	public String decodeJwt(String token) throws UnsupportedEncodingException {
		String payload = token.split("\\.")[1];
		return new String(Base64.decodeBase64(payload), "UTF-8");
	}

	
    @Override
    public RequestFilterAction filter(Request request){
        	
    	if (request.header("Authorization").firstValue().matches("Bearer [a-zA-Z0-9&._-]{1,}")) {
        	
        	String authtoken = request.header("Authorization").firstValue();
        	
        	ObjectMapper objectMapper = new ObjectMapper();

    		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    		
    		 Errors errors;

    		String str;
			try {
				
				String pattern = "^\\S{4}75-\\S{4}$";
				
				str = decodeJwt(authtoken);
				
				Token token = objectMapper.readValue(str, Token.class);
				
				String test = token.getRepresentation().getId();
				
				if(test.matches(pattern)) {
					
					Error error = new Error(400, null, "response", null);
					List<Error> listOfErros = new ArrayList<>();
					listOfErros.add(error);
                   				
					Errors errorList = new Errors(listOfErros);

					return RequestFilterAction.stopWith(ResponseDefinition.badRequest(errorList));
				}
			} catch (UnsupportedEncodingException  | JsonProcessingException e) {
				e.printStackTrace();
			}
			
			return RequestFilterAction.continueWith(request);
        }
		return null;

    	
    }

    @Override
    public String getName() {
        return "Authorization";
    }
Below is the error snapshot:
b

Bas Dijkstra

05/14/2023, 10:30 AM
I am assuming that the endpoint you’re invoking isn’t the WireMock instance? What does your WireMock instance return when you invoke it directly? I suspect that there’s some transformation happening in the service you’re invoking, and that that’s where the 400 code in the response body comes from. Please let me know if my assumptions are wrong :)
s

Shruti Mishra

05/14/2023, 10:45 AM
Hi @Bas Dijkstra Actually the requirement is to have a 400 response only in this case. But I am receiving 422 response instead of 400. Let me share the whole code, Below is the main stub class, in which 2 classes are registered requestfilter and response transformer. In request filter class, in one of the check I am expecting 400 response, but I am getting 422. Below is the main stub class
Copy code
package com.example.wiremock.stub;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import static com.github.tomakehurst.wiremock.client.WireMock.*;

import javax.annotation.PostConstruct;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.common.ConsoleNotifier;
import com.github.tomakehurst.wiremock.junit.WireMockRule;

import org.assertj.core.api.Assertions;

@Component
public class LuukuWiremockStub {

	@Autowired
	private static WireMockServer wireMockServer;


	@PostConstruct
	public void startWireMock() {
		wireMockServer = new WireMockServer(options().port(8082).httpsPort(8001).jettyHeaderBufferSize(16834)
				.extensions(BasicAuthRequestFilter.class, LuukuResponseTransformer.class)
				.notifier(new ConsoleNotifier(true)));
		wireMockServer.start();
			
		wireMockServer

		.stubFor(get(urlPathEqualTo("/todos"))
				
			 .withHeader("x-request-id", equalTo("83b26afe-e440-4a5a-b62c-aa5c21070db8"))
				  
		    .withHeader("x-session-id", equalTo("83b26afe-e440-4a5a-b62c-aa5c21070db8"))
				
			// .withHeader("x-request-id", matching("[0-9a-fA-F]{8}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{12}"))
			  
			//  .withHeader("x-session-id", matching("[0-9a-fA-F]{8}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{4}\\\\-[0-9a-fA-F]{12}"))
			  
		    .withHeader("x-api-key", equalTo("V7Qx9EAVpIsvAjrMsxibCucSM0Kyu3Mi"))
			  
			.withHeader("Authorization", matching("Bearer [a-zA-Z0-9&._-]{1,}"))
			  
			// .withHeader("Accept", containing("application/json"))
			     			  
			  .withQueryParam("context", equalTo("Pankin ostopolku")) 

				.willReturn(aResponse() 
						.withStatus(200).withHeader("Content-Type", APPLICATION_JSON_VALUE)
						.withBodyFile("BasicInfo163.json")));


}
}
Below is the request filter class
Copy code
package com.example.wiremock.stub;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import com.example.wiremock.errorhandler.BadRequestError;
import com.example.wiremock.errorhandler.MockError;
import com.example.wiremock.errorhandler.MockErrorResponse;
import com.example.wiremock.luukuresponse.LuukkuBasicInfoResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.common.Errors;
import com.github.tomakehurst.wiremock.common.Errors.Error;
import com.github.tomakehurst.wiremock.common.Errors.Error.Source;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilterAction;
import com.github.tomakehurst.wiremock.extension.requestfilter.StubRequestFilter;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;

import java.util.ArrayList;
import java.util.List;


@Component
public class BasicAuthRequestFilter extends StubRequestFilter { 


	
	public String decodeJwt(String token) throws UnsupportedEncodingException {
		String payload = token.split("\\.")[1];
		return new String(Base64.decodeBase64(payload), "UTF-8");
	}

	
    @Override
    public RequestFilterAction filter(Request request){
        	
    	if (request.header("Authorization").firstValue().matches("Bearer [a-zA-Z0-9&._-]{1,}")) {
        	
        	String authtoken = request.header("Authorization").firstValue();
        	
        	ObjectMapper objectMapper = new ObjectMapper();

    		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    		
    		 Errors errors;

    		String str;
			try {
				
				String pattern = "^\\S{4}75-\\S{4}$";
				
				str = decodeJwt(authtoken);
				
				Token token = objectMapper.readValue(str, Token.class);
				
				String test = token.getRepresentation().getId();
				
				if(test.matches(pattern)) {
					
					Error error = new Error(400, null, "response", null);
					List<Error> listOfErros = new ArrayList<>();
					listOfErros.add(error);
                   				
					Errors errorList = new Errors(listOfErros);

					return RequestFilterAction.stopWith(ResponseDefinition.badRequest(errorList));
				}
			} catch (UnsupportedEncodingException  | JsonProcessingException e) {
				e.printStackTrace();
			}
			
			return RequestFilterAction.continueWith(request);
        }
		return null;

    	
    }

    @Override
    public String getName() {
        return "Authorization";
    }
}
Hi @Bas Dijkstra Below is the response transformer class
Copy code
package com.example.wiremock.stub;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.wiremock.luukuresponse.Individual;
import com.example.wiremock.luukuresponse.LuukkuBasicInfoResponse;
import com.example.wiremock.luukuresponse.Name;
import com.example.wiremock.luukuresponse.StreetAddresses;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;
import com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilterAction;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;

public class LuukuResponseTransformer extends ResponseDefinitionTransformer{
	
	@Autowired
	LuukkuBasicInfoResponse luukkuBasicInfoResponse;

	
	public static String decodeJwt(String token) throws UnsupportedEncodingException {
		String payload = token.split("\\.")[1];
		return new String(Base64.decodeBase64(payload), "UTF-8");
	}
	

     @Override
     public String getName() {
         return "example";
     }

	@Override
	public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files,
			Parameters parameters){

		  
     	String authtoken = request.header("Authorization").firstValue();
    	
     	ObjectMapper objectMapper = new ObjectMapper();

 		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

 		String str;
 		
 		Token token;
				
				String pattern = "^\\S{4}68-\\S{4}$";
				
				try {
					str = decodeJwt(authtoken);
					token = objectMapper.readValue(str, Token.class);
					String ssn = token.getRepresentation().getId();

				
				StreetAddresses streetAddresses= new StreetAddresses();
				 streetAddresses.setType("1");
				 streetAddresses.setAddressCategory("1");
				 streetAddresses.setAddressLine("Ansatie 2 L 3"+"SSN");
				 streetAddresses.setPostalCode("1740");
				 streetAddresses.setCity("VIENA");
				 streetAddresses.setCountry("Vienna");
				 streetAddresses.setValidMailingAddress(true);
				 streetAddresses.setStartDate("23-09-2022");
				 streetAddresses.setChangeTimestamp("ABC");
				 streetAddresses.setLastModifierId("12");
				 ArrayList<StreetAddresses> streetAddresseLists = new ArrayList<StreetAddresses>();//NOSONAR
				 streetAddresseLists.add(streetAddresses);
			   
			   Name names = new Name("00060","Arisalo "+"SSN ","ki "+"SSN ","Arisalo Ki");
			   ArrayList<Name> namesList = new ArrayList<Name>();//NOSONAR
			  namesList.add(names);

			  		   
			   Individual individual = new Individual();
			   individual.setCustomerId(ssn);
			   individual.setResponsibleBank("599869");
			   individual.setLanguageCode("FI");
			   individual.setHomeCountry("FI");
			   individual.setSector("FI");
			   individual.setLegalForm("143");
			   individual.setPlaceOfDomicile("FI");
			   individual.setTaxCountry("FI");
			   individual.setTaxCode("0");
			   individual.setStreetAddresses(streetAddresseLists);
			   individual.setPhoneNumbers(null);
			   individual.setElectronicAddresses(null);
			   individual.setIndividualIdentifications(null);
			   individual.setGenderType("N");
			   individual.setNationalityCode("FI");
			   individual.setOccupation("");
			   individual.setOccupationBranch("FI");
			   individual.setOccupationPosition("ST");
			   individual.setLifeSituation("34");
			   individual.setNames(namesList);
			   
			   LuukkuBasicInfoResponse luukkuBasicInfoResponse = new LuukkuBasicInfoResponse();
				 luukkuBasicInfoResponse.setIndividual(individual);	
				
				
	    return new ResponseDefinitionBuilder()
	        .withBody(Json.write(luukkuBasicInfoResponse))
	        .withStatus(200)
	        .withHeader("Content-Type", "application/json")
	        .build();
					
				} catch (UnsupportedEncodingException | JsonProcessingException e) {
					e.printStackTrace();
				}
				return null;

				

	}

}
b

Bas Dijkstra

05/14/2023, 11:20 AM
I’ll try and have a closer look tomorrow
s

Shruti Mishra

05/14/2023, 11:21 AM
Okay
b

Bas Dijkstra

05/14/2023, 11:53 AM
Hmmm.. I just had a closer look right now (had to open Slack on my laptop anyway) but I don’t think I can help out here.
s

Shruti Mishra

05/14/2023, 12:01 PM
Okay @Bas Dijkstra no issues
5 Views