Why i recived "Unable to find com.example.Api_Angular.Dao.Person with id 4" instead of "Person with this id does not exist".
#GetMapping("/persons/{id}")
public Person getPerson(#PathVariable int id)
{
Person person = personService.getPersonById(id);
System.out.println(person);
if(!(person instanceof Person))
{
throw new NoPersonException("Person with this id does not exist");
}
return person;
}
What im getting:
{
"status": 400,
"msg": "Unable to find com.example.Api_Angular.Dao.Person with id 4",
"request": "uri=/myApp/persons/4"
}
What it should be:
{
"status": 400,
"msg": "Person with this id does not exist",
"request": "uri=/myApp/persons/4"
}
My custom exception:
public class NoPersonException extends RuntimeException {
String msg;
public String getMsg() {
return msg;
}
public NoPersonException() {
}
public NoPersonException(String message) {
this.msg = message;
}
}
Error response:
#Data
#AllArgsConstructor
public class ErrorDetails {
private int status;
private String msg;
private String request;
public ErrorDetails() {
}
}
Exception controller:
#RestControllerAdvice
public class CustomizedResponseEntityExceptionHandler{
#ExceptionHandler
public ResponseEntity<ErrorDetails> response(NoPersonException e,WebRequest webRequest)
{
ErrorDetails customerErrorResponse=new ErrorDetails(HttpStatus.NOT_FOUND.value(),e.getMessage(),webRequest.getDescription(false));
return new ResponseEntity<>(customerErrorResponse,HttpStatus.NOT_FOUND);
}
#ExceptionHandler
public ResponseEntity<ErrorDetails> generalresponse(Exception e,WebRequest webRequest)
{
ErrorDetails customerErrorResponse=new ErrorDetails(HttpStatus.BAD_REQUEST.value(),e.getMessage(),webRequest.getDescription(false));
return new ResponseEntity<>(customerErrorResponse,HttpStatus.BAD_REQUEST);
}
Is there problem with type of exception which is called?
Have you any solution how to solve this problem?
Im using spring boot 2.2.
It sure looks like you are getting an EntityNotFoundException when you call personService.getPersonById(id). You should try wrapping that in a try/catch block to learn more.
Related
Using the JBPM Business Central Workbench - Ver 7.52
How do I add the data object 'definitions' to a Kie Builder when dynamically compiling a GDST?
Create a simple data object:
package com.stackoverflow.question1;
/** This class was automatically generated by the data modeler tool. */
public class message implements java.io.Serializable {
static final long serialVersionUID = 1L;
private java.lang.String status;
private java.lang.String name;
private java.lang.String message;
public message() {}
public message(java.lang.String status, java.lang.String name,
java.lang.String message) {
this.status = status;
this.name = name;
this.message = message;
}
public java.lang.String getStatus() {
return this.status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
public java.lang.String getName() {
return this.name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public java.lang.String getMessage() {
return this.message;
}
public void setMessage(java.lang.String message) {
this.message = message;
}
}
Create a GDST,looks like:
DRL Extracted from the GDST looks like :
package com.stackoverflow.question1;
//from row number: 1
//Name was null
rule "Row 1 MsgRules"
dialect "mvel"
when
MSG : message( name == null )
then
modify( MSG ) {
setMessage( "Name was null" )
}
end
//from row number: 2
//Name was not null
rule "Row 2 MsgRules"
dialect "mvel"
when
MSG : message( name != null )
then
modify( MSG ) {
setMessage( "Name was not null" )
}
end
Download the JAR and extract the contents of the KJAR:
Use 7-zip to extract the contents:
Use this code to build the GDST from scratch
public static KieContainer loadGdstIntoContainer( String gdstFileName) {
logger.info("KieUtilities:loadKieContainer - Started");
try {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
//URL resource = KieUtilities.class.getClassLoader().getResource("BaseClaim.class");
//kieFileSystem.write(ResourceFactory.newUrlResource(resource));
kieFileSystem.write(ResourceFactory.newClassPathResource("MsgRules.gdst"));
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
kieBuilder.buildAll();
if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
throw new RuntimeException("Build Errors:\n" + kieBuilder.getResults().toString());
}
KieRepository kieRepository = kieServices.getRepository();
KieContainer kieContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
logger.info("KieUtilities:loadKieContainer - Finished");
return kieContainer;
}
catch(Exception ex) {
logger.info("KieUtilities:loadKieContainer - Failed");
logger.info(ex.getLocalizedMessage());
throw ex;
}
}
How do I resolve this error:
Unable to resolve ObjectType 'message' : [Rule name='Row 1 MsgRules']
I have tried adding the following so the builder would find the data object class but that does not work.
URL resource = KieUtilities.class.getClassLoader().getResource("message.class");
kieFileSystem.write(ResourceFactory.newUrlResource(resource));
I am writing a simple get method using webclient to fetch property information. But then, I am getting below's error response message:
{
"timestamp": "2019-02-25T06:57:03.487+0000",
"path": "/modernmsg/getentity",
"status": 500,
"error": "Internal Server Error",
"message": "JSON decoding error: Cannot deserialize instance of `com.reputation.api.modernmsg.model.Entity` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.reputation.api.modernmsg.model.Entity` out of START_ARRAY token\n at [Source: UNKNOWN; line: -1, column: -1]"
}
Actual json response is:
[
{
"name": "Point Breeze",
"street": "488 Lemont Dr",
"city": "Nashville",
"state": "TN",
"postal_code": "37216",
"slug": "point-breeze"
}
]
Below is the method in my controller class to fetch property:
#RequestMapping(method = RequestMethod.GET, value = "/getentity")
public Mono<Entity> getEntity(#RequestParam("token") String token, #RequestParam("name") String name) {
return service.fetchEntity(token, name);
}
And my fetchEntity method is:
public Mono<Entity> fetchEntity(String token, String name) {
String url = host + version + entityEndpoint + "?token=" + token + "&name=" + name;
return webClient.get().uri(url).retrieve().bodyToMono(Entity.class);
}
Below is my Entity model:
package com.reputation.api.modernmsg.model;
import java.util.List;
public class Entity {
private List<ModernMsgEntity> modernMsgEntity;
public List<ModernMsgEntity> getModernMsgEntity() {
return modernMsgEntity;
}
public void setModernMsgEntity(List<ModernMsgEntity> modernMsgEntity) {
this.modernMsgEntity = modernMsgEntity;
}
}
ModernMsgEntity model is:
package com.reputation.api.modernmsg.model;
public class ModernMsgEntity {
private String name;
private String street;
private String city;
private String state;
private String postal_code;
private String slug;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostal_code() {
return postal_code;
}
public void setPostal_code(String postal_code) {
this.postal_code = postal_code;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
}
Let me know if you need more information.
This is more of a JSON deserialization problem. Looking at your entity class, you're setting things up to expect a JSON response like:
{
"modernMsgEntity": [
{
"name": "Point Breeze",
"street": "488 Lemont Dr",
"city": "Nashville",
"state": "TN",
"postal_code": "37216",
"slug": "point-breeze"
}
]
}
If you want Jackson to deserialize an array of objects directly, you have to tell it so:
Flux<ModernMsgEntity> messages = webClient.get().uri(url).retrieve().bodyToFlux(ModernMsgEntity.class);
My RestPictureServices Class
#Service
#TestProfile
public class RestPictureServices implements SahaPictureServices {
#Autowired
private PictureRepository pictureRepository;
#Autowired
private DozerBeanMapper mapper;
#Override
public Collection<SahaPicture> pictures() {
// TODO Auto-generated method stub
return null;
}
#Override
public SahaPicture pictureOfSaha(Long sahaId) {
// TODO Auto-generated method stub
return null;
}
#Override
public SahaPicture save(SahaPicture picture) {
SahaPictureEntity pictureEntity=new SahaPictureEntity();
mapper.map(picture, pictureEntity);
pictureRepository.save(pictureEntity);
SahaPicture savedPicture=new SahaPicture();
mapper.map(pictureEntity, savedPicture);
return savedPicture;
}
#Override
public Boolean delete(Long id) {
// TODO Auto-generated method stub
return true;
}
#Override
public SahaPicture update(Long id, SahaPicture picture) {
// TODO Auto-generated method stub
return null;
}
}
My SahaPictureController class
#JsonRestController
#RequestMapping(path = "/saha/picture")
public class PictureController {
#Autowired
#Qualifier("restPictureServices")
private SahaPictureServices pictureServices;
#RequestMapping(method = RequestMethod.POST)
public SahaPicture singleSave(#RequestBody SahaPicture picture) {
return pictureServices.save(picture);
}
}
My PictureSahaRepository interface
public interface PictureRepository extends CrudRepository<SahaPictureEntity,Long> {
}
My picture Model class
public class SahaPicture {
private MultipartFile file;
//getter and setter methods
}
This is SahaPictureEntity class
#Entity
#Table(name="SahaPicture")
public class SahaPictureEntity {
#Id
#GeneratedValue
private Long id;
#Column
#Lob
private MultipartFile file;
//getter and setter methods
}
My JsonRestController Annotation
#RestController
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
#Retention(RetentionPolicy.RUNTIME)
public #interface JsonRestController {
}
My Services Interface
public interface SahaPictureServices {
Collection<SahaPicture> pictures();
SahaPicture pictureOfSaha(Long sahaId);
SahaPicture save(SahaPicture picture);
Boolean delete(Long id);
SahaPicture update(Long id, SahaPicture picture);
}
My Service Configuration Class using dozer mapping jar.
#Configuration
public class ServiceConfiguration {
#Bean
public DozerBeanMapper mapper() {
return new DozerBeanMapper();
}
}
How can I insert a file or an image to db with rest full services Spring boot. I am trying to restfull services to insert a file but I have got an error
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
at [Source: java.io.PushbackInputStream#21d5ad7d; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
at [Source: java.io.PushbackInputStream#21d5ad7d; line: 1, column: 3]
The request and response is in below picture.
enter image description here
You will want to create a REST method that includes a MultipartFile parameter. That object has a getBytes() method as well as a getInputStream() method you can use to get the data. You can then create your object and save it to the repository.
See https://spring.io/guides/gs/uploading-files/ and http://www.concretepage.com/spring-4/spring-4-mvc-single-multiple-file-upload-example-with-tomcat as good references for how to upload files with Spring .
Here is an example on the front end of how I upload a file to a REST service using jQuery.
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
url: "/restapi/requests/replay/upload",
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader(header,token);
},
data: new FormData($("#upload-file-form")[0]),
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function () {
// Handle upload success
addText( "File uploaded successfully.")
},
error: function () {
// Handle upload error
addText( "File upload error.")
}
});
Then here is what the Rest controller looks like:
#RestController
public class ReplayRestController {
#Autowired
private ApplicationContext applicationContext;
#RequestMapping(value="/restapi/requests/replay/upload", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<?> processUpload(
#RequestParam("uploadfile") MultipartFile uploadfile,
#RequestParam("databaseWriteIdUpload") String databaseWriteId,
#RequestParam("recordsToUse")ReplayUpload.RecordsToUse recordsToUse
) {
try {
String fileName = uploadfile.getOriginalFilename();
if (databaseWriteId == null || "".equals(databaseWriteId)) {
databaseWriteId = fileName;
}
ReplayUpload replayUpload = applicationContext.getBean( ReplayUpload.class );
replayUpload.process( uploadfile.getInputStream(), databaseWriteId, recordsToUse );
}
catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK); }
}
Whenever I am executing a POST request an error "405 method not found" is coming, although I have included a required POST method in it. I don't know why the error is coming.
i had tried a lot, I am not getting what the problem is. Please help me out with the same.
My resource file is :
#Path("/customer")
public class CustomerResource {
CustomerDao service = new CustomerDao();
#GET
#Path("/greet")
public String greetCustomer() {
return "Hello, Welcome to our site !!";
}
#GET
#Path("/{name}")
public String getCustomerByName(#PathParam("name") String name) {
return service.getCustomerByName(name).toString();
}
#GET
#Path("/{firstname}-{lastname}")
public String getCustomerByName(#PathParam("firstname") String first,
#PathParam("lastname") String last) {
Collection<Customer> customerCollection = service.getAllCustomers();
for (Customer customer : customerCollection) {
if (customer.getFirstname().equalsIgnoreCase(first)
&& customer.getLastname().equalsIgnoreCase(last)) {
return customer.toString();
}
}
return "Customer with " + first + " " + last + "not found";
}
#GET
#Path("/range/{start}")
#Produces("text/plain")
public String getCustomersInRange(#QueryParam("start") int start) {
List<Customer> allCustomerList = new ArrayList<Customer>(service.getAllCustomers());
List<Customer> customerListInRange = new ArrayList<Customer>();
if (start < allCustomerList.size()) {
for (int i = start; i < allCustomerList.size(); i++) {
customerListInRange.add(allCustomerList.get(i));
}
return customerListInRange.toString();
} else {
return "No customers in this range";
}
}
#POST
#Path("/add")
#Consumes("application/x-www-form-urlencoded")
public String createCustomer(#FormParam("firstname") String first,
#FormParam("lastname") String last) {
Customer newCustomer = new Customer();
newCustomer.setFirstname(first);
newCustomer.setLastname(last);
service.addCustomer(newCustomer);
return newCustomer.toString();
}
#PUT
#Path("/{id}")
#Produces("text/plain")
#Consumes("application/x-www-form-urlencoded")
public String updateCustomer(#PathParam("id") int id,
#FormParam("firstname") String first,
#FormParam("lastname") String last) {
System.out.println(first + " " + last);
Customer customer = service.updateCustomer(id, first, last);
if (customer != null) {
return "Updated Customer : " + customer.toString();
} else {
return "Customer with this id : " + id + "not found";
}
}
#DELETE
#Path("/{id}")
#Produces("text/plain")
public String deleteCustomer(#PathParam("id") int id) {
Customer customer = service.deleteCustomer(id);
if (customer != null) {
return "Deleted Customer: " + customer.toString();
} else {
return "Customer with id : " + id + "was not found";
}
}
}
And my service file is:
public class CustomerDao {
static private List<Customer> customerList = new ArrayList<Customer>();
static {
customerList.add(new Customer(101, "Roy", "Singh", "roy#gmail.com", "Pune"));
customerList.add(new Customer(102, "Joy", "Jackson", "joy#gmail.com", "Nagpur"));
customerList.add(new Customer(103, "Soy", "Nichol", "soy#gmail.com", "Mumbai"));
customerList.add(new Customer(104, "Toy", "Sim", "toy#gmail.com", "Nasik"));
customerList.add(new Customer(105, "Robin", "Singh", "john#gmail.com", "Nasik"));
}
public Customer getCustomerById(int id) {
for (Customer cust : customerList) {
if (cust.getId() == id) {
return cust;
}
}
return null;
}
public Customer getCustomerByName(String name) {
for (Customer cust : customerList) {
if (cust.getFirstname().equals(name)) {
return cust;
}
}
return null;
}
public List<Customer> getAllCustomers() {
return customerList;
}
public List<Customer> getCustomersByCity(String city) {
List<Customer> customersByCity = new ArrayList<Customer>();
for (Customer cust : customerList) {
if (cust.getCity().equals(city)) {
customersByCity.add(cust);
}
}
return customersByCity;
}
public void addCustomer(Customer cust) {
customerList.add(cust);
}
public Customer updateCustomer(int id, String firstname, String lastname) {
List<Customer> customers = getAllCustomers();
for (Customer customer : customers) {
if (customer.getId() == id) {
customer.setFirstname(firstname);
customer.setLastname(lastname);
return customer;
}
}
return null;
}
public Customer deleteCustomer(int id) {
List<Customer> customers = getAllCustomers();
for (Customer customer : customers) {
if (customer.getId() == id) {
customers.remove(customer);
return customer;
}
}
return null;
}
}
The path am using is :
http://localhost:8080/CustomerServiceApp/rest/customer/add
The error am getting on postman is:
405 method not allowed
The exception occured is:
org.apache.wink.server.internal.registry.ResourceRegistry - The system cannot find any method in the resource.CustomerResource class that supports POST. Verify that a method exists.
org.apache.wink.server.internal.RequestProcessor - The following error occurred during the invocation of the handlers chain: WebApplicationException (405) with message 'null' while processing POST request sent to http://localhost:8080/CustomerServiceApp/rest/customer/add
In my case I need subscribe to TFS events (create/delete team project, workitem, checkin, iteration, areas) for realization some business logic. I based on this manual. Now I can catch only workitem and checkin events, but I need more (team project, iteration, areas). In this list, I did not find the right events.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.Integration.Server;
using Microsoft.TeamFoundation.VersionControl.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
public class WorkItemChangedEventHandler : ISubscriber
{
public string Name
{
get { return "WorkItemChangedEventHandler"; }
}
public SubscriberPriority Priority
{
get { return SubscriberPriority.Normal; }
}
public Type[] SubscribedTypes()
{
var types = new List<Type>
{
typeof(Microsoft.TeamFoundation.WorkItemTracking.Server.WorkItemChangedEvent),// working
typeof(Microsoft.TeamFoundation.VersionControl.Server.CheckinNotification),// working
typeof(Microsoft.TeamFoundation.Integration.Server.ProjectCreatedEvent)// NOT working
};
return types.ToArray();
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType,
object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
statusCode = 0;
properties = null;
statusMessage = String.Empty;
try
{
EventLog.WriteEntry("WorkItemChangedEventHandler", string.Format("Entity: {0} was modified", notificationEventArgs.GetType()));
}
catch (Exception ex)
{
EventLog.WriteEntry("WorkItemChangedEventHandler", ex.Message + ex.StackTrace);
}
return EventNotificationStatus.ActionPermitted;
}
}
I have one class for CheckinNotificationEventHandler:
public class CheckinNotificationEventHandler : ISubscriber
{
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(CheckinNotification) };
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
if (notificationType == NotificationType.Notification && notificationEventArgs is CheckinNotification)
{
...
}
return EventNotificationStatus.ActionPermitted;
}
}
and a second class for WorkItemChangedEventHandler:
public class WorkItemChangedEventHandler : ISubscriber
{
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(Microsoft.TeamFoundation.WorkItemTracking.Server.WorkItemChangedEvent) };
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
...
}
return EventNotificationStatus.ActionPermitted;
}
}