Checkmarx : Improper Error Handling in data access layer of web application - java

I have a webapp with a controller layer, a service layer, and a data access layer.
Checkmarx complains about improper error handling when I call getSingleResult in my data access layer where methods look like this :
public FilterWorkflow getNextStatusesForAction(final Long currentStatus, final String actionRequested) {
Query query = this.getEntityManager().createQuery(GET_NEXT_STATUSES_FOR_ACTION);
query.setParameter("currentStatus_Id", currentStatus);
query.setParameter("actionRequested", actionRequested);
return (FilterWorkflow) query.getSingleResult();
}
This is called from the service layer like this :
#Override
#Transactional(value="txManager", rollbackFor = Exception.class)
public SomeFilter executeAction(SomeFilter bf, final String action requested) throws Exception {
Long currentStatusID = bf.getFilteStatus().getTableId();
FilterWorkflow fw = this.someDAO.getNextStatusesForAction(currentStatusID, actionRequested);
return this.updateFilterStatus(fw, bf, actionRequested);
}
which gets called in the controller layer :
public String execute(SomeFilter bf, final String command) {
try {
bf = this.someService.executeAction(bf, command);
} catch (Exception e) {
LOGGER.info(e.getMessage());
FacesUtil.addErrorMessage(this.msgApp.getMessage("error_message"));
return null;
}
return null;
}
I think the exception is handled, because there is nothing more to do about the exceptions that getSingleResult can throw, other than displaying an error message to the user, and logging that error.
Am I missing something ?

Related

Hibernate not deleting object even though the debug is ok?

I'm trying to delete an Object using Hibernate but the thing is not deleting.
I debugged the program to make sure the Object is correct and it is, so I'm guessing the problem might be in something I have no idea what it is ... annotations, configuration ?? Maybe someone can help !
Here's the program:
Controller:
// Erased the imports to make it simpler
#RestController
public class Controlador {
#Autowired
private FisicHostDao fisicHostDao;
#Autowired
private CredentialService credentialService;
#RequestMapping(value = "/fisicHost/{id}/credentials", method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
public List<Credential> credentialsByFisicHost(#PathVariable(value = "id") final Long fisicHostId, ModelMap modelMap){
FisicHost optionalFisicHost = fisicHostDao.findById(fisicHostId);
if (optionalFisicHost == null) {
// Responder con 404
}
FisicHost fisicHost = optionalFisicHost;
return fisicHost.getCredentials();
}
// This is the method handling the request / response
#RequestMapping(value = "/fisicHost/{id}/credentials", method = RequestMethod.POST)
public String deleteCredential(#PathVariable(value = "id") String credId){
String[] parts = credId.split("-");
int id = Integer.parseInt(parts[1]);
Credential c = credentialService.getCredentialById(id);
credentialService.delete(c);
return "justreturnsomething";
}
}
As you can see in the picture the object is not null and it does matches the object I want to delete ...
So why is it not deleting ?
I'm guessing you need to commit a transaction so that the delete actually gets committed to the database.
See Transaction
Eg:
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
try {
doHibernateStuff(session);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
throw e;
}
} finally {
session.close();
}

Javax Validation with RESTfull webservice(jersey)?

I am currently working in a service where i have to use validation with service.We are getting the input from client through request class storing in the database using entity by repository,where we have to give the annotations and where we have to give the bindingresult parameters.While we calling the the service the validation have to take place.Here,I have attached the sample code.
this is the service class where i tried to implement the validation
public long create(#Valid Document document,BindingResult bindingResult,DocumentResourceRequest DocumentResourceRequest,
long agreementId) throws Exception {
// TODO Auto-generated method stub
logger.info("In DocumentServiceImpl createLoanDocument");
Document documentObject = new Document(new lend(
agreementId));
documentObject.setDocumentType(DocumentResourceRequest
.getDocumentType());
documentObject.setDocumentDetails(DocumentResourceRequest
.getDocumentDetails());
documentObject.setRemarks(DocumentResourceRequest.getRemarks());
documentObject.setDocumentStatus(DocumentResourceRequest
.getDocumentStatus());
documentObject.setCreatedBy(DocumentResourceRequest
.getCreatedBy());
documentObject.setCreatedOn(new Date());
try {
if(document != null)
{
document = loanDocumentRepo.saveAndFlush(documentObject);//DocumentRepository
}else(bindingResult.getAllErrors())//if getting errors
{
}
} catch (Exception e) {
throw new Exception("Error in persisting Document-->" + e);
}
return document.getId();
}
'

JavaEE Transaction rollback

I have got a problem with transaction rollback.
I need to first insert a user into the database, and then insert into another table some kind of log of who inserted the user.
If there is an exception when inserting this log-message, the whole transaction should be rolled back (i.e. user needs to be removed again).
The .ear is deployed on Wildfly 8.1, persistence is achieved through Hibernate with MySQL.
My class looks like this
#Stateless
#Remote(AdministratorBiznesowyService.class)
#Transactional(rollbackOn = Exception.class)
public class AdministratorBiznesowyServiceBean implements AdministratorBiznesowyService {
The method looks like this
#Override
#Transactional(rollbackOn = Exception.class)
public void insertUser(String userSessionId, User user) throws AdministratorBiznesowyException {
checkPermission(userSessionId);
try {
userBusiness.insertUser(user);
log.insertLog(
authenticationObjectBusiness.getUserIdForSessionId(userSessionId),
LogEnum.CREATE, user);
} catch (AuthenticationException e) {
ServerLogModule.logActionError(Messages
.getErrorMessage("server.authorization.noPermission"));
throw new AdministratorBiznesowyException();
} catch (Exception e1) {
ServerLogModule.logActionError(Messages
.getErrorMessage("server.exception"));
throw new AdministratorBiznesowyException();
}*/
}
The insertUser implementation in userBusiness:
#Override
public void insertUser(User user) throws AdministratorBiznesowyException {
try {
UserEntity userEntity = adminConvertUtils.convertUserToEntity(user);
userEntityFacade.create(userEntity);
} catch (Exception e) {
throw new AdministratorBiznesowyException();
}
}
And my log.insertLog currently for test-purposes just throws an exception.
throw new LogException();
and its implementation is like this:
#ApplicationException(rollback=true)
public class LogException extends RuntimeException {
AdministratorBiznesowyException:
#ApplicationException(rollback = true)
public class AdministratorBiznesowyException extends CommunicationException {
CommunicationException:
public class CommunicationException extends Exception {
So now, when I successfully call insertUser and directly after that get an exception, the new user still gets added to the database (I check through MySQL Workbench).
What else can I do to get this to rollback?
If any other code is needed, please comment, thank you in advance.

Removing/deleting from google datastore using endpoints, illegal arguement exception, delete with non-zero content length not supported

I'm trying to delete objects from the datastore (using cloud endpoints)
I know the connection is valid because I'm pulling/inserting objects with no problem
However when I try to delete using various approaches I get the same exception
java.lang.illegalArgumentException:DELETE with non-zero content length is not supported
approach 1(using the raw datastore service and the key I stored when inserting the item):
#ApiMethod(name = "removeRPurchase")
public RPurchase removeRPurchase(RPurchase purchase) {
NamespaceManager.set(purchase.getAccount());
DatastoreService d=DatastoreServiceFactory.getDatastoreService();
Key k=KeyFactory.stringToKey(purchase.getKeyrep());
try {
d.delete(k);
} catch (Exception e) {
e.printStackTrace();
purchase=null;
}
return purchase;
}
Approach 2
#ApiMethod(name = "removeRPurchase")
public RPurchase removeRPurchase(RPurchase purchase) {
NamespaceManager.set(purchase.getAccount());
Key k=KeyFactory.stringToKey(purchase.getKeyrep());
EntityManager mgr = getEntityManager();
RPurchase removed=null;
try {
RPurchase rpurchase = mgr.find(RPurchase.class, k);
mgr.remove(rpurchase);
removed=rpurchase;
} finally {
mgr.close();
}
return removed;
}
Ive also tried various variations with the entity manager and the Id, but all with the same exception
The object that i've passed in does contain the namespace in the account, and it does contain the 'KeytoString' of the key associated with the object
the endpoint is called as it should in an AsyncTask endpoint.removeRPurchase(p).execute();
Any help suggestions are appreciated
Make your API method a POST method like this:
#ApiMethod(name = "removeRPurchase" path = "remove_r_purchase", httpMethod = ApiMethod.HttpMethod.POST)
public RPurchase removeRPurchase(RPurchase purchase) {
NamespaceManager.set(purchase.getAccount());
DatastoreService d=DatastoreServiceFactory.getDatastoreService();
Key k=KeyFactory.stringToKey(purchase.getKeyrep());
try {
d.delete(k);
} catch (Exception e) {
e.printStackTrace();
purchase=null;
}
return purchase;
}
I had the same problem because I was using httpMethod = ApiMethod.HttpMethod.DELETE. The error it gives is correct. Simply change it to a POST and do whatever you want inside that API method like delete entities, return entities, etc.
How about trying out the following :
#ApiMethod(
name = "removeRPurchase",
httpMethod = HttpMethod.DELETE
)
public void removeRPurchase(#Named("id") String id) {
//Now take the id and plugin in your datastore code to retrieve / delete
}

Handling Exception custom in JAX-WS

I have web service, developed using JAX-WS. Now i wanted to throw SOAPFault with customized error codes on certain conditions.
I have a webfault:
#WebFault(name = "BankExceptionFault1_Fault", targetNamespace = NS.namespace)
public class BankException extends Exception {
private WebMethodStatus faultInfo;
public BankException(Errors error) {
this(error, error.name());
}
public WebMethodStatus getFaultInfo() {
return faultInfo;
}
public BankException(Errors error, String description) {
super(error.getErrorCode());
this.faultInfo = new WebMethodStatus(error, description);
}
}
And In some method, for a given condition, throws exception:
#Override
#WebMethod(operationName = "UpdateAccountRecord")
#WebResult(name = "Result")
#LogExecution
public WebMethodStatus updateAccountRecord(
#WebParam(name = "Request") UpdateAccountRequest request) throws BankException {
if (!Boolean.parseBoolean(specialMode)) {
throw new BankException(Errors.INVALID_RUNNING_MODE,
"Can't update account record. For updating need special running mode");
}
service.updateAccountRecord(request);
return new WebMethodSuccessStatus();
}
In spring-mvc app, I want to catch my exception:
try {
wsPort.updateAccountRecord(updateAccountRequest);
} catch (BankException e) {
throwException(e);
}
catch(RemoteAccessException e){
throwException(e);
}
But always return RemoteAccessException, if try to update account using sring-mvc app.
detailMessage:Could not access remote service at [http://localhost:8080/my-app-2.1.1-SNAPSHOT/app/MyApp]
cause: java.lang.IllegalStateException: Current event not START_ELEMENT or END_ELEMENT
But if I use soapui for update account, returns correct exception:
BNK00017
Can't update account record. For updating need special running mode
If wsPort is something like an injected JaxWsPortProxyFactoryBean, then it's likely that your exception is being wrapped by RemoteAccessException. Try using RemoteAccessException.getCause() and see what you get...

Categories