Why methods doesn't see values set in constructor? (Spring Boot) - spring

I have a class AuthorizationService like this:
#Service
public class AuthorizationService {
private final String code;
private final String client_id;
private final String redirect_uri;
private final String scope;
private final String show_dialog;
#Autowired
public AuthorizationService(
#Value("${spotify-property.response_type}") String code,
#Value("${spotify-property.client_id}") String client_id,
#Value("${spotify-property.redirect_uri}") String redirect_uri,
#Value("${spotify-property.scope}") String scope,
#Value("${spotify-property.redirect_uri}") String show_dialog) {
this.code = code;
this.client_id = client_id;
this.redirect_uri = redirect_uri;
this.scope = scope;
this.show_dialog = show_dialog;
System.out.println(code); //works
}
public ResponseEntity<HttpHeaders> getSpotifyRedirectionCode() {
HttpHeaders headers = new HttpHeaders();
System.out.println(client_id); //doesn't work
System.out.println(this.code); //does not work either
System.out.println(redirect_uri);
System.out.println(scope);
System.out.println(show_dialog);
//more code doesn't matter
return new ResponseEntity<>(headers, HttpStatus.TEMPORARY_REDIRECT);
}
Why these variables are ok in constructor but in methods are null, how to set them in correct way? Also
#Value("${spotify-property.response_type}")
private final String code;
does not work either.

Your class fields are final so get instantiated without your configuration values.
You can either use the constructor as you have before, or remove the final from your fields.

I'm not sure if my answer is 100% correct. But I believe that you cannot change final variables. The right way would be to remove the final keyword and keep the #Value annotations on the fields and the you don't have to use it in the constructor.
#Service
#RequiredArgsConstructor
public class AuthorizationService {
#Value("${spotify-property.response_type}")
private String code;
#Value("${spotify-property.client_id}")
private String client_id;
#Value("${spotify-property.redirect_uri}")
private String redirect_uri;
#Value("${spotify-property.scope}")
private String scope;
#Value("${spotify-property.redirect_uri}")
private String show_dialog;
public ResponseEntity<HttpHeaders> getSpotifyRedirectionCode() {
HttpHeaders headers = new HttpHeaders();
System.out.println(client_id); //works
System.out.println(this.code); //works too
System.out.println(this.redirect_uri);
System.out.println(this.scope);
System.out.println(this.show_dialog);
//more code doesn't matter
return new ResponseEntity<>(headers, HttpStatus.TEMPORARY_REDIRECT);
} }

Related

How to generate cache CustomKey for Redis in Spring Boot

I have spring boot application which is integrated with Redis cache. Have to implement caching for one of the method call. That method argument is an object with multiple params which is external Request object. This object params will vary for each request also based on that param and its values output of the method is varies. I need to create a cache key using that Request object field/param values. How to achieve it.
We can use SimpleKeyGenerator only when method params are static?
UserService.java
#Cacheable(value = "usercache", keyGenerator="customKeyGenerator")
public UserResponse getUserResp(User user){
//Some backend calls
return user
}
User.java
public class User {
private String firstname;
private String lastname;
private Integer age;
private Date dob;
private Address address;
// Another 10 params
}
In this method implementation User object is dynamic. I have to create a cache key based on User object fields which is having valid non null values. How to achieve it.
I have implemented as like below.
User.java
public class User implements Serializable {
private String firstname;
private String lastname;
private Integer age;
private Date dob;
private Address address;
// Another 10 params
#Override
public int hashCode() {
final int prime = 31;
//Add necessary fields
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
//Add necessary fields
}
}
public class UserKeyGenerator implements KeyGenerator{
private static final String UNDERSCORE_DELIMITER = "_";
#Override
public Object generate(Object target, Method method, Object... params) {
String cacheKey = null;
if(params.length > 0) {
StringJoiner paramStrJoiner = new StringJoiner(UNDERSCORE_DELIMITER);
User userReq = (User) params[0];
paramStrJoiner.add(target.getClass().getSimpleName());
paramStrJoiner.add(method.getName());
paramStrJoiner.add(String.valueOf(userReq.hashCode()));
cacheKey = paramStrJoiner.toString();
}
return cacheKey;
}

Spring Controller Test: Postman vs JUnit - Field error request rejected value [null]

I'm a beginner on Spring framework, trying to test the Controller.
The funny thing is, using Postman, I got the correct response, but not in JUnit where receive Actual :400 (bad request) instead of Expected :200.
This is due to empty field passengerCount because appears null. The class of the request is different of the response. This latter doesn't have a field for the passenger.
Controller
#Validated
#RestController
#RequestMapping("flights")
public class BusyFlightsController {
CrazyAirDatabase crazyAirService;
#Autowired
public BusyFlightsController(CrazyAirDatabase crazyAirService) {
this.crazyAirService = new CrazyAirDatabase();
}
#RequestMapping(value = "/crazy-air-response", method = RequestMethod.GET, produces = "application/json")
public List<CrazyAirResponse> getCrazyAirResponse(
#Valid CrazyAirRequest crazyAirRequest,
#RequestParam("origin") String origin,
#RequestParam("destination") String destination,
#RequestParam("departureDate") String departureDate,
#RequestParam("returnDate") String returnDate,
#RequestParam("passengerCount") int passengerCount
) {
crazyAirRequest = new CrazyAirRequest(origin, destination, departureDate, returnDate,
passengerCount);
return crazyAirService.getCrazyAirResponse(crazyAirRequest);
}
}
CrazyAirRequest class
public class CrazyAirRequest {
#IATACodeConstraint
private String origin;
#IATACodeConstraint
private String destination;
private String departureDate;
private String returnDate;
private int passengerCount;
public CrazyAirRequest(String origin, String destination, String departureDate,
String returnDate, int passengerCount) {
this.origin = origin;
this.destination = destination;
this.departureDate = departureDate;
this.returnDate = returnDate;
this.passengerCount = passengerCount;
}
// Getters
}
CrazyAirResponse class
public class CrazyAirResponse {
private String airline;
private double price;
private String cabinClass;
private String departureAirportCode;
private String destinationAirportCode;
private String departureDate;
private String arrivalDate;
public CrazyAirResponse(String airline, double price, String cabinClass, String departureAirportCode,
String destinationAirportCode, String departureDate, String arrivalDate) {
this.airline = airline;
this.price = price;
this.cabinClass = cabinClass;
this.departureAirportCode = departureAirportCode;
this.destinationAirportCode = destinationAirportCode;
this.departureDate = departureDate;
this.arrivalDate = arrivalDate;
}
// Getters
}
Repo CrazyAirDatabase
#Component
public class CrazyAirDatabase implements CrazyAirService {
List<CrazyAirResponse> list;
public CrazyAirDatabase() {
list = new ArrayList<>(
Arrays.asList(
new CrazyAirResponse("Ryanair", 125, "E", "LHR",
"BRN", "2018-10-08", "2020-10-08")
);
}
#Override
public List<CrazyAirResponse> getCrazyAirResponse(CrazyAirRequest request) {
return list.stream()
.filter(t -> t.getDepartureAirportCode().equals(request.getOrigin()) &&
t.getDestinationAirportCode().equals(request.getDestination()) &&
t.getDepartureDate().equals(request.getDepartureDate()) &&
t.getArrivalDate().equals(request.getReturnDate())
)
.collect(Collectors.toList());
}
}
Test
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class BusyFlightsControllerTest {
#Autowired
MockMvc mockMvc;
#Mock
CrazyAirRequest crazyAirRequest;
#InjectMocks
private BusyFlightsController controller;
#Mock
CrazyAirService service;
#Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Test
public void testino() throws Exception {
crazyAirRequest = new CrazyAirRequest("LHR",
"BRN", "2018-10-08", "2020-10-08", 120);
List<CrazyAirResponse> crazyAirResponse = Arrays.asList(new CrazyAirResponse("Ryanair", 125,
"E", "LHR",
"BRN", "2018-10-08", "2020-10-08")
);
when(service.getCrazyAirResponse(crazyAirRequest)).thenReturn(crazyAirResponse);
ObjectMapper objectMapper = new ObjectMapper();
String airplane = objectMapper.writeValueAsString(crazyAirResponse);
ResultActions result = mockMvc.perform(get("/flights/crazy-air-response")
.contentType(MediaType.APPLICATION_JSON)
.content(airplane)
);
result.andExpect(status().isOk());
}
}
If I put this:
ResultActions result = mockMvc.perform(get("/flights/crazy-air-response?origin=LHR&destination=CTA&departureDate=some&returnDate=some&passengerCount=1")
.contentType(MediaType.APPLICATION_JSON)
.content(airplane)
);
Test is passed.
Then, need I perform Postman first, and after to copy and paste the query to pass the test?

Spring Boot marshall Xml from RestTemplate without RootElement

I am using a RestTemplate like this:
return this.getForEntity(baseUrl, BasicResponse.class, parameters);
This is the BasicResponse class:
public class BasicResponse {
private String status;
private String statusMsg;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusMsg() {
return statusMsg;
}
public void setStatusMsg(String statusMsg) {
this.statusMsg = statusMsg;
}
}
No exceptions are thrown but the fields in the returned ResponseEntity body are 'null'. I think it's because the element does not have a valid XML structure (as in no root element). I do not have control over the parsed XML. How can I map my object?
Since the XML is not valid,
I believe that you will not be able to use RestTemplate.getForEntity
to get a BasicResponse object.
Try this:
private static final String VALUE_END_TAG = "</blammy>";
private static final String VALUE_START_TAG = "<blammy>";
private XmlMapper xmlMapper; // initialize this correctly, somewhere off page.
method stuff
{
final String actualResponse;
final StringBuilder correctedResponse = new StringBuilder();
final BasicResponse returnValue;
actualResponse = restTemplate.getForEntity(baseUrl, BasicResponse.class, parameters);
correctedResponse.append(VALUE_START_TAG);
correctedResponse.append(actualResponse);
correctedResponse.append(VALUE_END_TAG);
returnValue = xmlMapper.readValue(correctedResponse.toString(), BasicResponse.class);
return returnValue;
}
Use some reasonable value as the element name in the start and end tags,
perhaps "" and "".
Consider using some Jackson annotations,
for example #JacksonXmlRootElement(localName = "blammy")
(this local name matches my example).

Spring Boot request body semi-required fields

In our application user can write a message based on user id or screen name.
class Message {
public final Long userId;
public final String screenName;
public final String text;
#JsonCreator
public Message(#JsonProperty(value = "user_id", required = ???) Long userId,
#JsonProperty(value = "screen_name", required = ???) String screenName,
#JsonProperty(value = "text", required = true) String text) {
this.userId = userId;
this.screenName = screenName;
this.text = text;
}
}
Fields userId and screenName can't be optional at same time, one should be provided.
How in Spring Boot to mark that they are semi-required?
This seems like more of a validation concern rather than deserialization.
Create a Validator then put #Valid within the #RequestMapping on the controller.
See more here:
Spring REST Validation Example
From jenkov tutorials:
#JsonValue
The Jackson annotation #JsonValue tells Jackson that Jackson should
not attempt to serialize the object itself, but rather call a method
on the object which serializes the object to a JSON string. Note that
Jackson will escape any quotation marks inside the String returned by
the custom serialization, so you cannot return e.g. a full JSON
object. For that you should use #JsonRawValue instead (see previous
section).
The #JsonValue annotation is added to the method that Jackson is to
call to serialize the object into a JSON string. Here is an example
showing how to use the #JsonValue annotation:
public class PersonValue {
public long personId = 0;
public String name = null;
#JsonValue
public String toJson(){
return this.personId + "," + this.name;
}
}
The output you would get from asking Jackson to serialize a
PersonValue object is this:
"0,null"
So you can use #JsonValue and put your code either to ignore or not from some fields when you try to convert into JSON
#JsonValue
public String toJson(){
//ignore fields or include them here
}
Just throw an IllegalArgumentException. The best case would be to deserialize, then run through a validator though so you separate the concerns of serialization, and domain validation.
class Message {
public final Long userId;
public final String screenName;
public final String text;
#JsonCreator
public Message(#JsonProperty(value = "user_id", required = false) Long userId,
#JsonProperty(value = "screen_name", required = false) String screenName,
#JsonProperty(value = "text", required = true) String text) {
if(userId == null && screenName == null) {
throw new IllegalArgumentException("userId or screenName must be provided.");
}
this.userId = userId;
this.screenName = screenName;
this.text = text;
}
}

#ConfigurationProperties referencing properties that themselves reference other properties

project.name=my-project
base.url=http://localhost:8080
cas.url=http://my-server:8010/cas
cas.callback.url=${base.url}/${project.name}
Basically I want to use the above in a spring-boot ConfigurationProperties but the casCallbackUrl is always null.
#Component
#ConfigurationProperties(prefix = "cas")
#Getter
#Setter
public class CasSettings {
#NotBlank
private String url; //this is resolved correctly
#NotBlank
private String callbackUrl; //callbackUrl is null
}
update
Well I got it working by camelCasing the property names, but according to the documentation you should be able to use dot notation for property names.
from:
cas.callback.url=${base.url}/${project.name}
to:
cas.callbackUrl=${base.url}/${project.name}
Why is spring-boot not picking up the dot notation?
The dot represents a separate object within the configuration properties object. cas.callback-url would work.
Spring relaxed property is not relaxed enugh to to transform dot notated properties to camel case fields. But you can implement it yourself easily:
#Service
#PropertySource("classpath:git.properties")
public class MngmntService implements EnvironmentAware {
private BuildStatus buildStatus;
private static final Logger LOG = LoggerFactory.getLogger(MngmntService.class);
#Override
public void setEnvironment(Environment env) {
RelaxedPropertyResolver pr = new RelaxedPropertyResolver(env, "git.");
buildStatus = new BuildStatus();
for (Field field : BuildStatus.class.getDeclaredFields()) {
String dotNotation = StringUtils.join(
StringUtils.splitByCharacterTypeCamelCase(field.getName()),
'.'
);
field.setAccessible(true);
try {
field.set(buildStatus, pr.getProperty(dotNotation, field.getType()));
} catch (IllegalArgumentException | IllegalAccessException ex) {
LOG.error("Error setting build property.", ex);
}
}
}
public BuildStatus getBuildStatus() {
return buildStatus;
}
Property object:
public class BuildStatus implements Serializable {
private String tags;
private String branch;
private String dirty;
private String commitId;
private String commitIdAbbrev;
private String commitTime;
private String closestTagName;
private String buildTime;
private String buildHost;
private String buildVersion;
...
}

Resources