void setRollbackOnly() {
   try {
     transactionManager.setRollbackOnly();
   } catch (javax.transaction.SystemException se) {
     se.printStackTrace();
   }
 }
  public void onMessage(final Message message) {
    try {
      // Step 9. We know the client is sending a text message so we cast
      TextMessage textMessage = (TextMessage) message;

      // Step 10. get the text from the message.
      String text = textMessage.getText();

      System.out.println("message " + text + " received");

      if (!textMessage.getJMSRedelivered()) {
        // Step 11. On first delivery get the transaction, take a look, and throw an exception
        Transaction tx = tm.getTransaction();

        if (tx != null) {
          System.out.println("something is wrong, there should be no global transaction: " + tx);
        } else {
          System.out.println(
              "there is no global transaction, although the message delivery is using a local transaction");
          System.out.println("let's throw an exception and see what happens");
          throw new RuntimeException("DOH!");
        }
      } else {
        // Step 12. Print the message
        System.out.println(
            "The message was redelivered since the message delivery used a local transaction");
      }

    } catch (JMSException e) {
      e.printStackTrace();
    } catch (SystemException e) {
      e.printStackTrace();
    }
  }
Esempio n. 3
0
  public static void main(String[] args) {
    UserTransaction ut = null;
    try {
      boolean abort = false;
      System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
      System.setProperty(Context.PROVIDER_URL, "t3://localhost:7001");

      ut = getUserTransaction();
      ut.begin();

      MessagePublisher mp =
          new MessagePublisher("jms/JTATestJMSConnectionFactory", "jms/JTATestJMSQueue", false);
      mp.publishMessage("Hello JMS2");
      mp.publishMessage("Hello again JMS2");

      new AmitkJTADao("jdbc/JTATestDataSource")
          .updateRecord(1, new Date(System.currentTimeMillis()));

      if (abort) throw new Exception("Forcefully aborting transaction");

      ut.commit();

    } catch (Exception e) {
      e.printStackTrace();
      try {
        if (null != ut) ut.rollback();
      } catch (SystemException se) {
        se.printStackTrace();
      } finally {
        ut = null;
      }
    }
  }
  /*
   * (non-Javadoc)
   * @see org.mobicents.slee.runtime.transaction.SleeTransactionManager#mandateTransaction()
   */
  public void mandateTransaction() throws TransactionRequiredLocalException {

    try {
      final Transaction tx = getTransaction();
      if (tx == null) throw new TransactionRequiredLocalException("Transaction Mandatory");
      final int status = tx.getStatus();
      if (status != Status.STATUS_ACTIVE && status != Status.STATUS_MARKED_ROLLBACK) {
        throw new IllegalStateException("There is no active tx, tx is in state: " + status);
      }
    } catch (SystemException e) {
      throw new SLEEException(e.getMessage(), e);
    }
  }
  void execute(final ActivityHandle handle, final int activityFlags)
      throws StartActivityException, SLEEException {

    final SleeTransactionManager txManager = sleeContainer.getTransactionManager();

    final Runnable runnable =
        new Runnable() {

          public void run() {
            boolean rollback = true;
            try {
              txManager.begin();
              sleeEndpoint._startActivity(handle, activityFlags);
              rollback = false;
            } catch (NotSupportedException e) {
              throw new SLEEException(e.getMessage(), e);
            } catch (SystemException e) {
              throw new SLEEException(e.getMessage(), e);
            } finally {
              try {
                if (rollback) {
                  txManager.rollback();
                } else {
                  txManager.commit();
                }
              } catch (Throwable e) {
                throw new SLEEException(e.getMessage(), e);
              }
            }
          }
        };

    Transaction tx = null;
    try {
      tx = txManager.getTransaction();
      if (tx != null) {
        txManager.suspend();
      }
      runnable.run();
    } catch (SystemException e) {
      throw new SLEEException(e.getMessage(), e);
    } finally {
      if (tx != null) {
        try {
          txManager.resume(tx);
        } catch (Throwable e) {
          throw new SLEEException(e.getMessage(), e);
        }
      }
    }
  }
Esempio n. 6
0
 /** 重载父类方法,设置事务的状态标识为回滚状态 */
 public void rollback() throws SQLException {
   JDBCTransaction tx = TransactionManager.getTransaction();
   try {
     if (tx != null) tx.setRollbackOnly();
   } catch (IllegalStateException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (SystemException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Esempio n. 7
0
  public void setRollbackOnly() {
    if (transaction == null) {
      throw new IllegalStateException("Current thread is not associated with a transaction.");
    }

    try {
      synchronized (this) {
        transaction.setRollbackOnly();
      }
    } catch (SystemException e) {
      throw (IllegalStateException)
          new IllegalStateException("Failed to set transaction to rollback only: " + e.getMessage())
              .initCause(e);
    }
  }
Esempio n. 8
0
 /**
  * Rollback a transaction
  *
  * @exception SystemException Thrown if an error occurs
  */
 public void rollbackTransaction() throws SystemException {
   Long key = Long.valueOf(Thread.currentThread().getId());
   TransactionImpl tx = txs.get(key);
   if (tx != null) {
     try {
       tx.rollback();
     } catch (Throwable t) {
       SystemException se = new SystemException("Error during rollback");
       se.initCause(t);
       throw se;
     } finally {
       txs.remove(key);
     }
   } else {
     throw new IllegalStateException("No transaction to rollback");
   }
 }
Esempio n. 9
0
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      String showid = request.getParameter("si");

      String[] pics;
      pics = request.getParameterValues("pics[]");

      String[] comms;
      comms = request.getParameterValues("comms[]");

      utx.begin();
      EntityManager em = emf.createEntityManager();
      for (int i = 0; i < pics.length; i++) {
        Ecpresentations etemp = em.getReference(Ecpresentations.class, showid);
        Ecinfo ef = new Ecinfo();
        ef.setPicy(pics[i]);
        ef.setDetails(comms[i]);
        ef.setShowid(etemp);
        em.persist(ef);
      }
      utx.commit();
      RequestDispatcher view = request.getRequestDispatcher("addinforeport.jsp");
      view.forward(request, response);
      em.close();
    } catch (NotSupportedException ex) {
      ex.printStackTrace();
    } catch (SystemException ex) {
      ex.printStackTrace();
    } catch (RollbackException ex) {
      ex.printStackTrace();
    } catch (HeuristicMixedException ex) {
      ex.printStackTrace();
    } catch (HeuristicRollbackException ex) {
      ex.printStackTrace();
    } catch (SecurityException ex) {
      ex.printStackTrace();
    } catch (IllegalStateException ex) {
      ex.printStackTrace();
    }
  }
  @PostConstruct
  private void init() {
    try {
      userTransaction.begin();

      initData();

      userTransaction.commit();
    } catch (NotSupportedException e) {
      e.printStackTrace();
    } catch (SystemException e) {
      e.printStackTrace();
    } catch (HeuristicRollbackException e) {
      e.printStackTrace();
    } catch (javax.transaction.RollbackException e) {
      e.printStackTrace();
    } catch (HeuristicMixedException e) {
      e.printStackTrace();
    }
  }
Esempio n. 11
0
  /**
   * Example for sending a message fire and forget
   *
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final String methodName = "doGet";

    // We simply return some text showing what we've done
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    WLMJMSMessageProducer wlmConnection = null;
    boolean complete = false;
    try {
      // Begin a transaction
      userTransaction.begin();

      // Print the user transaction status
      out.println(WLMJMSTranUtils.summarizeUserTranStatus(userTransaction));

      // Create our JMS connection/session/producer using the WLM connection logic
      // Many fire-and-forget scenarios are for exactly once delivery, where a
      // database is updated in the same transaction as sending the request.
      // For this reason in this example we begin a transaction and send
      // a persistent message.
      // As such JDBC operations could be inserted into this sample, and would
      // be coordinated in an atomic transaction with sending the request.
      //
      // If you are instead looking to send nonpersistent messages, such as publishing
      // some non-critical state data on a topic, then you should consider
      // removing the transaction, changing the transaction
      // boolean in the getMessageProducer() call to false, and setting the DeliveryMode
      // to NON_PERSISTENT when sending the message.
      out.println("JMS destination: " + fireAndForgetTarget);
      wlmConnection =
          wlmJMSAttach.getMessageProducer(fireAndForgetTarget, true, Session.AUTO_ACKNOWLEDGE);

      // TODO: Replace this section with business logic
      // We create a temporary queue solely for the purpose of finding out where
      // we are connected, as the temporary queue name should show this.
      // This is inefficient, so it is for demonstration purposes only.
      TemporaryQueue temporaryQueue = wlmConnection.getSession().createTemporaryQueue();
      String temporaryQueueName = temporaryQueue.getQueueName();
      out.println("Temporary queue showing where we are connected:");
      out.println(temporaryQueueName);
      temporaryQueue.delete();
      String exampleMessageBody =
          this.getClass().getName()
              + " (thread \""
              + Thread.currentThread().getName()
              + "\") sending at "
              + new Date();
      Message message = wlmConnection.getSession().createTextMessage(exampleMessageBody);
      out.println("Sending message \"" + exampleMessageBody + "\"");

      // Send the message
      wlmConnection
          .getProducer()
          .send(
              message,
              DeliveryMode.PERSISTENT, /* We are persistent in this example */
              wlmConnection.getProducer().getPriority() /* Default priority */,
              0 /* Do not expire */);
      out.println("JMSMessageID: " + message.getJMSMessageID());

      // Commit the transaction
      userTransaction.commit();

      // Mark that we're complete, so that we throw any exception seen during cleanup,
      // and do not attempt rollback of the transaction
      complete = true;
    } catch (HeuristicMixedException e) {
      if (log.enabled()) log.logExStack(methodName, "Transaction HeuristicMixedException", e);
      throw new ServletException("Transaction HeuristicMixedException: " + e.getMessage(), e);
    } catch (HeuristicRollbackException e) {
      if (log.enabled()) log.logExStack(methodName, "Transaction HeuristicRollbackException", e);
      throw new ServletException("Transaction HeuristicRollbackException: " + e.getMessage(), e);
    } catch (RollbackException e) {
      if (log.enabled()) log.logExStack(methodName, "Transaction RollbackException", e);
      throw new ServletException("Transaction RollbackException: " + e.getMessage(), e);
    } catch (NotSupportedException e) {
      if (log.enabled()) log.logExStack(methodName, "Transaction NotSupportedException", e);
      throw new ServletException("Transaction NotSupportedException: " + e.getMessage(), e);
    } catch (SystemException e) {
      if (log.enabled()) log.logExStack(methodName, "Transaction SystemException", e);
      throw new ServletException("Transaction SystemException: " + e.getMessage(), e);
    } catch (JMSException e) {
      if (log.enabled()) log.logRootExMsg(methodName, "JMSException in business logic", e);
      throw new ServletException("JMSException: " + e.getMessage(), e);
    } finally {
      // Rollback if we didn't complete
      if (!complete)
        try {
          userTransaction.rollback();
        } catch (SystemException e) {
          // We are already on an exception path, so we should not throw this exception
          if (log.enabled()) log.logExStack(methodName, "Exception during rollback", e);
        }

      // Close off our resources, ensuring we only throw an exception if we completed
      // our earlier logic, so we don't override an earlier exception that being thrown.
      if (wlmConnection != null)
        try {
          wlmConnection.close(complete);
        } catch (JMSException e) {
          throw new ServletException("JMSException on Connection close: " + e.getMessage(), e);
        }
    }
  }
Esempio n. 12
0
  public String execute() {
    String rtnVal = SUCCESS;
    UserTransaction tx = null;

    try {
      sampleName = sampleName != null && sampleName.equals("0") ? null : sampleName;

      if (jobType != null) {
        boolean isProjectRegistration = eventName.equals(Constants.EVENT_PROJECT_REGISTRATION);
        boolean isSampleRegistration = eventName.equals(Constants.EVENT_SAMPLE_REGISTRATION);

        if (projectName == null
            || projectName.equals("0")
            || eventName == null
            || eventName.equals("0")) throw new Exception("Project or Event type is not selected.");

        if (jobType.equals("insert")) { // loads single event
          tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
          tx.begin();
          psewt.loadAll(
              null,
              this.createMultiLoadParameter(projectName, loadingProject, loadingSample, beanList));
          this.reset();
        } else if (jobType.equals("grid")) { // loads multiple events from grid view
          tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
          tx.begin();
          for (GridBean gBean : gridList) {
            if (gBean != null) {
              if (isProjectRegistration
                  && gBean.getProjectName() != null
                  && gBean.getProjectPublic() != null) {
                loadingProject = new Project();
                loadingProject.setProjectName(gBean.getProjectName());
                loadingProject.setIsPublic(Integer.valueOf(gBean.getProjectPublic()));
              } else if (isSampleRegistration
                  && gBean.getSampleName() != null
                  && gBean.getSamplePublic() != null) {
                loadingSample = new Sample();
                loadingSample.setSampleName(gBean.getSampleName());
                loadingSample.setParentSampleName(gBean.getParentSampleName());
                loadingSample.setIsPublic(Integer.valueOf(gBean.getSamplePublic()));
              } else {
                if (gBean.getSampleName() != null) {
                  this.sampleName = gBean.getSampleName();
                }
              }
              List<FileReadAttributeBean> fBeanList = gBean.getBeanList();
              if (fBeanList != null && fBeanList.size() > 0) {
                psewt.loadAll(
                    null,
                    this.createMultiLoadParameter(
                        projectName, loadingProject, loadingSample, fBeanList));
              }
            }
          }
          this.reset();

        } else if (jobType.equals("file")) { // loads data from a CSV file to grid view
          if (!this.uploadFile.canRead()) {
            throw new Exception("Error in reading the file.");
          } else {
            try {
              CSVReader reader = new CSVReader(new FileReader(this.uploadFile));

              int lineCount = 0;
              List<String> columns = new ArrayList<String>();

              String currProjectName = null;

              gridList = new ArrayList<GridBean>();
              boolean hasSampleName = false;
              String[] line;
              while ((line = reader.readNext()) != null) {
                if (lineCount != 1) {
                  if (lineCount == 0) {
                    Collections.addAll(columns, line);
                    hasSampleName = columns.indexOf("SampleName") >= 0;
                  } else {
                    int colIndex = 0;

                    currProjectName = line[colIndex++];
                    if (!isProjectRegistration && !currProjectName.equals(this.projectName)) {
                      throw new Exception(MULTIPLE_SUBJECT_IN_FILE_MESSAGE);
                    }

                    GridBean gBean = new GridBean();
                    gBean.setProjectName(currProjectName);

                    if (hasSampleName) {
                      gBean.setSampleName(line[(colIndex++)]);
                    }

                    if (isProjectRegistration) {
                      gBean.setProjectName(currProjectName);
                      gBean.setProjectPublic(line[(colIndex++)]);
                    } else if (isSampleRegistration) {
                      gBean.setParentSampleName(line[(colIndex++)]);
                      gBean.setSamplePublic(line[(colIndex++)]);
                    }

                    gBean.setBeanList(new ArrayList<FileReadAttributeBean>());
                    for (; colIndex < columns.size(); colIndex++) {
                      FileReadAttributeBean fBean = new FileReadAttributeBean();
                      fBean.setProjectName(
                          isProjectRegistration ? currProjectName : this.projectName);
                      fBean.setAttributeName(columns.get(colIndex));
                      fBean.setAttributeValue(line[colIndex]);
                      gBean.getBeanList().add(fBean);
                    }
                    this.gridList.add(gBean);
                  }
                }
                lineCount++;
              }
              jobType = "grid";
            } catch (Exception ex) {
              throw ex;
            }
          }
        } else if (jobType.equals("template")) { // download template
          List<EventMetaAttribute> emaList =
              readPersister.getEventMetaAttributes(projectName, eventName);

          /*
           * removing the sanity check on sample requirement since multiple sample support is in action
           * by hkim 5/2/13
          ModelValidator validator = new ModelValidator();
          validator.validateEventTemplateSanity(emaList, projectName, sampleName, eventName);
          */

          TemplatePreProcessingUtils cvsUtils = new TemplatePreProcessingUtils();
          String templateType = jobType.substring(jobType.indexOf("_") + 1);
          downloadStream =
              cvsUtils.buildFileContent(templateType, emaList, projectName, sampleName, eventName);
          downloadContentType = templateType.equals("c") ? "csv" : "vnd.ms-excel";
          rtnVal = Constants.FILE_DOWNLOAD_MSG;
        }
      }

    } catch (Exception ex) {
      logger.error("Exception in EventLoader : " + ex.toString());
      ex.printStackTrace();
      if (ex.getClass() == ForbiddenResourceException.class) {
        addActionError(Constants.DENIED_USER_EDIT_MESSAGE);
        return Constants.FORBIDDEN_ACTION_RESPONSE;
      } else if (ex.getClass() == ForbiddenResourceException.class) {
        addActionError(Constants.DENIED_USER_EDIT_MESSAGE);
        return LOGIN;
      } else if (ex.getClass() == ParseException.class)
        addActionError(Constants.INVALID_DATE_MESSAGE);
      else {
        addActionError(ex.toString());
      }

      // deletes uploaded files in event of error
      if (loadedFiles != null && loadedFiles.size() > 0) {
        for (String filePath : loadedFiles) {
          File tempFile = new File(fileStoragePath + filePath);
          if (tempFile.exists()) tempFile.delete();
        }
      }

      try {
        if (tx != null) tx.rollback();
      } catch (SystemException se) {
        addActionError(se.toString());
      }

      rtnVal = ERROR;
    } finally {
      try {
        // get project list for the drop down box
        List<String> projectNameList = new ArrayList<String>();
        if (projectNames == null || projectNames.equals("")) {
          projectNameList.add("ALL");
        } else if (projectNames.contains(",")) {
          projectNameList.addAll(Arrays.asList(projectNames.split(",")));
        } else {
          projectNameList.add(projectNames);
        }
        projectList = readPersister.getProjects(projectNameList);

        if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) {
          tx.commit();
        }

        if (jobType != null && jobType.equals("grid") && this.uploadFile != null) {
          this.uploadFile.delete();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }

    return rtnVal;
  }
  /** @see com.idega.block.importer.business.ImportFileHandler#handleRecords() */
  @Override
  public boolean handleRecords() {
    failedRecords = new ArrayList();
    errorLog = new TreeMap();
    report = new Report(file.getFile().getName()); // Create a report file.
    // It will be located in
    // the Report dir

    IWTimestamp t = IWTimestamp.RightNow();
    t.setAsDate();
    today = t.getDate();
    t.setDay(1);
    firstDayInCurrentMonth = t.getTimestamp();
    t.addDays(-1);
    lastDayInPreviousMonth = t.getTimestamp();

    transaction = this.getSessionContext().getUserTransaction();

    Timer clock = new Timer();
    clock.start();

    try {
      // initialize business beans and data homes
      communeUserBusiness =
          (CommuneUserBusiness) this.getServiceInstance(CommuneUserBusiness.class);
      schoolBusiness = (SchoolBusiness) this.getServiceInstance(SchoolBusiness.class);

      schoolHome = schoolBusiness.getSchoolHome();
      schoolTypeHome = schoolBusiness.getSchoolTypeHome();
      schoolYearHome = schoolBusiness.getSchoolYearHome();
      schoolClassHome = (SchoolClassHome) this.getIDOHome(SchoolClass.class);
      schoolClassMemberHome = (SchoolClassMemberHome) this.getIDOHome(SchoolClassMember.class);
      communeHome = (CommuneHome) this.getIDOHome(Commune.class);
      studyPathHome = (SchoolStudyPathHome) this.getIDOHome(SchoolStudyPath.class);
      placementImportDateHome =
          (PlacementImportDateHome) this.getIDOHome(PlacementImportDate.class);

      try {
        season =
            schoolBusiness.getCurrentSchoolSeason(schoolBusiness.getCategoryElementarySchool());
      } catch (FinderException e) {
        e.printStackTrace();
        println("NackaHighSchoolPlacementHandler: School season is not defined.");
        return false;
      }

      transaction.begin();

      // iterate through the records and process them
      String item;
      int count = 0;
      boolean failed = false;

      while (!(item = (String) file.getNextRecord()).trim().equals("")) {
        count++;

        if (!processRecord(item, count)) {
          failedRecords.add(item);
          failed = true;
          // break;
        }

        if ((count % 100) == 0) {
          System.out.println(
              "NackaHighSchoolHandler processing RECORD ["
                  + count
                  + "] time: "
                  + IWTimestamp.getTimestampRightNow().toString());
        }

        item = null;
      }

      if (!failed) {
        if (!terminateOldPlacements()) {
          failed = true;
        }
      }

      printFailedRecords();

      clock.stop();
      println("Number of records handled: " + (count - 1));
      println(
          "Time to handle records: "
              + clock.getTime()
              + " ms  OR "
              + ((int) (clock.getTime() / 1000))
              + " s");

      // success commit changes
      if (!failed) {
        transaction.commit();
      } else {
        transaction.rollback();
      }

      report.store(false);

      return !failed;

    } catch (Exception e) {
      e.printStackTrace();
      try {
        transaction.rollback();
      } catch (SystemException e2) {
        e2.printStackTrace();
      }

      report.store(false);

      return false;
    }
  }
  /**
   * Function accepts parameter in Map. The patient count will be obfuscated if the user is OBFUS
   */
  public void generateResult(Map param) throws CRCTimeOutException, I2B2DAOException {

    SetFinderConnection sfConn = (SetFinderConnection) param.get("SetFinderConnection");
    SetFinderDAOFactory sfDAOFactory = (SetFinderDAOFactory) param.get("SetFinderDAOFactory");

    // String patientSetId = (String)param.get("PatientSetId");
    String queryInstanceId = (String) param.get("QueryInstanceId");
    String TEMP_DX_TABLE = (String) param.get("TEMP_DX_TABLE");
    String resultInstanceId = (String) param.get("ResultInstanceId");
    // String itemKey = (String) param.get("ItemKey");
    String resultTypeName = (String) param.get("ResultOptionName");
    String processTimingFlag = (String) param.get("ProcessTimingFlag");
    int obfuscatedRecordCount = (Integer) param.get("ObfuscatedRecordCount");
    int transactionTimeout = (Integer) param.get("TransactionTimeout");
    TransactionManager tm = (TransactionManager) param.get("TransactionManager");
    this.setDbSchemaName(sfDAOFactory.getDataSourceLookup().getFullSchema());
    Map ontologyKeyMap = (Map) param.get("setFinderResultOntologyKeyMap");
    String serverType = (String) param.get("ServerType");
    CallOntologyUtil ontologyUtil = (CallOntologyUtil) param.get("CallOntologyUtil");
    List<String> roles = (List<String>) param.get("Roles");
    String tempTableName = "";
    PreparedStatement stmt = null;
    boolean errorFlag = false, timeoutFlag = false;
    String itemKey = "";

    int actualTotal = 0, obsfcTotal = 0;
    boolean obfscDataRoleFlag = false;
    try {
      LogTimingUtil logTimingUtil = new LogTimingUtil();
      logTimingUtil.setStartTime();
      obfscDataRoleFlag = checkDataObscRole(sfDAOFactory.getOriginalDataSourceLookup(), roles);
      itemKey = getItemKeyFromResultType(sfDAOFactory, resultTypeName);

      log.debug("Result type's " + resultTypeName + " item key value " + itemKey);

      LogTimingUtil subLogTimingUtil = new LogTimingUtil();
      subLogTimingUtil.setStartTime();
      ConceptsType conceptsType = ontologyUtil.callGetChildren(itemKey);
      if (conceptsType != null && conceptsType.getConcept().size() < 1) {
        throw new I2B2DAOException(
            "Could not fetch children result type "
                + resultTypeName
                + " item key [ "
                + itemKey
                + " ]");
      }
      subLogTimingUtil.setEndTime();
      if (processTimingFlag != null) {
        if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) {
          ProcessTimingReportUtil ptrUtil =
              new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup());
          ptrUtil.logProcessTimingMessage(
              queryInstanceId,
              ptrUtil.buildProcessTiming(
                  subLogTimingUtil,
                  "BUILD - " + resultTypeName + " : Ontology Call(GetChildren) ",
                  ""));
        }
      }

      String itemCountSql =
          " select count(distinct PATIENT_NUM) as item_count  from "
              + this.getDbSchemaName()
              + "observation_fact obs_fact  "
              + " where obs_fact.patient_num in (select patient_num from "
              + TEMP_DX_TABLE
              + "    ) "
              + " and obs_fact.concept_cd in (select concept_cd from "
              + this.getDbSchemaName()
              + "concept_dimension  where concept_path like ?)";

      ResultType resultType = new ResultType();
      resultType.setName(resultTypeName);
      stmt = sfConn.prepareStatement(itemCountSql);

      CancelStatementRunner csr = new CancelStatementRunner(stmt, transactionTimeout);
      Thread csrThread = new Thread(csr);
      csrThread.start();

      for (ConceptType conceptType : conceptsType.getConcept()) {

        String dimCode = this.getDimCodeInSqlFormat(conceptType);

        itemCountSql =
            " select count(distinct PATIENT_NUM) as item_count  from "
                + this.getDbSchemaName()
                + " observation_fact "
                + " where "
                + " patient_num in (select patient_num from "
                + TEMP_DX_TABLE
                + " )  and "
                + conceptType.getFacttablecolumn()
                + " IN (select "
                + conceptType.getFacttablecolumn()
                + " from "
                + getDbSchemaName()
                + conceptType.getTablename()
                + "  "
                + " where "
                + conceptType.getColumnname()
                + " "
                + conceptType.getOperator()
                + " "
                + dimCode
                + ")";

        stmt = sfConn.prepareStatement(itemCountSql);

        // // smuniraju: Currently, in postgres, a timeout value > 0 will result in "setQueryTimeout
        // is not yet implemented"
        // stmt.setQueryTimeout(transactionTimeout);
        int queryTimeout =
            (serverType.equalsIgnoreCase(DAOFactoryHelper.POSTGRES)) ? 0 : transactionTimeout;
        stmt.setQueryTimeout(queryTimeout);

        log.debug("Executing count sql [" + itemCountSql + "]");

        //
        subLogTimingUtil.setStartTime();
        ResultSet resultSet = stmt.executeQuery();
        if (csr.getSqlFinishedFlag()) {
          timeoutFlag = true;
          throw new CRCTimeOutException("The query was canceled.");
        }
        resultSet.next();
        int demoCount = resultSet.getInt("item_count");
        subLogTimingUtil.setEndTime();
        if (processTimingFlag != null) {
          if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) {
            ProcessTimingReportUtil ptrUtil =
                new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup());
            ptrUtil.logProcessTimingMessage(
                queryInstanceId,
                ptrUtil.buildProcessTiming(
                    subLogTimingUtil,
                    "BUILD - "
                        + resultTypeName
                        + " : COUNT SQL for "
                        + conceptType.getDimcode()
                        + " ",
                    "sql=" + itemCountSql));
          }
        }
        //

        actualTotal += demoCount;
        if (obfscDataRoleFlag) {
          GaussianBoxMuller gaussianBoxMuller = new GaussianBoxMuller();
          demoCount = (int) gaussianBoxMuller.getNormalizedValueForCount(demoCount);
          obsfcTotal += demoCount;
        }
        DataType mdataType = new DataType();
        mdataType.setValue(String.valueOf(demoCount));
        mdataType.setColumn(conceptType.getName());
        mdataType.setType("int");
        resultType.getData().add(mdataType);
      }
      csr.setSqlFinishedFlag();
      csrThread.interrupt();
      stmt.close();

      edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory of =
          new edu.harvard.i2b2.crc.datavo.i2b2result.ObjectFactory();
      BodyType bodyType = new BodyType();
      bodyType.getAny().add(of.createResult(resultType));
      ResultEnvelopeType resultEnvelop = new ResultEnvelopeType();
      resultEnvelop.setBody(bodyType);

      JAXBUtil jaxbUtil = CRCJAXBUtil.getJAXBUtil();

      StringWriter strWriter = new StringWriter();
      subLogTimingUtil.setStartTime();
      jaxbUtil.marshaller(of.createI2B2ResultEnvelope(resultEnvelop), strWriter);
      subLogTimingUtil.setEndTime();
      tm.begin();
      IXmlResultDao xmlResultDao = sfDAOFactory.getXmlResultDao();
      xmlResultDao.createQueryXmlResult(resultInstanceId, strWriter.toString());
      //
      if (processTimingFlag != null) {
        if (!processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.NONE)) {
          ProcessTimingReportUtil ptrUtil =
              new ProcessTimingReportUtil(sfDAOFactory.getDataSourceLookup());
          if (processTimingFlag.trim().equalsIgnoreCase(ProcessTimingReportUtil.DEBUG)) {
            ptrUtil.logProcessTimingMessage(
                queryInstanceId,
                ptrUtil.buildProcessTiming(subLogTimingUtil, "JAXB - " + resultTypeName, ""));
          }
          logTimingUtil.setEndTime();
          ptrUtil.logProcessTimingMessage(
              queryInstanceId,
              ptrUtil.buildProcessTiming(logTimingUtil, "BUILD - " + resultTypeName, ""));
        }
      }
      tm.commit();
    } catch (com.microsoft.sqlserver.jdbc.SQLServerException sqlServerEx) {
      // if the setQueryTimeout worked, then the message would be timed
      // out
      if (sqlServerEx.getMessage().indexOf("timed out") > -1) {
        timeoutFlag = true;
        throw new CRCTimeOutException(sqlServerEx.getMessage(), sqlServerEx);
      } else if (sqlServerEx
              .getMessage()
              .indexOf( // if the stmt.cancel()
                  // worked, then this
                  // exception is
                  // thrown
                  "The query was canceled.")
          > -1) {

        timeoutFlag = true;
        throw new CRCTimeOutException(sqlServerEx.getMessage(), sqlServerEx);
      } else {

        errorFlag = true;
        log.error("Sqlserver error while executing sql", sqlServerEx);
        throw new I2B2DAOException("Sqlserver error while executing sql", sqlServerEx);
      }

    } catch (SQLException sqlEx) {
      // catch oracle query timeout error ORA-01013
      if (sqlEx.toString().indexOf("ORA-01013") > -1) {
        timeoutFlag = true;
        throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx);
      }
      if (sqlEx.getMessage().indexOf("The query was canceled.") > -1) {
        timeoutFlag = true;
        throw new CRCTimeOutException(sqlEx.getMessage(), sqlEx);
      }
      errorFlag = true;
      log.error("Error while executing sql", sqlEx);
      throw new I2B2DAOException("Error while executing sql", sqlEx);
    } catch (Exception sqlEx) {

      errorFlag = true;
      log.error("QueryResultPatientSetGenerator.generateResult:" + sqlEx.getMessage(), sqlEx);
      throw new I2B2DAOException(
          "QueryResultPatientSetGenerator.generateResult:" + sqlEx.getMessage(), sqlEx);
    } finally {

      IQueryResultInstanceDao resultInstanceDao = sfDAOFactory.getPatientSetResultDAO();

      if (errorFlag) {
        resultInstanceDao.updatePatientSet(
            resultInstanceId, QueryStatusTypeId.STATUSTYPE_ID_ERROR, 0);
      } else {
        // set the setsize and the description of the result instance if
        // the user role is obfuscated
        if (timeoutFlag == false) { // check if the query completed
          try {
            tm.begin();

            String obfusMethod = "", description = null;
            if (obfscDataRoleFlag) {
              obfusMethod = IQueryResultInstanceDao.OBSUBTOTAL;
              // add () to the result type description
              // read the description from result type

            } else {
              obfuscatedRecordCount = actualTotal;
            }
            IQueryResultTypeDao resultTypeDao = sfDAOFactory.getQueryResultTypeDao();
            List<QtQueryResultType> resultTypeList =
                resultTypeDao.getQueryResultTypeByName(resultTypeName);

            // add "(Obfuscated)" in the description
            // description = resultTypeList.get(0)
            //		.getDescription()
            //		+ " (Obfuscated) ";
            String queryName =
                sfDAOFactory
                    .getQueryMasterDAO()
                    .getQueryDefinition(
                        sfDAOFactory
                            .getQueryInstanceDAO()
                            .getQueryInstanceByInstanceId(queryInstanceId)
                            .getQtQueryMaster()
                            .getQueryMasterId())
                    .getName();

            resultInstanceDao.updatePatientSet(
                resultInstanceId,
                QueryStatusTypeId.STATUSTYPE_ID_FINISHED,
                null,
                // obsfcTotal,
                obfuscatedRecordCount,
                actualTotal,
                obfusMethod);

            description = resultTypeList.get(0).getDescription() + " for \"" + queryName + "\"";

            // set the result instance description
            resultInstanceDao.updateResultInstanceDescription(resultInstanceId, description);
            tm.commit();
          } catch (NotSupportedException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          } catch (SystemException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          } catch (SecurityException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          } catch (IllegalStateException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          } catch (RollbackException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          } catch (HeuristicMixedException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          } catch (HeuristicRollbackException e) {
            throw new I2B2DAOException(
                "Failed to write obfuscated description " + e.getMessage(), e);
          }
        }
      }
    }
  }