Java tutorial
package com.webbfontaine.valuewebb.gtns; import com.webbfontaine.valuewebb.action.tt.TtGenHome; import com.webbfontaine.valuewebb.authentication.AuthenticatorBean; import com.webbfontaine.valuewebb.gtns.fis.FisInterface; import com.webbfontaine.valuewebb.model.TtGen; import com.webbfontaine.valuewebb.model.util.DBUtils; import com.webbfontaine.valuewebb.model.util.GCNetUtils; import com.webbfontaine.valuewebb.model.util.Utils; import org.apache.commons.lang3.StringUtils; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.async.Asynchronous; import org.jboss.seam.annotations.async.Expiration; import org.jboss.seam.annotations.async.IntervalCron; import org.jboss.seam.async.QuartzTriggerHandle; import org.jboss.seam.log.Log; import org.jboss.seam.log.Logging; import org.jboss.seam.transaction.Transaction; import javax.persistence.EntityManager; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import static com.webbfontaine.valuewebb.model.constants.Constants.*; import static com.webbfontaine.valuewebb.model.constants.Messages.FCVR_ALREADY_EXIST; /** * Copyrights 2002-2010 Webb Fontaine * This software is the proprietary information of Webb Fontaine. * Its use is subject to License terms. * User: nigiyan * Date: Oct 21, 2010 */ @Name("TTGTNSSynchronizer") @AutoCreate @Scope(ScopeType.APPLICATION) public class TTGTNSSynchronizer { private static final Object LOCK = new Object(); private static final Log LOGGER = Logging.getLog(TTGTNSSynchronizer.class); private final static String UPDATE_TT_SQL = "UPDATE TT_GEN SET SUBMITTED_TO_GCNET = 1 WHERE TT_ID = ?"; public TTGTNSSynchronizer() { } @Asynchronous public QuartzTriggerHandle findSentFCVRScheduleTask(@Expiration Date when, @IntervalCron String interval) { LOGGER.debug("Scheduler to upload FCVR started"); long startTime = System.currentTimeMillis(); synchronized (LOCK) { // allow only one async thread to do this EntityManager entityManager = (EntityManager) Component.getInstance("entityManager", ScopeType.STATELESS, true); List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSentTTIdsGH)).getResultList(); LOGGER.debug("Found Sent TTs: {0}", ttIDs); if (ttIDs.isEmpty()) { return null; } for (Long ttId : ttIDs) { TtGen ttGen = entityManager.find(TtGen.class, ttId); if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread continue; } FisInterface fisInterface = new FisInterface(); LOGGER.debug("Sending request to upload FCVR for TT # {0}, FCVR Number = {1}", ttGen.getId(), ttGen.getFcvrNum()); List<String> uploadErrors = fisInterface.sendFCVRUploadRequest(ttGen); if (uploadErrors != null) { if (uploadErrors.isEmpty()) { LOGGER.debug( "Request to upload FCVR for TT # {0}, FCVR Number = {1} is successfully sent, setting GCNet Submission Flag 'true'", ttGen.getId(), ttGen.getFcvrNum()); updateTTFlag(ttGen); } else { if (!GCNetUtils.isContain(uploadErrors, FCVR_ALREADY_EXIST)) { LOGGER.debug("Error(s) during upload FCVR: {0}", GCNetUtils.constraintUploadErrors(uploadErrors)); if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) { LOGGER.error("Can not login with 'daemon' identity to update TTs"); return null; } updateTTForSentError(ttGen, uploadErrors); AuthenticatorBean.getDaemonIdentity().logout(); } } } } } LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime); return null; } @Asynchronous public QuartzTriggerHandle getFCVRStatusScheduleTask(@Expiration Date when, @IntervalCron String interval) { LOGGER.debug("Scheduler to get FCVR status started"); long startTime = System.currentTimeMillis(); synchronized (LOCK) { // allow only one async thread to do this EntityManager entityManager = (EntityManager) Component.getInstance("entityManager", ScopeType.STATELESS, true); List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSubmittedSentTTIds)) .getResultList(); LOGGER.debug("Found Sent and Uploaded TTs: {0}", ttIDs); if (ttIDs.isEmpty()) { return null; } if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) { LOGGER.error("Can not login with 'daemon' identity to get TTs status and update TTs"); return null; } for (Long ttId : ttIDs) { TtGen ttGen = entityManager.find(TtGen.class, ttId); if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread continue; } FisInterface fisInterface = new FisInterface(); LOGGER.debug("Sending request to get FCVR status for TT # {0}, FCVR Number = {1}", ttGen.getId(), ttGen.getFcvrNum()); Map<String, List<String>> remSt = fisInterface.retrieveFCVRValidationStatus(ttGen.getFcvrNum(), new Date()); if (remSt != null) { String key = (String) remSt.keySet().toArray()[0]; if (GCNetUtils.isRejected(key)) { LOGGER.debug( "Got successfully FCVR 'Rejected' status for TT # {0}, FCVR Number = {1}, setting GCNet Submission Flag 'false'. Error message is: {2}", ttGen.getId(), ttGen.getFcvrNum(), remSt.get(key)); ttGen.setSubmittedToGCNet(false); updateTTForSentError(ttGen, remSt.get(key)); } else { if (GCNetUtils.isAccepted(key)) { LOGGER.debug( "Got successfully FCVR 'Accepted' status for TT # {0}, FCVR Number = {1}, setting GCNet Submission Flag 'false'", ttGen.getId(), ttGen.getFcvrNum()); ttGen.setSubmittedToGCNet(false); updateTT(ttGen, RESPONSE_OK); } else { if (GCNetUtils.isSubmitted(key)) { LOGGER.debug( "TT # {0}, FCVR Number = {1} is still in Submitted status on GCNet side", ttGen.getId(), ttGen.getFcvrNum()); } } } } } AuthenticatorBean.getDaemonIdentity().logout(); } LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime); return null; } private static void updateTTFlag(TtGen ttGen) { Connection conn = null; PreparedStatement ps = null; try { conn = Utils.getSQLConnection(); conn.setAutoCommit(false); ps = conn.prepareStatement(UPDATE_TT_SQL); ps.setLong(1, ttGen.getId()); ps.executeUpdate(); conn.commit(); } catch (SQLException e) { LOGGER.error("Error in updating GCNet Submission Flag for TT with id {0}, error {1}", ttGen.getId(), e); } finally { DBUtils.closeResource(ps); DBUtils.closeResource(conn); } } protected void updateTTForSentError(TtGen ttGen, List<String> errorMessages) { String errMessage = StringUtils.join(errorMessages.toArray(), '\n'); errMessage = StringUtils.defaultString(StringUtils.trimToNull(errMessage), "N/A"); ttGen.setFcvrCurrentSentError(errMessage); updateTT(ttGen, ERROR_RESPONSE); } protected static void updateTT(TtGen ttGen, String operation) { LOGGER.debug("Going to execute {0} operation on TT with id {1}.", operation, ttGen.getId()); assert !StringUtils.isEmpty(operation) && ttGen != null : "ttGen and requestedOperation must not be null"; UserTransaction utx = null; try { utx = Transaction.instance(); utx.begin(); TtGenHome ttGenHome = createTTHomeInstance(ttGen); if (ttGenHome.performDirectTaskWithoutDocumentCheck(operation).equals(UPDATED)) { if (RESPONSE_OK.equals(operation)) { utx.commit(); utx = Transaction.instance(); utx.begin(); ttGenHome.pickUp(); } utx.commit(); } else { LOGGER.error("Failed to execute {0} operation for TT with id {1}. Will continue with next TTs", operation, ttGen.getId()); utx.rollback(); } } catch (Exception e) { LOGGER.error("Exception on updating TT with id: {0} for operation: {1} fails", e, ttGen.getId(), operation); if (utx != null) { try { utx.rollback(); } catch (SystemException sex) { LOGGER.error("", sex); } } } } private static TtGenHome createTTHomeInstance(TtGen ttGen) { return TtGenHome.createInstance(ttGen); } }