private Calendar getDateOnlyCalendar() {
   Calendar calendar = GregorianCalendar.getInstance();
   calendar.set(Calendar.HOUR, 0);
   calendar.set(Calendar.MINUTE, 0);
   calendar.set(Calendar.SECOND, 0);
   calendar.set(Calendar.MILLISECOND, 0);
   return calendar;
 }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    System.out.println("Publicty Chair Servlet RuleML-2009");
    out.println("Publicty Chair Servlet RuleML-2009");

    Calendar cal = new GregorianCalendar();

    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);

    String date;

    if (month == 10 || month == 11 || month == 12) date = "" + year + month + day;
    else date = "" + year + "0" + month + day;

    date = "date(" + date + ":integer).";
    System.out.println("Publicty Chair Servlet Console update:");
    System.out.println(date);
  }
Example #3
0
  @Override
  public void init(FilterConfig fc) throws ServletException {
    Calendar c = new GregorianCalendar();
    nextReportingHour = c.get(Calendar.HOUR_OF_DAY) + 1;
    String t = fc.getInitParameter("maxTotalSimultaneousRequests");
    if (t != null)
      try {
        maxTotalSimultaneousRequests = Integer.parseInt(t);
      } catch (NumberFormatException e) {
        log.error("Bad value for parameter 'maxTotalSimultaneousRequests': '" + t + "'");
        log.error("Using the default value of 10 instead");
      }

    //        t=fc.getInitParameter("maxSimultaneousRequests");
    //        if(t!=null)
    //        try {
    //            maxSimultaneousRequests=Integer.parseInt(t);
    //        }
    //        catch(Exception e) {
    //            log.error("Bad value for parameter 'maxSimultaneousRequests': '"+t+"'");
    //            log.error("Using the default value of 3 instead");
    //        }

    contactInfo = fc.getInitParameter("contactInfo");
    if (log.isDebugEnabled()) log.debug("contactInfo=" + contactInfo);
    addressInHeader = fc.getInitParameter("addressInHeader");
    if (log.isDebugEnabled()) log.debug("addressInHeader=" + addressInHeader);

    String eA = fc.getInitParameter("equivalentAddresses");
    if (eA != null) { // comma/blank/tab separated list of shortAddr=shortAddr
      // e.g. 157.55.33=157.55.32, 157.55.34=157.55.32, 157.55.35=157.55.32, 157.55.36=157.55.32,
      // 157.55.37=157.55.32
      // or 157.55.*=157.55.0
      // or 69.171.224-255=69.171.224
      String first, pair, second;
      StringTokenizer findPairs = new StringTokenizer(eA, ",\t ");
      StringTokenizer findValues;
      while (findPairs.hasMoreTokens()) {
        pair = findPairs.nextToken();
        findValues = new StringTokenizer(pair, "=");
        first = findValues.nextToken();
        second = findValues.nextToken();
        if (first.endsWith(".*")) {
          first = first.substring(0, first.indexOf(".*"));
          for (int i = 0; i < 256; i++) equivalentAddresses.put(first + "." + i, second);
        } else if (first.contains("-")) {
          int offset = first.lastIndexOf('.');
          String base = first.substring(0, offset);
          String rest = first.substring(offset + 1);
          StringTokenizer range = new StringTokenizer(rest, "-");
          int start = Integer.parseInt(range.nextToken());
          int end = Integer.parseInt(range.nextToken());
          for (int i = start; i < end; i++) {
            System.out.println(
                "adding " + base + "." + i + "=" + second + " to the equivalence table");
            equivalentAddresses.put(base + "." + i, second);
          }
        } else equivalentAddresses.put(first, second);
      }
    }

    String iA = fc.getInitParameter("ignorableAddresses");
    if (iA != null) {
      StringTokenizer st = new StringTokenizer(iA, ", ");
      while (st.hasMoreTokens()) ignorableAddresses.add(st.nextToken());
    }
  }
Example #4
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String longAddr = null, shortAddr, s, transactionKey = null;
    int count;
    boolean ignorable = false;

    synchronized (simultaneousRequestsByShortIPAddr) {
      if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) {
        log.error(
            "This system has exceeded the maxTotalSimultaneousRequests limit of "
                + maxTotalSimultaneousRequests);
        log.error(simultaneousRequestsByShortIPAddr);
        for (String str : simultaneousRequests) log.error(str);
        ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE);
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body><h1>Service Temporarily Unavailable</h1>");
        writer.println(
            "The system is experiencing a severe load and is temporarily unable to accept new requests");
        if (contactInfo != null)
          writer.println("<p>Contact " + contactInfo + " for more information</p>");
        writer.println("</body></html>");
        writer.close();
        return;
      }
      if (addressInHeader != null) {
        @SuppressWarnings("unchecked")
        Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader);
        while (addrs.hasMoreElements()) {
          longAddr = addrs.nextElement();
          if (longAddr == null) {
            if (++addressInHeaderErrorCount < 10)
              log.error("Expected a " + addressInHeader + " header but got null");
            continue;
          }
          if (longAddr.lastIndexOf('.') >= 0) break;
        }
      }
      if (longAddr == null) longAddr = request.getRemoteAddr();
      int i = longAddr.lastIndexOf('.');
      if (i < 0) {
        log.error("bogus IP address: '" + longAddr + "'");
        longAddr = "0.0.0.0";
      }
      shortAddr = longAddr.substring(0, i); // trim off 4th number group
      // that lets us spot requests from clusters
      s = equivalentAddresses.get(shortAddr); // map one short addr to another?
      if (s != null) shortAddr = s;
      if (ignorableAddresses.contains(shortAddr)) {
        ignorable = true;
      } else {
        Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr);
        if (icount != null) count = icount;
        else count = 0;

        int maxSimultaneousRequests =
            (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4;
        if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1;
        if (count >= maxSimultaneousRequests) {
          log.error(
              "IP addr "
                  + shortAddr
                  + ".* has exceeded "
                  + maxSimultaneousRequests
                  + " simultaneous requests!");
          log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests);
          log.error("totalSimultaneousRequests=" + totalSimultaneousRequests);
          for (String str : simultaneousRequests) log.error(str);
          //
          // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); //
          // someday
          ((HttpServletResponse) response).setStatus(429); // too many requests
          response.setContentType("text/html");
          PrintWriter writer = response.getWriter();
          writer.println(
              "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>");
          writer.println(
              "You have exceeded the maximum simultaneous request value of "
                  + maxSimultaneousRequests);
          writer.println("<p>This message and your IP address have been logged and reported</p>");
          if (contactInfo != null)
            writer.println("<p>Contact " + contactInfo + " for more information</p>");
          writer.println("</body></html>");
          writer.close();
          return;
        }
        simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1);
        icount = totalRequests.get(shortAddr);
        if (icount != null) count = icount;
        else count = 0;
        totalRequests.put(shortAddr, count + 1);
        totalSimultaneousRequests++;
        transactionKey =
            new StringBuilder((new Date(System.currentTimeMillis())).toString())
                .append('|')
                .append(shortAddr)
                .append('|')
                .append(((HttpServletRequest) request).getQueryString())
                .toString();
        simultaneousRequests.add(transactionKey);
      }
    }

    try {
      HttpServletResponseWrapper wrapper =
          new HttpServletResponseWrapper((HttpServletResponse) response);
      chain.doFilter(request, wrapper);
    } finally {
      if (!ignorable)
        synchronized (simultaneousRequestsByShortIPAddr) {
          totalSimultaneousRequests--;
          simultaneousRequests.remove(transactionKey);
          count = simultaneousRequestsByShortIPAddr.get(shortAddr);
          if (count == 1) // prune them from the table
          simultaneousRequestsByShortIPAddr.remove(shortAddr);
          else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1);
        }
    }

    Calendar c = new GregorianCalendar();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    if (hour == 0 && nextReportingHour == 24) { // new day!
      // you could reset your daily limits table here
      nextReportingHour = 0;
    }

    if (hour >= nextReportingHour) { // generate the hourly report
      // you could reset your hourly limits table here
      nextReportingHour = hour + 1;

      if (log.isInfoEnabled()) {
        HashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
        List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet());
        List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values());
        TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues);
        Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]);
        int size = sortedArray.length;

        for (int i = 0; i < size; i++)
          map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]);
        Iterator<String> it = map.keySet().iterator();
        String key;
        StringBuilder sb = new StringBuilder("Top 10 users in the last hour");
        for (int i = 0; i < 10 && it.hasNext(); i++) {
          key = it.next();
          sb.append("\n    ").append(key).append(" : ").append(map.get(key));
        }
        log.info(sb);
      }
      totalRequests.clear();
    }
  }
  private void _jspService(
      javax.servlet.http.HttpServletRequest request,
      javax.servlet.http.HttpServletResponse response,
      com.caucho.jsp.PageContextImpl pageContext,
      javax.servlet.ServletContext application,
      javax.servlet.http.HttpSession session,
      TagState _jsp_state)
      throws Throwable {
    javax.servlet.jsp.JspWriter out = pageContext.getOut();
    final javax.el.ELContext _jsp_env = pageContext.getELContext();
    javax.servlet.ServletConfig config = getServletConfig();
    javax.servlet.Servlet page = this;
    javax.servlet.jsp.tagext.JspTag _jsp_parent_tag = null;
    com.caucho.jsp.PageContextImpl _jsp_parentContext = pageContext;
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");

    out.write(_jsp_string0, 0, _jsp_string0.length);
    CP_Classes.EthnicGroup ethnic;
    synchronized (pageContext.getSession()) {
      ethnic = (CP_Classes.EthnicGroup) pageContext.getSession().getAttribute("ethnic");
      if (ethnic == null) {
        ethnic = new CP_Classes.EthnicGroup();
        pageContext.getSession().setAttribute("ethnic", ethnic);
      }
    }
    out.write(_jsp_string1, 0, _jsp_string1.length);
    CP_Classes.Login logchk;
    synchronized (pageContext.getSession()) {
      logchk = (CP_Classes.Login) pageContext.getSession().getAttribute("logchk");
      if (logchk == null) {
        logchk = new CP_Classes.Login();
        pageContext.getSession().setAttribute("logchk", logchk);
      }
    }
    out.write(_jsp_string1, 0, _jsp_string1.length);
    CP_Classes.Translate trans;
    synchronized (pageContext.getSession()) {
      trans = (CP_Classes.Translate) pageContext.getSession().getAttribute("trans");
      if (trans == null) {
        trans = new CP_Classes.Translate();
        pageContext.getSession().setAttribute("trans", trans);
      }
    }
    out.write(_jsp_string1, 0, _jsp_string1.length);
    // added to check whether organisation is a consulting company
    // Mark Oei 09 Mar 2010
    out.write(_jsp_string1, 0, _jsp_string1.length);
    CP_Classes.Organization Org;
    synchronized (pageContext.getSession()) {
      Org = (CP_Classes.Organization) pageContext.getSession().getAttribute("Org");
      if (Org == null) {
        Org = new CP_Classes.Organization();
        pageContext.getSession().setAttribute("Org", Org);
      }
    }
    out.write(_jsp_string1, 0, _jsp_string1.length);
    CP_Classes.Create_Edit_Survey CE_Survey;
    synchronized (pageContext.getSession()) {
      CE_Survey =
          (CP_Classes.Create_Edit_Survey) pageContext.getSession().getAttribute("CE_Survey");
      if (CE_Survey == null) {
        CE_Survey = new CP_Classes.Create_Edit_Survey();
        pageContext.getSession().setAttribute("CE_Survey", CE_Survey);
      }
    }
    out.write(_jsp_string2, 0, _jsp_string2.length);
    // by lydia Date 05/09/2008 Fix jsp file to support Thai language
    out.write(_jsp_string3, 0, _jsp_string3.length);
    out.print((trans.tslt("Delete Ethnic Group")));
    out.write(_jsp_string4, 0, _jsp_string4.length);
    out.print((trans.tslt("Edit Ethnic Group")));
    out.write(_jsp_string5, 0, _jsp_string5.length);
    out.print((trans.tslt("Please enter Ethnic Group")));
    out.write(_jsp_string6, 0, _jsp_string6.length);
    out.print((trans.tslt("Add Ethnic Group")));
    out.write(_jsp_string7, 0, _jsp_string7.length);
    out.print((trans.tslt("Please enter Ethnic Group")));
    out.write(_jsp_string8, 0, _jsp_string8.length);

    String username = (String) session.getAttribute("username");

    if (!logchk.isUsable(username)) {
      out.write(_jsp_string9, 0, _jsp_string9.length);
    } else {

      if (request.getParameter("proceed") != null) {
        int PKOrg = new Integer(request.getParameter("proceed")).intValue();
        logchk.setOrg(PKOrg);
      }

      if (request.getParameter("Delete") != null) {

        int Ethnic_ID = new Integer(request.getParameter("ethnic_ID")).intValue();
        boolean bIsDeleted = ethnic.deleteRecord(Ethnic_ID, logchk.getPKUser());

        if (bIsDeleted) {

          out.write(_jsp_string10, 0, _jsp_string10.length);
        }
      }

      if (request.getParameter("Edit") != null) {
        int Ethnic_ID = new Integer(request.getParameter("ethnic_ID")).intValue();

        String txtEthnic = request.getParameter("txtEthnic");
        boolean bIsEdited =
            ethnic.editRecord(Ethnic_ID, txtEthnic, logchk.getOrg(), logchk.getPKUser());

        if (bIsEdited) {

          out.write(_jsp_string11, 0, _jsp_string11.length);

        } else {

          out.write(_jsp_string12, 0, _jsp_string12.length);
        }
      }

      if (request.getParameter("Add") != null) {

        String txtEthnic = request.getParameter("txtEthnic");

        boolean bExist = ethnic.existRecord(txtEthnic, logchk.getOrg());

        if (!bExist) {
          boolean bIsAdded = ethnic.addRecord(txtEthnic, logchk.getOrg(), logchk.getPKUser());

          if (bIsAdded) {

            out.write(_jsp_string13, 0, _jsp_string13.length);
          }
        } else {

          out.write(_jsp_string14, 0, _jsp_string14.length);
        }
      }

      out.write(_jsp_string15, 0, _jsp_string15.length);
      out.print((trans.tslt("Ethnic Group")));
      out.write(_jsp_string16, 0, _jsp_string16.length);
      out.print((trans.tslt("To Add, click on the Add button")));
      out.write(_jsp_string17, 0, _jsp_string17.length);
      out.print(
          (trans.tslt("To Edit, click on the relevant radio button and click on the Edit button")));
      out.write(_jsp_string17, 0, _jsp_string17.length);
      out.print(
          (trans.tslt(
              "To Delete, click on the relevant radio button and click on the Delete button")));
      out.write(_jsp_string18, 0, _jsp_string18.length);
      out.print((trans.tslt("Organisation")));
      out.write(_jsp_string19, 0, _jsp_string19.length);

      // Added to check whether organisation is also a consulting company
      // if yes, will display a dropdown list of organisation managed by this company
      // else, it will display the current organisation only
      // Mark Oei 09 Mar 2010
      String[] UserDetail = new String[14];
      UserDetail = CE_Survey.getUserDetail(logchk.getPKUser());
      boolean isConsulting = true;
      isConsulting =
          Org.isConsulting(UserDetail[10]); // check whether organisation is a consulting company
      if (isConsulting) {
        Vector vOrg = logchk.getOrgList(logchk.getCompany());

        for (int i = 0; i < vOrg.size(); i++) {
          votblOrganization vo = (votblOrganization) vOrg.elementAt(i);
          int PKOrg = vo.getPKOrganization();
          String OrgName = vo.getOrganizationName();

          if (logchk.getOrg() == PKOrg) {
            out.write(_jsp_string20, 0, _jsp_string20.length);
            out.print((PKOrg));
            out.write(_jsp_string21, 0, _jsp_string21.length);
            out.print((OrgName));
            out.write(_jsp_string22, 0, _jsp_string22.length);
          } else {
            out.write(_jsp_string20, 0, _jsp_string20.length);
            out.print((PKOrg));
            out.write('>');
            out.print((OrgName));
            out.write(_jsp_string22, 0, _jsp_string22.length);
          }
        }
      } else {
        out.write(_jsp_string23, 0, _jsp_string23.length);
        out.print((logchk.getSelfOrg()));
        out.write('>');
        out.print((UserDetail[10]));
        out.write(_jsp_string24, 0, _jsp_string24.length);
      } // End of isConsulting
      out.write(_jsp_string25, 0, _jsp_string25.length);
      out.print((trans.tslt("Ethnic Group")));
      out.write(_jsp_string26, 0, _jsp_string26.length);

      /** ****************** Edited by James 17 Oct 2007 ********************** */
      Vector v = ethnic.getAllEthnics(logchk.getOrg());

      for (int i = 0; i < v.size(); i++) {
        voEthnic vo = (voEthnic) v.elementAt(i);

        int ethnic_ID = vo.getPKEthnic();
        String ethnic_Desc = vo.getEthnicDesc();

        out.write(_jsp_string27, 0, _jsp_string27.length);
        out.print((ethnic_ID));
        out.write(_jsp_string28, 0, _jsp_string28.length);
        out.print((ethnic_Desc));
        out.write(_jsp_string29, 0, _jsp_string29.length);
        out.print((ethnic_Desc));
        out.write(_jsp_string30, 0, _jsp_string30.length);
      }

      out.write(_jsp_string31, 0, _jsp_string31.length);
      out.print((trans.tslt("Ethnic Group")));
      out.write(_jsp_string32, 0, _jsp_string32.length);
      out.print((trans.tslt("Add")));
      out.write(_jsp_string33, 0, _jsp_string33.length);
      out.print((trans.tslt("Edit")));
      out.write(_jsp_string34, 0, _jsp_string34.length);
      out.print((trans.tslt("Delete")));
      out.write(_jsp_string35, 0, _jsp_string35.length);
    }
    out.write(_jsp_string36, 0, _jsp_string36.length);
    // by lydia Date 05/09/2008 Fix jsp file to support Thai language
    out.write(_jsp_string37, 0, _jsp_string37.length);

    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);

    out.write(_jsp_string38, 0, _jsp_string38.length);
    // Denise 05/01/2010 update new email address
    out.write(_jsp_string39, 0, _jsp_string39.length);
    out.print((year));
    out.write(_jsp_string40, 0, _jsp_string40.length);
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      Response responseVO =
          bean.insertItem(
              conn,
              (JournalHeaderVO) inputPar,
              userSessionPars,
              request,
              response,
              userSession,
              context);
      if (responseVO.isError()) {
        conn.rollback();
        return responseVO;
      }

      if (inputPar instanceof JournalHeaderWithVatVO) {
        JournalHeaderWithVatVO vo = (JournalHeaderWithVatVO) inputPar;

        // insert vat rows in the specified vat register...
        Response regRes =
            vatRegisterAction.insertVatRows(
                conn, vo.getVats(), userSessionPars, request, response, userSession, context);
        if (regRes.isError()) {
          conn.rollback();
          return regRes;
        }

        // retrieve payment instalments...
        Response payRes =
            payAction.executeCommand(
                new LookupValidationParams(vo.getPaymentCodeREG10(), new HashMap()),
                userSessionPars,
                request,
                response,
                userSession,
                context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        PaymentVO payVO = (PaymentVO) ((VOListResponse) payRes).getRows().get(0);
        GridParams gridParams = new GridParams();
        gridParams
            .getOtherGridParams()
            .put(ApplicationConsts.PAYMENT_CODE_REG10, vo.getPaymentCodeREG10());
        payRes =
            paysAction.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        java.util.List rows = ((VOListResponse) payRes).getRows();

        // create expirations in DOC19 ONLY if:
        // - there are more than one instalment OR
        // - there is only one instalment and this instalment has more than 0 instalment days
        if (rows.size() > 1
            || (rows.size() == 1
                && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() > 0)) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          PaymentInstalmentVO inVO = null;
          pstmt =
              conn.prepareStatement(
                  "insert into DOC19_EXPIRATIONS(COMPANY_CODE_SYS01,DOC_TYPE,DOC_YEAR,DOC_NUMBER,DOC_SEQUENCE,PROGRESSIVE,DOC_DATE,EXPIRATION_DATE,NAME_1,NAME_2,VALUE,PAYED,DESCRIPTION,CUSTOMER_SUPPLIER_CODE,PROGRESSIVE_REG04,CURRENCY_CODE_REG03) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
          long startTime = vo.getItemDateACC05().getTime(); // item date...
          if (payVO.getStartDayREG10().equals(ApplicationConsts.START_DAY_END_MONTH)) {
            Calendar cal = Calendar.getInstance();
            if (cal.get(cal.MONTH) == 10
                || cal.get(cal.MONTH) == 3
                || cal.get(cal.MONTH) == 5
                || cal.get(cal.MONTH) == 8) cal.set(cal.DAY_OF_MONTH, 30);
            else if (cal.get(cal.MONTH) == 1) {
              if (cal.get(cal.YEAR) % 4 == 0) cal.set(cal.DAY_OF_MONTH, 29);
              else cal.set(cal.DAY_OF_MONTH, 28);
            } else cal.set(cal.DAY_OF_MONTH, 31);
            startTime = cal.getTime().getTime();
          }
          BigDecimal amount = null;

          for (int i = 0; i < rows.size(); i++) {
            inVO = (PaymentInstalmentVO) rows.get(i);
            pstmt.setString(1, vo.getCompanyCodeSys01ACC05());
            pstmt.setString(2, vo.getDocTypeDOC19());
            pstmt.setBigDecimal(3, vo.getItemYearACC05());
            pstmt.setBigDecimal(4, null);
            pstmt.setBigDecimal(5, vo.getDocSequenceDOC19());
            pstmt.setBigDecimal(
                6,
                ProgressiveUtils.getConsecutiveProgressive(
                    "DOC19_EXPIRATIONS", "PROGRESSIVE", conn));
            pstmt.setDate(7, vo.getItemDateACC05());
            pstmt.setDate(
                8,
                new java.sql.Date(
                    startTime
                        + inVO.getInstalmentDaysREG17().longValue()
                            * 86400
                            * 1000)); // expiration date
            pstmt.setString(9, vo.getName_1REG04());
            pstmt.setString(10, vo.getName_2REG04());
            amount =
                vo.getTotalValue()
                    .multiply(inVO.getPercentageREG17())
                    .divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP)
                    .setScale(vo.getTotalValue().scale(), BigDecimal.ROUND_HALF_UP); // value

            pstmt.setBigDecimal(11, amount);
            pstmt.setString(12, "N");

            if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE))
              pstmt.setString(
                  13,
                  resources.getResource("sale generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            else
              pstmt.setString(
                  13,
                  resources.getResource("purchase generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            pstmt.setString(14, vo.getCustomerCodeSAL07());
            pstmt.setBigDecimal(15, vo.getProgressiveREG04());
            pstmt.setString(16, vo.getCurrencyCodeREG01());
            pstmt.execute();
          }
          pstmt.close();
        }

        // create an item registration for proceeds, according to expiration settings (e.g. retail
        // selling):
        // there must be only one instalment and this instalment has 0 instalment days
        if (rows.size() == 1
            && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() == 0) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          HashMap map = new HashMap();
          map.put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01ACC05());
          map.put(ApplicationConsts.PARAM_CODE, ApplicationConsts.CASE_ACCOUNT);
          Response res =
              userParamAction.executeCommand(
                  map, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
          String caseAccountCode = ((VOResponse) res).getVo().toString();

          JournalHeaderVO jhVO = new JournalHeaderVO();
          jhVO.setCompanyCodeSys01ACC05(vo.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jhVO.setDescriptionACC05(
                resources.getResource("sale generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("customer")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_INVOICE_PROCEEDS);
          } else {
            jhVO.setDescriptionACC05(
                resources.getResource("purchase generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("supplier")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_PURCHASE_INVOICE_PAYED);
          }

          jhVO.setItemDateACC05(new java.sql.Date(System.currentTimeMillis()));
          jhVO.setItemYearACC05(new BigDecimal(Calendar.getInstance().get(Calendar.YEAR)));

          JournalRowVO jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setAccountCodeAcc02ACC06(vo.getCreditAccountCodeAcc02SAL07());
            jrVO.setAccountCodeACC06(vo.getCustomerCodeSAL07());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_CUSTOMER);
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setAccountCodeAcc02ACC06(vo.getDebitAccountCodeAcc02PUR01());
            jrVO.setAccountCodeACC06(vo.getSupplierCodePUR01());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_SUPPLIER);
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);

          jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          jrVO.setAccountCodeAcc02ACC06(caseAccountCode);
          jrVO.setAccountCodeACC06(caseAccountCode);
          jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_ACCOUNT);
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);
          Response proceedsRes =
              bean.insertItem(conn, jhVO, userSessionPars, request, response, userSession, context);
          if (proceedsRes.isError()) {
            conn.rollback();
            return proceedsRes;
          }
        }
      }

      Response answer = responseVO;

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while inserting a new item in the journal",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
 private boolean isNewFileNeeded(Calendar todayCalendar) {
   return todayCalendar.get(Calendar.DATE) != getPerformanceLogCalendar().get(Calendar.DATE);
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      address = PAConfiguration.getAddress();
      port = PAConfiguration.getPort(instantiation);
      poslAddress = PAConfiguration.getPOSL(instantiation, topic);
      rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
      messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
      System.out.println("5 Publicty Chair Servlet");
      System.out.println(response.toString());

      BufferedReader brd = request.getReader();

      String input = "";
      String message = "";

      while (!input.equals("</RuleML>")) {

        input = brd.readLine();

        message = message + input;
      }
      String[] varOrder = getVariableOrder(message);
      System.out.println("Received Message: " + message);

      //	BackwardReasoner br = new BackwardReasoner();
      //   Iterator solit =null;
      //   DefiniteClause dc = null;
      //   SymbolTable.reset();

      POSLParser pp = new POSLParser();
      // String contents = "c(a).\nc(b).\nc(c).";

      Date t1 = new GregorianCalendar().getTime();
      System.out.println(t1.getHours() + ":" + t1.getMinutes());
      // append time to contents

      System.out.println("day: " + t1.getDay());
      System.out.println("day: " + t1.getYear());
      System.out.println("day: " + t1.getMonth());

      // time
      String time = "time(" + t1.getHours() + ":integer).";
      System.out.println(time);

      String url = poslAddress;

      // String url = "http://www.jdrew.org/oojdrew/test.posl";
      String contents = "";

      // day of the week
      int day = t1.getDay();
      boolean weekday = true;

      if (day == 0 || day == 6) {
        weekday = false;
      }

      String dayOfWeek;

      if (weekday) {
        dayOfWeek = "day(weekday).";
      } else {
        dayOfWeek = "day(weekend).";
      }
      // full date
      Calendar cal = new GregorianCalendar();

      int year = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH) + 1;
      int day2 = cal.get(Calendar.DAY_OF_MONTH);

      String date;

      String day3 = "" + day2;

      if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7
          || day2 == 8 || day2 == 9) {

        day3 = "0" + day2;
      }

      if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3;
      else date = "" + year + "0" + month + day3;

      date = "date(" + date + ":integer).";

      System.out.println(date);

      String url2 = rdfAddress;
      HttpClient client2 = new HttpClient();
      GetMethod method2 = new GetMethod(url2);
      method2.setFollowRedirects(true);
      String typestr = "";
      // Execute the GET method
      int statusCode2 = client2.executeMethod(method2);
      if (statusCode2 != -1) {
        typestr = method2.getResponseBodyAsString();
      }
      System.out.println("Types: " + typestr);
      Types.reset();
      RDFSParser.parseRDFSString(typestr);

      try {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        method.setFollowRedirects(true);

        // Execute the GET method
        int statusCode = client.executeMethod(method);
        if (statusCode != -1) {
          contents = method.getResponseBodyAsString();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      contents = contents + "\n" + time;
      contents = contents + "\n" + dayOfWeek;
      contents = contents + "\n" + date;

      BackwardReasoner br = new BackwardReasoner();
      Iterator solit = null;
      DefiniteClause dc = null;
      SymbolTable.reset();

      pp.parseDefiniteClauses(contents);

      br.loadClauses(pp.iterator());
      System.out.println("TEST");
      Iterator it = pp.iterator();
      while (it.hasNext()) {
        DefiniteClause d = (DefiniteClause) it.next();
        System.out.println("Loaded clause: " + d.toPOSLString());
      }

      br = new BackwardReasoner(br.clauses, br.oids);

      MessageParser m = new MessageParser(message);
      Element atom = null;

      try {

        atom = m.parseForContent();

      } catch (Exception e) {

        System.out.println("Invalid Message");
        // out.flush();

      }

      QueryBuilder q = new QueryBuilder(atom);
      String query = q.generateDoc();
      System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
      RuleMLParser qp = new RuleMLParser();

      try {

        dc = qp.parseRuleMLQuery(query);

      } catch (Exception e) {
        System.out.println("Invalid Query");
        // out.flush();
      }

      // solit = br.iterativeDepthFirstSolutionIterator(dc);

      solit = br.iterativeDepthFirstSolutionIterator(dc);

      int varSize = 0;

      while (solit.hasNext()) {

        Vector data = new Vector();

        BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

        Hashtable varbind = gl.varBindings;
        javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
        root.setAllowsChildren(true);

        javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

        int i = 0;
        Object[][] rowdata = new Object[varbind.size()][2];
        varSize = varbind.size();

        Enumeration e = varbind.keys();
        while (e.hasMoreElements()) {
          Object k = e.nextElement();
          Object val = varbind.get(k);
          String ks = (String) k;
          rowdata[i][0] = ks;
          rowdata[i][1] = val;
          i++;
        }

        data.addElement(rowdata);
        String[] messages = new String[data.size()];
        MessageGenerator g =
            new MessageGenerator(
                data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder);
        messages = g.Messages2();

        String appender = "";

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        for (int i1 = 0; i1 < data.size(); i1++) {
          System.out.println(i1 + ")" + messages[i1].toString());
          props.put("text", messages[i1].toString());
          InputStream in = msg.sendGetMessage(props);
        }
        System.out.println("NEXT MESSAGE");
      }

      MessageGenerator g =
          new MessageGenerator(
              null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel());

      URL sender = new URL(address + ":" + port);
      HttpMessage msg = new HttpMessage(sender);
      Properties props = new Properties();

      String finalMessage = g.finalMessage(query);

      System.out.println(finalMessage);

      props.put("text", finalMessage);
      InputStream in = msg.sendGetMessage(props);

      System.out.println("Stop_Communication");

    } catch (Exception e) {
      System.out.println("ERROR has occured : " + e.toString());
    }
    out.close();
  }