use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.
the class EntityTestSuite method testTransactionUtilMoreThanTimeout.
/*
* This test will verify that a transaction which takes longer than the pre-set timeout are rolled back.
*/
public void testTransactionUtilMoreThanTimeout() throws Exception {
GenericTransactionException caught = null;
try {
GenericValue testValue = delegator.makeValue("Testing", "testingId", "timeout-test");
// timeout set to 10 seconds
boolean transBegin = TransactionUtil.begin(10);
delegator.create(testValue);
Thread.sleep(20 * 1000);
TransactionUtil.commit(transBegin);
} catch (GenericTransactionException e) {
caught = e;
} finally {
assertNotNull("timeout thrown", caught);
delegator.removeByAnd("Testing", "testingId", "timeout-test");
}
}
use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.
the class PayPalEvents method cancelPayPalOrder.
/**
* Event called when customer cancels a paypal order
*/
public static String cancelPayPalOrder(HttpServletRequest request, HttpServletResponse response) {
Locale locale = UtilHttp.getLocale(request);
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
// get the stored order id from the session
String orderId = (String) request.getSession().getAttribute("PAYPAL_ORDER");
// attempt to start a transaction
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
} catch (GenericTransactionException gte) {
Debug.logError(gte, "Unable to begin transaction", module);
}
// cancel the order
boolean okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
if (okay) {
try {
TransactionUtil.commit(beganTransaction);
} catch (GenericTransactionException gte) {
Debug.logError(gte, "Unable to commit transaction", module);
}
} else {
try {
TransactionUtil.rollback(beganTransaction, "Failure in processing PayPal cancel callback", null);
} catch (GenericTransactionException gte) {
Debug.logError(gte, "Unable to rollback transaction", module);
}
}
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resourceErr, "payPalEvents.previousPayPalOrderHasBeenCancelled", locale));
return "success";
}
use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.
the class EntitySyncContext method assembleValuesToStore.
public ArrayList<GenericValue> assembleValuesToStore() throws SyncDataErrorException {
// simulate two ordered lists and merge them on-the-fly for faster combined sorting
// make it an ArrayList to easily merge in sorted lists
ArrayList<GenericValue> valuesToStore = new ArrayList<GenericValue>();
if (this.nextUpdateTxTime != null && (this.nextUpdateTxTime.equals(currentRunEndTime) || this.nextUpdateTxTime.after(currentRunEndTime))) {
// this means that for all entities in this pack we found on the last pass that there would be nothing for this one, so just return nothing...
return valuesToStore;
}
// Debug.logInfo("Getting values to store; currentRunStartTime=" + currentRunStartTime + ", currentRunEndTime=" + currentRunEndTime, module);
int entitiesSkippedForKnownNext = 0;
// iterate through entities, get all records with tx stamp in the current time range, put all in a single list
for (ModelEntity modelEntity : entityModelToUseList) {
int insertBefore = 0;
// first test to see if we know that there are no records for this entity in this time period...
Timestamp knownNextUpdateTime = this.nextEntityUpdateTxTime.get(modelEntity.getEntityName());
if (knownNextUpdateTime != null && (knownNextUpdateTime.equals(currentRunEndTime) || knownNextUpdateTime.after(currentRunEndTime))) {
entitiesSkippedForKnownNext++;
continue;
}
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin(7200);
} catch (GenericTransactionException e) {
throw new SyncDataErrorException("Unable to begin JTA transaction", e);
}
try {
// get all values that were updated, but NOT created in the current time range; if no info on created stamp, that's okay we'll include it here because it won't have been included in the valuesToCreate list
EntityCondition createdBeforeStartCond = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunStartTime));
EntityCondition findValCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunStartTime), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime), createdBeforeStartCond);
EntityListIterator eli = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findValCondition).orderBy(ModelEntity.STAMP_TX_FIELD, ModelEntity.STAMP_FIELD).queryIterator();
GenericValue nextValue = null;
long valuesPerEntity = 0;
while ((nextValue = eli.next()) != null) {
// find first value in valuesToStore list, starting with the current insertBefore value, that has a STAMP_TX_FIELD after the nextValue.STAMP_TX_FIELD, then do the same with STAMP_FIELD
while (insertBefore < valuesToStore.size() && valuesToStore.get(insertBefore).getTimestamp(ModelEntity.STAMP_TX_FIELD).before(nextValue.getTimestamp(ModelEntity.STAMP_TX_FIELD))) {
insertBefore++;
}
while (insertBefore < valuesToStore.size() && valuesToStore.get(insertBefore).getTimestamp(ModelEntity.STAMP_FIELD).before(nextValue.getTimestamp(ModelEntity.STAMP_FIELD))) {
insertBefore++;
}
valuesToStore.add(insertBefore, nextValue);
valuesPerEntity++;
}
eli.close();
// if we didn't find anything for this entity, find the next value's Timestamp and keep track of it
if (valuesPerEntity == 0) {
Timestamp startCheckStamp = new Timestamp(System.currentTimeMillis() - syncEndBufferMillis);
EntityCondition findNextCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunEndTime), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime));
EntityListIterator eliNext = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findNextCondition).orderBy(ModelEntity.STAMP_TX_FIELD).queryIterator();
// get the first element and it's tx time value...
GenericValue firstVal = eliNext.next();
eliNext.close();
Timestamp nextTxTime;
if (firstVal != null) {
nextTxTime = firstVal.getTimestamp(ModelEntity.CREATE_STAMP_TX_FIELD);
} else {
// no results? well, then it's safe to say that up to the pre-querytime (minus the buffer, as usual) we are okay
nextTxTime = startCheckStamp;
}
if (this.nextUpdateTxTime == null || nextTxTime.before(this.nextUpdateTxTime)) {
this.nextUpdateTxTime = nextTxTime;
Debug.logInfo("EntitySync: Set nextUpdateTxTime to [" + nextTxTime + "]", module);
}
Timestamp curEntityNextTxTime = this.nextEntityUpdateTxTime.get(modelEntity.getEntityName());
if (curEntityNextTxTime == null || nextTxTime.before(curEntityNextTxTime)) {
this.nextEntityUpdateTxTime.put(modelEntity.getEntityName(), nextTxTime);
Debug.logInfo("EntitySync: Set nextEntityUpdateTxTime to [" + nextTxTime + "] for the entity [" + modelEntity.getEntityName() + "]", module);
}
}
} catch (GenericEntityException e) {
try {
TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleValuesToStore", e);
} catch (GenericTransactionException e2) {
Debug.logWarning(e2, "Unable to call rollback()", module);
}
throw new SyncDataErrorException("Error getting values to store from the datasource", e);
} catch (Throwable t) {
try {
TransactionUtil.rollback(beganTransaction, "General error in assembleValuesToStore", t);
} catch (GenericTransactionException e2) {
Debug.logWarning(e2, "Unable to call rollback()", module);
}
throw new SyncDataErrorException("Caught runtime error while getting values to store", t);
}
try {
TransactionUtil.commit(beganTransaction);
} catch (GenericTransactionException e) {
throw new SyncDataErrorException("Commit transaction failed", e);
}
}
if (entitiesSkippedForKnownNext > 0) {
if (Debug.infoOn())
Debug.logInfo("In assembleValuesToStore skipped [" + entitiesSkippedForKnownNext + "/" + entityModelToUseList + "] entities for the time period ending at [" + currentRunEndTime + "] because of next known update times", module);
}
// TEST SECTION: leave false for normal use
boolean logValues = false;
if (logValues && valuesToStore.size() > 0) {
StringBuilder toStoreInfo = new StringBuilder();
for (GenericValue valueToStore : valuesToStore) {
toStoreInfo.append("\n-->[");
toStoreInfo.append(valueToStore.get(ModelEntity.STAMP_TX_FIELD));
toStoreInfo.append(":");
toStoreInfo.append(valueToStore.get(ModelEntity.STAMP_FIELD));
toStoreInfo.append("] ");
toStoreInfo.append(valueToStore.getPrimaryKey());
}
Debug.logInfo(toStoreInfo.toString(), module);
}
// this calculation is false, so it needs to be nullified
if (valuesToStore.size() > 0) {
this.nextUpdateTxTime = null;
}
return valuesToStore;
}
use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.
the class ControlServlet method doGet.
/**
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long requestStartTime = System.currentTimeMillis();
RequestHandler requestHandler = this.getRequestHandler();
HttpSession session = request.getSession();
// setup DEFAULT character encoding and content type, this will be overridden in the RequestHandler for view rendering
String charset = request.getCharacterEncoding();
// setup content type
String contentType = "text/html";
if (UtilValidate.isNotEmpty(charset) && !"none".equals(charset)) {
response.setContentType(contentType + "; charset=" + charset);
response.setCharacterEncoding(charset);
} else {
response.setContentType(contentType);
}
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
// set the Entity Engine user info if we have a userLogin
if (userLogin != null) {
GenericDelegator.pushUserIdentifier(userLogin.getString("userLoginId"));
}
// workaraound if we are in the root webapp
String webappName = UtilHttp.getApplicationName(request);
String rname = "";
if (request.getPathInfo() != null) {
rname = request.getPathInfo().substring(1);
}
if (rname.indexOf('/') > 0) {
rname = rname.substring(0, rname.indexOf('/'));
}
UtilTimer timer = null;
if (Debug.timingOn()) {
timer = new UtilTimer();
timer.setLog(true);
timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Begun, encoding=[" + charset + "]", module);
}
// Setup the CONTROL_PATH for JSP dispatching.
String contextPath = request.getContextPath();
if (contextPath == null || "/".equals(contextPath)) {
contextPath = "";
}
request.setAttribute("_CONTROL_PATH_", contextPath + request.getServletPath());
if (Debug.verboseOn()) {
Debug.logVerbose("Control Path: " + request.getAttribute("_CONTROL_PATH_"), module);
}
// for convenience, and necessity with event handlers, make security and delegator available in the request:
// try to get it from the session first so that we can have a delegator/dispatcher/security for a certain user if desired
Delegator delegator = null;
String delegatorName = (String) session.getAttribute("delegatorName");
if (UtilValidate.isNotEmpty(delegatorName)) {
delegator = DelegatorFactory.getDelegator(delegatorName);
}
if (delegator == null) {
delegator = (Delegator) getServletContext().getAttribute("delegator");
}
if (delegator == null) {
Debug.logError("[ControlServlet] ERROR: delegator not found in ServletContext", module);
} else {
request.setAttribute("delegator", delegator);
// always put this in the session too so that session events can use the delegator
session.setAttribute("delegatorName", delegator.getDelegatorName());
}
LocalDispatcher dispatcher = (LocalDispatcher) session.getAttribute("dispatcher");
if (dispatcher == null) {
dispatcher = (LocalDispatcher) getServletContext().getAttribute("dispatcher");
}
if (dispatcher == null) {
Debug.logError("[ControlServlet] ERROR: dispatcher not found in ServletContext", module);
}
request.setAttribute("dispatcher", dispatcher);
Security security = (Security) session.getAttribute("security");
if (security == null) {
security = (Security) getServletContext().getAttribute("security");
}
if (security == null) {
Debug.logError("[ControlServlet] ERROR: security not found in ServletContext", module);
}
request.setAttribute("security", security);
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
if (visualTheme != null) {
UtilHttp.setVisualTheme(request, visualTheme);
}
request.setAttribute("_REQUEST_HANDLER_", requestHandler);
ServletContextHashModel ftlServletContext = new ServletContextHashModel(this, FreeMarkerWorker.getDefaultOfbizWrapper());
request.setAttribute("ftlServletContext", ftlServletContext);
// setup some things that should always be there
UtilHttp.setInitialRequestInfo(request);
VisitHandler.getVisitor(request, response);
// set the Entity Engine user info if we have a userLogin
String visitId = VisitHandler.getVisitId(session);
if (UtilValidate.isNotEmpty(visitId)) {
GenericDelegator.pushSessionIdentifier(visitId);
}
// display details on the servlet objects
if (Debug.verboseOn()) {
logRequestInfo(request);
}
// some containers call filters on EVERY request, even forwarded ones, so let it know that it came from the control servlet
request.setAttribute(ControlFilter.FORWARDED_FROM_SERVLET, Boolean.TRUE);
String errorPage = null;
try {
// the ServerHitBin call for the event is done inside the doRequest method
requestHandler.doRequest(request, response, null, userLogin, delegator);
} catch (RequestHandlerException e) {
Throwable throwable = e.getNested() != null ? e.getNested() : e;
if (throwable instanceof IOException) {
// the connection with the browser is lost and so there is no need to serve the error page; a message is logged to record the event
if (Debug.warningOn())
Debug.logWarning(e, "Communication error with the client while processing the request: " + request.getAttribute("_CONTROL_PATH_") + request.getPathInfo(), module);
if (Debug.verboseOn())
Debug.logVerbose(throwable, module);
} else {
Debug.logError(throwable, "Error in request handler: ", module);
request.setAttribute("_ERROR_MESSAGE_", UtilCodec.getEncoder("html").encode(throwable.toString()));
errorPage = requestHandler.getDefaultErrorPage(request);
}
} catch (RequestHandlerExceptionAllowExternalRequests e) {
errorPage = requestHandler.getDefaultErrorPage(request);
Debug.logInfo("Going to external page: " + request.getPathInfo(), module);
} catch (Exception e) {
Debug.logError(e, "Error in request handler: ", module);
request.setAttribute("_ERROR_MESSAGE_", UtilCodec.getEncoder("html").encode(e.toString()));
errorPage = requestHandler.getDefaultErrorPage(request);
}
if (errorPage != null) {
Debug.logError("An error occurred, going to the errorPage: " + errorPage, module);
RequestDispatcher rd = request.getRequestDispatcher(errorPage);
// use this request parameter to avoid infinite looping on errors in the error page...
if (request.getAttribute("_ERROR_OCCURRED_") == null && rd != null) {
request.setAttribute("_ERROR_OCCURRED_", Boolean.TRUE);
Debug.logError("Including errorPage: " + errorPage, module);
// NOTE DEJ20070727 after having trouble with all of these, try to get the page out and as a last resort just send something back
try {
rd.include(request, response);
} catch (Throwable t) {
Debug.logWarning("Error while trying to send error page using rd.include (will try response.getOutputStream or response.getWriter): " + t.toString(), module);
String errorMessage = "ERROR rendering error page [" + errorPage + "], but here is the error text: " + request.getAttribute("_ERROR_MESSAGE_");
try {
response.getWriter().print(errorMessage);
} catch (Throwable t2) {
try {
int errorToSend = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
Debug.logWarning("Error while trying to write error message using response.getOutputStream or response.getWriter: " + t.toString() + "; sending error code [" + errorToSend + "], and message [" + errorMessage + "]", module);
response.sendError(errorToSend, errorMessage);
} catch (Throwable t3) {
// wow, still bad... just throw an IllegalStateException with the message and let the servlet container handle it
throw new IllegalStateException(errorMessage);
}
}
}
} else {
if (rd == null) {
Debug.logError("Could not get RequestDispatcher for errorPage: " + errorPage, module);
}
String errorMessage = "<html><body>ERROR in error page, (infinite loop or error page not found with name [" + errorPage + "]), but here is the text just in case it helps you: " + request.getAttribute("_ERROR_MESSAGE_") + "</body></html>";
response.getWriter().print(errorMessage);
}
}
// sanity check: make sure we don't have any transactions in place
try {
// roll back current TX first
if (TransactionUtil.isTransactionInPlace()) {
Debug.logWarning("*** NOTICE: ControlServlet finished w/ a transaction in place! Rolling back.", module);
TransactionUtil.rollback();
}
// now resume/rollback any suspended txs
if (TransactionUtil.suspendedTransactionsHeld()) {
int suspended = TransactionUtil.cleanSuspendedTransactions();
Debug.logWarning("Resumed/Rolled Back [" + suspended + "] transactions.", module);
}
} catch (GenericTransactionException e) {
Debug.logWarning(e, module);
}
// run these two again before the ServerHitBin.countRequest call because on a logout this will end up creating a new visit
if (response.isCommitted() && request.getSession(false) == null) {
// response committed and no session, and we can't get a new session, what to do!
// without a session we can't log the hit, etc; so just do nothing; this should NOT happen much!
Debug.logError("Error in ControlServlet output where response isCommitted and there is no session (probably because of a logout); not saving ServerHit/Bin information because there is no session and as the response isCommitted we can't get a new one. The output was successful, but we just can't save ServerHit/Bin info.", module);
} else {
try {
UtilHttp.setInitialRequestInfo(request);
VisitHandler.getVisitor(request, response);
if (requestHandler.trackStats(request)) {
ServerHitBin.countRequest(webappName + "." + rname, request, requestStartTime, System.currentTimeMillis() - requestStartTime, userLogin);
}
} catch (Throwable t) {
Debug.logError(t, "Error in ControlServlet saving ServerHit/Bin information; the output was successful, but can't save this tracking information. The error was: " + t.toString(), module);
}
}
if (Debug.timingOn())
timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Done", module);
// sanity check 2: make sure there are no user or session infos in the delegator, ie clear the thread
GenericDelegator.clearUserIdentifierStack();
GenericDelegator.clearSessionIdentifierStack();
}
use of org.apache.ofbiz.entity.transaction.GenericTransactionException in project ofbiz-framework by apache.
the class JmsServiceEngine method runXaQueue.
protected Map<String, Object> runXaQueue(ModelService modelService, Map<String, Object> context, Element server) throws GenericServiceException {
String serverName = server.getAttribute("jndi-server-name");
String jndiName = server.getAttribute("jndi-name");
String queueName = server.getAttribute("topic-queue");
String userName = server.getAttribute("username");
String password = server.getAttribute("password");
String clientId = server.getAttribute("client-id");
InitialContext jndi = null;
XAQueueConnectionFactory factory = null;
XAQueueConnection con = null;
try {
jndi = JNDIContextFactory.getInitialContext(serverName);
factory = (XAQueueConnectionFactory) jndi.lookup(jndiName);
} catch (GeneralException ge) {
throw new GenericServiceException("Problems getting JNDI InitialContext.", ge.getNested());
} catch (NamingException ne) {
JNDIContextFactory.clearInitialContext(serverName);
try {
jndi = JNDIContextFactory.getInitialContext(serverName);
factory = (XAQueueConnectionFactory) jndi.lookup(jndiName);
} catch (GeneralException ge2) {
throw new GenericServiceException("Problems getting JNDI InitialContext.", ge2.getNested());
} catch (NamingException ne2) {
throw new GenericServiceException("JNDI lookup problems.", ne2);
}
}
try {
con = factory.createXAQueueConnection(userName, password);
if (clientId.length() > 1)
con.setClientID(userName);
con.start();
// enlist the XAResource
XAQueueSession session = con.createXAQueueSession();
XAResource resource = session.getXAResource();
if (TransactionUtil.getStatus() == TransactionUtil.STATUS_ACTIVE)
TransactionUtil.enlistResource(resource);
Queue queue = (Queue) jndi.lookup(queueName);
QueueSession qSession = session.getQueueSession();
QueueSender sender = qSession.createSender(queue);
// create/send the message
Message message = makeMessage(session, modelService, context);
sender.send(message);
if (TransactionUtil.getStatus() != TransactionUtil.STATUS_ACTIVE)
session.commit();
Debug.logInfo("Message sent.", module);
// close the connections
sender.close();
session.close();
con.close();
} catch (GenericTransactionException gte) {
throw new GenericServiceException("Problems enlisting resource w/ transaction manager.", gte.getNested());
} catch (NamingException ne) {
throw new GenericServiceException("Problems with JNDI lookup.", ne);
} catch (JMSException je) {
throw new GenericServiceException("JMS Internal Error.", je);
}
return ServiceUtil.returnSuccess();
}
Aggregations