EJB异步提交和存取过程的使用

来源:互联网 发布:java数据结构编程 编辑:程序博客网 时间:2024/05/29 12:31
1.EJB 异步类Event.class
package org.jboss.seam.core;import static org.jboss.seam.annotations.Install.BUILT_IN;import java.util.List;import org.jboss.seam.Component;import org.jboss.seam.ScopeType;import org.jboss.seam.annotations.Install;import org.jboss.seam.annotations.Name;import org.jboss.seam.annotations.Scope;import org.jboss.seam.annotations.intercept.BypassInterceptors;import org.jboss.seam.async.AbstractDispatcher;import org.jboss.seam.async.CronSchedule;import org.jboss.seam.async.Dispatcher;import org.jboss.seam.async.Schedule;import org.jboss.seam.async.TimerSchedule;import org.jboss.seam.contexts.Contexts;import org.jboss.seam.core.Expressions.MethodExpression;import org.jboss.seam.core.Init.ObserverMethod;import org.jboss.seam.core.Init.ObserverMethodExpression;import org.jboss.seam.log.LogProvider;import org.jboss.seam.log.Logging;/** * Support for Seam component-driven events *  * @author Gavin King * */@Scope(ScopeType.EVENT)@BypassInterceptors@Name("org.jboss.seam.core.events")@Install(precedence=BUILT_IN)public class Events {      private static final LogProvider log = Logging.getLogProvider(Events.class);      /**    * Add a new listener for a given event type    *     * @param type the event type    * @param methodBindingExpression a method binding, expressed in EL    * @param argTypes the argument types of the method binding    */   public void addListener(String type, String methodBindingExpression, Class... argTypes)   {      MethodExpression methodBinding = Expressions.instance().createMethodExpression(methodBindingExpression, Object.class, argTypes);      Init.instance().addObserverMethodExpression(type, methodBinding);   }      /**    * Raise an event that is to be processed synchronously    *     * @param type the event type    * @param parameters parameters to be passes to the listener method    */   public void raiseEvent(String type, Object... parameters)   {      //TODO: find a way to map event parameters to params in an EL-defined listener      log.trace("Processing event:" + type);      List list = Init.instance().getObserverMethodExpressions(type);      if (list!=null)      {         for (ObserverMethodExpression listener: list )         {            listener.getMethodBinding().invoke(parameters);         }      }      List observers = Init.instance().getObserverMethods(type);      if (observers!=null)      {         for (ObserverMethod observer: observers)         {            String name = observer.getComponent().getName();            Object listener = Component.getInstance( name, observer.isCreate(), false );            if ( observer.getComponent().hasUnwrapMethod() )            {               listener = observer.getComponent().getScope().getContext().get(name);            }                        if (listener!=null)            {               observer.getComponent().callComponentMethod(listener, observer.getMethod(), parameters);            }         }      }   }      /**    * Raise an event that is to be processed asynchronously    *     * @param type the event type    * @param parameters parameters to be passes to the listener method    */   public void raiseAsynchronousEvent(String type, Object... parameters)   {      getDispatcher().scheduleAsynchronousEvent(type, parameters);   }   /**    * Raise an event that is to be processed according to a "schedule"    *     * @see TimerSchedule (EJB, quartz or JDK timer service)    * @see CronSchedule (quartz timer service only)    *     * @param type the event type    * @param schedule the schedule object, specific to the dispatcher strategy    * @param parameters parameters to be passes to the listener method    */   public void raiseTimedEvent(String type, Schedule schedule, Object... parameters)   {      getDispatcher().scheduleTimedEvent(type, schedule, parameters);   }      /**    * Raise an event that is to be processed after successful completion of     * the current transaction    *     * @param type the event type    * @param parameters parameters to be passes to the listener method    */   public void raiseTransactionSuccessEvent(String type, Object... parameters)   {      getDispatcher().scheduleTransactionSuccessEvent(type, parameters);   }      /**    * Raise an event that is to be processed after the current transaction    * ends    *     * @param type the event type    * @param parameters parameters to be passes to the listener method    */   public void raiseTransactionCompletionEvent(String type, Object... parameters)   {      getDispatcher().scheduleTransactionCompletionEvent(type, parameters);   }      /**    * @return the Dispatcher object to use for dispatching asynchronous    * and timed events    */   protected Dispatcher getDispatcher()   {      return AbstractDispatcher.instance();   }      public static boolean exists()   {      return Contexts.isEventContextActive() && instance()!=null;   }   public static Events instance()   {      return (Events) Component.getInstance(Events.class, ScopeType.EVENT);   }   }
2.调用异步代码,定义全局变量:public static final String BACKUP_MONTHLY_STOCK = "BACKUP_MONTHLY_STOCK";传入参数:BACKUP_MONTHLY_STOCK 字符串Events.instance().raiseAsynchronousEvent(BACKUP_MONTHLY_STOCK, endPeriod, company, getUsername());注入Observer(String type),这样可以达到异步监听的事件,取得connection,然后调用存取过程BACKUP_MONTHLY_STOCK_PKG,获得传递的参数,并执行
 @Observer("BACKUP_MONTHLY_STOCK")    public void backUpMonthlyStock(String endPeriod, String companyAid, String userName) throws SQLException {    Session session = (Session) entityManager.getDelegate();    @SuppressWarnings("deprecation")    Connection connection = session.connection();    CallableStatement callableStatement = null;    try {        callableStatement = connection.prepareCall(BACKUP_MONTHLY_STOCK_PKG);        callableStatement.setString(1, endPeriod); // endPeriod        callableStatement.setString(2, companyAid); // companyAid        callableStatement.setString(3, userName); // Month-End user name        callableStatement.registerOutParameter(4, java.sql.Types.VARCHAR); // Error Message        callableStatement.registerOutParameter(5, java.sql.Types.VARCHAR); // retcode        // execute BACKUP_MONTHLY_STOCK_PKG.fn_main        callableStatement.executeUpdate();        String errbuf = callableStatement.getString(4); // return Error Message        String retcode = callableStatement.getString(5);// return retcode        // retcode : 0 --> fail 1 --> success        // errbuf : when retcode = 0, shows error message.        // when retcode = 1, value is null.        System.out.println("UserName" + userName);        System.out.println("retcode" + retcode);        System.out.println("errbuf" + errbuf);        // if (retcode != null && retcode.equals(1)) {        // return;        // } else {        // throw new Exception(errbuf);        // }    } catch (SQLException e) {        throw e;    } finally {        if (callableStatement != null) {        callableStatement.close();        }        if (connection != null) {        connection.close();        }        if (session != null) {        session.disconnect();        }    }    }
3:存取过程:BACKUP_MONTHLY_STOCK_PKG
create or replacePACKAGE BODY      BACKUP_MONTHLY_STOCK_PKG is------------------------------------------------------------------------------------- 主程式 Main Program-----------------------------------------------------------------------------------procedure fn_main (x_p_end_period     in  varchar2,                   x_p_aid_company    in  varchar2,                   x_p_backup_user    in  varchar2,                   errbuf             out varchar2,                   retcode            out varchar2)is        --x_ln_end_period        varchar2(10);    x_ln_ret_code          number := 1;        begin             --x_ln_end_period := to_char(sysdate,'yyyy-MM');                  delete_IM_ITEM_STOCK_PERIOD(x_p_end_period,x_p_aid_company);                  INSERT INTO AGBS.IM_ITEM_STOCK_PERIOD (                                                 AID,                                                 AID_ITEM_STOCK,                                                  AID_COMPANY,                                                  AID_ITEM,                                                  AID_WAREHOUSE,                                                  END_PERIOD,                                                  IN_MIT_QUANTITY,                                                  QUANTITY,                                                  ASSIGNED_QUANTITY,                                                  RESERVED_QUANTITY,                                                  DO_IN_PROGRESS_QUANTITY,                                                  QC_QUANTITY,                                                  OUT_MIT_QUANTITY,                                                  DAILY_BEGIN_QUANTITY,                                                  MONTH_BEGIN_QUANTITY,                                                  LAST_MONTH_BEGIN_QUANTITY,                                                  USER_CREATED,                                                  DATE_CREATED,                                                  USER_LAST_MODIFIED,                                                  DATE_LAST_MODIFIED,                                                 USER_BACKUP)                                           SELECT                                                  fn_get_new_aid('IM_ITEM_STOCK_PERIOD'),                                                 AID,                                                  AID_COMPANY,                                                  AID_ITEM,                                                  AID_WAREHOUSE,                                                 x_p_end_period,                                                  IN_MIT_QUANTITY,                                                  QUANTITY,                                                     ASSIGNED_QUANTITY,                                                  RESERVED_QUANTITY,                                                  DO_IN_PROGRESS_QUANTITY,                                                     QC_QUANTITY,                                                  OUT_MIT_QUANTITY,                                                  DAILY_BEGIN_QUANTITY,                                                     MONTH_BEGIN_QUANTITY,                                                  LAST_MONTH_BEGIN_QUANTITY,                                                  USER_CREATED,                                                     DATE_CREATED,                                                  USER_LAST_MODIFIED,                                                  DATE_LAST_MODIFIED,                                                 x_p_backup_user                                            FROM AGBS.IM_ITEM_STOCK                                            WHERE AID_COMPANY = x_p_aid_company ;                          retcode := x_ln_ret_code;                          exception                when others then                  x_ln_ret_code := 0;                  errbuf :=  'System Failure:  ' ||SQLCODE||' -ERROR- '||SQLERRM;                          end fn_main;  ------------------------------------------------------------------------------------- delete period record-----------------------------------------------------------------------------------    procedure delete_IM_ITEM_STOCK_PERIOD(x_p_end_period     in  varchar2,                                          x_p_aid_company    in  varchar2)    is             BEGIN        delete from AGBS.IM_ITEM_STOCK_PERIOD          where END_PERIOD = x_p_end_period            and AID_COMPANY = x_p_aid_company;        END delete_IM_ITEM_STOCK_PERIOD;        ------------------------------------------------------------------------------------- 取得 New AID-----------------------------------------------------------------------------------    FUNCTION fn_get_new_aid(x_in_table_name varchar2) return varchar2    is         x_ln_aid varchar2(16);    BEGIN        select ADDI.GENERATE_AID('AGBS', x_in_table_name) into x_ln_aid          FROM DUAL;                  RETURN x_ln_aid;        END fn_get_new_aid;    end BACKUP_MONTHLY_STOCK_PKG;
原创粉丝点击