How to validate a form in play framework - playframework-2.5

I want do validate a form after filling with a json object.
By stepping throw the code I see the correct values in the Post Object but I will get no errors if the title is under 5 chars. Why, had some one an idea?
#Constraints.Required
#Constraints.MinLength(5)
private String title;
Post post = Json.fromJson(json, Post.class);
if(postForm.hasErrors()){

/*
example
*/
private FormFactory formFactory;
#Inject
YourContructor(FormFactory formFactory){
this.formFactory
}
#BodyParser.Of(value = BodyParser.Json.class)
public static Result create() {
JsonNode json = request().body().asJson();
Form<Post> post= formFactory.form(Post.class).bind(json);
if(post.hasErrors()){
return badRequest(post.errorsAsJson());
}
return ok(json);
}

Related

How to test repository without entity setters

I could use a constructor, but I want another way considering the case with many parameters.
Also, I don't want to change private fields to public.
please help me
#Test
#DisplayName("save the post")
void savePost() {
// Arrange
String title = "title...";
String contents = "contents...";
Post post = new Post(title, contents);
// Act
Post savedPost = postRepository.save(post);
...

How to get two attributes of a model in the same HTML file

Code
#RequestMapping(value = "/cars", params = "request")
public String showSomeAmountCars(HttpServletRequest request, Model model) {
String count = request.getParameter("count");
int parsedCount = Integer.parseInt(count);
model.addAttribute("someCars", carService.getCars(parsedCount));
return "cars";
}
In the method showSomeAmountCars I get some number of cars using parameter in URL link.
In the method showAllCars I get the whole list of cars.
Expected behavior
if I request /cars, then I get the list of cars from the HTML file
if I request /cars?count = 2, then I get the list of two cars from the same HTML file
Question
How can I get the two added attributes in the HTML file and make sure they don't conflict?
You can have an optional request parameter like this:
#GetMapping("/cars")
public String showSomeAmountCars(#RequestParam(name = "cars", required = false) Integer count, Model model) {
if( count == null ) {
model.addAttribute("cars", carService.getCars());
} else {
model.addAttribute("cars", carService.getCars(count));
}
return "cars";
}

Execute a simple call to a WebAPI Get using RestRequest and a single string parameter

I have the following code in my receiving controller:
[Route("api/StudentUserId/{string}"), HttpGet]
public StudentDto StudentUserId(string userId)
{
StudentModel sm = new StudentModel(userId);
StudentDto dto = sm.ConvertToDto();
return dto;
}
After running this project, I have another project that I use to test the WebAPI controller calls. I use the following code to read a student record form the database using their userId:
protected T SendRequestToReadItemUsingString<T>(string resource, string userId) where T : new()
{
string resourceString = string.Format("{0}/{{userId}}", resource);
RestRequest request = new RestRequest(resourceString, Method.GET);
request.AddUrlSegment("userId", userId);
RestClient restClient = new RestClient(Service.Location);
var response = restClient.Execute<T>(request);
T retVal = response.Data;
return retVal;
}
Comparible code seems to work if I change the userId to an int Id in both the controller and calling code. I can't seem to get it to work with string. If I place a breakpoint in the controller code it never hits it and the calling code just returns a null.
Thanks for your help
Please note that WebApi works based on reflection this means that your curly braces {vars} must match the same name in your methods.
Therefore to match this api/StudentUserId/{string} your method needs to be declare like this:
[Route("api/StudentUserId/{userId}"), HttpGet]
public StudentDto StudentUserId(string userId)
return userId;
}
Where the parameter {string} was replaced by userId.
If you want to read more about this Routing Rules here is similar post on this;
WebApi Routing Configuration

Post Binary array to Web API Controller

I am trying to POST form data which consists of few string variable and binary array.
Below is the Model for the form data.
public class FileModel
{
public string Path { get; set; }
public byte[] File { get; set; }
}
Below is my Web API Controller.
[Route("")]
public IHttpActionResult Post([FromBody]FileModel media)
{
// Can I use ??
byte[] requestFile = media.File;
string requestFilePath = media.Path;
//Process the above variables
return Ok();
}
I would like to know Can I use the following code to de-serialize the following code snippet to to read the values from the JSON payload including the binary data?
byte[] requestFile = media.File;
string requestFilePath = media.Path;
If Yes, Do I need to define any formatter class to get it working?
I normally use POSTMAN to test my RESTful endpoints.
Is it possible to use POSTMAN still to POST binary array? May be not need to write my own client
You'll need to use a serializer to serialize complex objects (multiple fields) as content for a Http Request.
For your code snippet to read the object from the content you can use this:
var requestContent = Request.Content.ReadAsAsync<FileModel>(GetJsonSerializer()).Result;
Here's the serializer boilerplate code.
private JsonMediaTypeFormatter GetJsonSerializer()
{
JsonSerializerSettings settings = new JsonSerializerSettings()
{
PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All,
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All
};
return new JsonMediaTypeFormatter() { SerializerSettings = settings };
}
I'm not sure how to use POSTMAN to test this. A simple .net client would be:
var Client = new HttpClient();
Client.BaseAddress = new Uri("localhost"); //whatever your endpoint is
FileModel objectToSend = new FileModel();
var objectContent = new ObjectContent<FileModel>(objectToSend, GetJsonSerializer() );
var response = Client.PostAsync("uri", objectContent);
You are able to use POSTMAN to test binary file input. Selecting the body tab, you can then pick the radio button "binary" and then choose file.

ASP.NET MVC 3 Parse JSon object and display data

I have a class
public class ConversionResultModel
{
public string ProcessId { get; set; }
public bool Result { get; set; }
public string Message { get; set; }
}
sending it to view using JSon
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> clientUpload)
{
string destinationPath = "";
JsonResult result = null;
var fileModel = new ConversionResultModel();
fileModel.ProcessId = "4558-95559-554";
fileModel.Result = true;
fileModel.Message = "test.pdf";
result = Json(new { fileModel }, "text/plain");
return result;
}
How to parse such JSon object at client side using JS or jQuery and read values?
I have tried to parse JSon object with code below but get Undefined error in alert
var obj = $.parseJSON(e.response);
alert(e.obj);
I receive JSon object like this
{"fileModel":{"ProcessId":"4558-95559-554","Result":true,"Message":null,"SourceFile":null,"ConvertedFileName":"test.pdf","ConvertedFileSize":1233444,"DownloadUrl":"http://localhost:2008/download?path=4558-95559-554","DeleteUrl":"http://localhost:2008/download?path=4558-95559-554"}}
You do not need to parse it. Just set data type to JSON during ajax request and then use received data object like entity and you easily can access to any property:
var id = data.ProcessId;
Anyway, using jQuery you can parse JSON string:
var data = jQuery.parseJSON(stringData);
P.S:
Use the following code sample for converting object to JSON in ASP.NET MVC:
return this.Json(fileModel);
http://api.jquery.com/jQuery.parseJSON/
In your case, I think you're getting back the correct JSON, but your alert is looking at the wrong object. Try alert(obj.SomeProperty) rather than alert(e.obj). e.obj doesn't exist, which is likely why you're getting an "undefined" error. For example, alert(obj.fileModel.ProcessId); should work.

Resources