Play framework error: not found: value message - java

I have a route, controller and view defined. When I do a get request for the home directory, which is "/", I am getting the error not found: value message. index.scala.html:2.
routes:
GET / controllers.HomeController.index(message: String, name: String)
GET /count controllers.CountController.count
GET /message controllers.AsyncController.message
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
index.scala.html:
#(name: String)
#(message: String)
#main("Welcome to Sparta") {
#welcome(message, style = "java")
}
HomeController.java:
package controllers;
import play.mvc.*;
import play.*;
import views.html.*;
import java.util.Date;
public class HomeController extends Controller {
public String name;
public String message;
public Result index(String name, String message) {
name = "TEST NAME";
message = "Test message";
return ok(name, "message: " + message);
}
}
Why is the error telling me I have not defined a value for message?

Your route and index method in the controller is not correct. If you are sending any parameters to the server, they come into the picture. Your URL does look like you are sending some parameter with it, so please remove parameters for the index method.
public Result index() {
name = "TEST NAME";
message = "Test message";
return ok(name, "message: " + message);
}

Related

Exception error message not display in springboot project

i try to display simple error massage for the unavailable resource of my service model by extending my class with RuntimeException but didn't display
TodoService Implementation
#Override
public String retrieveTodoStatusById(Long id) {
Optional<String> optionalTodo = Optional.ofNullable(todoRepository.findStatusById(id));
System.out.println("OptionalTodo " +optionalTodo );
String status = optionalTodo.orElseThrow(TodoNotFoundException::new);
return status;
}
TodoNotFoundException
package mang.io.todosrestapi.exceptionhandler;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
#ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Todo not available")
public class TodoNotFoundException extends RuntimeException{
public TodoNotFoundException(){
}
public TodoNotFoundException(String message){
super(message);
}
}
default error with no message is display
Every time i run the exception error message is not display
How can display the error message?
Try to add this line in your application.properties file:
server.error.include-message=always

I want to take value from one API response body and use into another api request using Cucumber gherkin

Scenario: Verify the manifest of published app
1. Given Base url "baseUrl" and path "basepath"
2. And Headers are
3. And Query parameter
4. And App with below details
5. When I execute the another API with Base url "baseUrl" and path "basePath"
6. And Append with Attributevalue (complete url will be , baseUrl + basePath + AttributeValue )
7. And api headers
8. And query parameters
9. Then Success message with 200 status code
I have implemented something very similar recently. You can utilize below code and modify it to your need. You'll probably need to omit some steps from your feature . Those steps are included as part of step def implementation in below code
Feature
#get
Scenario: get employee
Given an employee exist in the database with id "2"
When user retrieves employee info by id
Then the status code for get employee is 200
StepDefs
import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.And;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
public class secondIT {
public static Response response;
public static ValidatableResponse json;
public static RequestSpecification request;
public static String id;
public static JsonPath jsonPathEvaluator;
#Given("an employee exist in the database with id {string}")
public void an_employee_exists_with_id(String ID){
secondIT.id=ID;
RestAssured.baseURI = "http://dummy.www.com/api/v1";
secondIT.request = RestAssured.given();
}
#When("user retrieves employee info by id")
public void user_retrieves_employee_info_by_id(){
secondIT.response = secondIT.request.pathParam("id", secondIT.id).get("/employee/{id}");
secondIT.jsonPathEvaluator = secondIT.response.jsonPath();
assertNotNull(response);
}
#Then("the status code for get employee is {int}")
public void verify_status(int sc){
System.out.println("status code check.. " );
secondIT.json = secondIT.response.then().statusCode(sc);
System.out.println("status code: " + secondIT.response.getStatusCode());
assertEquals(sc,secondIT.response.getStatusCode());
}
}

Updating specific part of value in hash map dynamically

I have a spring boot app with a HTTP post request handler. It accepts a payload that I parse and outputs a JSON. I have handled it that it needs to accept a payload of certain parameters(18).
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
#Validated
#RestController
public class MockController {
#Autowired
MockConfig mockconfig;
private static final Logger LOGGER = LoggerFactory.getLogger(MockController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "hello!";
}
String[] parse;
#PostMapping(value = "/")
public String payloader(#RequestBody String params ) throws IOException{
LOGGER.debug("code is hitting");
parse = params.split("\\|");
String key;
String value;
String dyn;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<?, ?> resultJsonObj = new Gson().fromJson(value, Map.class);
}
else {
key = params;
value = predictionFeatureMap.get(key);
}
return value;
}
}
My config class is where I get the input and output from a file and put them into a hashmap.
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.springframework.context.annotation.Configuration;
#Configuration
public class MockConfig {
private Map<String, String> predictionFeatureMap = new HashMap<String, String>();
public Map<String,String> getPredictionFeatureMap() throws IOException {
return predictionFeatureMap;
}
public MockConfig() throws IOException {
init();
}
private Map<String, String> init() throws IOException {
Scanner sc = new Scanner (new File("src/test/resources/Payload1.txt"));
int counter = 1;
String key = "";
while (sc.hasNextLine()) {
if(counter % 2 != 0) {
key = sc.nextLine();
}else {
predictionFeatureMap.put(key, sc.nextLine());
}
counter++;
}
sc.close();
return predictionFeatureMap;
}
}
This is the key and value in the file that I'm trying to work with specifically.
Not_enough_parameters
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:8", "version": "0.97", "coreName": "Patient_Responsibility"}
(The JSON string is the response to too much or too little parameters... the paramter length should be 18.)
Example input:
ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0
This input would pass because it has 18 parameters...
What I want to do is if a user curls for example 5 parameters
ncs|56-2629193|1972-03-28|20190218|77067
I want the value(JSON error message) to have the 'actual' field updated like:
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:5", "version": "0.97", "coreName": "Patient_Responsibility"}
without hardcoding it into the txt file or hashmap...
I have tried getting the index of the string and replacing the '8' character with parse.length() and casting it as a char but it just gives me this output:
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting:1 actual:", "version": "0.97", "coreName": "Nulogix_Patient_Responsibility"}
How do I parse or index the JSON to update this value? Or is there a hashmap method to deal with this?
When working with a framework, you usually handle errors using the frameworks way of handling errors.
To handle errors in spring boot you typically use a controller advice that will assist in handling errors. This is created by annotating a class with #ControllerAdvice.
There you can catch thrown exceptions and build responses that will be returned to the calling client.
#PostMapping(value = "/")
public String payloader(#RequestBody String params ) throws IOException{
LOGGER.debug("code is hitting");
parse = params.split("\\|");
String key;
String value;
String dyn;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
// Here you throw a custom runtime exception and pass what
// parameters you want that will help you build your error
// message you are passing to your client.
final String errorMessage = String.format(
"Payload has incorrect amount of parts: expecting:%d actual:%d",
predictionFeatureMap.size(),
parse.length);
throw new MyException(errorMessage);
}
else {
key = params;
value = predictionFeatureMap.get(key);
}
return value;
}
Then in a controller advice class
#ControllerAdvice
public class Foo extends ResponseEntityExceptionHandler {
#ExceptionHandler(MyException.class)
public ResponseEntity<MyCustomErrorBody> handleControllerException(HttpServletRequest request, MyException ex) {
// Build your error response here and return it.
// Create a class that will represent the json error body
// and pass it as body and jackson will deserialize it for
// you into json automatically.
final MyCustomErrorBody body = new MyCustomErrorBody(false, ex.getMessage(), "0.97", "Patient_Responsibility")
return ResponseEntity.unprocessableEntity().body(myCustomErrorBody).build();
}
}
public class MyCustomErrorBody {
private boolean status;
private String errorMessage;
private String version;
private String coreName;
// constructor and getters setters ommitted
}
Links about spring boot error handling:
Official spring boot documentation
Baeldung exception-handling-for-rest-with-spring

How to trap the 413 error in Play Framework?

I want to return a JSON response instead of HTML.
I dont know how to trap it.
For example i set the 'play.http.parser.maxMemoryBuffer' to 1MB, and if the request body will exceed 1 MB, it will return a JSON response but not HTML format saying that it is a bad response.
According to the documentation:
To switch from HTML to JSON response you can add this line to application.conf
play.http.errorHandler = play.http.JsonHttpErrorHandler
If you also want to customize the message, you should instead add this line to application.conf
play.http.errorHandler = "com.example.ErrorHandler"
Obviously, the line above, should point to your own implementation of the error handler, that could look like this:
package com.example
import play.http.HttpErrorHandler;
import play.mvc.*;
import play.mvc.Http.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Singleton;
#Singleton
public class ErrorHandler implements HttpErrorHandler {
public CompletionStage<Result> onClientError(RequestHeader request, int statusCode, String message) {
if (statusCode == 413) {
return CompletableFuture.completedFuture(Results.status(statusCode, "A client error occurred: " + message + " The payload size should be lower than 1Mb."));
} else {
return CompletableFuture.completedFuture(Results.status(statusCode, "A client error occurred: " + message));
}
}
public CompletionStage<Result> onServerError(RequestHeader request, Throwable exception) {
return CompletableFuture.completedFuture(
Results.internalServerError("A server error occurred: " + exception.getMessage()));
}
}

jersey #PathParam: how to pass a variable which contains more than one slashes

package com.java4s;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("/customers")
public class RestServicePathParamJava4s {
#GET
#Path("{name}/{country}")
#Produces("text/html")
public Response getResultByPassingValue(
#PathParam("name") String name,
#PathParam("country") String country) {
String output = "Customer name - "+name+", Country - "+country+"";
return Response.status(200).entity(output).build();
}
}
In web.xml I have specified URL pattern as /rest/* and in RestServicePathParamJava4s.java we specified class level #Path as /customers and method level #Path as {name}/{country}
So the final URL should be
http://localhost:2013/RestPathParamAnnotationExample/rest/customers/Java4/USA
and the response should be displayed as
Customer name - Java4, Country - USA
If I give the 2 input given below it is showing an error. How to solve this?
http://localhost:2013/RestPathParamAnnotationExample/rest/customers/Java4:kum77./#.com/USA`
Here Java4:kum77./#.com this one is one string and it contains forward slash. how to accept this by using #PathParam or whatever I need to use MultivaluedMap. If somebody knows this plz help me. if anyone knows what is MultivaluedMap, give me a simple example?
You'll need to use a regex for for the name path expression
#Path("{name: .*}/{country}")
This will allow anything to be in the name template, and the last segment will be the country.
Test
#Path("path")
public class PathParamResource {
#GET
#Path("{name: .*}/{country}")
#Produces("text/html")
public Response getResultByPassingValue(#PathParam("name") String name,
#PathParam("country") String country) {
String output = "Customer name - " + name + ", Country - " + country + "";
return Response.status(200).entity(output).build();
}
}
$ curl http://localhost:8080/api/path/Java4:kum77./#.com/USA
Customer name - Java4:kum77./#.com, Country - USA
$ curl http://localhost:8080/api/path/Java4/USA
Customer name - Java4, Country - USA

Categories