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();
}
'
Related
i want save data and check the data after call save method
but the value is not present in same request
i have two method depend each other
the two function communcation with each other by kafka
the first method save the data and after save using jpa call second method
find the recourd from database using jpa
and check the instanse using isPresent()
but in the second method i cant find the data save
but after this request i can find data
return exciption NoSuchElement
Try out several ways like:
1-use flush and saveAndFlush
2-sleep method 10000 milsec
3-use entityManger with #Transactional
but all of them not correct
i want showing you my two method from code:
i have producer and consumer
and this is SaveOrder method (first method):
note : where in the first method have all ways i used
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void saveOrder(Long branchId,AscOrderDTO ascOrderDTO) throws Exception {
ascOrderDTO.validation();
if (ascOrderDTO.getId() == null) {
ascOrderDTO.setCreationDate(Instant.now());
ascOrderDTO.setCreatedBy(SecurityUtils.getCurrentUserLogin().get());
//add user
ascOrderDTO.setStoreId(null);
String currentUser=SecurityUtils.getCurrentUserLogin().get();
AppUser appUser=appUserRepository.findByLogin(currentUser);
ascOrderDTO.setAppUserId(appUser.getId());
}
log.debug("Request to save AscOrder : {}", ascOrderDTO);
AscOrder ascOrder = ascOrderMapper.toEntity(ascOrderDTO);
//send notify to branch
if(!branchService.orderOk())
{
throw new BadRequestAlertException("branch not accept order", "check order with branch", "branch");
}
ascOrder = ascOrderRepository.save(ascOrder);
/*
* log.debug("start sleep"); Thread.sleep(10000); log.debug("end sleep");
*/
entityManager.setFlushMode(FlushModeType.AUTO);
entityManager.flush();
entityManager.clear();
//ascOrderRepository.flush();
try {
producerOrder.addOrder(branchId,ascOrder.getId(),true);
stateMachineHandler.stateMachine(OrderEvent.EMPTY, ascOrder.getId());
stateMachineHandler.handling(ascOrder.getId());
//return ascOrderMapper.toDto(ascOrder);
}
catch (Exception e) {
// TODO: handle exception
ascOrderRepository.delete(ascOrder);
throw new BadRequestAlertException("cannot deliver order to Branch", "try agine", "Try!");
}
}
in this code go to producer :
producerOrder.addOrder(branchId,ascOrder.getId(),true);
and this is my producer:
public void addOrder(Long branchId, Long orderId, Boolean isAccept) throws Exception {
ObjectMapper obj = new ObjectMapper();
try {
Map<String, String> map = new HashMap<>();
map.put("branchId", branchId.toString());
map.put("orderId", orderId.toString());
map.put("isAccept", isAccept.toString());
kafkaTemplate.send("orderone", obj.writeValueAsString(map));
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
}
and in this code go to consumer:
kafkaTemplate.send("orderone", obj.writeValueAsString(map));
this is my consumer:
#KafkaListener(topics = "orderone", groupId = "groupId")
public void processAddOrder(String mapping) throws Exception {
try {
log.debug("i am in consumer add Order");
ObjectMapper mapper = new ObjectMapper(); Map<String, String> result = mapper.readValue(mapping,
HashMap.class);
branchService.acceptOrder(Long.parseLong(result.get("branchId")),Long.parseLong(result.get("orderId")),
Boolean.parseBoolean(result.get("isAccept")));
log.debug(result.toString());
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
}
**and this code go to AcceptOrder (second method) : **
branchService.acceptOrder(Long.parseLong(result.get("branchId")),Long.parseLong(result.get("orderId")),
Boolean.parseBoolean(result.get("isAccept")));
this is my second method :
public AscOrderDTO acceptOrder(Long branchId, Long orderId, boolean acceptable) throws Exception {
ascOrderRepository.flush();
try {
if (branchId == null || orderId == null || !acceptable) {
throw new BadRequestAlertException("URl invalid query", "URL", "Check your Input");
}
if (!branchRepository.findById(branchId).isPresent() || !ascOrderRepository.findById(orderId).isPresent()) {
throw new BadRequestAlertException("cannot find branch or Order", "URL", "Check your Input");
}
/*
* if (acceptable) { ascOrder.setStatus(OrderStatus.PREPARING); } else {
* ascOrder.setStatus(OrderStatus.PENDING); }
*/
Branch branch = branchRepository.findById(branchId).get();
AscOrder ascOrder = ascOrderRepository.findById(orderId).get();
ascOrder.setDiscount(50.0);
branch.addOrders(ascOrder);
branchRepository.save(branch);
log.debug("///////////////////////////////Add order sucess////////////////////////////////////////////////");
return ascOrderMapper.toDto(ascOrder);
} catch (Exception e) {
// TODO: handle exception
throw new Exception(e.getMessage());
}
}
Adding Thread.sleep() inside saveOrder makes no sense.
processAddOrder executes on a completely different thread, with a completely different persistence context. All the while, your transaction from saveOrder might still be ongoing, with none of the changes made visible to other transactions.
Try splitting saveOrder into a transactional method and sending the notification, making sure that the transaction ends before the event handling has a chance to take place.
(Note that this approach introduces at-most-once semantics. You have been warned)
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 ?
I wrote some java code using javax.naming.directory to authenticate a user in AD using ldap, that code working fine as I'm expecting. But the same code i need to implement using Spring ldap api. Any one can help on these.
To Initialize
private void setDefaultInitialContext() throws Exception
{
LOG.debug("Setting default initail context");
try
{
this.moLdapEnv.put(JAVA_NAMING_FACTORY_INITIAL, COM_SUN_JNDI_LDAP_LDAP_CTX_FACTORY);
this.moLdapEnv.put(JAVA_NAMING_PROVIDER_URL, PropertiesReader.getLdapProperty(LDAP_URL) + ":" + PropertiesReader.getLdapProperty(LDAP_PORT));
this.moLdapEnv.put(JAVA_NAMING_SECURITY_AUTHENTICATION, PropertiesReader.getLdapProperty(LDAP_AUTHTYPE));
this.moLdapEnv.put(JAVA_NAMING_SECURITY_PRINCIPAL, PropertiesReader.getLdapProperty(LDAP_BIND_USER_DN));
this.moLdapEnv.put(JAVA_NAMING_SECURITY_CREDENTIALS, PropertiesReader.getLdapProperty(LDAP_PASSWORD));
this.moLdapContext = new InitialDirContext(this.moLdapEnv);
LOG.debug("Default initail context is set");
} catch (Exception exception)
{
LOG.error("An Exception occurred LdapDao setting default initial context :" + exception.getMessage(), exception);
throw exception;
}
}
Authenticate:
public Boolean authenticate(String asUsername, String asUserPassword) throws Exception
{
NamingEnumeration<SearchResult> results = null;
Boolean liAuthResult = Boolean.FALSE;
try
{
setDefaultInitialContext();
SearchControls controls = new SearchControls();
controls.setSearchScope(2);
results = this.moLdapContext.search(PropertiesReader.getLdapProperty(LDAP_SEARCH_BASE_DN),
"(&(objectclass=person)(sAMAccountName=" + asUsername + ")(memberOf=" + PropertiesReader.getLdapProperty(LDAP_GROUP_DN) + "))",
controls);
if (null != results && results.hasMore())
{
SearchResult searchResult = (SearchResult) results.next();
if (null != searchResult)
{
moAttributes = searchResult.getAttributes();
Attribute userDnAttr = moAttributes.get(DISTINGUISHED_NAME);
String userDn = (String) userDnAttr.get();
this.moLdapContext.close();
this.moLdapEnv.put(JAVA_NAMING_SECURITY_PRINCIPAL, userDn);
this.moLdapEnv.put(JAVA_NAMING_SECURITY_CREDENTIALS, asUserPassword);
this.moLdapEnv.put(COM_SUN_JNDI_LDAP_CONNECT_POOL, FALSE);
this.moLdapContext = new InitialDirContext(this.moLdapEnv);
liAuthResult = Boolean.TRUE;
}
LOG.debug("User Authenticated successfully");
}
} catch (NamingException exception)
{
throw exception;
} catch (Exception exception)
{
throw exception;
} finally
{
closeAllResources(results);
}
return liAuthResult;
}
There's a separate chapter on authentication in the Spring LDAP reference manual. If you have specific questions feel free to ask.
Please note that for authentication/authorization purposes you really should look into Spring Security (which in turn uses Spring LDAP under the covers).
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
}
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...