How to call a Put method from a Post method in the rest controller - spring

i have 2 methods, the first one is a PUT method and the second one is a POST method and i want to call the first one in the second one but it doesn't work.
Here's my code :
PUT Method
#PutMapping("/classifs")
public ResponseEntity<Classif> updateClassif(#Valid #RequestBody Classif classif) throws URISyntaxException {
Classif result = classifRepository.save(classif);
return ResponseEntity.ok();
}
POST Method
#PostMapping(value = "/classifs/maj", headers = "accept=application/json")
public void tableauClassif(#RequestBody ClassificationHolder classificationHolder) {
for(ClassifLineHolder line : classificationHolder.getDetails()){
for(Classif c : line.getMapClassif().values()){
if(c.getId() != null && c.getId() !=0)
this.updateClassif(c); //this i what i tried to do but it does'nt work !!
else
classifRepository.save(c);
}
}
}

Related

How to extract path variable in citrus simulator framework for multiple scenario?

#Scenario("MyRestServiceScenario")
#RequestMapping(value = "/services/rest/simulator/{StudentId}", method = RequestMethod.GET)
public class MyRestServiceSimulator extends AbstractSimulatorScenario {
#Override
public void run(ScenarioDesigner scenario) {
scenario
.http()
.receive()
.get()
scenario.conditional().when(/*StudentId == something*/).actions(
scenario.http()
.send()
.response(HttpStatus.OK)
.payload(new ClassPathResource(template1.json))
);
scenario.conditional().when(/*StudentId == something*/).actions(
scenario.http()
.send()
.response(HttpStatus.NOT_FOUND)
.payload(new ClassPathResource(template2.json))
);
scenario.conditional().when(/*StudentId == something*/).actions(
scenario.http()
.send()
.response(HttpStatus.CREATED)
.payload(new ClassPathResource(template3.json))
);
}
}
On the basis of path variable of URI I need to return some responses. I am not getting any way to that. Same thing for Delete request. Is there any way I can fetch that variable or that URL so I can use that variable in scenario and return responses according to Path variable?

ASP.NET 5, MVC 6, API response status

I have a controller in my MVC 6 API project. There is a post method and what I want is to validate posted value and return some error back to a client if data are not valid.
[HttpPost]
public void Post([FromBody]PostedHistoricalEvent value)
{
if (!IsHistoricalEventValid(value))
{
//return error status code
}
}
Now I wonder why Post method in the default template does not have any returning type but void and how then one should return an error http status code with some message?
An action method that has no return type (void) will return an EmptyResult, or an 200 OK without a response body.
If you want to alter the response, then you can either change the return type and return an HttpStatusCodeResult:
public IActionResult Post(...)
{
// ...
return new HttpStatusCodeResult(400);
}
Or set it on the Controller.Response:
public void Post(...)
{
// ...
Response.StatusCode = 400;
}

Can XUnit handle tests handle class and decimal parameters in the same method?

I have a test method with the following signature:
public void TheBigTest(MyClass data, decimal result)
{
And I'd like to run this in XUnit 2.1. I've got my CalculationData class all set up and that works if I remove the second parameter. But when I try to pass in the expected result as a second parameter by doing:
[Theory, ClassData(typeof(CalculationData)), InlineData(8893)]
It doesn't work. The test fails with a:
The test method expected 2 parameter values, but 1 parameter value was
provided.
Any ideas?
The class specified in the ClassData attribute needs to be an enumerable class that returns all of the parameters for the test method, not just the first one.
So, in your example, you would need something like:
public class CalculationData : IEnumerable<object[]>
{
IEnumerable<object[]> parameters = new List<object[]>()
{
new object[] { new MyClass(), 8893.0m },
new object[] { new MyClass(), 1234.0m },
// ... other data...
};
public IEnumerator<object[]> GetEnumerator()
{
return parameters.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
You can then add parameters to your MyClass class to enhance your test data.

Understanding Get Method Overrides

I am totally new to Web API an am not understanding how to Filter get calls.
This method returns all items in my database.
// GET: api/LogEntries
public IQueryable<LogEntry> GetLogEntries()
{
return db.LogEntries;
}
This method returns a specific item in my database.
// GET: api/LogEntries/5
[ResponseType(typeof(LogEntry))]
public IHttpActionResult GetLogEntry(int id)
{
LogEntry logEntry = db.LogEntries.Find(id);
if (logEntry == null)
{
return NotFound();
}
return Ok(logEntry);
}
So now I want to filter the returned records so I created this method but it won't work because the specific item method gets called. I seem to be missing a concept and am hoping you can point me to more clear understanding. Thanks
// GET: api/LogEntries
public IQueryable<LogEntry> GetLogEntries(string levelID)
{
int levIdInt;
if (Int32.TryParse(levelID, out levIdInt))
{
return db.LogEntries.Take(300).Where(l => (int)l.Level == levIdInt).OrderByDescending(d => d.TimeStamp);
}
return db.LogEntries.Where(i => i.ID < 0);
}
You need to specify the route for that method
[Route("api/LogEntries/Level/{levelID}"]
public IQueryable<LogEntry> GetLogEntries(string levelID)
{}
More on routing is available here http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

What I am supposed to return from a server-side method called by ajax?

I have the following jQuery script:
$(document).ready(function() {
$("#resendActivationEmailLink").bind("click", function(event) {
$.get($(this).attr("href"), function() {
$("#emailNotActivated").html("<span>not yet activated. email sent!</span>");
}, "html");
event.preventDefault();
});
});
Basically, when a user clicks a link the following server-side method is invoked:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
String resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
return "dummy";
}
and some business logic is executed on the server but there is no real outcome from the server to be used on the client/browser side apart from an ajax success or an ajax failure.
Now what I am really not sure about is what my server-side method is supposed to return!
Currently it just returns the string dummy but of course this is only temporary. Should I go for no return type (void) or null or something else??
Note that I can change the datatype parameter of the jQuery get method.
EDIT:
I have altered my server-side method as follows:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET)
public #ResponseBody void resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
}
#ResponseBody is required because this is an ajax call.
There is no point in returning a dummy value in this case. If you are not doing anything with the return value, then you can just do something like this:
#RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET)
#ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void resendActivationEmail(#PathVariable String token) {
preferencesService.resendActivationEmail(token);
}
There will be a 204 response code instead of a 200 but that should be fine.
I'm assuming you are returning JSON from the server (from your server code: produces = "application/json").
Since you don't care about what gets returned, i.e. you are not handling the return value in your callback function, after $.get, then you can just return "{}", or if you want to handle the response you can go with something like:
{ "success": true }
// or
{ "error": "Error messages here" }

Resources