java common function for duplicate code - java

public UMRResultObject insertDocumentation(UMRDocumentationDTO documentationDTO)
{
Session session = UMRHibernateUtil.getUmrSession();
Transaction tx = null;
List<UMRDTO> duplicateDocumentationList=null;
String objectType =documentationDTO.getId().getObjectType();
String objectName =documentationDTO.getId().getObjectName();
try
{
duplicateDocumentationList = dao.getFilteredDocumentationList(objectType, objectName, false, session);
if(duplicateDocumentationList.isEmpty())
{
tx = session.beginTransaction();
dao.insertDocumentation(documentationDTO, session);
tx.commit();
ro.setSuccess(true);
ro.getMessages().add("Record Inserted Successfully");
if (ro.isSuccess())
{
if("Domain".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
else if("DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
return ro;
}
}
else
{
ro.getMessages().add("Documentation for '" + objectName + "' "
+ objectType+ " already exists! \n");
logger.info("Documentation for '" + objectName + "' "
+ objectType+ " already exists! \n");
}
}
return ro;
}
public UMRResultObject updateDocumentation(UMRDocumentationDTO documentationDTO)
{
Session session = UMRHibernateUtil.getUmrSession();
Transaction tx = null;
try
{
String objectType = documentationDTO.getId().getObjectType();
if("Domain".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(documentationDTO.getId().getObjectName(), documentationDTO.getDocumentationLink());
}
else if("DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(documentationDTO.getId().getObjectName(), documentationDTO.getDocumentationLink());
}
tx = session.beginTransaction();
dao.updateDocumentation(documentationDTO, session);
tx.commit();
ro.setSuccess(true);
ro.getMessages().add("Record Updated Successfully");
if(ro.isSuccess())
{
if("Domain".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
else if("DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
return ro;
}
}
I dont want to ducplicate the code in if(ro.isSuccess()) and want to refactor the code but unable to get any further from this
I tried making another method for it unable to use documentationDTO what should I do

You can do something like this:
if(ro.isSuccess()){
populateMap(objectType, objectName, documentationDTO);
return ro;
}
Method would be like below:
private void populateMap(String objectType, String objectName, UMRDocumentationDTO documentationDTO){
if("Domain".equals(objectType) || "DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
}

Related

WildFly 13 migration - Only session and message-driven beans with bean-managed transaction demarcation are allowed to access UserTransaction

I have an "XAManager" class that I'm using for a JCA component inside WildFly 13.
In the standalone-full.xml the resource adapter in question is defined as so:
...
<resource-adapter id="myTest.ear#LuceneConnector-ra-impl-0.1.0.rar">
<archive>
myTest.ear#LuceneConnector-ra-impl-0.1.0.rar
</archive>
<transaction-support>XATransaction</transaction-support>
<connection-definitions>
<connection-definition class-name="com.impl.LuceneManagedConnectionFactory" jndi-name="java:jboss/eis/LuceneConnector" enabled="true" use-java-context="true" pool-name="LuceneConnection" use-ccm="true">
<xa-pool>
<min-pool-size>0</min-pool-size>
<max-pool-size>10</max-pool-size>
<prefill>false</prefill>
<use-strict-min>false</use-strict-min>
<flush-strategy>FailingConnectionOnly</flush-strategy>
<pad-xid>false</pad-xid>
<wrap-xa-resource>true</wrap-xa-resource>
</xa-pool>
<security>
<application/>
</security>
</connection-definition>
</connection-definitions>
</resource-adapter>
....
This class is being used in the ManagedConnection class of the JCA, being returned in the getXAResource() method:
public XAResource getXAResource()
throws ResourceException {
if (this.xaResource == null) {
this.xaResource = new LuceneXAManager(this);
}
if (LuceneManagedConnection.LOGGER.isDebugEnabled()) {
LuceneManagedConnection.LOGGER.debug("XAResource=" + this.xaResource);
}
return this.xaResource;
}
The class definition is as follows:
public class LuceneXAManager
implements XAResource {
static final String _CVS = "$Revision: 1.12 $";
private static final Logger LOGGER = Logger.getLogger(IndexWriter.class);
private LuceneManagedConnection lmc = null;
// private final CACClientLocal cacClientLocal = null;
// private final CACCommunityLocal cacCommunityLocal = null;
public LuceneXAManager(final LuceneManagedConnection lmc) {
this.lmc = lmc;
}
/**
* {#inheritDoc}
*/
public void commit(final Xid xid, final boolean arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("commit transaction : " + xid + " int " + arg1);
}
List<LuceneDocumentTransferWrapper> tasks = this.lmc.getLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
if (tasks != null) {
TransactionManager tm = null;
Transaction tx = null;
try {
InitialContext ctx = new InitialContext();
tm = (TransactionManager)ctx.lookup("java:jboss/TransactionManager");
tx = tm.suspend();
UserTransaction ut = (UserTransaction)ctx.lookup("java:jboss/UserTransaction");
ut.begin();
for (LuceneDocumentTransferWrapper wrapper : tasks) {
String operation = wrapper.getCommand();
Object dataObject = wrapper.getDataObject();
IndexWriter writer = null;
if (wrapper.getCommunityId() != null) {
if (LuceneManagedConnection.DO_RECREATE_INDEX.equals(operation)) {
IndexWriterManager.createNewVNIndexFor(this.loadCommunity(wrapper.getCommunityId()));
continue;
} else {
writer = IndexWriterManager.getVNWriterFor(wrapper.getCommunityId());
if (writer == null) {
writer = IndexWriterManager.getVNWriterFor(this.loadCommunity(wrapper.getCommunityId()));
}
}
if (writer == null) {
throw new IllegalArgumentException("Failed to get index writer for community " + wrapper.getCommunityId());
}
} else if (wrapper.getClientId() != null) {
if (LuceneManagedConnection.DO_RECREATE_INDEX.equals(operation)) {
IndexWriterManager.createNewIndexFor(this.loadClient(wrapper.getClientId()));
continue;
} else {
writer = IndexWriterManager.getWriterFor(wrapper.getClientId());
if (writer == null) {
writer = IndexWriterManager.getWriterFor(this.loadClient(wrapper.getClientId()));
}
}
if (writer == null) {
throw new IllegalArgumentException("Failed to get index writer for client " + wrapper.getClientId());
}
} else {
throw new IllegalArgumentException("Have no clientId or communityId");
}
if (LuceneManagedConnection.DO_DELETE_DOCUMENTS.equals(operation)) {
List<Long> documentIds = (List<Long>)dataObject;
writer.deleteDocuments(documentIds);
} else if (LuceneManagedConnection.DO_INDEX_DOCUMENT.equals(operation)) {
Document document = (Document)dataObject;
writer.addDocument(document);
} else if (LuceneManagedConnection.DO_UPDATE_INDEX.equals(operation)) {
Document document = (Document)dataObject;
if (Document.DOCUMENT_STATUS_ACTIVE.equals(document.getStatus())
|| Document.DOCUMENT_STATUS_WAITING.equals(document.getStatus())
|| Document.DOCUMENT_STATUS_OUTDATED.equals(document.getStatus())) {
writer.updateDocument(document, null);
} else {
writer.deleteDocument(document);
}
} else if (LuceneManagedConnection.DO_INDEX_CONTAINER.equals(operation)) {
Container container = (Container)dataObject;
writer.deleteContainer(container.getRfid());
writer.addContainer(container);
} else {
throw new IllegalArgumentException(" Wrong command " + operation);
}
}
ut.commit();
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Failed to handle commit for transaction " + xid, e);
HashSet<Long> failedDocuments = new HashSet<Long>();
for (LuceneDocumentTransferWrapper wrapper : tasks) {
failedDocuments.clear();
if (LuceneManagedConnection.DO_DELETE_DOCUMENTS.equals(wrapper.getCommand())) {
failedDocuments.addAll((List)wrapper.getDataObject());
} else if (LuceneManagedConnection.DO_INDEX_DOCUMENT.equals(wrapper.getCommand())) {
failedDocuments.add(((Document)wrapper.getDataObject()).getId());
} else if (LuceneManagedConnection.DO_UPDATE_INDEX.equals(wrapper.getCommand())) {
failedDocuments.add(((Document)wrapper.getDataObject()).getId());
}
for (Long id : failedDocuments) {
LuceneXAManager.LOGGER.error("Possible Lucene index corruption - failed to '" + wrapper.getCommand() + "' document (id=" + id
+ ")");
}
}
throw new XAException(XAException.XAER_RMFAIL);
} finally {
try {
if (tm != null && tx != null) {
tm.resume(tx);
}
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Error while close resume session", e);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
}
}
/**
* {#inheritDoc}
*/
public void end(final Xid xid, final int arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("end transaction : " + xid);
}
}
/**
* {#inheritDoc}
*/
public void forget(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("forget transaction : " + xid);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
/**
* {#inheritDoc}
*/
public int getTransactionTimeout()
throws XAException {
return 0;
}
/**
* {#inheritDoc}
*/
public boolean isSameRM(final XAResource arg0)
throws XAException {
return false;
}
/**
* {#inheritDoc}
*/
public int prepare(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("prepare transaction : " + xid);
}
List<LuceneDocumentTransferWrapper> tasks = this.lmc.getLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
List<Long> clientWriter = new ArrayList<Long>();
List<Long> communityWriter = new ArrayList<Long>();
if (tasks != null) {
for (LuceneDocumentTransferWrapper wrapper : tasks) {
if (wrapper.getCommunityId() != null) {
if (!communityWriter.contains(wrapper.getCommunityId())) {
communityWriter.add(wrapper.getCommunityId());
}
} else {
if (!clientWriter.contains(wrapper.getClientId())) {
clientWriter.add(wrapper.getClientId());
}
}
}
}
TransactionManager tm = null;
try {
InitialContext ctx = new InitialContext();
tm = (TransactionManager)ctx.lookup(CACBean.JDNI_TX_MANAGER);
tm.suspend();
UserTransaction ut = (UserTransaction)ctx.lookup(CACBean.JDNI_USERTRANACTION);
ut.begin();
for (Long clientId : clientWriter) {
IndexWriter writer = IndexWriterManager.getWriterFor(clientId);
if (writer == null) {
if (IndexWriterManager.getWriterFor(this.loadClient(clientId)) == null) {
throw new IllegalArgumentException("Failed to get index writer for client " + clientId);
}
}
}
for (Long communityId : communityWriter) {
IndexWriter writer = IndexWriterManager.getVNWriterFor(communityId);
if (writer == null) {
if (IndexWriterManager.getVNWriterFor(this.loadCommunity(communityId)) == null) {
throw new IllegalArgumentException("Failed to get index writer for community " + communityId);
}
}
}
ut.commit();
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Failed to handle prepare for transaction " + xid, e);
throw new XAException(XAException.XAER_RMFAIL);
} finally {
// try {
// if (tm != null && tx != null) {
// tm.resume(tx);
// }
// } catch (Exception e) {
// LuceneXAManager.LOGGER.warn("Error while close resume session", e);
// }
}
return XAResource.XA_OK;
}
/**
* {#inheritDoc}
*/
public Xid[] recover(final int arg0)
throws XAException {
return null;
}
/**
* {#inheritDoc}
*/
public void rollback(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("rollback transaction : " + xid);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
/**
* {#inheritDoc}
*/
public boolean setTransactionTimeout(final int arg0)
throws XAException {
return false;
}
/**
* {#inheritDoc}
*/
public void start(final Xid arg0, final int arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("start transaction : " + arg0 + " int " + arg1);
}
}
private Client loadClient(final Long clientId)
throws RemoteException, CreateException, NamingException, CACException {
....
return client;
}
private Community loadCommunity(final Long communityId)
throws RemoteException, CreateException, NamingException, CACException {
....
return community;
}
}
The problem I'm having is that when trying to get the UserTransaction via JNDI I get Caused by: javax.naming.NameNotFoundException: UserTransaction [Root exception is java.lang.IllegalStateException: WFLYEJB0137: Only session and message-driven beans with bean-managed transaction demarcation are allowed to access UserTransaction]
I tried annotating my class with #Stateless and #TransactionManagement(TransactionManagementType.BEAN) to get over this issue but to no use.
I've also tried injecting the UserTransaction via #Inject UserTransaction but in this case the UserTransaction is null.
Any ideas ?

Can't Update Multi record Error Transaction is Inactive

I am trying to update multi records with Transaction ebean, however when I am trying more than one record, there is an error on the screen :
[IllegalStateException: Transaction is Inactive]
any idea please ?
public Result savemulti(String selected) throws PersistenceException {
Form<Computer> computerForm = formFactory.form(Computer.class).bindFromRequest();
if(computerForm.hasErrors()) {return badRequest(views.html.computers.editMulti.render(AuthorisedUser.findByEmail(request().username()), computerForm, selected));}
java.util.Date dtcreate = new java.util.Date();
String connectedEmail = ctx().session().get("email");
AuthorisedUser singleUser = AuthorisedUser.findByEmail(connectedEmail);
String[] ids = selected.split(";");
Transaction txn = Ebean.beginTransaction();
try{
for (String temp : ids){
Computer savedComputer = Computer.find.byId(Long.parseLong(temp));
if (savedComputer != null){
Computer newComputerData = computerForm.get();
savedComputer.company = newComputerData.company;
savedComputer.discontinued = newComputerData.discontinued;
savedComputer.introduced = newComputerData.introduced;
savedComputer.name = newComputerData.name;
savedComputer.status = newComputerData.status;
savedComputer.moddt = new java.sql.Timestamp(dtcreate.getTime());
savedComputer.modby = singleUser.userName;
savedComputer.site = singleUser.site;
savedComputer.update();
flash("success", "Computer [ " + computerForm.get().name + " ] has been updated");
txn.commit();
}
}
} finally {
txn.end();
}
return GO_HOME;
}
I just put for before transaction and it works perfectly, thank you.
public Result savemulti(String selected) throws PersistenceException {
Form<Computer> computerForm = formFactory.form(Computer.class).bindFromRequest();
if(computerForm.hasErrors()) {return badRequest(views.html.computers.editMulti.render(AuthorisedUser.findByEmail(request().username()), computerForm, selected));}
java.util.Date dtcreate = new java.util.Date();
String connectedEmail = ctx().session().get("email");
AuthorisedUser singleUser = AuthorisedUser.findByEmail(connectedEmail);
String[] ids = selected.split(";");
for (String temp : ids)
{
Transaction txn = Ebean.beginTransaction();
try
{
Computer savedComputer = Computer.find.byId(Long.parseLong(temp));
if (savedComputer != null)
{
Computer newComputerData = computerForm.get();
savedComputer.company = newComputerData.company;
savedComputer.active = newComputerData.active;
savedComputer.discontinued = newComputerData.discontinued;
savedComputer.introduced = newComputerData.introduced;
savedComputer.name = newComputerData.name;
savedComputer.status = newComputerData.status;
savedComputer.moddt = new java.sql.Timestamp(dtcreate.getTime());
savedComputer.modby = singleUser.userName;
savedComputer.site = singleUser.site;
savedComputer.update();
txn.commit();
}
}
finally { txn.end(); }
}
flash("success", "Computers [ " + selected + " ] has been updated");
return GO_HOME;
}

How can I call an EJB3 session bean in a JSP?

I am developing an application in Eclipse using EJBs and JPA.
My Session bean is :
package itso.bank.session;
import itso.bank.entities.Account;
import itso.bank.entities.Customer;
import itso.bank.entities.Transaction;
import itso.bank.exception.ITSOBankException;
import itso.bank.service.EJBBankService;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
/**
* Session Bean implementation class EJBBankBean
*/
#Stateless
public class EJBBankBean implements EJBBankService {
#PersistenceContext (unitName="RAD8JPA", type=PersistenceContextType.TRANSACTION)
private EntityManager entityMgr;
/**
* Default constructor.
*/
public EJBBankBean() {
// TODO Auto-generated constructor stub
}
public void addCustomer(Customer customer) throws ITSOBankException {
System.out.println("addCustomer: " + customer.getSsn());
entityMgr.persist(customer);
}
public void closeAccount(String ssn, String id) throws ITSOBankException {
System.out.println("closeAccount: " + id + " of customer " + ssn);
Account account = getAccount(id);
Transaction[] trans = getTransactions(id);
for (Transaction tx : trans) {
entityMgr.remove(tx);
}
entityMgr.remove(account);
System.out.println("closed account with " + trans.length + " transactions");
}
public void deleteCustomer(String ssn) throws ITSOBankException {
System.out.println("deleteCustomer: " + ssn);
Customer customer = getCustomer(ssn);
Account[] accounts = getAccounts(ssn);
for (Account acct : accounts) {
closeAccount(ssn, acct.getId());
}
entityMgr.remove(customer);
}
public void deposit(String id, BigDecimal amount) throws ITSOBankException {
System.out.println("deposit: " + id + " amount " + amount);
Account account = getAccount(id);
try {
Transaction tx = account.processTransaction(amount, Transaction.CREDIT);
entityMgr.persist(tx);
} catch (Exception e) {
throw new ITSOBankException(e.getMessage());
}
}
public Account getAccount(String id) throws ITSOBankException {
System.out.println("getAccount: " + id);
try {
return entityMgr.find(Account.class, id);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
throw new ITSOBankException(id);
}
}
public Account[] getAccounts(String ssn) throws ITSOBankException {
System.out.println("getAccounts: " + ssn);
Query query = null;
try {
query = entityMgr.createNamedQuery("getAccountsBySSN");
query.setParameter(1, ssn);
List<Account> accountList = query.getResultList();
Account[] array = new Account[accountList.size()];
return accountList.toArray(array);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
throw new ITSOBankException(ssn);
}
}
public Customer getCustomer(String ssn) throws ITSOBankException {
System.out.println("getCustomer: " + ssn);
//Query query = null;
try {
//query = entityMgr.createNamedQuery("getCustomerBySSN");
//query.setParameter(1, ssn);
//return (Customer)query.getSingleResult();
return entityMgr.find(Customer.class, ssn);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
throw new ITSOBankException(ssn);
}
}
public Customer[] getCustomers(String partialName) throws ITSOBankException {
System.out.println("getCustomer: " + partialName);
Query query = null;
try {
query = entityMgr.createNamedQuery("getCustomersByPartialName");
query.setParameter(1, partialName);
List<Customer> beanlist = query.getResultList();
Customer[] array = new Customer[beanlist.size()];
return beanlist.toArray(array);
} catch (Exception e) {
throw new ITSOBankException(partialName);
}
}
public Customer[] getCustomersAll() {
System.out.println("getCustomers: all");
Query query = null;
try {
query = entityMgr.createNamedQuery("getCustomers");
List<Customer> beanlist = query.getResultList();
Customer[] array = new Customer[beanlist.size()];
return beanlist.toArray(array);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
return null;
}
}
public Transaction[] getTransactions(String accountID) throws ITSOBankException {
System.out.println("getTransactions: " + accountID);
Query query = null;
try {
query = entityMgr.createNamedQuery("getTransactionsByID");
query.setParameter(1, accountID);
List<Transaction> transactionsList = query.getResultList();
Transaction[] array = new Transaction[transactionsList.size()];
return transactionsList.toArray(array);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
throw new ITSOBankException(accountID);
}
}
public String openAccount(String ssn) throws ITSOBankException {
System.out.println("openAccount: " + ssn);
Customer customer = getCustomer(ssn);
int acctNumber = (new java.util.Random()).nextInt(899999) + 100000;
String id = "00" + ssn.substring(0, 1) + "-" + acctNumber;
Account account = new Account();
account.setId(id);
entityMgr.persist(account);
List<Customer> custSet = Arrays.asList(customer);
account.setCustomers(custSet);
System.out.println("openAccount: " + id);
return id;
}
public void transfer(String idDebit, String idCredit, BigDecimal amount) throws ITSOBankException {
System.out.println("transfer: " + idCredit + " " + idDebit + " amount " + amount);
withdraw(idDebit, amount);
deposit(idCredit, amount);
}
public void updateCustomer(String ssn, String title, String firstName, String lastName) throws ITSOBankException {
System.out.println("updateCustomer: " + ssn);
Customer customer = getCustomer(ssn);
customer.setTitle(title);
customer.setLastName(lastName);
customer.setFirstName(firstName);
System.out.println("updateCustomer: " + customer.getTitle() + " " + customer.getFirstName() + " " + customer.getLastName());
}
public void withdraw(String id, BigDecimal amount) throws ITSOBankException {
System.out.println("withdraw: " + id + " amount " + amount);
Account account = getAccount(id);
try {
Transaction tx = account.processTransaction(amount, Transaction.DEBIT);
entityMgr.persist(tx);
} catch (Exception e) {
throw new ITSOBankException(e.getMessage());
}
}
}
My JPA is already connected to the EJB project. My question is how I call the session bean from a Java Server Page, without the need for servlets?
Thank you!
Simply, Annotate Service Implementation class by #Named annotation
#Stateless
#Named("eJBBankBean")
public class EJBBankBean implements EJBBankService {....}
In your JSP file, use:
#{ejbBankBean.yourServiceMethod(parameter1_ifAny,parameter2_ifAny)}
#Named is CDI Annotation, without #Named EJB Bean will not visible in JSP EL i.e. '$' or Unified EL i.e. '#'
I suppose there must be a reason for not using an MVC framework.
So, supposing you are using a local interface, this is the cleanest and standard way I remember for invoking an ejb from a .jsp
<ejb-local-ref>
<ejb-ref-name>MyBeanName</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>com.myapp.ejb.MyBeanLocal</local>
</ejb-local-ref>
Then from your jsp
<%
String lookupUrl = "java:comp/env/MyBeanName";
Context ctx = new javax.naming.InitialContext();
MyBeanNameLocal ejbLocal = (MyBeanNameLocal) ctx.lookup(lookupUrl);
String output = ejbLocal.myBusinessMethod();
%>

QuickBooks NULL CallbackHandler

I'm trying to perform a batch operation in QuickBook but getting null callbackhandler.
private static void AddBulkCustomer(DataService ds) throws FMSException{
BatchOperation bo = new BatchOperation();
Customer c1 = new Customer();
c1.setGivenName("Customer 3");
c1.setDisplayName("Disp Customer 3");
EmailAddress email = new EmailAddress();
email.setAddress("customer1#zzz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b3");
c1= null;
c1 = new Customer();
c1.setGivenName("Customer 4");
c1.setDisplayName("Disp Customer 4");
email = null;
email = new EmailAddress();
email.setAddress("customer2#z2zz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b4");
// String strQuery = " select * from customer where givenname ='"+c1.getGivenName()+"'";
// bo.addQuery(strQuery, "b3Query");
ds.executeBatchAsync(bo, new AsyncCallBackBatch());
}
For AsyncCallback operation
public class AsyncCallBackBatch implements CallbackHandler {
#Override
public void execute(CallbackMessage callbackMsg) {
System.out.println("asyncCallbackBatch is executing... ");
try {
System.out.println("QR = "+callbackMsg.getFMSException().toString());
BatchOperation BO = callbackMsg.getBatchOperation();
if (BO != null) {
List<String> bId = BO.getBIds();
for (String strBId : bId) {
if (BO.isFault(strBId)) {
Fault fault = BO.getFault(strBId);
System.out.println("asyncCallBackBatch Error Code : "+ fault.getError().get(0).getCode() + " "+ "Error : "
+ fault.getError().get(0).getDetail()+ ", Message : "+ fault.getError().get(0).getMessage());
} else if (BO.isEntity(strBId)) {
System.out.println("Batch having entity message.. ");
Customer cust = (Customer) BO.getEntity(strBId);
System.out.println("cust id : " + cust.getId()+ " CustName = " + cust.getGivenName());
} else if (BO.isQuery(strBId)) {
System.out.println("Batch having Query ... Parsing... ");
QueryResult qR = BO.getQueryResponse(strBId);
System.out.println("Query : " + qR.getTotalCount());
} else if (BO.isReport(strBId)) {
System.out.println("Batch having Report... ");
Report report = BO.getReport(strBId);
System.out.println(" " + report.getClass().getName());
} else {
System.out.println("Something went wrong... ");
}
}
}else{
System.out.println("Batch Operation terminated, reason: NULL callbackMsg ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
OAuthAuthorizer oAuth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
//403352746
try {
Context context = new Context(oAuth, ServiceType.QBO, "403352746");
System.out.println("RealmID : "+context.getRealmID());
context.setCustomerRequestTimeout(99999);
System.out.println("TimeOut Set to = "+context.getCustomerRequestTimeout());
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
DataService ds = new DataService(context);
AddBulkCustomer(ds);
System.out.println("Operation Complete..");
} catch (Exception e) {
e.printStackTrace();
}
}
When I debug, in execute method, I'm getting Null BatchOperation in return. I'm not sure performing Batch operation is allowed in sandbox environment.
I found the solution after so much of testing and communication with Quickbooks Devs thought would be helpful for others.
In sandbox environment even if you set the config properties to sandbox URL it still picks as PROD URL in Callbackhandler.
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
In this case they called this as a bug, currently all you can do is to make a trial account in PROD and then test this.

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