Spring Cloud Stream conflicts with Hystrix - java

I have a RestController with Hystrix and Spring Cloud Stream channels:
#RestController
#RequestMapping(value = "/api/products")
#EnableBinding(ProductProcessor.class)
public class ProductUiController {
/*******
* LISTENERS
*******/
private List<Product> listenAllProducts;
private Product listenProduct;
/*******
* CHANNELS
*******/
#Autowired
#Qualifier(ProductProcessor.OUTPUT_DELETE)
private MessageChannel channel_delete;
#Autowired
#Qualifier(ProductProcessor.OUTPUT_CREATE)
private MessageChannel channel_create;
#Autowired
#Qualifier(ProductProcessor.OUTPUT_UPDATE)
private MessageChannel channel_update;
Logger logger = Logger.getLogger(ProductUiController.class);
#Autowired
RabbitTemplate rabbitTemplate;
#Autowired
RabbitAdmin rabbitAdmin;
#Autowired
private LoadBalancerClient loadBalancer;
/**
* returns all the products in the database
*
* #return
*/
#RequestMapping(method = RequestMethod.GET)
#HystrixCommand(fallbackMethod = "getAllProductsFallback")
public List<Product> getAllProducts() {
try {
ServiceInstance instance = loadBalancer.choose("product-service");
URI uri = instance.getUri();
URL obj = new URL(uri.toString() + "/products");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.getResponseCode();
} catch (MalformedURLException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
return this.listenAllProducts;
}
/**
* Returns a specific product from product-service
*
* #param id
* #return
*/
#RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Product getProduct(#PathVariable("id") Long id) {
try {
ServiceInstance instance = loadBalancer.choose("product-service");
URI uri = instance.getUri();
URL obj = new URL(uri.toString() + "/products/" + id);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.getResponseCode();
} catch (MalformedURLException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
System.out.println("RETURNED PRODUCT = " + listenProduct);
return listenProduct;
}
#HystrixCommand(fallbackMethod = "addProductFallback")
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Product addProduct(#RequestBody Product product) {
logger.info("SENT VIA OUTPUT_CREATE: " + product);
channel_create.send(MessageBuilder.withPayload(product).build());
return product;
}
#HystrixCommand(fallbackMethod = "removeProductFallback")
#RequestMapping(method = RequestMethod.DELETE)
public void removeProduct(#RequestParam("id") Long id) {
logger.info("SENT VIA OUTPUT_DELETE: " + id);
this.channel_delete.send(MessageBuilder.withPayload(id).build());
}
/**************************************/
/**********LISTENERS*******************/
/**************************************/
/**
* Receiver for all products
*
* #param products
*/
#StreamListener(ProductProcessor.INPUT_GETALL)
public void listenerGetAllProducts(List<Product> products) {
logger.info("RECEIVED FROM INPUT_GETALL: " + products);
listenAllProducts = products;
}
/**
* Receiver for product
*
* #param product
*/
#StreamListener(ProductProcessor.INPUT_GET)
public void listenerGetProduct(Product product) {
logger.info("RECEIVED FROM INPUT_GET: " + product);
listenProduct = product;
}
/**************************************/
/**********FALLBACK METHODS************/
/**************************************/
/**
* Fallback method for getAllProducts
*
* #return
*/
public List<Product> getAllProductsFallback(Throwable e) {
logger.info("getAllProductsFallback");
return listenAllProducts;
}
/**
* Fallback method for addProduct
*
* #param product
* #return
*/
Product addProductFallback(Product product) {
logger.info("addProductFallback");
return null;
}
/**
* Fallback method for delete
*
* #param id
*/
void removeProductFallback(Long id) {
logger.info("removeProductFallback");
}
}
In the implementation HystrixCommand makes a getDeclaredMethod to ProductUiController to find the fallback methods but #EnableBinding hides class methods from reflection, any clue of a workaround?

Solution: Moved #EnableBinding to main SpringBootApplication class.

Related

Spring RestService - target invocation exception

I'm trying to invoke a service using Spring's RestOperations class, but am getting a target invocation exception on the line where it invokes rest.getForObject. This is the method where the exception gets thrown:
#Override
#SuppressWarnings("unchecked")
public List<INorcaSummarySystemDTO> getNorcaSummaryBySystem(String systemName, Date fromDate){
List<INorcaSummarySystemDTO> norcaSummarySystem = new ArrayList<>();
try {
URI uri = UriComponentsBuilder.fromUriString(configuration.getDacqUrl() +
"/fa/api/v1/facility/1/norcasummarysystem")
.build().toUri();
NorcaSummarySystemDTO[] list = rest.getForObject(uri.toString(), NorcaSummarySystemDTO[].class);
norcaSummarySystem = Arrays.asList(list);
} catch (RestClientException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Exception while getting Norca summary system. Error: {}", e.getMessage());
LOG.trace(e.getMessage(), e);
}
return null;
}
return norcaSummarySystem;
}
The URI that it's invoking works when I call it from postman:
http://localhost:8181/fa/api/v1/facility/1/norcasummarysystem
Here's a picture of it in the debugger:
I'm modeling the call from another class which does the same thing, i.e. uses the rest client to return a list array of DTOs, based on the two lines in particular:
BarcodeDataDTO[] barcodeData = restClient.getForObject(uri.toString(), BarcodeDataDTO[].class);
dacqBarcodeDataDTOS = Arrays.asList(barcodeData);
This is the full method from that class:
List<BarcodeDataDTO> dacqBarcodeDataDTOS;
try {
URI uri = UriComponentsBuilder
.fromUriString(
servicesConfiguration.getDacqUrl() +API_V1_PATH + Constants.URI_FACILITY +
facility.getFacilityName() + Constants.URI_SYSTEM +
URLEncoder.encode(system.getSystemName(),StandardCharsets.UTF_8) +
Constants.URI_OBJECT + objectId + Constants.URI_BARCODES)
.queryParam(Constants.SCAN_TIME, DATE_TIME_FORMATTER.format(scanTime)).build().toUri();
BarcodeDataDTO[] barcodeData = restClient.getForObject(uri.toString(), BarcodeDataDTO[].class);
dacqBarcodeDataDTOS = Arrays.asList(barcodeData);
} catch (RestClientException restException) {
LOGGER.error(restException.getMessage(), restException);
return Collections.emptyList();
} catch (Exception e) {
throw new ConnectionFailureException(
"Fail to fetch barcode data from data aquisition layer. The exception is: " + e);
}
This is the code for the RestController being invoked:
package com.sick.ilcore.dacq.controller;
/**
* <p>NorcaSummaryController class.</p>
*
*/
#CrossOrigin
#RestController
#RequestMapping(CommonConstants.API_V1 + "/facility/{facilityName}")
public class NorcaSummaryController {
#Autowired
private IBarcodeDataService barcodedataService;
/**
*
* #param system name
* #param fromDate - optional from date in yyyy-MM-dd format
*
* #return NORCA totals by system
*/
#GetMapping(value = "/norcasummarysystem")
private List<INorcaSummarySystemDTO> getNorcaSummaryBySystem(
#RequestParam("systemName") Optional<String> systemName,
#RequestParam("fromDate") #DateTimeFormat(pattern="yyyy-MM-dd") Optional<Date> fromDate) {
String systemNameVal = null;
if (systemName.isPresent()) {
systemNameVal = systemName.get();
}
else {
systemNameVal = "all";
}
Date fromDateVal = DACQUtils.calcFromDateVal(fromDate);
List<INorcaSummarySystemDTO> norcaList = barcodedataService.getNorcaSummaryBySystem(systemNameVal, fromDateVal);
return norcaList;
}
The problem turned out to be a jackson exception that showed up after a couple of hours. A quick google revealed that I had to add a default constructor to the DTOs.

Why does REST request give me a HTTP Status 500 - Internal Server Error?

I deployed and ran the code from NetbeansMy ApplicationConfig.java file. When I tried to see the result at http://rasmus:8080/FinalFlightWebService/webresources/Flights/?token=salajane It gave me a 500 internal server error.
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
resources.add(jsonProvider);
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(ee.ttu.idu0075.FlightsResource.class);
}
My REST java file
/**
* Creates a new instance of FlightsResource
*/
public FlightsResource() {
}
/**
* Retrieves representation of an instance of ee.ttu.idu0075.FlightsResource
*
* #param token
* #return an instance of ee.ttu.idu0075._2015.ws.invoice.FlightType
*/
#GET
#Produces("application/json")
public GetFlightListResponse getFlightList(#QueryParam("token") String token) {
FinalFlightWebService fws = new FinalFlightWebService();
GetFlightListRequest request = new GetFlightListRequest();
request.setToken(token);
return fws.getFlightList(request);
}
#GET
#Path("{id: \\d+}") //supports digits only
#Produces("application/json")
public TicketType getTicket(#PathParam("id") String id, #QueryParam("token") String token) {
FinalFlightWebService fws = new FinalFlightWebService();
GetTicketRequest request = new GetTicketRequest();
request.setId(BigInteger.valueOf(Integer.parseInt(id)));
request.setToken(token);
return fws.getTicket(request);
}
#PUT
#Consumes("application/json")
public void putJson(FlightType content) {
}
Does anyone know what I need to change to not get the HTTP Status 500 - Internal Server Error?
Added this to end and everything worked:
#Provider
public class DebugExceptionMapper implements ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception exception) {
exception.printStackTrace();
return Response.serverError().entity(exception.getMessage()).build();
}
}

Spring RestTemplate exchange throws UnhandledHttpStatusException

Overview:
I am going to use RestTemplate to invoke a get request from external REST webservice.
My code is as follows:
#Slf4j
#Component("AccMemberDetailsApiControllerImpl")
public class AccMemberDetailsApiControllerImpl implements MemberDetailsApiController {
private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type";
private static final String AUTHORIZATION_HEADER_NAME = "Authorization";
private static final String USERID_PARAMETER_NAME = "userId";
private static final String VEHICLEID_PARAMETER_NAME = "vehicleId";
private static final ObjectMapper mapper = new ObjectMapper();
/**
* This constant is used to check whether or not the response from ACC is an empty JSON string
*/
private static final String EMPTY_RESPONSE = "{}";
#Value("${com.blss.memberServices.provider.posServiceURL}")
private String accPosServiceURL;
#Autowired
private RestTemplate restTemplate;
#Autowired
private AccTokenUtility accTokenUtility;
#Autowired
private ResourceMessage resourceMessage;
void setAccTokenUtility(AccTokenUtility accTokenUtility) {
this.accTokenUtility = accTokenUtility;
}
void setResourceMessage(ResourceMessage resourceMessage) {
this.resourceMessage = resourceMessage;
}
/**
* #see MemberDetailsApiController#getMemberDetails(String, String)
*/
#Override
public MemberDetailsModel getMemberDetails(String storeId, String membershipIdentifier) {
/**
* Getting CAD token
*/
String token = accTokenUtility.getCadToken();
/**
* Preparing the request
*/
HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set(CONTENT_TYPE_HEADER_NAME, MediaType.APPLICATION_JSON_VALUE);
headers.set(AUTHORIZATION_HEADER_NAME, token);
HttpEntity<String> entity = new HttpEntity<>(headers);
/**
* Creating the dispatch URL by means of userId and vehicleId
*/
String dispatchURL = accPosServiceURL + "DispatchedEvent/{userId}/{vehicleId}";
/**
* Creating the URL variables and being valued by corresponding method parameters
*/
Map<String, String> parameters = new HashMap<>();
// parameters.put(USERID_PARAMETER_NAME, storeId);
parameters.put(USERID_PARAMETER_NAME, "mr2");
// parameters.put(VEHICLEID_PARAMETER_NAME, membershipIdentifier);
parameters.put(VEHICLEID_PARAMETER_NAME, "VEH1");
/**
* Calling the rest webservice and returning response with body of type {#link AccMemberDetails}
*/
ResponseEntity<String> response;
MemberDetailsModel memberDetailsModel = null;
AccMemberDetails accMemberDetails;
try {
response = restTemplate.exchange(dispatchURL, HttpMethod.GET, entity, String.class, parameters);
if (response == null || StringUtils.isBlank(response.getBody()) || EMPTY_RESPONSE.equals(response.getBody())) {
throw new ResourceNotFoundException(resourceMessage.getMessage(MEMBER_ERROR_NOT_FOUND, storeId, membershipIdentifier));
} else {
accMemberDetails = deserialize(response.getBody(), AccMemberDetails.class);
String accErrorMessage = accMemberDetails.getUserMessage();
if (!StringUtils.isBlank(accErrorMessage)) {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_ERROR_MESSAGE_FROM_API, "ACC", accErrorMessage));
}
memberDetailsModel = convert(accMemberDetails);
}
} catch (RestClientException e) {
handleExceptions(e, storeId, membershipIdentifier);
}
return memberDetailsModel;
}
/**
* This method is responsible for deserializing string REST response into an object of type {#link AccMemberDetails}
*/
<T> T deserialize(final String response, final Class<T> responseClass) {
try {
return mapper.readValue(response, responseClass);
} catch (IOException e) {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_ERROR_MAP_RESPONSE_OBJECT), e);
}
}
/**
* This method is responsible for converting an instance of type {#link AccMemberDetails} to an instance of type
* {#link MemberDetailsModel}
*
* #param accMemberDetails an instance of type {#link AccMemberDetails}
* #return an instance of type {#link MemberDetailsModel}
*/
MemberDetailsModel convert(AccMemberDetails accMemberDetails) {
MemberDetailsModel memberDetailsModel = new MemberDetailsModel();
memberDetailsModel.setEventId(accMemberDetails.getEventId());
memberDetailsModel.setMemberName(accMemberDetails.getMemberName());
memberDetailsModel.setMembershipNumber(accMemberDetails.getMembershipNumber());
memberDetailsModel.setMembershipLevel(accMemberDetails.getPricingLevel());
return memberDetailsModel;
}
/**
* This method is responsible for handling Exceptions may be thrown by ACC REST webservice
*
* #param e an instance of type {#link RestClientException}
* #param storeId an instance of type {#link String} and used in building exception messages
* #param membershipIdentifier an instance of type {#link String} and used in building exception messages
*/
private void handleExceptions(RestClientException e, String storeId, String membershipIdentifier) {
if (e instanceof HttpStatusCodeException) {
HttpStatusCodeException httpStatusCodeException = (HttpStatusCodeException) e;
HttpStatus httpStatusCode = httpStatusCodeException.getStatusCode();
if (404 == httpStatusCode.value()) {
throw new ResourceNotFoundException(resourceMessage.getMessage(MEMBER_ERROR_NOT_FOUND, storeId, membershipIdentifier), e);
} else if (500 == httpStatusCode.value()) {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_SERVER_ERROR, "ACC"), e);
} else {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_HTTP_STATUS_CODE_ERROR, "HttpStatusCodeException", "ACC"), e);
}
} else {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_REST_CLIENT_ERROR, "RestClientException", "ACC"), e);
}
}
Problem
However I got UnhandledHttpStatusException after calling "restTemplate.exchange(dispatchURL, HttpMethod.GET, entity, String.class, parameters);" in the code snippet. the exception stack trace is as follows:
Caused by: org.springframework.web.client.UnknownHttpStatusCodeException: Unknown status code [443] null
at org.springframework.web.client.DefaultResponseErrorHandler.getHttpStatusCode(DefaultResponseErrorHandler.java:60)
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:50)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:629)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:565)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:484)
at com.blss.retailServices.memberServices.controllers.impl.acc.AccMemberDetailsApiControllerImpl.getMemberDetails(AccMemberDetailsApiControllerImpl.java:110)
Now I would be grateful if anyone could suggest me a solution.
I called this webservice with curl by using "-v" in order to get more info in response. As a result, I got the same exception (443) from their side. So, It sounds like they should have a better exception handler to return meaningful exception messages.

Exception in CXF client for web service

I have generated CXF client for a secured web service (file upload) and try to call it. I have following files in my generated folder
CarbonAppUploader(class)
CarbonAppUploaderPortType(Interface)
UploadApp(class).
.........
..........
Following is my client
public class MyTest {
public static void main(String[] args) throws IOException {
JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean();
clientFactory.setAddress( "https://localhost:8243/services/CarbonAppUploader.CarbonAppUploaderHttpsEndpoint/" );
clientFactory.setServiceClass( CarbonAppUploader.class );
clientFactory.setUsername("admin");
clientFactory.setPassword("admin");
UploadApp req = new UploadApp();
FileInputStream fileInputStream;
File file1 = new File("/home/malintha/support/....../AxisCApp-1.0.0.car");
byte[] bFile = new byte[(int) file1.length()];
//convert file into array of bytes
fileInputStream = new FileInputStream(file1);
fileInputStream.read(bFile);
fileInputStream.close();
//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream("/home/malintha/support/....../AxisCApp-1.0.0.car");
fileOuputStream.write(bFile);
fileOuputStream.close();
org.wso2.carbon.application.upload.xsd.ObjectFactory of=new org.wso2.carbon.application.upload.xsd.ObjectFactory();
UploadedFileItem file=new UploadedFileItem();
file.setFileName(of.createUploadedFileItemFileName("AxisCApp-1.0.0.car"));
file.setFileName(of.createUploadedFileItemFileType("CAR"));
file.setDataHandler(of.createUploadedFileItemDataHandler(bFile));
List<UploadedFileItem> flies=new ArrayList<UploadedFileItem>();
flies.add(0,file);
UploadApp myApp = new UploadApp();
myApp.fileItems=flies;
req.getFileItems().add( file );
CarbonAppUploaderPortType uploadSvc = (CarbonAppUploaderPortType) clientFactory.create();
uploadSvc.uploadApp( req );
}
}
when I run this class I got a exception as follows
INFO: Creating Service {http://upload.application.carbon.wso2.org/}CarbonAppUploaderService from class org.wso2.carbon.application.upload.CarbonAppUploader
Exception in thread "main" java.lang.IllegalArgumentException: org.wso2.carbon.application.upload.CarbonAppUploader is not an interface
at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:470)
clientFactory.create(); method call cause this exception. How can I solve this ?
This is carbonAppUploader class
#WebServiceClient(name = "CarbonAppUploader",
wsdlLocation = "file:/home/malintha/software/axis2-bin/bin/src/org/CappUpload /src/main/resources/myService.wsdl",
targetNamespace = "http://upload.application.carbon.wso2.org")
public class CarbonAppUploader extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploader");
public final static QName CarbonAppUploaderHttpsSoap12Endpoint = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploaderHttpsSoap12Endpoint");
public final static QName CarbonAppUploaderHttpsSoap11Endpoint = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploaderHttpsSoap11Endpoint");
public final static QName CarbonAppUploaderHttpsEndpoint = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploaderHttpsEndpoint");
static {
URL url = null;
try {
url = new URL("file:/home/malintha/software/axis2-bin/bin/src/org/CappUpload/src/main/resources/myService.wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(CarbonAppUploader.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "file:/home/malintha/software/axis2-bin/bin/src/org/CappUpload/src/main/resources/myService.wsdl");
}
WSDL_LOCATION = url;
}
public CarbonAppUploader(URL wsdlLocation) {
super(wsdlLocation, SERVICE);
}
public CarbonAppUploader(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public CarbonAppUploader() {
super(WSDL_LOCATION, SERVICE);
}
/**
*
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap12Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap12Endpoint() {
return super.getPort(CarbonAppUploaderHttpsSoap12Endpoint, CarbonAppUploaderPortType.class);
}
/**
*
* #param features
* A list of {#link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap12Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap12Endpoint(WebServiceFeature... features) {
return super.getPort(CarbonAppUploaderHttpsSoap12Endpoint, CarbonAppUploaderPortType.class, features);
}
/**
*
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap11Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap11Endpoint() {
return super.getPort(CarbonAppUploaderHttpsSoap11Endpoint, CarbonAppUploaderPortType.class);
}
/**
*
* #param features
* A list of {#link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap11Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap11Endpoint(WebServiceFeature... features) {
return super.getPort(CarbonAppUploaderHttpsSoap11Endpoint, CarbonAppUploaderPortType.class, features);
}
/**
*
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsEndpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsEndpoint() {
return super.getPort(CarbonAppUploaderHttpsEndpoint, CarbonAppUploaderPortType.class);
}
/**
*
* #param features
* A list of {#link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsEndpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsEndpoint(WebServiceFeature... features) {
return super.getPort(CarbonAppUploaderHttpsEndpoint, CarbonAppUploaderPortType.class, features);
}
}

Exception when saving a result

I am developping J2EE application with appfuse , i have a webform called easyVolAction that contain a method search() I need to save the result of search method in database but and an excpetion is generated when clicking in the action search :NullPointerException in object trajet .I created TrajetDaoHibernate:
public TrajetDaoHibernate() {
super(TrajetModel.class);
}
/**
* {#inheritDoc}
*/
#SuppressWarnings("unchecked")
public List<TrajetModel> getTrajet() {
Session session = getSessionFactory().getCurrentSession();
Query qry = session.createQuery("from TrajetModel u order by upper(u.id)");
return qry.list();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) {
if (log.isDebugEnabled()) {
log.debug("user's id: " + trajet.getId());
}
Session session = getSessionFactory().getCurrentSession();
session.saveOrUpdate(trajet);
// necessary to throw a DataIntegrityViolation and catch it in UserManager
session.flush();
return trajet;
}
#Override
public TrajetModel save(TrajetModel trajet) {
return this.saveTrajet(trajet);
}
and TrajetDao:
public interface TrajetDao extends GenericDao {
List<TrajetModel> getTrajet();
TrajetModel saveTrajet(TrajetModel trajet);
}
and trajetManager:
#Service("trajetManager")
public class TrajetModelImpl extends GenericManagerImpl<TrajetModel, Long> implements TrajetManager {
private TrajetDao trajetDao;
#Autowired
public void setTrajetModelDao(TrajetDao trajetDao) {
this.dao = trajetDao;
this.trajetDao = trajetDao;
}
/**
* {#inheritDoc}
*/
public TrajetModel getTrajet(String trajetId) {
return trajetDao.get(new Long(trajetId));
}
/**
* {#inheritDoc}
*/
public List<TrajetModel> getTrajet() {
return trajetDao.getAllDistinct();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) throws TrajetExistsException {
try {
return trajetDao.saveTrajet(trajet);
} catch (DataIntegrityViolationException e) {
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
} catch (JpaSystemException e) { // needed for JPA
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
}
}
}
finnaly the action where i declare the search method:
public String recherche() throws IOException, TrajetExistsException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
// String url1 =
// FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("hidden");
String departAller = request.getParameter("easyVolRobot:villeDepart");
String arriveeAller = request.getParameter("easyVolRobot:villeArrivee");
String jourAller = request.getParameter("easyVolRobot:jourDep");
String moisAller = request.getParameter("easyVolRobot:dateDep");
String jourRetour = request.getParameter("easyVolRobot:jourDep");
String moisRetour = request.getParameter("easyVolRobot:dateArr");
String jourAllerPlus1 = jourAller + 1;
parametre = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAller + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
parametre1 = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAllerPlus1 + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
String response = sendGetRequest(url, parametre);
// insert();
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(
"/data/crawl/root/siteSNCF.html"));
out.print(response);
} finally {
if (out != null)
out.close();
}
// tableau de resultats des trajets
List<TrajetModel> listTrajets = new ArrayList<TrajetModel>();
// trajet
//TrajetModel trajet = new TrajetModel();
File input = new File("/data/crawl/root/siteSNCF.html");
Document doc = Jsoup.parse(input, "UTF-8",
"http://www.easyvols.org/france-voyage");
for (Element vol : doc.select("div.vols")) {
//trajet = new TrajetModel();
for (Element allerRetour : vol.select("div.aller-retour")) {
Elements aeroport = allerRetour.select("div.aeroport");
System.out.println(aeroport.text());
Elements depart = allerRetour.select("div.depart");
Elements arrive = allerRetour.select("div.arrivee");
Elements date = allerRetour.select("div.date");
trajet.setNom(aeroport.text());
trajet.setVilleDepart(depart.text());
trajet.setVilleArrive(arrive.text());
trajet.sethArrive(12);
trajet.sethDepart(11);
trajet.sethReqt(14);
}
Elements prix2 = vol.select("div.tarif");
trajet.setPrice(prix2.text());
trajet = trajetManager.saveTrajet(trajet);
System.out.println(trajet);}
return"mainMenu";
}
why you comment this line out?
//TrajetModel trajet = new TrajetModel();
I see no other line where you create the TrajetModel.
If that object is not initiated you get the NPE here:
trajet.setNom(aeroport.text());

Categories

Resources