Ladies_Man

#sonic autorun Autotest

Nov 15th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 29.67 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.ResultSet;
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Set;
  11.  
  12. import org.apache.commons.logging.Log;
  13. import org.apache.commons.logging.LogFactory;
  14. import org.joda.time.DateTime;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16.  
  17. import ru.it.metasonic.ruspost.infopoint.utils.AttributeHelper;
  18. import ru.it.metasonic.ruspost.infopoint.utils.BOHelper;
  19. import ru.lbpm.metasonic.businessobjects.DbHelper;
  20. import ru.lbpm.metasonic.businessobjects.DbHelper.ValueWrapper;
  21.  
  22. import com.jcom1.api.constants.Constants.Storage.BusinessObject20;
  23. import com.jcom1.api.dto.init.InitProcessInstanceData;
  24. import com.jcom1.api.dto.interfaces.IProcessInstanceBean;
  25. import com.jcom1.api.dto.interfaces.IStorageInstanceBean;
  26. import com.jcom1.api.dto.interfaces.ISubjectInstanceBean;
  27. import com.jcom1.api.dto.interfaces.storages.IStorageInstanceItemBeanReducedToId;
  28. import com.jcom1.api.exceptions.ConnectionException;
  29. import com.jcom1.api.exceptions.ProcessInstanceNotAvailableException;
  30. import com.jcom1.api.interfaces.IAuthorizationAdministrationApi;
  31. import com.jcom1.api.interfaces.IAuthorizationApi;
  32. import com.jcom1.api.interfaces.IBo20AccessApi;
  33. import com.jcom1.api.interfaces.ICommonApi;
  34. import com.jcom1.api.interfaces.IInstanceAdministrationApi;
  35. import com.jcom1.api.util.IViewStorageInstanceItemPair;
  36. import com.jcom1.api.util.Pair;
  37. import com.jcom1.runtime.refinement.AbstractRefinement;
  38. import com.jcom1.runtime.refinement.FunctionStateRequest;
  39. import com.jcom1.runtime.refinement.FunctionStateResponse;
  40. import com.jcom1.runtime.refinement.RefinementGenerator;
  41.  
  42. import de.metasonic.businessobjects.model.interfaces.IView;
  43. import de.metasonic.refinement.global.api.ApiUtils;
  44.  
  45. /**
  46.  * @generated
  47.  */
  48. /**
  49.  * This method is called when the named function state is reached State:
  50.  * автозапуск формирования StateType: FUNCTION
  51.  *
  52.  * Return values "FunctionTransitionDescription_WZGO8WRYEeaW6tb5t7D8Ag" when
  53.  * result is "" to go to state Ожидание запуска
  54.  *
  55.  * @return return the id of the transition to follow e.g. // return new
  56.  *         FunctionStateResponse("transitionXXXXXXXX");
  57.  */
  58. @RefinementGenerator(id = "InternalSubjectDescription_rhsOwWRXEeaW6tb5t7D8Ag")
  59. public class Оператор_по_контролю_ОПС_ОтделаRefinement extends
  60.         AbstractRefinement {
  61.  
  62.     @Autowired
  63.     ICommonApi commonApi;
  64.  
  65.     @Autowired
  66.     IBo20AccessApi accessApi;
  67.  
  68.     @Autowired
  69.     IAuthorizationApi authApi;
  70.  
  71.     @Autowired
  72.     IAuthorizationAdministrationApi administrationApi;
  73.  
  74.     IInstanceAdministrationApi instanceAdminApi = null;
  75.  
  76.     private final String opsControlDescriptionId = "ProcessDescription_pn9a4VMdEeaL5PGyiwnPkA";
  77.     private final String opsControlFirstStateDescrId = "FunctionStateDescription_NZI2wWqtEeaiwr50C3BsOA";
  78.     private final String opsControlRecieveStateDescrId = "ReceiveStateDescription_qpvqI2UHEea_wrD0qXtRKA";
  79.     private final String opsControlFirstStateTransitionDescrId = "FunctionTransitionDescription_1_ah0WqtEeaiwr50C3BsOA";
  80.  
  81.     private final String DB_URL = "jdbc:hsqldb:hsql://localhost/jcom1";
  82.     private final String DB_USER = "sa";
  83.     private final String DB_PSW = "";
  84.  
  85.     private final String UFPS_INDEX = "UFPS_INDEX";
  86.     private final String UFPS_NAME = "UFPS_NAME";
  87.     private final String POSTAMT_INDEX = "POSTAMT_INDEX";
  88.     private final String POSTAMT_NAME = "POSTAMT_NAME";
  89.     private final String UM_GROUP = "UM_GROUP";
  90.     private final String UM_USER = "UM_USER";
  91.     private final String UM_GROUP_AS_INDEX = "INDX";
  92.     private final String UM_GROUP_AS_ROLE = "ROLE";
  93.  
  94.     private final String DEPARTMENT_CONTROLLER_GROUP_ID = "DEPARTMENT_CONTROLLER_GROUP_ID";
  95.  
  96.     private final String COMMON_INFO = "commonInfo";
  97.     private final String POSTAMT = "infoPoint";
  98.     private final String METADATA = "metaData";
  99.  
  100.     private final List<String> obsParamNames = Arrays.asList("autorunDate",
  101.             "autorunHour", "autorunMinute", "endPoint");
  102.     private final String AUTOTEST_MARK1 = "atest";
  103.     private final String AUTOTEST_MARK2 = "autotest";
  104.     private boolean ATEST = false;
  105.     private String ATEST_RES = "";
  106.  
  107.     private int departmentControllerGroupId;
  108.     /**
  109.      * @generated
  110.      */
  111.     private final static Log log = LogFactory
  112.             .getLog("com.jcom1.refinement.автозапуск_автоформирования_плана.оператор_по_контролю_опс_отделаrefinement");
  113.  
  114.     /**
  115.      * This method is called when the named function state is reached State:
  116.      * автозапуск формирования StateType: FUNCTION
  117.      *
  118.      * Return values "FunctionTransitionDescription_WZGO8WRYEeaW6tb5t7D8Ag" when
  119.      * result is "" to go to state Ожидание запуска
  120.      *
  121.      * @return return the id of the transition to follow e.g. // return new
  122.      *         FunctionStateResponse("transitionXXXXXXXX");
  123.      */
  124.     @RefinementGenerator(id = "FunctionStateDescription_G_53Y2RYEeaW6tb5t7D8Ag")
  125.     public FunctionStateResponse functionавтозапуск_формирования(
  126.             FunctionStateRequest functionStateRequest) {
  127.         log.debug("\n");
  128.  
  129.         // Autotest area
  130.         IView iView = null;
  131.         IViewStorageInstanceItemPair autorunPrimeIViewAndItem = null;
  132.         int processCounter = 0;
  133.         boolean exampleCreated = false, exampleAttributesSet = false, examRes = false;
  134.  
  135.         try {
  136.             autorunPrimeIViewAndItem = getPrimeIViewAndItem(getSubjectInstance());
  137.             iView = (IView) autorunPrimeIViewAndItem.getiView();
  138.  
  139.             // find if any field contains "atest"
  140.             for (String p : obsParamNames)
  141.                 if (null != BOHelper.getAttribute(iView, p)
  142.                         && !((String) BOHelper.getAttribute(iView, p))
  143.                                 .isEmpty()
  144.                         && (AUTOTEST_MARK1.equalsIgnoreCase((String) BOHelper
  145.                                 .getAttribute(iView, p)) || AUTOTEST_MARK2
  146.                                 .equalsIgnoreCase((String) BOHelper
  147.                                         .getAttribute(iView, p)))) {
  148.                     ATEST = true;
  149.                     break;
  150.                 }
  151.  
  152.             if (ATEST)
  153.                 log.debug("[TEST]: starting autotest. single example proc will be launched");
  154.  
  155.         } catch (Throwable th) {
  156.             log.error(
  157.                     "Error while retrieving BO data. autotest cant be launched",
  158.                     th);
  159.         }
  160.  
  161.         try {
  162.             instanceAdminApi = ApiUtils.lookupInstanceAdministrationApi();
  163.         } catch (ConnectionException e1) {
  164.             log.error("error retrieving instanceAdministrationApi");
  165.         }
  166.  
  167.         String departmentControllerGroupIdQuery = "SELECT ID AS DEPARTMENT_CONTROLLER_GROUP_ID FROM UM_GROUP WHERE NAME = ?";
  168.  
  169.         String ufpsQuery = "SELECT DISTINCT UFPS_INDEX, UFPS_NAME FROM POSTAMT_VIEW";
  170.  
  171.         // query to get user belonging to RUSPOST_DEPARTMENT_CONTROLLER group
  172.         // and a right region group
  173.         String potentialOwnersQuery = "SELECT A.UM_GROUP AS UFPS_INDEX, A.UM_USER, B.UM_GROUP AS DEPARTMENT_CONTROLLER_GROUP_ID "
  174.                 + "FROM UM_GROUP_UM_USER A "
  175.                 + "LEFT JOIN UM_GROUP_UM_USER B "
  176.                 + "ON A.UM_USER = B.UM_USER "
  177.                 + "WHERE A.UM_GROUP = ? AND B.UM_GROUP = ?";
  178.  
  179.         String postamtQuery = "SELECT POSTAMT_INDEX, POSTAMT_NAME FROM POSTAMT_VIEW WHERE UFPS_INDEX = ?";
  180.  
  181.         try (final Connection connection = DbHelper
  182.                 .getConnection(DbHelper.PROP_DB_INT);) {
  183.             log.debug("connection has been set");
  184.  
  185.             // form query as SELECT TOP 1 ID AS ...
  186.             departmentControllerGroupId = getDepartmentControllerGroupId(
  187.                     connection, departmentControllerGroupIdQuery,
  188.                     AttributeHelper.RUSPOST_DEPARTMENT_CONTROLLER_ROLE);
  189.             log.debug(DEPARTMENT_CONTROLLER_GROUP_ID + ": "
  190.                     + departmentControllerGroupId);
  191.  
  192.             // get all ufps
  193.             List<Pair> ufpsIndexNamePairs = getUfpsIndexNamePairs(connection,
  194.                     ufpsQuery);
  195.  
  196.             for (Pair ufpsIndexNamePair : ufpsIndexNamePairs) {
  197.  
  198.                 String ufpsIndex = ufpsIndexNamePair.getFirstElement();
  199.                 String ufpsName = ufpsIndexNamePair.getSecondElement();
  200.                 log.debug("     ufps: " + ufpsIndex + " / " + ufpsName);
  201.  
  202.                 // retrieve potential owners as:
  203.                 // users from current Ufps group that also belong to
  204.                 // RUSPOST-DEPARTMENT-CONTROLLER group
  205.                 // form query as ... WHERE a.UM_GROUP = 249030 AND b.UM_GROUP =
  206.                 // 13
  207.                 List<String> potentialOwners = getPotentialOwners(connection,
  208.                         potentialOwnersQuery, Integer.valueOf(ufpsIndex),
  209.                         departmentControllerGroupId);
  210.  
  211.                 if (0 == potentialOwners.size()) {
  212.                     log.warn("POTENTIAL ERROR in the system configuration. Skipping plan process creation for Ufps: "
  213.                             + ufpsIndex
  214.                             + "/"
  215.                             + ufpsName
  216.                             + "Reason: no potential owners were found for this Ufps");
  217.                     continue;
  218.                 }
  219.  
  220.                 // now as we got potOwners list
  221.                 // lets iterate over all postamts of current ufps
  222.                 List<Pair> postamtIndexNamePairs = getPostamtIndexNamePairs(
  223.                         connection, postamtQuery, ufpsIndex);
  224.  
  225.                 for (Pair postamtIndexNamePair : postamtIndexNamePairs) {
  226.  
  227.                     processCounter++;
  228.  
  229.                     // autotest
  230.                     if (ATEST && exampleCreated) {
  231.                         // example already created.
  232.                         // we dont need no more proc to launch
  233.                         // count 'em all
  234.                         continue;
  235.                     }
  236.  
  237.                     String postamtIndex = postamtIndexNamePair
  238.                             .getFirstElement();
  239.                     String postamtName = postamtIndexNamePair
  240.                             .getSecondElement();
  241.                     log.debug("     postamt: " + postamtIndex + " / "
  242.                             + postamtName);
  243.  
  244.                     // ============================================================================================================
  245.                     // now as we got single postamt
  246.                     // lets create a process for it
  247.                     log.debug("launching process");
  248.                     IProcessInstanceBean processInstanceBean = null;
  249.                     String procName = null;
  250.                     try {
  251.                         SimpleDateFormat sdf = new SimpleDateFormat(
  252.                                 "dd/MM/yyyy HH:mm:ss");
  253.                         procName = postamtName + " Контроль ОПС ["
  254.                                 + sdf.format(new Date()) + "]";
  255.                         String creatorId = commonApi.getSubjectInstanceBean(
  256.                                 functionStateRequest.getSubjectInstanceId())
  257.                                 .getEditor();
  258.                         int priority = 3;
  259.  
  260.                         processInstanceBean = createProcessInstance(
  261.                                 opsControlDescriptionId, procName, creatorId,
  262.                                 priority);
  263.  
  264.                         log.debug("process '" + procName + "' has been created");
  265.                     } catch (Exception e) {
  266.                         log.error("error creating process instance with name: "
  267.                                 + procName);
  268.                     }
  269.  
  270.                     // autotest
  271.                     if (ATEST && !exampleCreated) {
  272.                         log.debug("[TEST]: single example process has been created");
  273.  
  274.                         exampleCreated = true;
  275.                         examRes = examineSingleProcess(processInstanceBean,
  276.                                 potentialOwners.toArray(new String[0]));
  277.  
  278.                         // now as we examined example process
  279.                         // avoid all the stuff below
  280.                         // as it can be launched on production server
  281.                         continue;
  282.                     }
  283.  
  284.                     if (null != processInstanceBean) {
  285.                         log.debug("retrieving prime BO and setting pot :) owners");
  286.                         ISubjectInstanceBean primeSubjectInstanceBean = getPrimeSubject(processInstanceBean);
  287.  
  288.                         // retrieve prime BO to preset it's attributes
  289.                         IView operationPlan = createPrimeBO(primeSubjectInstanceBean);
  290.  
  291.                         if (null != operationPlan) {
  292.                             // ============================================================================================================
  293.                             log.debug("retrieving opPlanCommonInfo");
  294.  
  295.                             // explicitly create commonInfo BO
  296.                             Class<?> opPlanCommonInfoType = BOHelper.getType(
  297.                                     operationPlan, COMMON_INFO);
  298.                             log.debug("comInfoTypeClass:"
  299.                                     + opPlanCommonInfoType);
  300.                             Object opPlanCommonInfoImpl = opPlanCommonInfoType
  301.                                     .newInstance();
  302.                             BOHelper.setAttribute(operationPlan, COMMON_INFO,
  303.                                     opPlanCommonInfoImpl);
  304.  
  305.                             Object commonInfo = BOHelper.getAttribute(
  306.                                     operationPlan, COMMON_INFO);
  307.  
  308.                             // retrieve newly created commonInfo and set
  309.                             // it'sattributes
  310.                             if (null != commonInfo) {
  311.                                 log.debug("commonInfo retrieved. setting date attributes");
  312.  
  313.                                 DateTime today = DateTime.now();
  314.                                 Date periodStart = today.minusMonths(1)
  315.                                         .toDate();
  316.                                 Date periodEnd = today.toDate();
  317.                                 Date deadline = today.plusWeeks(1).toDate();
  318.  
  319.                                 BOHelper.setAttribute(commonInfo,
  320.                                         "periodStart", periodStart);
  321.                                 BOHelper.setAttribute(commonInfo, "periodEnd",
  322.                                         periodEnd);
  323.                                 BOHelper.setAttribute(commonInfo, "createDate",
  324.                                         periodEnd);
  325.                                 BOHelper.setAttribute(commonInfo, "deadline",
  326.                                         deadline);
  327.  
  328.                                 log.debug("date attribuites has been set");
  329.                             } else {
  330.                                 log.debug("error retrieving commonInfo");
  331.                             }
  332.  
  333.                             // ============================================================================================================
  334.                             log.debug("retrieving opPlanPostamt");
  335.  
  336.                             // explicitly create postamt BO
  337.                             Class<?> postamtType = BOHelper.getType(
  338.                                     operationPlan, POSTAMT);
  339.                             log.debug("postamtTypeCLass: " + postamtType);
  340.                             IView postamtImpl = (IView) (postamtType
  341.                                     .newInstance());
  342.                             BOHelper.setAttribute(postamtImpl,
  343.                                     "postamtPostamtIndex", postamtIndex);
  344.  
  345.                             List<IView> postamtViews = accessApi.getViews(
  346.                                     primeSubjectInstanceBean, postamtImpl);
  347.  
  348.                             if (1 == postamtViews.size()) {
  349.                                 BOHelper.setAttribute(operationPlan, POSTAMT,
  350.                                         postamtViews.get(0));
  351.                                 log.debug("postamt has been set");
  352.                             } else {
  353.                                 log.debug("error retrieving postamt by index: "
  354.                                         + postamtIndex
  355.                                         + " - no postamts at all or more than one postamt exists");
  356.                             }
  357.  
  358.                             // ============================================================================================================
  359.  
  360.                             // first of all - release subj instance
  361.                             // from current proc stater
  362.                             // while proc at it's fist stage
  363.                             log.debug("releasing process from user-proc_starter");
  364.                             commonApi.releaseSubjectInstance(Long
  365.                                     .valueOf(primeSubjectInstanceBean.getId()),
  366.                                     opsControlFirstStateDescrId);
  367.  
  368.                             // get any potential owner and assign him a task
  369.                             log.debug("setting new assignee from pot.owners");
  370.                             String singlePotentialOwner = potentialOwners
  371.                                     .get(0);
  372.                             commonApi.assignSubjectInstance(Long
  373.                                     .valueOf(primeSubjectInstanceBean.getId()),
  374.                                     singlePotentialOwner);
  375.  
  376.                             // save BO for the operation plan number
  377.                             // to be composed correctly (correct region index)
  378.                             log.debug("saving BO changes");
  379.                             saveNewPrimeBO(primeSubjectInstanceBean,
  380.                                     operationPlan);
  381.  
  382.                             // push the process to the Edit stage
  383.                             log.debug("pushing process forward");
  384.                             String sid = primeSubjectInstanceBean.getId();
  385.                             boolean ignoreMissingData = true;
  386.  
  387.                             commonApi.followFunctionTransition(sid,
  388.                                     opsControlFirstStateTransitionDescrId,
  389.                                     primeSubjectInstanceBean.getEditor(),
  390.                                     ignoreMissingData,
  391.                                     primeSubjectInstanceBean.getEditor());
  392.  
  393.                             log.debug("proc has been pushed successfully");
  394.  
  395.                             // now release assignee from the task
  396.                             // and set him as pot owner
  397.                             log.debug("setting potential owners");
  398.                             commonApi.releaseSubjectInstance(Long
  399.                                     .valueOf(primeSubjectInstanceBean.getId()),
  400.                                     opsControlRecieveStateDescrId);
  401.                             instanceAdminApi.setPotentialOwners(Long
  402.                                     .valueOf(primeSubjectInstanceBean.getId()),
  403.                                     potentialOwners.toArray(new String[0]));
  404.  
  405.                             ISubjectInstanceBean newPrimeBean = getPrimeSubject(processInstanceBean);
  406.                             log.debug("Editor has been removed. Potential owners["
  407.                                     + newPrimeBean.getPotentialOwners().length
  408.                                     + "/" + potentialOwners.size() + "]:");
  409.                             for (String o : newPrimeBean.getPotentialOwners())
  410.                                 log.debug("-->" + o);
  411.  
  412.                         } else {
  413.                             log.debug("theres no opPlan BO for process: "
  414.                                     + procName);
  415.                         }
  416.                     } else {
  417.                         log.debug("theres no procInstanceBean for process: "
  418.                                 + procName);
  419.                     }
  420.  
  421.                     if (!ATEST) {
  422.                         log.debug("all done");
  423.                         log.debug("\n");
  424.                     } else {
  425.                         log.debug("all the processes have been iterated");
  426.                     }
  427.  
  428.                 }
  429.             }
  430.  
  431.         } catch (Throwable e2) {
  432.             e2.printStackTrace();
  433.         }
  434.  
  435.         // autotest area
  436.         if (ATEST) {
  437.             ATEST_RES = ATEST_RES.length() > 2 ? ATEST_RES.substring(0,
  438.                     ATEST_RES.length() - 2) + ". all done. " : ATEST_RES
  439.                     + "[error while processing test]";
  440.  
  441.             log.debug("[TEST]: saving results into BO. *wait for full completion - otherwise consider an error");
  442.  
  443.             try {
  444.                 String procNumRes = "pssblProcNum:"
  445.                         + String.valueOf(processCounter);
  446.                 String overallRes = examRes ? "GOOD: " : "BAD: ";
  447.  
  448.                 String resultsToShow = overallRes + ATEST_RES + procNumRes;
  449.                 log.debug("[TEST]: " + resultsToShow);
  450.  
  451.                 BOHelper.setAttribute(iView, "endPoint", resultsToShow);
  452.  
  453.                 savePrimeIViewAndItem(getSubjectInstance(),
  454.                         autorunPrimeIViewAndItem);
  455.  
  456.                 log.debug("[TEST]: autotest fully complete\n");
  457.  
  458.             } catch (Exception e) {
  459.                 e.printStackTrace();
  460.             }
  461.         }
  462.  
  463.         return null;
  464.     }
  465.  
  466.     private int getDepartmentControllerGroupId(Connection connection,
  467.             String query, String departmentControllerGroupId) throws Exception {
  468.         log.debug("getRuspostDepartmentControllerGroupId begin");
  469.         log.debug("executing: " + query);
  470.  
  471.         List<ValueWrapper> valueWrappers = new ArrayList<ValueWrapper>();
  472.  
  473.         valueWrappers.add(new ValueWrapper(departmentControllerGroupId,
  474.                 String.class));
  475.  
  476.         int id = (int) DbHelper.executeQuery(connection, query, valueWrappers,
  477.                 true, new DbHelper.ResulSetHandler() {
  478.                     @Override
  479.                     public Object processResultSet(ResultSet rerSet)
  480.                             throws Exception {
  481.  
  482.                         if (rerSet.next())
  483.                             return rerSet
  484.                                     .getInt(DEPARTMENT_CONTROLLER_GROUP_ID);
  485.  
  486.                         return -1;
  487.                     }
  488.                 });
  489.  
  490.         log.debug("getRuspostDepartmentControllerGroupId end");
  491.         return id;
  492.     }
  493.  
  494.     private List<Pair> getUfpsIndexNamePairs(Connection connection, String query)
  495.             throws Exception {
  496.         log.debug("getUfpsIndexNamePairs begin");
  497.         log.debug("executing: " + query);
  498.  
  499.         List<ValueWrapper> valueWrappers = new ArrayList<ValueWrapper>();
  500.  
  501.         List<Pair> ufpsIndexNamePairs = (List<Pair>) DbHelper.executeQuery(
  502.                 connection, query, valueWrappers, true,
  503.                 new DbHelper.ResulSetHandler() {
  504.                     @Override
  505.                     public Object processResultSet(ResultSet result)
  506.                             throws Exception {
  507.                         List<Pair> ufpsIndexNamePairs = new ArrayList<Pair>();
  508.  
  509.                         while (result.next()) {
  510.  
  511.                             int ufpsIndex = result.getInt(UFPS_INDEX);
  512.                             String ufpsName = result.getString(UFPS_NAME);
  513.                             log.debug("  ufps: " + ufpsIndex + " / " + ufpsName);
  514.  
  515.                             ufpsIndexNamePairs.add(new Pair(String
  516.                                     .valueOf(ufpsIndex), ufpsName));
  517.                         }
  518.  
  519.                         return ufpsIndexNamePairs;
  520.                     }
  521.                 });
  522.  
  523.         log.debug("getUfpsIndexNamePairs end");
  524.         return ufpsIndexNamePairs;
  525.     }
  526.  
  527.     private List<Pair> getPostamtIndexNamePairs(Connection connection,
  528.             String query, String ufpsIndex) throws Exception {
  529.         log.debug("getPostamtIndexNamePairs begin");
  530.         log.debug("executing: " + query);
  531.         int ufpsIndexInt = Integer.valueOf(ufpsIndex);
  532.  
  533.         List<ValueWrapper> valueWrappers = new ArrayList<ValueWrapper>();
  534.  
  535.         valueWrappers.add(new ValueWrapper(ufpsIndexInt, Integer.class));
  536.  
  537.         List<Pair> postamtIndexNamePairs = (List<Pair>) DbHelper.executeQuery(
  538.                 connection, query, valueWrappers, true,
  539.                 new DbHelper.ResulSetHandler() {
  540.                     @Override
  541.                     public Object processResultSet(ResultSet result)
  542.                             throws Exception {
  543.                         List<Pair> postamtIndexNamePairs = new ArrayList<Pair>();
  544.  
  545.                         while (result.next()) {
  546.  
  547.                             int postamtIndex = result.getInt(POSTAMT_INDEX);
  548.                             String postamtName = result.getString(POSTAMT_NAME);
  549.                             log.debug("  postamt: " + postamtIndex + " / "
  550.                                     + postamtName);
  551.  
  552.                             postamtIndexNamePairs.add(new Pair(String
  553.                                     .valueOf(postamtIndex), postamtName));
  554.                         }
  555.  
  556.                         return postamtIndexNamePairs;
  557.                     }
  558.                 });
  559.  
  560.         log.debug("getPostamtIndexNamePairs end");
  561.         return postamtIndexNamePairs;
  562.     }
  563.  
  564.     private List<String> getPotentialOwners(Connection connection,
  565.             String query, int ufpsIndex, int departmentControllerGroupId)
  566.             throws Exception {
  567.         log.debug("getPotentialOwners begin");
  568.         log.debug("executing: " + query);
  569.  
  570.         List<ValueWrapper> valueWrappers = new ArrayList<ValueWrapper>();
  571.  
  572.         valueWrappers.add(new ValueWrapper(ufpsIndex, Integer.class));
  573.         valueWrappers.add(new ValueWrapper(departmentControllerGroupId,
  574.                 Integer.class));
  575.  
  576.         List<String> potOwnersIds = (List<String>) DbHelper.executeQuery(
  577.                 connection, query, valueWrappers, true,
  578.                 new DbHelper.ResulSetHandler() {
  579.                     @Override
  580.                     public Object processResultSet(ResultSet result)
  581.                             throws Exception {
  582.                         List<String> potOwnersIds = new ArrayList<String>();
  583.  
  584.                         while (result.next()) {
  585.  
  586.                             int ufpsIndex = result.getInt(UFPS_INDEX);
  587.                             int userId = result.getInt(UM_USER);
  588.                             int departmentControllerGroupId = result
  589.                                     .getInt(DEPARTMENT_CONTROLLER_GROUP_ID);
  590.  
  591.                             log.debug("  user: " + ufpsIndex + " / [" + userId
  592.                                     + "] / " + departmentControllerGroupId);
  593.  
  594.                             potOwnersIds.add(String.valueOf(userId));
  595.                         }
  596.  
  597.                         return potOwnersIds;
  598.                     }
  599.                 });
  600.  
  601.         log.debug("getPotentialOwners end");
  602.         return potOwnersIds;
  603.     }
  604.  
  605.     private boolean examineSingleProcess(
  606.             IProcessInstanceBean processInstanceBean, String[] potOwners)
  607.             throws Throwable {
  608.         log.debug("[TEST]: attempting to test an example process created:");
  609.         log.debug("[TEST]: pid: " + processInstanceBean.getId()
  610.                 + ", potOwner: " + potOwners[0]);
  611.  
  612.         if (null != processInstanceBean) {
  613.             ATEST_RES += "procCreate ok, ";
  614.             log.debug("[TEST]:    retrieving prime BO and setting pot :) owners");
  615.  
  616.             // retrieve prime BO to preset it's attributes
  617.             ISubjectInstanceBean primeSubjectInstanceBean = getPrimeSubject(processInstanceBean);
  618.             IView operationPlan = createPrimeBO(primeSubjectInstanceBean);
  619.  
  620.             if (null != operationPlan) {
  621.                 // ============================================================================================================
  622.                 ATEST_RES += "getBO ok, ";
  623.                 log.debug("[TEST]:        retrieving opPlanCommonInfo");
  624.  
  625.                 // explicitly create commonInfo BO
  626.                 Class<?> opPlanCommonInfoType = BOHelper.getType(operationPlan,
  627.                         COMMON_INFO);
  628.                 log.debug("[TEST]:        comInfoTypeClass:"
  629.                         + opPlanCommonInfoType);
  630.                 Object opPlanCommonInfoImpl = opPlanCommonInfoType
  631.                         .newInstance();
  632.                 BOHelper.setAttribute(operationPlan, COMMON_INFO,
  633.                         opPlanCommonInfoImpl);
  634.  
  635.                 Object commonInfo = BOHelper.getAttribute(operationPlan,
  636.                         COMMON_INFO);
  637.  
  638.                 if (null != commonInfo) {
  639.                     log.debug("[TEST]:            attempting to set values");
  640.  
  641.                     Date today = DateTime.now().toDate();
  642.                     BOHelper.setAttribute(commonInfo, "periodStart", today);
  643.  
  644.                     log.debug("[TEST]:            successfully set");
  645.                     ATEST_RES += "valueSet ok, ";
  646.                 } else {
  647.                     ATEST_RES += "null commonInfo, ";
  648.                 }
  649.  
  650.                 log.debug("[TEST]:        releasing process from its initial owner");
  651.                 String formerEditor = this.getSubjectInstance().getEditor();
  652.                 commonApi.releaseSubjectInstance(
  653.                         Long.valueOf(primeSubjectInstanceBean.getId()),
  654.                         opsControlFirstStateDescrId);
  655.                 String currEditor = getPrimeSubject(processInstanceBean).getEditor();
  656.                 log.debug("[TEST]:            formerEditor: " + formerEditor + ", curr: " + currEditor);
  657.                
  658.                 ATEST_RES = !"".equals(formerEditor) && null == currEditor ?
  659.                         ATEST_RES + "rm-rfEditor ok, " : ATEST_RES + "rm-rfEditor NO, ";
  660.  
  661.                 // get any potential owner and assign him a task
  662.                 log.debug("[TEST]:        setting new assignee=potOwner");
  663.                 instanceAdminApi.setPotentialOwners(
  664.                         Long.valueOf(primeSubjectInstanceBean.getId()),
  665.                         potOwners);
  666.  
  667.                 ISubjectInstanceBean newPrimeBean = getPrimeSubject(processInstanceBean);
  668.                 if (null != newPrimeBean.getPotentialOwners()) {
  669.  
  670.                     ATEST_RES += "potOwnrSet ok, ";
  671.                     log.debug("[TEST]:        assignee has been successfully set");
  672.                 } else {
  673.                     ATEST_RES += "NO potOwnr, ";
  674.                     log.debug("[TEST]:        assignee has NOT been set");
  675.                 }
  676.  
  677.                 log.debug("[TEST]:        attempting to remove example process");
  678.                 String pid = processInstanceBean.getId();
  679.                 instanceAdminApi.removeProcessInstance(pid);
  680.                 try {
  681.                     IProcessInstanceBean pibNull = commonApi
  682.                             .getProcessInstanceBean(pid);
  683.  
  684.                     if (null != pibNull) {
  685.                         ATEST_RES += "NO rm-rf";
  686.                         log.debug("[TEST]:            not removed. still there");
  687.                     }
  688.                 } catch (ProcessInstanceNotAvailableException e) {
  689.                     ATEST_RES += "rm-rfProc ok, ";
  690.                     log.debug("[TEST]:            successfully removed");
  691.  
  692.                     return true;
  693.                 }
  694.  
  695.             } else {
  696.                 ATEST_RES += "null operPlan, ";
  697.             }
  698.         } else {
  699.             ATEST_RES += "null process, ";
  700.         }
  701.  
  702.         return false;
  703.     }
  704.  
  705.     private ISubjectInstanceBean getPrimeSubject(
  706.             IProcessInstanceBean processInstanceBean) throws Exception {
  707.         ICommonApi commonApi = ApiUtils.lookupCommonApi();
  708.         String subjectInstanceId = processInstanceBean.getSubjectInstances()[0];
  709.         ISubjectInstanceBean subjectInstanceBean = commonApi
  710.                 .getSubjectInstanceBean(subjectInstanceId);
  711.         return subjectInstanceBean;
  712.     }
  713.  
  714.     private IView createPrimeBO(ISubjectInstanceBean subjectInstanceBean)
  715.             throws Exception {
  716.         IBo20AccessApi bo20AccessApi = ApiUtils.lookupBo20AccessApi();
  717.         Set<IStorageInstanceBean> storages = bo20AccessApi.getStorages(
  718.                 subjectInstanceBean, null);
  719.         IStorageInstanceBean storage = storages.iterator().next();
  720.         IView iView = bo20AccessApi.createIViewOnStorage(subjectInstanceBean,
  721.                 storage);
  722.         return iView;
  723.     }
  724.  
  725.     private void saveNewPrimeBO(ISubjectInstanceBean subjectInstanceBean,
  726.             IView iView) throws Exception {
  727.         IBo20AccessApi bo20AccessApi = ApiUtils.lookupBo20AccessApi();
  728.         Set<IStorageInstanceBean> storages = bo20AccessApi.getStorages(
  729.                 subjectInstanceBean, null);
  730.         IStorageInstanceBean storage = storages.iterator().next();
  731.         bo20AccessApi
  732.                 .saveNewIViewInStorage(subjectInstanceBean, iView, storage);
  733.     }
  734.  
  735.     private void savePrimeIViewAndItem(
  736.             ISubjectInstanceBean subjectInstanceBean,
  737.             IViewStorageInstanceItemPair iViewStorageInstanceItemPair)
  738.             throws Exception {
  739.         IBo20AccessApi bo20AccessApi = ApiUtils.lookupBo20AccessApi();
  740.         bo20AccessApi.saveIView(subjectInstanceBean,
  741.                 iViewStorageInstanceItemPair);
  742.     }
  743.  
  744.     private IViewStorageInstanceItemPair getPrimeIViewAndItem(
  745.             ISubjectInstanceBean subjectInstanceBean) throws Exception {
  746.         IBo20AccessApi bo20AccessApi = ApiUtils.lookupBo20AccessApi();
  747.         Set<IStorageInstanceBean> storages = bo20AccessApi.getStorages(
  748.                 subjectInstanceBean, null);
  749.         IStorageInstanceBean storageInstanceBean = storages.iterator().next();
  750.         Set<IStorageInstanceItemBeanReducedToId> storageItems = bo20AccessApi
  751.                 .getItems(subjectInstanceBean, storageInstanceBean);
  752.         IStorageInstanceItemBeanReducedToId storageItem = storageItems
  753.                 .iterator().next();
  754.         String actionType = BusinessObject20.Action.READ;
  755.         IViewStorageInstanceItemPair iViewStorageInstanceItemPair = bo20AccessApi
  756.                 .getIViewAndItem(subjectInstanceBean, storageItem, actionType);
  757.         return iViewStorageInstanceItemPair;
  758.     }
  759.  
  760.     private Map<String, String> processVersions = new HashMap<String, String>();
  761.  
  762.     private IProcessInstanceBean createProcessInstance(
  763.             String processDescriptionId, String name, String userId,
  764.             int priority) throws Exception {
  765.         ICommonApi commonApi = ApiUtils.lookupCommonApi();
  766.  
  767.         String processVersionId = getLatestProcessVersionId(processDescriptionId);
  768.  
  769.         InitProcessInstanceData initProcessInstanceData = new InitProcessInstanceData(
  770.                 processVersionId,
  771.                 com.jcom1.api.constants.Constants.Process.Mode.PRODUCTIVE);
  772.  
  773.         initProcessInstanceData.setName(name);
  774.         initProcessInstanceData.setCreatorId(userId);
  775.         initProcessInstanceData.setPriority(priority);
  776.  
  777.         String processInstanceId = commonApi
  778.                 .createProcessInstance(initProcessInstanceData);
  779.  
  780.         IProcessInstanceBean processInstance = commonApi
  781.                 .getProcessInstanceBean(processInstanceId);
  782.  
  783.         return processInstance;
  784.     }
  785.  
  786.     private String getLatestProcessVersionIdFromDB(Connection connection,
  787.             String query, String processDescriptionId) throws Exception {
  788.         log.debug("getLatestProcessVersionIdFromDB begin");
  789.         log.debug("executing: " + query);
  790.         final String LATEST_VER_ID = "LATEST_VER_ID";
  791.  
  792.         List<ValueWrapper> valueWrappers = new ArrayList<ValueWrapper>();
  793.  
  794.         valueWrappers.add(new ValueWrapper(processDescriptionId, String.class));
  795.  
  796.         String lastestVerId = (String) DbHelper.executeQuery(connection, query,
  797.                 valueWrappers, true, new DbHelper.ResulSetHandler() {
  798.                     @Override
  799.                     public Object processResultSet(ResultSet rerSet)
  800.                             throws Exception {
  801.  
  802.                         if (rerSet.next())
  803.                             return rerSet.getString(LATEST_VER_ID);
  804.  
  805.                         return String.valueOf(-1);
  806.                     }
  807.                 });
  808.  
  809.         return lastestVerId;
  810.     }
  811.  
  812.     private String getLatestProcessVersionId(String processDescriptionId)
  813.             throws Exception {
  814.         log.debug("getLatestProcessVersionId begin");
  815.         String processVersion = processVersions.get(processDescriptionId);
  816.  
  817.         if (processVersion == null) {
  818.  
  819.             String latestProcVersionQuery = "SELECT ID AS LATEST_VER_ID "
  820.                     + "FROM RT_PROCDESC " + "WHERE UPLOADDATE = ( "
  821.                     + "     SELECT MAX(UPLOADDATE) " + "        FROM RT_PROCDESC "
  822.                     + "     WHERE JPASS_ID = ?)";
  823.  
  824.             try (final Connection connection = DbHelper
  825.                     .getConnection(DbHelper.PROP_DB_INT);) {
  826.  
  827.                 processVersion = getLatestProcessVersionIdFromDB(connection,
  828.                         latestProcVersionQuery, processDescriptionId);
  829.                 processVersions.put(processDescriptionId, processVersion);
  830.  
  831.             } catch (Exception e2) {
  832.                 log.error("error while retrieving latest process version for process: "
  833.                         + processDescriptionId);
  834.             }
  835.         }
  836.         log.debug("latest ver: " + processVersion);
  837.         log.debug("getLatestProcessVersionId end");
  838.         return processVersion;
  839.     }
  840.  
  841. }
Add Comment
Please, Sign In to add comment